// j3dvrmlのランチャ
#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 *args[8];

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

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

  strcpy_s(basePath, szDrive);
  strcat_s(basePath, szDir);
  strcpy_s(classPath, "\"");
  strcat_s(classPath, basePath);
  strcat_s(classPath, "j3dvrml.jar;");
  strcat_s(classPath, basePath);
  strcat_s(classPath, "acerola3d\\*;\"");
  strcpy_s(libPath, "-Djava.library.path=\"");
  strcat_s(libPath, basePath);
  strcat_s(libPath, "acerola3d\"");

  if ((!lpCmdLine)||(!strlen(lpCmdLine))) {
    args[0] = "javaw.exe";
    args[1] = "-cp";
    args[2] = classPath;
    args[3] = libPath;
    args[4] = "jp.sourceforge.acerola3d.j3dvrml.J3DVrml";
    args[5] = NULL;
  } else {
    args[0] = "javaw.exe";
    args[1] = "-cp";
    args[2] = classPath;
    args[3] = libPath;
    args[4] = "jp.sourceforge.acerola3d.j3dvrml.J3DVrml";
    args[5] = "-open";
    args[6] = lpCmdLine;
    args[7] = NULL;
  }

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

  // メッセージボックスに文字列を表示します。
  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;
}
