// sutl.cpp : Defines the class behaviors for the application.
//

#include "stdafx.h"
#include "sutl.h"
#include "sutlDlg.h"
#include "ReqDlg.h"
#include "catexcp.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

#define EXE_CVTDAT  "WGSDFCVT.EXE"
#define ANYCVT      "WGSDFCVT\\*.CVT"

#pragma optimize("",off)
static GBOOL runCVT(const CHAR *pCmdLine);
LPVOID threadParm;
UINT wgsthread(VOID *parm);
VOID chkcvt(VOID);
static VOID hferror(INT code,CHAR *estring);
DllExport VOID wgsmsx(INT argc,
                      CHAR **argv,
                      CDialog *pDlg,
                      CStatic *pSrc,
                      CStatic *pDst,
                      CProgressCtrl *pSPrg,
                      CProgressCtrl *pMPrg,
                      VOID (*pfErr)(INT eCode,CHAR *eString));

CSutlDlg* pMW=NULL;
CReqDlg* pRD=NULL;
CStatic* pST=NULL;
CProgressCtrl* pPRG=NULL;
GBOOL isService=FALSE;
GBOOL bReqWarned=FALSE;
INT globalExit=0;

/////////////////////////////////////////////////////////////////////////////
// CSutlApp

BEGIN_MESSAGE_MAP(CSutlApp, CWinApp)
     //{{AFX_MSG_MAP(CSutlApp)
     //}}AFX_MSG_MAP
     ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSutlApp construction

CSutlApp::CSutlApp()
{
     m_wgsthr=NULL;
}

/////////////////////////////////////////////////////////////////////////////
// The one and only CSutlApp object

CSutlApp theApp;

/////////////////////////////////////////////////////////////////////////////
// CSutlApp initialization

BOOL CSutlApp::InitInstance()
{

#ifdef _AFXDLL
     Enable3dControls();           // Call this when using MFC in a shared DLL
#else
     Enable3dControlsStatic();     // Call this when linking to MFC statically
#endif
     pMW=new CSutlDlg;
     pRD=new CReqDlg;
     m_pMainWnd=pMW;
     pMW->Create(IDD_SUTL_DIALOG);
     pRD->Create(IDD_REQUIRES);
     if (!canRunWGSINT()) {
          MessageBox(NULL,NOPROCEED,
                    NULL,MB_ICONSTOP|MB_OK|MB_TASKMODAL|MB_SETFOREGROUND);
          exit(1);
     }
     changedir();
     m_wgsthr=AfxBeginThread(wgsthread,pMW->GetSafeHwnd(),THREAD_PRIORITY_NORMAL);
     return TRUE;
}

UINT
wgsthread(
LPVOID parm)
{
     CHAR argc=0;
     CHAR *argv[]={""};

     CCatException* mainExcept=new CCatException;
     threadParm=parm;
     pST=(CStatic *)pMW->GetDlgItem(IDC_INTINFO);
     pPRG=(CProgressCtrl *)pMW->GetDlgItem(IDC_PROGRESS1);

     isService=isWgstartRunning();
     TRY {
          chkcvt();
          wgsint();
          wgsmsx(argc,argv,pMW,NULL,pST,NULL,pPRG,hferror);
          threadParm=NULL;
          mainExcept->Delete();
          dfaStop();
          ::PostMessage((HWND)parm,WM_QUIT,0,0);
          return(0);
     }
     CATCH(CCatException, e) {
          pMW->ShowWindow(SW_HIDE);
          globalExit=e->m_errorCode;
          if (globalExit == ERROR_FAIL) {
               e->Catastro();
          }
          dfaStop();
          if (threadParm != NULL) {
               ::PostMessage((HWND)threadParm,WM_QUIT,0,0);
          }
          return(0);
     }
     END_CATCH
}

static VOID
hferror(
INT,
CHAR *estring)
{
     CCatException* hfExcept=new CCatException;
     hfExcept->SetError(ERROR_FAIL,estring);
     THROW(hfExcept);
}

void CSutlApp::changedir(VOID)
{
     USHORT namlen;
     HMODULE hMod;
     CHAR *fptr;
     CHAR drch;
     CHAR tmpFnm[260];
     CHAR valBuf[260];

     stlcpy(tmpFnm,m_pszExeName,260);
     stlcat(tmpFnm,".EXE",260);
     hMod=GetModuleHandle(tmpFnm);
     if (hMod != NULL) {
          namlen=(USHORT)GetModuleFileName(hMod,valBuf,260);
          fptr=valBuf+strlen(valBuf);
          while ((*fptr != '\\') && (fptr >= valBuf)) {
               fptr--;
          }
          if (*fptr == '\\') {
               *fptr='\0';
          }
          _chdir(valBuf);
          fptr=valBuf+strlen(valBuf);
          while ((*fptr != ':') && (fptr >= valBuf)) {
               fptr--;
          }
          if (*fptr == ':') {
               if (fptr > valBuf) {
                    drch=*(fptr-1);
                    if (isalpha(drch)) {
                         _chdrive(drch-'A'+1);
                    }
               }
          }
     }
}

VOID
chkcvt(VOID)
{
     Cffblk fb;

     CCatException* ccExcept=new CCatException;
     if (fnd1st(&fb,ANYCVT,0)) {
          if (isService) {
               ccExcept->SetError(ERROR_FAIL,"Cannot convert data files while"
                    "" SVR_NAME " is active as a service, please run as an App first.");
               THROW(ccExcept);
          }
          if (fnd1st(&fb,EXE_CVTDAT,0)) {
               if (!runCVT(EXE_CVTDAT)) {
                    ccExcept->SetError(ERROR_RECOVER,"Data file conversion failed.");
                    THROW(ccExcept);
               }
          }
     }
     ccExcept->Delete();
}

int CSutlApp::ExitInstance()
{
     if (pMW != NULL) {
          if (m_wgsthr != NULL) {
               ::WaitForSingleObject(m_wgsthr->m_hThread,INFINITE);
          }
          if (bReqWarned) {
               pMW->ShowWindow(SW_HIDE);
               pRD->WaitForClose();      // Wait for 15 seconds or until close is pressed.
          }
          pMW->DestroyWindow();
          pRD->DestroyWindow();
          delete pMW;
          delete pRD;
     }
     return(globalExit);
}

static GBOOL                       //   return TRUE-Ok
runCVT(                           // runs application
const CHAR *pCmdLine)              //   command line
{
     STARTUPINFO startInfo;
     PROCESS_INFORMATION procInfo;
     DWORD exitCode;

     memset(&startInfo,0,sizeof(STARTUPINFO));
     startInfo.cb=sizeof(STARTUPINFO);
     startInfo.lpTitle=(CHAR *)NULL;
     startInfo.dwFlags=STARTF_USESHOWWINDOW;
     startInfo.wShowWindow=(WORD)SW_SHOWDEFAULT;
     if (!CreateProcess(NULL,                // programm name
                        (LPTSTR)pCmdLine,    // command line string
                        NULL,                // process security attributes
                        NULL,                // thread security attributes
                        TRUE,                // handle inheritance flag
                        CREATE_DEFAULT_ERROR_MODE, // creation flags
                        NULL,                // new environment block
                        NULL,                // current directory name
                        &startInfo,          // STARTUPINFO
                        &procInfo)) {        // PROCESS_INFORMATION
          return(FALSE);
     }
     WaitForSingleObject(procInfo.hProcess,INFINITE);
     GetExitCodeProcess(procInfo.hProcess,&exitCode);
     CloseHandle(procInfo.hProcess);
     CloseHandle(procInfo.hThread);
     return((exitCode != 70) && (exitCode != 1));
}

#pragma optimize("",on)
