// A3Boardのランチャ
#include <windows.h>
#include <process.h>
#include <errno.h>

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow )
{
  int iRet;
  char path[MAX_PATH];
  char szDrive[_MAX_DRIVE], szDir[_MAX_DIR], szFileName[_MAX_FNAME], szExt[_MAX_EXT];
  char basePath[MAX_PATH];
  char classPath[MAX_PATH*2];
  char libPath[MAX_PATH];
  char tempPath[MAX_PATH];
  char tmpPath[MAX_PATH];
  char *args[5];

  iRet = GetModuleFileName(NULL, path, sizeof(path));

  _splitpath_s( path, szDrive, _MAX_DRIVE, szDir, _MAX_DIR, szFileName, _MAX_FNAME, szExt, _MAX_EXT );

  char tempF[MAX_PATH];
  GetEnvironmentVariable("TEMP",tempF,MAX_PATH);

  strcpy_s(basePath, szDrive);
  strcat_s(basePath, szDir);
  strcpy_s(classPath, "CLASSPATH=");
  strcat_s(classPath, basePath);
  strcat_s(classPath, "a3board.jar;");
  strcat_s(classPath, basePath);
  strcat_s(classPath, "acerola3d\\*;");
  strcpy_s(libPath, "PATH=");
  strcat_s(libPath, basePath);
  strcat_s(libPath, "acerola3d");
  strcpy_s(tempPath, "TEMP=");
  strcat_s(tempPath, tempF);
  strcpy_s(tmpPath, "TMP=");
  strcat_s(tmpPath, tempF);

  char *my_env[] = { classPath, libPath, tempPath, tmpPath, NULL };

  if ((!lpCmdLine)||(!strlen(lpCmdLine))) {
    args[0] = "javaw.exe";
    args[1] = "jp.sourceforge.acerola3d.a3board.A3Board";
    args[2] = NULL;
  } else {
    args[0] = "javaw.exe";
    args[1] = "jp.sourceforge.acerola3d.a3board.A3Board";
    args[2] = "-open";
    args[3] = lpCmdLine;
    args[4] = NULL;
  }

  iRet = _spawnvpe(_P_NOWAIT, "javaw.exe", args, my_env);

  // メッセージボックスに文字列を表示します。
  if(iRet == -1) {
    char *message;
    if(errno == ENOENT) {
      message = "Java6をインストールしてセットアップして下さい";
    } else if(errno == ENOMEM) {
      message = "メモリ不足です";
    } else if(errno == E2BIG) {
      message = "引数リストが 1024 バイトを超えてます";
    } else {
      message = "予期しないエラーが発生しました";
    }
    iRet = MessageBox(NULL, message, "エラー", MB_OK);
    return 1;
  }

  return 0;
}
