// not UNIX
// Strawberry.cpp : Defines the class behaviors for the application.
//

#include "stdafx.h"
#include "Strawberry.h"
#include "MainFrm.h"

#include "ChildFrm.h"
#include "IpFrame.h"
#include "StrawberryDoc.h"
#include "StrawberryView.h"
#include <initguid.h>/*Single-Instance Out-of-Process Servers*/
#include "Strawberry_i.c"/*Single-Instance Out-of-Process Servers*/

#include "Dialog.h"
#include "New_Class.h"
#include "Thread.h"
#include "Splash.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#define EXE_FILES 20

/////////////////////////////////////////////////////////////////////////////
// Angel
HRESULT CreateShortCut(LPCTSTR, LPTSTR, LPTSTR, LPTSTR);   
#include "shlobj.h" // Angel (CreateShortCut)
#include "DispDrv.h" 

/////////////////////////////////////////////////////////////////////////////
// The global variabels
BYTE a[60]; // for OLE
int b[60];

CStrawberryApp theApp; // The one and only CStrawberryApp object
CMainFrame* pMainFrame;
CFile *pGFile, file;
DWORD FileType=3; // 3 all // 5 Output // 6 Add
DWORD gl_flag, gl_open=0;  /* temporal */ 
DWORD Environment;
_TCHAR namef[_MAX_PATH];
_TCHAR string3[L_BUFER+2];
CRichEditCtrl *pOutput=NULL, *pActiveCtrl=NULL;
CStrawberryDoc *pActivePj=NULL, *pActiveFile=NULL, *pCompiled=NULL, *pActive=NULL;
CArchive *pAr, *pAr2;
CMultiDocTemplate *pDocTemplate1;
C2MultiDocTemplate *pDocTemplate2;
CProjectInfo *pInfo, *pInfo2, DefaultProject;
C_FrameWnd *pMain_Frame;
CWnd *pMainWindow;
CDC *pMain_DC=NULL;
CRect G_rectPaint(0,0,0,0);
CRgn G_rgnPaint;
DWORD G_FlagsMes=0;
CwProofTree *pProofTree=NULL;
CwInformation *pStack=NULL, *pVariables=NULL;
CThread *pThread;
/////////////////////////////////////////////////////////////////////////////

void Empty_dir( CString Dir, _TCHAR *Ext)
{
  WIN32_FIND_DATA FindFileData;
  MY_HANDLE hTemp;

  hTemp=FindFirstFile(ProgramPath+Dir+Ext, &FindFileData);
  if (INVALID_HANDLE_VALUE==hTemp)
    return;
  do
    DeleteFile(ProgramPath+Dir+FindFileData.cFileName);
  while(FindNextFile(hTemp, &FindFileData));
  FindClose(hTemp);
}

void SPEX_in_EXE(CString Installed) 
{
  WIN32_FIND_DATA FindFileData;
  MY_HANDLE hTemp;
  CString SpexFile, ExeFile, Dir;
  CFile fSpexFile, fExeFile;
  HGLOBAL Exe1 = NULL;
  HRSRC   res1 = NULL;
  void   *Buf1;
  HMODULE hModule=NULL; //GetModuleHandle(_T("Prolog.exe"));
  DWORD   size1, size, i;
  _TCHAR exe_dirs[6][32]=  // change 6 also in the for
  {
    _T("Examples\\"),
    _T("Cyrillic Transliteration\\"),
    _T("Games\\Memory Blocks\\"),
    _T("Games\\"),
    _T("OLE\\Servers\\"),
    _T("OLE\\"),
  };

  res1=FindResource(hModule,MAKEINTRESOURCE(IDR_EXE_1),RT_RCDATA);
  ASSERT(res1);
  size1=SizeofResource(hModule,res1);
  Exe1=LoadResource(hModule,res1);
  ASSERT(Exe1);
  Buf1=LockResource(Exe1);

  for(i=0; i<=6; i++)
  {
    if (i)
      Dir=exe_dirs[i-1];
    else
      Dir=Installed+_T("\\");
    hTemp=FindFirstFile(ProgramPath+Dir+_T("*.spex"), &FindFileData);
    if (INVALID_HANDLE_VALUE==hTemp)
    {
      FindClose(hTemp);
      continue;
    }
    do
    {
      SpexFile=ProgramPath+Dir+FindFileData.cFileName;
      ExeFile=SpexFile.Left(SpexFile.GetLength()-4)+_T("exe");
      if (fExeFile.Open(ExeFile, CFile::modeCreate | CFile::modeWrite))
      {
        CArchive ar1(&fExeFile, CArchive::store);
        ar1.Write(Buf1, size1);
        if (fSpexFile.Open(SpexFile, CFile::modeRead))
        {
          CArchive ar2(&fSpexFile, CArchive::load);
          while(size=ar2.Read(string3, L_BUFER))
            ar1.Write(string3, size);
          ar2.Close();
          fSpexFile.Close();
        }
        ar1.Close();
        fExeFile.Close();

        DeleteFile(SpexFile);
      }
    }
    while(FindNextFile(hTemp, &FindFileData));
    FindClose(hTemp);
  }
}

BOOL C2DocManager::DoPromptFileName(CString& fileName, UINT nIDSTitle, DWORD lFlags, BOOL bOpenFileDialog, CDocTemplate* pTemplate)
{
  CFileDialog dlgFile(bOpenFileDialog);

  CString title;
  VERIFY(title.LoadString(nIDSTitle));

  dlgFile.m_ofn.Flags |= lFlags;
  if (!bOpenFileDialog)  // save as
    dlgFile.m_ofn.lpstrInitialDir=NULL;
  else if (gl_open&1)
  {
    gl_open=0;
    dlgFile.m_ofn.lpstrInitialDir=ProgramPath;
  }
  else if (gl_open&8)
  {
    gl_open=0;
    dlgFile.m_ofn.lpstrInitialDir=NULL;
  }
  else
  {
    CStrawberryDoc *pDocument;
    if ((CStrawberryDoc*)pMainFrame->MDIGetActive()==NULL)
      dlgFile.m_ofn.lpstrInitialDir=NULL;
    else
    {
      pDocument=(CStrawberryDoc*)pMainFrame->MDIGetActive()->GetActiveDocument();
      if (pDocument->m_FileType!=5) // not output
        dlgFile.m_ofn.lpstrInitialDir=pDocument->GetPathName();
      else
        dlgFile.m_ofn.lpstrInitialDir=NULL;
    }
  }    
    
  dlgFile.m_ofn.lpstrFilter = _T("Prolog Files (*.pro; *.spj; *.txt; *.rtf)\0*.pro;*.spj;*.txt;*.rtf\0\
Strawberry Projects (*.spj)\0*.spj\0Prolog Executable Files (*.exe; *.spex)\0*.exe;*.spex\0Special Files (*.def;*.add)\0\
*.def;*.add\0All Files (*.*)\0*.*\0");
  dlgFile.m_ofn.nFilterIndex = Environment&7;
  dlgFile.m_ofn.lpstrTitle = title;
  dlgFile.m_ofn.lpstrFile = fileName.GetBuffer(_MAX_PATH);

  BOOL bResult = dlgFile.DoModal() == IDOK ? TRUE : FALSE;
  fileName.ReleaseBuffer();
  Environment&=M1^7;
  Environment+=dlgFile.m_ofn.nFilterIndex;
  FileType=3;
  if (bResult)
  {
    if (!bOpenFileDialog)  // save as
    {
      DWORD FileType;
      CMDIChildWnd *pWnd=pMainFrame->MDIGetActive();
      if (pWnd==NULL)
        return 0;
      CString end(fileName.Right(4));
      if (end.CompareNoCase(_T(".spj"))==0)
        FileType=1;
      else if (end.CompareNoCase(_T(".rtf"))==0)
        FileType=2;
      else if (end.CompareNoCase(_T(".exe"))==0)
      {
        MessageBoxA(pMainFrame->m_hWnd, "You cannot save this information as an EXE file.",
                  "Strawberry Prolog", MB_OK | MB_ICONSTOP);
        return 0;
      }
      else if (end.CompareNoCase(_T("spex"))==0)
      {
        MessageBoxA(pMainFrame->m_hWnd, "You cannot save this information as an SPEX file.",
                  "Strawberry Prolog", MB_OK | MB_ICONSTOP);
        return 0;
      }
      else
        FileType=3;
      CStrawberryDoc *pDoc=(CStrawberryDoc*)pWnd->GetActiveDocument();
      if (pDoc->m_FileType!=FileType && pDoc->m_FileType!=5)
      {
        if (pDoc->m_FileType==1 || FileType==1) 
        {
          //pMainFrame->PostMessage(WM_USER, 0, (long)pWnd);
          if (FileType>1)
          {
            delete pDoc->m_pInfo;
            pDoc->m_pInfo=&DefaultProject;
          }
          else
          {
            pDoc->m_pInfo=pInfo=new CProjectInfo;
            pInfo->STACK_start=DefaultProject.STACK_start;
            pInfo->STACK_max=DefaultProject.STACK_max;
            pInfo->BUDA_start=DefaultProject.BUDA_start;
            pInfo->BUDA_max=DefaultProject.BUDA_max;
            pInfo->BUDA_S_start=DefaultProject.BUDA_S_start;
            pInfo->BUDA_S_max=DefaultProject.BUDA_S_max;
            pInfo->m_Settings=DefaultProject.m_Settings&0xff80ffff;
            pInfo->m_Settings|=0x20000*(pDoc->m_CharSet&63)+0x400*(pDoc->m_CharSet&64);
            pInfo->m_Break_point=DefaultProject.m_Break_point;
            pInfo->m_Colors=DefaultProject.m_Colors;
            pInfo->m_AddFile=DefaultProject.m_AddFile;
            pInfo->m_DefFile=DefaultProject.m_DefFile;
            pInfo->m_ExeFileName=DefaultProject.m_ExeFileName;
            pInfo->m_Comments=DefaultProject.m_Comments;
            pInfo->m_GetMethod=DefaultProject.m_GetMethod;
            pInfo->m_PostMethod=DefaultProject.m_PostMethod;
            pInfo->m_ProgArg=DefaultProject.m_ProgArg;
            int i=0, j=DefaultProject.m_FilesList.GetSize();
            for ( ; i<j; pInfo->m_FilesList.Add(DefaultProject.m_FilesList[i++]) );
            for (i=0; i<744; pInfo->m_Icon[i]=DefaultProject.m_Icon[i], i++);
            pInfo->m_lf=DefaultProject.m_lf;
          }
        }
        pDoc->m_FileType=FileType;
      }
    }
  }
  return bResult;
}

// CStrawberryApp

BEGIN_MESSAGE_MAP(CStrawberryApp, CWinApp)
  ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
  ON_COMMAND(ID_OPTIONS_ENVIRONMENT, OnOptionsEnvironment)
  ON_COMMAND(ID_OPTIONS_SETTINGS, OnOptionsSettings)
  ON_UPDATE_COMMAND_UI(ID_OPTIONS_SETTINGS, OnUpdateOptionsSettings)
  ON_UPDATE_COMMAND_UI(ID_RUN_COMPILE, OnUpdateRunCompile)
  ON_UPDATE_COMMAND_UI(ID_RUN_RUN, OnUpdateRunRun)
  ON_COMMAND(ID_RUN_COMPILE, OnRunCompile)
  ON_COMMAND(ID_RUN_RUN, OnRunRun)
  ON_COMMAND(ID_TRACE_STEP, OnTraceStep)
  ON_COMMAND(ID_TRACE_STOP, OnTraceStop)
  ON_COMMAND(ID_TRACE_PROOFTREE, OnProofTree)
  ON_COMMAND(ID_HELP_OPERATORS, OnHelpOperators)
  ON_COMMAND(ID_TOOLS_STACK, OnToolsStack)
  ON_COMMAND(ID_TOOLS_SYSTEMLIST, OnToolsSystemList)
  ON_COMMAND(ID_TOOLS_VARIABELS, OnToolsVariabels)
  ON_COMMAND(ID_TOOLS_WINDOWOBJECTS, OnToolsWindowObjects)
  ON_COMMAND(ID_TRACE_GO, OnTraceGo)
  ON_COMMAND(ID_TRACE_STEPOVER, OnTraceStepOver)
  ON_COMMAND(ID_TRACE_STEPOUT, OnTraceStepOut)
  ON_COMMAND(ID_RUN_NEXTANSWER, OnRunNextAnswer)
  ON_COMMAND(ID_RUN_LOOPCHECK, OnRunLoopCheck)
  ON_COMMAND(ID_TRACE_FIRSTSTEP, OnTraceFirstStep)
  ON_COMMAND(ID_TRACE_FROMNEXT, OnTraceFromNext)
  ON_UPDATE_COMMAND_UI(ID_TRACE_STOP, OnUpdateTraceStop)
  ON_UPDATE_COMMAND_UI(ID_TRACE_TRACE, OnUpdateTraceTrace)
  ON_COMMAND(ID_TRACE_TRACE, OnTraceTrace)
  ON_COMMAND(ID_OPTIONS_DEFAULT, OnOptionsDefault)
  ON_COMMAND(ID_TRACE_BREAKPOINT, OnTraceBreakPoint)
  ON_COMMAND(ID_RUN_BUILD_EXE, OnRunBuildExe)
  ON_UPDATE_COMMAND_UI(ID_FILE_SAVE, OnUpdateFileSave)
  ON_COMMAND(ID_TOOLS_OBJBROW, OnObjectBrowser)
  ON_COMMAND(ID_FILE_OPEN_EX, OnFileOpenEx)
  ON_COMMAND(ID_FILE_OPEN_ST, OnFileOpenSt)
  ON_COMMAND(ID_TOOLS_CLASSES, OnToolsClasses)
  ON_COMMAND(ID_TOOLS_INSTAL, OnInstallation)
#if TR
  ON_COMMAND(ID_TOOLS_MAKE, OnToolsMake)
  ON_COMMAND(ID_TOOLS_INFO, OnToolsInfo)
  ON_COMMAND(ID_TOOLS_CLOSEDTERMS, OnToolsClosedTerms)
  ON_COMMAND(ID_TOOLS_OPENTERMS, OnToolsOpenTerms)
  ON_COMMAND(ID_TOOLS_TREE, OnToolsTree)
  ON_COMMAND(ID_TOOLS_BLOCKS_GOOD, OnToolsGoodBlocks)
  ON_COMMAND(ID_TOOLS_HASHBLOCKS, OnToolsHashBlocks)
  ON_COMMAND(ID_TOOLS_EKLER, OnToolsEkler)
  ON_COMMAND(ID_TOOLS_CONSTANTS, OnToolsConstants)
  ON_COMMAND(ID_TOOLS_KEYMAP, OnToolsKeyMap)
  ON_COMMAND(ID_TOOLS_DFIELD, OnToolsDField)
  ON_COMMAND(ID_TOOLS_POINTERS, OnToolsPointers)
  ON_COMMAND(ID_TOOLS_FFIELD, OnToolsFField)
  ON_COMMAND(ID_TOOLS_GOODFFIELD, OnToolsGoodFField)
#endif
  // Standard file based document commands
  ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
  ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
  // Standard print setup command
  ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup)
  ON_COMMAND(ID_FILE_OPEN_WITH, OnFileOpenWith)
  ON_COMMAND(ID_FILE_SAVE_WITH, OnFileSaveWith)
END_MESSAGE_MAP()


// CStrawberryApp construction

CStrawberryApp::CStrawberryApp()
{
  EnableHtmlHelp();

  // TODO: add construction code here,
  // Place all significant initialization in InitInstance
}


// This identifier was generated to be statistically unique for your app
// You may change it if you prefer to choose a specific identifier

// {44AE5C03-81BB-11D1-A58A-444553540000}
static const CLSID clsid =
{ 0x44ae5c03, 0x81bb, 0x11d1, { 0xa5, 0x8a, 0x44, 0x45, 0x53, 0x54, 0x0, 0x0 } };
// {FB17C295-F9BA-45FD-B72A-B8A799A16A43} // za triene
//static const CLSID clsid =
//{ 0xFB17C295, 0xF9BA, 0x45FD, { 0xB7, 0x2A, 0xB8, 0xA7, 0x99, 0xA1, 0x6A, 0x43 } };
const GUID CDECL BASED_CODE _tlid =
        { 0x225AE543, 0xA2CE, 0x11D1, { 0xA5, 0x8A, 0x44, 0x45, 0x53, 0x54, 0x0, 0x0 } };
// 70BE0CA9-1690-4B43-B469-D14959687B25 // za triene        
const WORD _wVerMajor = 2;
const WORD _wVerMinor = 6;


// CStrawberryApp initialization

BOOL CStrawberryApp::InitInstance()
{
#ifdef UNICODE
  if (GetVersion()&0x80000000)
    MessageBoxA(NULL, // not VER_PLATFORM_WIN32_NT
      "You cannot run Strawberry Prolog for XP/NT/2000 on this platform. Go to www.dobrev.com and download Strawberry Prolog for 98/Me.",
      "Strawberry Prolog for XP/NT/2000", MB_OK | MB_ICONSTOP);
#endif

  int j, k;
  CString str;
  _TCHAR EXEfiles[EXE_FILES][32]=
  {
    _T("Memory Blocks"),
    _T("Horrible Racing"), // only for delete
    _T("Checkers"),
    _T("Chess"),
    _T("Don't be angry"),
    _T("Fifteen"),
    _T("Fire"),
    _T("Five Balls"),
    _T("Game 6x7"),
    _T("Matches"),
    _T("Mines"),
    _T("Rubik Cube"),
    _T("Samegame"),
    _T("Solitaire"),
    _T("Star Wars"),
    _T("Tetris"),
    _T("Tick-Tack-Toe 4x4"),
    _T("Tick-Tack-Toe"),
    _T("Tick-Tack-Toe 3x3x3 More A"),
    _T("Type"),
  };

  delete m_pDocManager;
  m_pDocManager=new C2DocManager;

  // InitCommonControls() is required on Windows XP if an application
  // manifest specifies use of ComCtl32.dll version 6 or later to enable
  // visual styles.  Otherwise, any window creation will fail.
  InitCommonControls();
  CWinApp::InitInstance();

  // Change the registry key under which our settings are stored
  // TODO: You should modify this string to be something appropriate
  // such as the name of your company or organization
  SetRegistryKey(_T("AE - Dimiter Dobrev"));
#if PROF
  LoadStdProfileSettings(12);  // Load standard INI file options (including MRU)
#else
  LoadStdProfileSettings(5);  // Load standard INI file options (including MRU)
#endif
  Environment=GetProfileInt( _T("Settings"), _T("Environment"), HALF | 0x2c1); //1+64+128+512
  // Parse command line for standard shell commands, DDE, file open
  CCommandLineInfo cmdInfo;
  ParseCommandLine(cmdInfo); // taken up because of the splash
#if TR==0 // save mode
  if (cmdInfo.m_nShellCommand!=CCommandLineInfo::AppUnregister
		  && !cmdInfo.m_bRunEmbedded && !cmdInfo.m_bRunAutomated //plamen: if run as com server
       && (cmdInfo.m_nShellCommand!=CCommandLineInfo::FileOpen
        || m_lpCmdLine[0]!='/' || m_lpCmdLine[2]!=' '
         || (m_lpCmdLine[1]!='x' && m_lpCmdLine[1]!='e' && m_lpCmdLine[1]!='r') ))
  {
    if (Environment&0x80000)
    {
#if PROF
      CString MiddleStr=_T("");
#else
      CString MiddleStr=_T(" or try with the Middle edition where the size of the system arrays is much bigger");
#endif
      if (IDYES==MessageBox(NULL,
        _T("Strawberry Prolog was not properly shut down. The reason for the crash may be that some of the system arrays are overloaded. Try to change your program")
        +MiddleStr+_T(".\n\nYou are in a save mode. In this mode syntax coloring is disabled. Do you want go out from the save mode?"),
        _T("Save Mode"), MB_ICONWARNING | MB_YESNO)) //| MB_DEFBUTTON2
        Environment&=0xfff7ffff;
    }
    else
      theApp.WriteProfileInt( _T("Settings"), _T("Environment"), Environment|0x80000);
  }
#endif
  hbrGrey = CreateSolidBrush(GetSysColor(COLOR_3DFACE));
// Source code for passwords coding - its missing
//***
  if ((Environment&512) && cmdInfo.m_nShellCommand!=CCommandLineInfo::AppUnregister
       && (cmdInfo.m_nShellCommand!=CCommandLineInfo::FileOpen
        || m_lpCmdLine[0]!='/' || m_lpCmdLine[2]!=' '
         || (m_lpCmdLine[1]!='x' && m_lpCmdLine[1]!='e' && m_lpCmdLine[1]!='r') )) // Splash
  // CG: The following block was added by the Splash Screen component.
\
  {
\
      CCommandLineInfo cmdInfo;
\
      ParseCommandLine(cmdInfo);
\
      if (cmdInfo.m_nShellCommand ==CCommandLineInfo::FileNew
       || (cmdInfo.m_nShellCommand ==CCommandLineInfo::FileOpen 
         && (((m_lpCmdLine[0]=='/' && m_lpCmdLine[1]=='e' && m_lpCmdLine[2]==' ')
          + (cmdInfo.m_strFileName.Right(4).CompareNoCase(_T(".spj"))!=0))%2) ))
      CSplashWnd::EnableSplashScreen(cmdInfo.m_bShowSplash);
\
  }

  if (!AfxSocketInit())
  {
    AfxMessageBox(IDP_SOCKETS_INIT_FAILED);
    return FALSE;
  }

  // Initialize OLE libraries
  if (!AfxOleInit())
  {
    AfxMessageBox(IDP_OLE_INIT_FAILED);
    return FALSE;
  }

	HRESULT hr = _Module.Init(NULL, GetModuleHandle(NULL), &_tlid); // Plamen
	if(FAILED(hr))
	{
    AfxMessageBox(IDP_OLE_INIT_FAILED);
    return FALSE;
	}

  AfxEnableControlContainer();
  // Standard initialization
  // If you are not using these features and wish to reduce the size
  // of your final executable, you should remove from the following
  // the specific initialization routines you do not need

  // Register the application's document templates.  Document templates
  //  serve as the connection between documents, frame windows and views

  pDocTemplate1 = new CMultiDocTemplate(IDR_ProjectTYPE,
      RUNTIME_CLASS(CStrawberryDoc),
      RUNTIME_CLASS(CChildFrame), // custom MDI child frame
      RUNTIME_CLASS(CStrawberryView));
  pDocTemplate1->SetContainerInfo(IDR_ProjectTYPE_CNTR_IP);
  pDocTemplate1->SetServerInfo(
      IDR_ProjectTYPE_SRVR_EMB, IDR_ProjectTYPE_SRVR_IP,
      RUNTIME_CLASS(CInPlaceFrame));
  AddDocTemplate(pDocTemplate1);
  // Connect the COleTemplateServer to the document template
  //  The COleTemplateServer creates new documents on behalf
  //  of requesting OLE containers by using information
  //  specified in the document template
  //m_server.ConnectTemplate(clsid, pDocTemplate1, TRUE); // TRUE or FALSE

  // Change of the places - better for TXT icon but changes the PRO and SPJ icons
  pDocTemplate2 = (C2MultiDocTemplate*)new CMultiDocTemplate(IDR_FileTYPE,
      RUNTIME_CLASS(CStrawberryDoc),
      RUNTIME_CLASS(CChildFrame), // custom MDI child frame
      RUNTIME_CLASS(CStrawberryView));
  pDocTemplate2->SetContainerInfo(IDR_ProjectTYPE_CNTR_IP);
  pDocTemplate2->SetServerInfo(
      IDR_ProjectTYPE_SRVR_EMB, IDR_ProjectTYPE_SRVR_IP,
      RUNTIME_CLASS(CInPlaceFrame));
  AddDocTemplate(pDocTemplate2);
  //m_server.ConnectTemplate(clsid, pDocTemplate2, TRUE); // why commented?
  // Register all OLE server factories as running.  This enables the
  //  OLE libraries to create objects from other applications

  //COleTemplateServer::RegisterAll();
      // Note: MDI applications register all server objects without regard
      //  to the /Embedding or /Automation on the command line
    
  DefaultProject.m_Settings=GetProfileInt( _T("Default Project"), _T("Settings"), 0x40001); // charset=2
  DefaultProject.m_Settings&=M1^6; // Active Break Point and St. is full as fail
  DefaultProject.m_Break_point=GetProfileInt( _T("Default Project"), _T("Break Point"), 1);
  DefaultProject.m_Colors=GetProfileInt( _T("Default Project"), _T("Colors"), 0);
  DefaultProject.m_AddFile=GetProfileString( _T("Default Project"), _T("AddFile"), _T("Standard.add"));
  DefaultProject.m_DefFile=GetProfileString( _T("Default Project"), _T("DefFile"), _T("Standard.def"));
  DefaultProject.m_ExeFileName=GetProfileString( _T("Default Project"), _T("ExeFileName"), _T("... (Default)"));
  DefaultProject.m_Comments=GetProfileString( _T("Default Project"), _T("Comments"), _T(""));
  DefaultProject.m_GetMethod=GetProfileString( _T("Default Project"), _T("GetMethod"), _T("new"));
  DefaultProject.m_PostMethod=GetProfileString( _T("Default Project"), _T("PostMethod"), _T("new"));
  DefaultProject.m_ProgArg=GetProfileString( _T("Default Project"), _T("ProgArg"), _T(""));

  DefaultProject.m_lf.lfHeight=GetProfileInt( _T("Default Project\\Font"), _T("lfHeight"), -16);
  DefaultProject.m_lf.lfWidth=GetProfileInt( _T("Default Project\\Font"), _T("lfWidth"), 0);
  DefaultProject.m_lf.lfEscapement=GetProfileInt( _T("Default Project\\Font"), _T("lfEscapement"), 0);
  DefaultProject.m_lf.lfOrientation=GetProfileInt( _T("Default Project\\Font"), _T("lfOrientation"), 0);
  DefaultProject.m_lf.lfWeight=GetProfileInt( _T("Default Project\\Font"), _T("lfWeight"), 0);
  my_strcpy(DefaultProject.m_lf.lfFaceName, GetProfileString( _T("Default Project\\Font"), _T("lfFaceName"), _T("Courier New")));
  DefaultProject.m_lf.lfItalic=(DefaultProject.m_Settings&0x40000000)!=0;
  DefaultProject.m_lf.lfUnderline=(DefaultProject.m_Settings&0x20000000)!=0;
  DefaultProject.m_lf.lfStrikeOut=(DefaultProject.m_Settings&0x10000000)!=0;
  DefaultProject.m_lf.lfCharSet=(DefaultProject.m_Settings&0x8000000)!=0;
  DefaultProject.m_lf.lfOutPrecision=(DefaultProject.m_Settings&0x4000000)!=0;
  DefaultProject.m_lf.lfClipPrecision=(DefaultProject.m_Settings&0x2000000)!=0;
  DefaultProject.m_lf.lfQuality=(DefaultProject.m_Settings&0x1000000)!=0;
  DefaultProject.m_lf.lfPitchAndFamily=(DefaultProject.m_Settings&0x800000)!=0;
  {
  LOGFONT lf;
  lf.lfHeight=GetProfileInt( _T("InfoFont"), _T("lfHeight"), -16);
  lf.lfWidth=GetProfileInt( _T("InfoFont"), _T("lfWidth"), 0);
  lf.lfEscapement=GetProfileInt( _T("InfoFont"), _T("lfEscapement"), 0);
  lf.lfOrientation=GetProfileInt( _T("InfoFont"), _T("lfOrientation"), 0);
  lf.lfWeight=GetProfileInt( _T("InfoFont"), _T("lfWeight"), 0);
  my_strcpy(lf.lfFaceName, GetProfileString( _T("InfoFont"), _T("lfFaceName"), _T("Courier New")));
  lf.lfItalic=(Environment&0x40000000)!=0;
  lf.lfUnderline=(Environment&0x20000000)!=0;
  lf.lfStrikeOut=(Environment&0x10000000)!=0;
  lf.lfCharSet=(Environment&0x8000000)!=0;
  lf.lfOutPrecision=(Environment&0x4000000)!=0;
  lf.lfClipPrecision=(Environment&0x2000000)!=0;
  lf.lfQuality=(Environment&0x1000000)!=0;
  lf.lfPitchAndFamily=(Environment&0x800000)!=0;
  InfoFont.CreateFontIndirect(&lf);
  }//for vars
  str=GetProfileString( _T("Settings"), _T("Project"), _T(""));
  c_black=GetProfileInt( _T("Settings"), _T("c_black"), RGB(0, 0, 0));
  c_red=GetProfileInt( _T("Settings"), _T("c_red"), RGB(255, 0, 0));
  c_green=GetProfileInt( _T("Settings"), _T("c_green"), RGB(0, 127, 0));
  c_blue=GetProfileInt( _T("Settings"), _T("c_blue"), RGB(0, 0, 255));
  c_violet=GetProfileInt( _T("Settings"), _T("c_violet"), RGB(255, 0, 255));
  c_output=GetProfileInt( _T("Settings"), _T("c_output"), RGB(0, 0, 255));
  synt_color[0]=GetProfileInt( _T("Settings"), _T("synt_color_Comment"), M1);
  synt_color[1]=GetProfileInt( _T("Settings"), _T("synt_color_String"), RGB(255,0,0));
  synt_color[2]=GetProfileInt( _T("Settings"), _T("synt_color_Integer"), RGB(255,0,0));
  synt_color[3]=GetProfileInt( _T("Settings"), _T("synt_color_Float"), RGB(255, 0, 0));
  synt_color[4]=GetProfileInt( _T("Settings"), _T("synt_color_Object"), M1);
  synt_color[5]=GetProfileInt( _T("Settings"), _T("synt_color_Operator"), RGB(0, 0, 0));
  synt_color[6]=GetProfileInt( _T("Settings"), _T("synt_color_Set_Operator"), RGB(0, 0, 255));
  synt_color[7]=GetProfileInt( _T("Settings"), _T("synt_color_Atom"), RGB(0,128,0));
  synt_color[8]=GetProfileInt( _T("Settings"), _T("synt_color_Functor"), RGB(0, 0, 255));
  synt_color[9]=GetProfileInt( _T("Settings"), _T("synt_color_Brackets"), RGB(0, 0, 0));
  synt_color[10]=GetProfileInt( _T("Settings"), _T("synt_color_Variable_gl"), RGB(255,0,0));
  synt_color[11]=GetProfileInt( _T("Settings"), _T("synt_color_Variable_local"), RGB(0,0,255));
  synt_color[12]=GetProfileInt( _T("Settings"), _T("synt_color_Variable_an"), RGB(255,0,255));
  synt_color[13]=GetProfileInt( _T("Settings"), _T("synt_color_Error_syntax"), RGB(255,0,255));
  synt_color[LAST_COLOR]=M1; // for unexisting color
  if (synt_color[0]==M1 || synt_color[4]==M1)
  {
    int sys_cw=GetSysColor(COLOR_WINDOW);
    if (synt_color[0]==M1)
      synt_color[0]=((sys_cw&0xff)+((sys_cw&0xff00) >> 8)>440)?RGB(0,128,0):RGB(255,255,0);
    if (synt_color[4]==M1)
      synt_color[4]=(((sys_cw&0xff00) >> 8)+((sys_cw&0xff0000) >> 16)>440)?RGB(0,0,255):RGB(0,255,255);
    //if (synt_color[13]==M1)
    //  synt_color[13]=((sys_cw&0xff)+((sys_cw&0xff00) >> 8)+((sys_cw&0xff0000) >> 16)>660)?RGB(128,128,128):RGB(255,255,255);
  }
  DefaultProject.STACK_start=GetProfileInt( _T("Default Project"), _T("STACK_start"), 2000);
  DefaultProject.BUDA_start=GetProfileInt( _T("Default Project"), _T("VARS_start"), MAX_VARS+2048);
  DefaultProject.BUDA_S_start=GetProfileInt( _T("Default Project"), _T("LINKS_start"), MAX_VARS+4096);
  if (DefaultProject.STACK_start<8)
    DefaultProject.STACK_start=8;
  if (DefaultProject.BUDA_start<MAX_VARS+2048)
    DefaultProject.BUDA_start=MAX_VARS+2048;
  if (DefaultProject.BUDA_S_start<MAX_VARS+4096)
    DefaultProject.BUDA_S_start=MAX_VARS+4096;
  STACK2=DefaultProject.STACK_start-8;
  BUDA3=DefaultProject.BUDA_start-MAX_VARS;
  BUDA_S2=DefaultProject.BUDA_S_start-MAX_VARS;
  DefaultProject.STACK_max=GetProfileInt( _T("Default Project"), _T("STACK_max"), 64000);
  DefaultProject.BUDA_max=GetProfileInt( _T("Default Project"), _T("VARS_max"), 0x100000);
  DefaultProject.BUDA_S_max=GetProfileInt( _T("Default Project"), _T("LINKS_max"), 0x100000);
  {
    HDC hDC=CreateDC(_T("DISPLAY"), NULL, NULL, NULL);
    Screen.cx=GetDeviceCaps(hDC, HORZRES);
    Screen.cy=GetDeviceCaps(hDC, VERTRES);
    if (Environment&HALF) // First Time
    {
      Environment&=HALFM;
      if (GetDeviceCaps(hDC, LOGPIXELSX) >= 120)
        Environment|=1024; // Big Toolbar 
    }
    DeleteDC(hDC);
  }
    
  // create main MDI Frame window
  pMainFrame = new CMainFrame;
  if (!pMainFrame->LoadFrame(IDR_MAINFRAME))
    return FALSE;
  m_pMainWnd = pMainFrame;
  // call DragAcceptFiles only if there's a suffix
  //  In an MDI app, this should occur immediately after setting m_pMainWnd
  // Enable drag/drop open
  m_pMainWnd->DragAcceptFiles();
  // Enable DDE Execute open
  EnableShellOpen(); //!problems
  RegisterShellFileTypes(TRUE);
    
  {//for vars
  _TCHAR szPathName[_MAX_PATH];
  my_strcpy(szPathName, theApp.m_pszExeName);
  _TCHAR szPathName2[_MAX_PATH];
  GetModuleFileName(NULL, szPathName, _MAX_PATH);  // NULL or theApp.m_hInstance ??
  int i=my_strlen(szPathName);
  for ( ; i>0 && szPathName[i-1]!='\\' && szPathName[i-1]!=':'; i--);
  szPathName[i]=0;
  ProgramPath=szPathName;
  {
    CFile file;
    if (file.Open(ProgramPath + _T("Default.sys"), CFile::modeRead) )
    {
      CArchive ar(&file, CArchive::load);
      int i;
      CString st;

      for (ar>>i; i-->0; ar>>st, DefaultProject.m_FilesList.Add(st) );
      for (i=0; i<744; ar>>DefaultProject.m_Icon[i++]);
      ar.Close();
      file.Close();
    }
  }
  GetModuleFileName(NULL, szPathName2, _MAX_PATH);
  GetShortPathName(szPathName2, szPathName, _MAX_PATH);
  
  RegDeleteKey(HKEY_CLASSES_ROOT, _T("Strawberry.Project\\shell\\Edit\\command"));
  RegDeleteKey(HKEY_CLASSES_ROOT, _T("Strawberry.Project\\shell\\Edit")); // Temporal
  
  CString strShortName(szPathName), strHead("Prolog.File\\shell\\");

et1:
  RegSetValue(HKEY_CLASSES_ROOT, strHead + _T("Execute\\command"), REG_SZ,
        (LPCTSTR)(strShortName + _T(" /e \"%1\"")), size_in_bytes(strShortName + _T(" /e \"%1\"")));
  RegSetValue(HKEY_CLASSES_ROOT, strHead + _T("open\\command"), REG_SZ,
        (LPCTSTR)(strShortName + _T(" \"%1\"")), size_in_bytes(strShortName + _T("\"%1\"")));
  RegSetValue(HKEY_CLASSES_ROOT, strHead + _T("print\\command"), REG_SZ,
        (LPCTSTR)(strShortName + _T(" /p \"%1\"")), size_in_bytes(strShortName + _T(" /p \"%1\"")));
  RegSetValue(HKEY_CLASSES_ROOT, strHead + _T("printto\\command"), REG_SZ,
        (LPCTSTR)(strShortName + _T(" /pt \"%1\" \"%2\" \"%3\" \"%4\"")), size_in_bytes(strShortName + _T(" /pt \"%1\" \"%2\" \"%3\" \"%4\"")));
  if (strHead=="Prolog.File\\shell\\")
  {
    strHead="Strawberry.Project\\shell\\";
    goto et1;
  }
  }//for vars
  
  if(!MitiGlobalAlloc() )
    return FALSE;

	#if !defined(_WIN32_WCE) || defined(_CE_DCOM) // Plamen
	// Register class factories via CoRegisterClassObject().
	if (FAILED(_Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_SINGLEUSE)))
		return FALSE;
	#endif // !defined(_WIN32_WCE) || defined(_CE_DCOM)

  // App was launched with /Embedding or /Automation switch.
  // Run app as automation server.
  if (cmdInfo.m_bRunEmbedded || cmdInfo.m_bRunAutomated)
  {
    // Don't show the main window
    status_fl|=64; // Run Directly;
    return TRUE;
  }
	/*	Run app as standart GUI exe, // Plamen
		but this instance MUST NOT be reused as com server,
		so make dummy instance and forget about it*/
	CComPtr<IStrawberrySvr> a;
	a.CoCreateInstance(__uuidof(Server));
	a.Detach();

  MitiText(""); // creates Output
  //free((void*)m_pszHelpFilePath);//Change the name of the .HLP file
  //m_pszHelpFilePath=_tcsdup("d:\\somedir\\myhelp.hlp");
#if TR
  //We Want Information
  DWORD ww=100;
  GetUserName(string3,&ww);
  MitiText(make_utf8(string3));
  MitiText("\r\n");
  MitiText(make_utf8(m_pszHelpFilePath));
  MitiText("\r\n");
  MitiText(make_utf8(ProgramPath));
  MitiText("\r\n");
  MitiText(make_utf8(m_lpCmdLine));
  MitiText("\r\n");
  
  //string2[unicodeToUTF8(0x410, (unsigned char*)string2)]=0;
  //MitiText(string2);
#endif

  // App was launched with /Unregserver or /Unregister switch.  Unregister
  // typelibrary.  Other unregistration occurs in ProcessShellCommand().
  if (cmdInfo.m_nShellCommand == CCommandLineInfo::AppUnregister)
  {
		_Module.UpdateRegistryAppId(FALSE); // Plamen
		_Module.UnregisterServer(TRUE);
    UnregisterShellFileTypes();
    //m_server.UpdateRegistry(OAT_DOC_OBJECT_SERVER, NULL, NULL, FALSE);
    //AfxOleUnregisterTypeLib(_tlid, _wVerMajor, _wVerMinor);
  }
  // App was launched standalone or with other switches (e.g. /Register
  // or /Regserver).  Update registry entries, including typelibrary.
  else
  {
		_Module.UpdateRegistryAppId(TRUE);
		_Module.RegisterServer(TRUE);
    //m_server.UpdateRegistry(OAT_DOC_OBJECT_SERVER);
    //COleObjectFactory::UpdateRegistryAll();
    //AfxOleRegisterTypeLib(AfxGetInstanceHandle(), _tlid);
  }
  pThread=(CThread*)AfxBeginThread( RUNTIME_CLASS(CThread), THREAD_PRIORITY_NORMAL);
                                                        // THREAD_PRIORITY_ABOVE_NORMAL
  FileType=3;
  // Dispatch commands specified on the command line
  if (cmdInfo.m_nShellCommand ==CCommandLineInfo::FileNew)
  {
    {  // add dir for start of EXE
      HKEY hKey;
      _TCHAR PrologDirTemp[_MAX_PATH];
      if (ERROR_SUCCESS == 
          RegCreateKey(HKEY_CLASSES_ROOT,_T("CLSID\\{44AE5C03-81BB-11D1-A58A-444553540000}\\LocalServer32"), &hKey))
      { 
        GetModuleFileName(NULL, PrologDirTemp, _MAX_PATH);
        RegSetValueEx(hKey,_T(""),NULL,REG_SZ,(unsigned char*)PrologDirTemp,size_in_bytes(PrologDirTemp));
        RegCloseKey(hKey);
      }
    }
    if (str=="" || (Environment&0x80000))
    {
#ifdef UNICODE
      OpenDocumentFile(ProgramPath+_T("Programs\\Fractals.pro"));
      SetCurrentDirectory(ProgramPath+_T("Programs"));
      //OpenDocumentFile(ProgramPath+_T("OLE\\Merlin.spj"));
      //SetCurrentDirectory(ProgramPath+_T("OLE"));
#else
      OpenDocumentFile(ProgramPath+_T("Programs\\Fractals for 98.pro"));
      SetCurrentDirectory(ProgramPath+_T("Programs"));
      //OpenDocumentFile(ProgramPath+_T("Games\\Chess.spj"));
      //SetCurrentDirectory(ProgramPath+_T("Games"));
#endif
    }
    else
    {
      OpenDocumentFile(str);
      my_strcpy(string3, str);
      int i=my_strlen(string3);
      while ( string3[--i]!='\\' && i!=0 );
      string3[i]=0;
      SetCurrentDirectory(string3);
    }
  }
  else
  {
    if (cmdInfo.m_nShellCommand==CCommandLineInfo::FileOpen && m_lpCmdLine[0]=='/' && m_lpCmdLine[2]==' ')
    { // If the command line string is ... run directly empty; else go normaly
      if (m_lpCmdLine[1]=='e')
      {
        my_strcpy(namef, cmdInfo.m_strFileName);
        status_fl|=64; // Run Directly
        if (cmdInfo.m_strFileName.Right(4).CompareNoCase(_T(".spj"))!=0)  
          pInfo2=&DefaultProject;
        else
          pInfo2=new CProjectInfo;
        pThread->PostThreadMessage(WM_USER, 3, 0);
        return TRUE;
      }
      else if (m_lpCmdLine[1]=='x')
      {
        my_strcpy(namef, cmdInfo.m_strFileName);
        status_fl|=64; // Run Directly
        pInfo2=new CProjectInfo;
        if (cmdInfo.m_strFileName.Right(4).CompareNoCase(_T(".exe"))!=0)  
          pThread->PostThreadMessage(WM_USER, 6, 1);
        else
          pThread->PostThreadMessage(WM_USER, 6, 0);
        return TRUE;
      }
      else if (m_lpCmdLine[1]=='r') // register
      {
        _TCHAR LinkDir[MAX_PATH];  // angel
        _TCHAR PrologDir[MAX_PATH];
        _TCHAR PrologPath[MAX_PATH];
        _TCHAR user_name[100];
        DWORD nSize=100;
        HRESULT hres; 
        HKEY hKey;
        DWORD result;
        DWORD cbSize=UNI2*MAX_PATH;
        int lr;
        DWORD dwType;
        _TCHAR files[97][32]=  // change 97 also in the for
        {
          _T("Standard.trm"),
          _T("Prolog.cnt"),
          _T("Prolog.hlp"),
          _T("Prolog.chm"),
          _T("Prolog.gid"),
          _T("OLE\\OLE.pro"),
          _T("OLE\\Excel.pro"),
          _T("OLE\\Word.pro"),
          _T("Examples\\Animate.exe"),
          _T("Examples\\Arc.pro"),
          _T("Examples\\Check Box.pro"),
          _T("Examples\\Cursor.exe"),
          _T("Examples\\DLL.pro"),
          _T("Examples\\Edit.exe"), 
          _T("Examples\\Fill Polygon.pro"),
          _T("Examples\\Fonts.pro"),
          _T("Examples\\Group Box.pro"),
          _T("Examples\\Menu.exe"),
          _T("Examples\\Question.exe"),
          _T("Examples\\Radio Buttons.pro"),
          _T("Examples\\Select Font.pro"),
          _T("Examples\\Set Active Window.pro"),
          _T("Examples\\Speed.exe"),
          _T("Examples\\Sun.exe"),
          _T("Examples\\Timer.pro"),
          _T("Examples\\Base.spj"),
          _T("Examples\\Base.exe"),
          _T("Examples\\Base.txt"),
          _T("Examples\\Draw.spj"),
          _T("Examples\\Draw.exe"),
          _T("Examples\\Graphic.spj"),
          _T("Examples\\Graphic.exe"),
          _T("Examples\\Hanoi.spj"),
          _T("Examples\\Hanoi.exe"),
          _T("Examples\\Mines.spj"),
          _T("Examples\\Mines.exe"),
          _T("Examples\\Lisp.pro"),
          _T("Examples\\House.dr"),
          _T("Examples\\Yes.dr"),
          _T("Examples\\Built_in.pro"),
          _T("Examples\\File.pro"),
          _T("Examples\\Function.pro"),
          _T("Examples\\Question.pro"),
          _T("Examples\\Study.pro"),

          _T("Games\\Checkers2.pro"),
          _T("Games\\Draughts.pro"),
          _T("Games\\Fifteen.pro"),
          _T("Games\\Five Balls.pro"),
          _T("Games\\Game 6x7.pro"),
          _T("Games\\Matches.pro"),
          _T("Games\\Checkers.pro"),
          _T("Games\\Checkers2.spj"),
          _T("Games\\Checkers2.exe"),
          _T("Games\\Master Mind.pro"),
          _T("Games\\Master Mind2.pro"),
          _T("Games\\Rubik Cube.pro"),
          _T("Games\\Numpuzzle.pro"),
          _T("Games\\Pyramid.pro"),
          _T("Programs\\Calculator.pro"),
          _T("Programs\\Eight Queens.pro"),
          _T("Programs\\Music.pro"),
          _T("Programs\\Notepad.pro"),
          _T("Programs\\Strawberry Chat.pro"),

          _T("Standard20.sys"),
          _T("servers.txt"),
          _T("OLE\\Strawberry.spj"),
          _T("OLE\\OLE.exe"),
          _T("AI\\World 1.exe"),
          _T("AI\\World 2.exe"),
          _T("AI\\AI 1.exe"),
          _T("AI\\AI 2.exe"),
          _T("Examples\\Arc.exe"),
          _T("Examples\\Check Box.exe"),
          _T("Examples\\Child Windows.exe"),
          _T("Examples\\DLL.exe"),
          _T("Examples\\Fill Polygon.exe"),
          _T("Examples\\Fonts.exe"),
          _T("Examples\\Group Box.exe"),
          _T("Examples\\List Box.exe"),
          _T("Examples\\Radio Buttons.exe"),
          _T("Examples\\Select Font.exe"),
          _T("Examples\\Set Active Window.exe"),
          _T("Examples\\Timer.exe"),
          _T("Examples\\Tree Box.exe"),
          _T("Games\\Row.exe"),
          _T("Games\\Shoot.exe"),
          _T("Games\\Santase.exe"),
          _T("Games\\Numpuzzle.exe"),
          _T("Games\\Pyramid.exe"),
          _T("Games\\loder.exe"),
          _T("Games\\Snake.exe"),
          _T("Programs\\Calculator.exe"),
          _T("Programs\\Eight Queens.exe"),
          _T("Programs\\Graphic.exe"),
          _T("Programs\\Music.exe"),
          _T("Programs\\Notepad.exe"),
          _T("OLE\\Word.exe"),
        };

        GetCurrentDirectory(MAX_PATH,PrologDir);
        ProgramPath=PrologDir;

        GetModuleFileName(NULL, PrologDir, MAX_PATH); //GetModuleHandle(_T("Prolog.exe"))
        k=my_strlen(PrologDir);
        for ( ; k>1 && PrologDir[k-1]!='\\' && PrologDir[k-1]!=':'; k--);
        PrologDir[k-1]=0;
        if (ProgramPath!=PrologDir)
        {  
#ifdef UNICODE
          MessageBox(NULL, 
          _T("The installation file is started from folder which contains the file Prolog.exe. This can make problems during the installation. It is better to move the installation file in different folder."), 
          _T("Installation of 2.92"), MB_OK | MB_ICONSTOP);
#endif
          GetCurrentDirectory(MAX_PATH,PrologDir);
        }
        ProgramPath+="\\";

        int i=0;
        for(; i<97; i++) DeleteFile(files[i]);
        CreateDirectory(_T("My Programs"), NULL);
        SPEX_in_EXE(cmdInfo.m_strFileName);

        for (i=0; i<3; i++)   // clean the old uninstalation (eventually) 2.91 in 3 places // 2.92
        {
          my_strcpy(LinkDir, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Strawberry Prolog "));
          if (i==0)
            my_strcat(LinkDir, _T("2.91 pro"));
          else if (i==1)
            my_strcat(LinkDir, _T("2.91 middle"));
          else
            my_strcat(LinkDir, _T("2.91 light"));
          lr = RegOpenKeyEx(HKEY_LOCAL_MACHINE, LinkDir, 0, KEY_READ, &hKey);
          if(ERROR_SUCCESS == lr)
          {
            lr = RegQueryValueEx(hKey,_T("UninstallString"), 0, &dwType,(unsigned char *)PrologPath, &cbSize);
            if(ERROR_SUCCESS == lr)
            {
              if (my_strstr(PrologPath,PrologDir)) 
                RegDeleteKey(HKEY_LOCAL_MACHINE, LinkDir); 
            }       
            RegCloseKey(hKey);
          }
        }
        if (cmdInfo.m_strFileName!="Register")
          theApp.WriteProfileString( _T("Settings"), _T("Installed"), cmdInfo.m_strFileName); 

        GetUserName(user_name,&nSize);
        GetWindowsDirectory(LinkDir,MAX_PATH);
        GetCurrentDirectory(MAX_PATH,PrologDir);
        GetCurrentDirectory(MAX_PATH,PrologPath);
        my_strcat(PrologPath,_T("\\Prolog.exe"));
        {  // add dir for start of EXE // the path is different when registration
          HKEY hKey;
          if (ERROR_SUCCESS==RegCreateKey(HKEY_CLASSES_ROOT,_T("CLSID\\{44AE5C03-81BB-11D1-A58A-444553540000}\\LocalServer32"), &hKey))
          { 
            RegSetValueEx(hKey,_T(""),NULL,REG_SZ,(unsigned char*)PrologPath,size_in_bytes(PrologPath));
            RegCloseKey(hKey);
          }
        }
        my_strcat(LinkDir,_T("\\profiles\\"));
        my_strcat(LinkDir,user_name);
        my_strcat(LinkDir,_T("\\Desktop\\Strawberry Prolog.lnk"));
        hres=CreateShortCut(PrologPath,LinkDir,_T("Strawberry Prolog"),PrologDir);
        if (!SUCCEEDED(hres))
        {
          GetWindowsDirectory(LinkDir,MAX_PATH);
          my_strcat(LinkDir,_T("\\Desktop\\Strawberry Prolog.lnk"));
          hres=CreateShortCut(PrologPath,LinkDir,_T("Strawberry Prolog"),PrologDir);
          if (!SUCCEEDED(hres))
          {
            GetWindowsDirectory(LinkDir,MAX_PATH);
            my_strcat(LinkDir,_T("\\All Users\\Desktop\\Strawberry Prolog.lnk"));
            hres=CreateShortCut(PrologPath,LinkDir,_T("Strawberry Prolog"),PrologDir);
            if (!SUCCEEDED(hres))
            {
              GetWindowsDirectory(LinkDir,MAX_PATH);
              i=my_strlen(LinkDir);
              my_strcpy(LinkDir+i-7,_T("Documents and Settings\\"));
              my_strcat(LinkDir,user_name);
              my_strcat(LinkDir,_T("\\Desktop\\Strawberry Prolog.lnk"));
              hres=CreateShortCut(PrologPath,LinkDir,_T("Strawberry Prolog"),PrologDir);
              if (!SUCCEEDED(hres))
              {
                my_strcpy(LinkDir+i-7,_T("Documents and Settings"));
                my_strcat(LinkDir,_T("\\All Users\\Desktop\\Strawberry Prolog.lnk"));
                hres=CreateShortCut(PrologPath,LinkDir,_T("Strawberry Prolog"),PrologDir);
                if (!SUCCEEDED(hres))
                  MessageBoxA(NULL, "A shortcut to Strawberry Prolog failed to be created on your desktop.",
                                "Installation", MB_OK | MB_ICONEXCLAMATION);
              }                    
            }                    
          }
        }
        if (SUCCEEDED(hres) && cmdInfo.m_strFileName!="Register")
        {
          i=my_strlen(PrologDir);
          j=my_strlen(PrologPath)-strlen("prolog.exe");
          k=my_strlen(LinkDir)-strlen("\\Strawberry Prolog.lnk");
          my_strcat(PrologDir+i,_T("\\"));
          my_strcat(PrologDir+i,cmdInfo.m_strFileName);
          my_strcpy(PrologPath+j,cmdInfo.m_strFileName);
          my_strcat(PrologPath+j,_T("\\"));
          my_strcat(PrologPath+j,cmdInfo.m_strFileName);
          my_strcat(PrologPath+j,_T(".exe"));
          my_strcpy(LinkDir+k+1,cmdInfo.m_strFileName);
          my_strcat(LinkDir+k+1,_T(".lnk"));
          CreateShortCut(PrologPath,LinkDir,(_TCHAR *)(LPCTSTR)cmdInfo.m_strFileName,PrologDir);
          my_strcpy(PrologPath+j,_T("prolog.exe"));
          PrologDir[i]=0;
        }
        GetWindowsDirectory(LinkDir,MAX_PATH);
        my_strcat(LinkDir,_T("\\profiles\\"));
        my_strcat(LinkDir,user_name);
        my_strcat(LinkDir,_T("\\Start Menu\\Programs\\Strawberry Prolog.lnk"));
        hres=CreateShortCut(PrologPath,LinkDir,_T("Strawberry Prolog"),PrologDir);
        if (!SUCCEEDED(hres))
        {
          GetWindowsDirectory(LinkDir,MAX_PATH);
          my_strcat(LinkDir,_T("\\Start Menu\\Programs\\Strawberry Prolog.lnk"));
          hres=CreateShortCut(PrologPath,LinkDir,_T("Strawberry Prolog"),PrologDir);
          if (!SUCCEEDED(hres))
          {
            GetWindowsDirectory(LinkDir,MAX_PATH);
            my_strcat(LinkDir,_T("\\All Users\\Start Menu\\Programs\\Strawberry Prolog.lnk"));
            hres=CreateShortCut(PrologPath,LinkDir,_T("Strawberry Prolog"),PrologDir);
            if (!SUCCEEDED(hres))
            {
              GetWindowsDirectory(LinkDir,MAX_PATH);
              i=my_strlen(LinkDir);
              my_strcpy(LinkDir+i-7,_T("Documents and Settings\\"));
              my_strcat(LinkDir,user_name);
              my_strcat(LinkDir,_T("\\Start Menu\\Programs\\Strawberry Prolog.lnk"));
              hres=CreateShortCut(PrologPath,LinkDir,_T("Strawberry Prolog"),PrologDir);
              if (!SUCCEEDED(hres))
              {
                my_strcpy(LinkDir+i-7,_T("Documents and Settings"));
                my_strcat(LinkDir,_T("\\All Users\\Start Menu\\Programs\\Strawberry Prolog.lnk"));
                hres=CreateShortCut(PrologPath,LinkDir,_T("Strawberry Prolog"),PrologDir);
                if (!SUCCEEDED(hres))
                  MessageBoxA(NULL, "A shortcut to Strawberry Prolog failed to be created in the Start Menu.",
                                "Installation", MB_OK | MB_ICONEXCLAMATION);
              }
            }
          }
        }
        j=my_strlen(PrologPath)-strlen("prolog.exe");
        k=my_strlen(LinkDir)-strlen("\\Strawberry Prolog.lnk");
        if (SUCCEEDED(hres) && cmdInfo.m_strFileName!="Register")
        {
          i=my_strlen(PrologDir);
          my_strcat(PrologDir+i,_T("\\"));
          my_strcat(PrologDir+i,cmdInfo.m_strFileName);
          my_strcpy(PrologPath+j,cmdInfo.m_strFileName);
          my_strcat(PrologPath+j,_T("\\"));
          my_strcat(PrologPath+j,cmdInfo.m_strFileName);
          my_strcat(PrologPath+j,_T(".exe"));
          my_strcpy(LinkDir+k+1,cmdInfo.m_strFileName);
          my_strcat(LinkDir+k+1,_T(".lnk"));
          CreateShortCut(PrologPath,LinkDir,(LPTSTR)(LPCTSTR)cmdInfo.m_strFileName,PrologDir);
          PrologDir[i]=0;
        }
        if (SUCCEEDED(hres) && MessageBoxA(NULL, "Do you want shortcuts to Strawberry Games in the Start Menu.", "Installation - Strawberry Games", MB_YESNO | MB_ICONQUESTION))
        {
          my_strcat(PrologDir,_T("\\Games"));

          my_strcpy(PrologPath+j,_T("Games\\"));
          j+=strlen("Games\\");

          my_strcpy(LinkDir+k,_T("\\Strawberry Games"));
          k+=strlen("\\Strawberry Games");
          
          CreateDirectory(LinkDir, NULL);
          my_strcpy(LinkDir+k++,_T("\\"));
                
          my_strcpy(LinkDir+k,_T("Master Mind.lnk"));
          DeleteFile(LinkDir);
          my_strcpy(LinkDir+k,_T("Row.lnk"));
          DeleteFile(LinkDir);

          for (i=2; i<EXE_FILES; i++)
          {
            my_strcpy(LinkDir+k,EXEfiles[i]);
            my_strcat(LinkDir+k,_T(".lnk"));
            my_strcpy(PrologPath+j,EXEfiles[i]);
            my_strcat(PrologPath+j,_T(".exe"));
            CreateShortCut(PrologPath,LinkDir,EXEfiles[i],PrologDir);
          }
          my_strcpy(LinkDir+k,_T("Memory Blocks.lnk"));
          my_strcpy(PrologPath+j,_T("\\Memory Blocks\\Variant1.exe"));
          my_strcat(PrologDir,_T("\\Memory Blocks"));
          CreateShortCut(PrologPath,LinkDir,_T("Memory Blocks"),PrologDir);
        }

#if PROF==2
        result = RegCreateKeyA(HKEY_LOCAL_MACHINE,"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Strawberry Prolog 2.92 pro", &hKey);
#elif PROF==1
        result = RegCreateKeyA(HKEY_LOCAL_MACHINE,"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Strawberry Prolog 2.92 middle", &hKey);
#else
        result = RegCreateKeyA(HKEY_LOCAL_MACHINE,"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Strawberry Prolog 2.92 light", &hKey);
#endif
        if (result == ERROR_SUCCESS) 
        { 
#if PROF==2
          result=RegSetValueEx(hKey,_T("DisplayName"),NULL,REG_SZ,(unsigned char*)_T("Strawberry Prolog 2.92 pro"),UNI2*26); 
#elif PROF==1
          result=RegSetValueEx(hKey,_T("DisplayName"),NULL,REG_SZ,(unsigned char*)_T("Strawberry Prolog 2.92 middle"),UNI2*29); 
#else
          result=RegSetValueEx(hKey,_T("DisplayName"),NULL,REG_SZ,(unsigned char*)_T("Strawberry Prolog 2.92 light"),UNI2*28); 
#endif
          GetCurrentDirectory(MAX_PATH,PrologDir);
          result=RegSetValueEx(hKey,_T("PrologDir"),NULL,REG_SZ,(unsigned char*)PrologDir,size_in_bytes(PrologDir));
          my_strcat(PrologDir,_T("\\Prolog.exe /Unregister"));
          result=RegSetValueEx(hKey,_T("UninstallString"),NULL,REG_SZ,(unsigned char*)PrologDir,size_in_bytes(PrologDir));
          RegCloseKey(hKey);
          MessageBox(NULL, _T("Strawberry Prolog was installed successfully in folder:\n")+ProgramPath, _T("Installation"), MB_OK | MB_ICONINFORMATION);
        }
        else
          MessageBox(NULL, _T("Strawberry Prolog was installed but the automatic uninstallation is not OK. If you want to uninstall you should to delete manually the Strawberry Prolog folder."), _T("Installation in ")+ProgramPath, MB_OK | MB_ICONWARNING);
        return FALSE;
      }
    }
    if (cmdInfo.m_nShellCommand ==CCommandLineInfo::AppUnregister)
    {
      _TCHAR DeskLink[MAX_PATH];  // Angel
      _TCHAR StartLink[MAX_PATH];
      _TCHAR WindowsDir[MAX_PATH];
      _TCHAR PrologDir[MAX_PATH]; 
      CString Installed, SP_string;
      CFile  ExeFile;
      HGLOBAL Exe = NULL;
      HRSRC   res = NULL;
      DWORD   size = 0;
      HKEY    hKey;
      DWORD   dwType;
      DWORD   cbSize=UNI2*MAX_PATH;
      int     i, j, r, lr;
      _TCHAR    user_name[100];
      DWORD   nSize=100;
      _TCHAR help_dirs[6][16]=  // change 6 also in the for
      {
          _T("Help\\lang\\"),  _T("Help\\ex\\"), _T("Help\\env\\"),
          _T("Help\\images\\"),_T("Help\\tut\\"),_T("Help\\ver\\")
      };

#if PROF==2
      SP_string="Strawberry Prolog version 2.92 (professional)";
#elif PROF==1
      SP_string="Strawberry Prolog version 2.92 (middle)";
#else
      SP_string="Strawberry Prolog version 2.92 (light)";
#endif
      Installed=GetProfileString( _T("Settings"), _T("Installed"), _T("")); 
      if (IDYES!=MessageBox(NULL, Installed + (Installed!=""?_T(" and "):_T("")) + SP_string
        +_T(" will be removed from your system. Now ")+(Installed!=""?_T("they are"):_T("it is"))
        +_T(" located at:\n")+ProgramPath+_T("\n\nDo you want to continue."),
        _T("Uninstallation"), MB_YESNO | MB_ICONQUESTION))
        return FALSE;
      for(i=0; i<6; i++)
      {
        Empty_dir(help_dirs[i], _T("*.gif"));
        Empty_dir(help_dirs[i], _T("*.html"));
      }
      if (Installed!="")
        if (IDYES==MessageBox(NULL,
          _T("Do you want to remove all files from directory \"")+Installed
            +_T("\"."), _T("Uninstallation"), MB_YESNO | MB_ICONQUESTION))
        {
          Empty_dir(Installed+_T("\\"), _T("*.*"));
          RemoveDirectory(ProgramPath+Installed);
        }
      RegDeleteKey(HKEY_CLASSES_ROOT, _T("Prolog.File\\shell\\Execute\\command"));
      RegDeleteKey(HKEY_CLASSES_ROOT, _T("Prolog.File\\shell\\Execute"));
      RegDeleteKey(HKEY_CLASSES_ROOT, _T("Strawberry.Project\\shell\\Execute\\command"));
      RegDeleteKey(HKEY_CLASSES_ROOT, _T("Strawberry.Project\\shell\\Execute"));
      // Here Unregister // Angel

      for(r=0; r<5; r++)
      {
        GetWindowsDirectory(DeskLink,MAX_PATH);
        GetWindowsDirectory(StartLink,MAX_PATH);
        if (r==0)
        {
          my_strcat(DeskLink,_T("\\Desktop\\Strawberry Prolog.lnk"));
          my_strcat(StartLink,_T("\\Start Menu\\Programs\\Strawberry Prolog.lnk"));
        }
        else if (r==1)
        {
          GetUserName(user_name,&nSize);
          my_strcat(DeskLink,_T("\\profiles\\"));
          my_strcat(DeskLink,user_name);
          my_strcat(DeskLink,_T("\\Desktop\\Strawberry Prolog.lnk"));
          my_strcat(StartLink,_T("\\profiles\\"));
          my_strcat(StartLink,user_name);
          my_strcat(StartLink,_T("\\Start Menu\\Programs\\Strawberry Prolog.lnk"));
        }
        else if (r==2)
        {
          my_strcat(DeskLink,_T("\\All Users\\Desktop\\Strawberry Prolog.lnk"));
          my_strcat(StartLink,_T("\\All Users\\Start Menu\\Programs\\Strawberry Prolog.lnk"));
        }
        else if (r==3)
        {
          GetUserName(user_name,&nSize);
          i=my_strlen(DeskLink);
          my_strcpy(DeskLink+i-7,_T("Documents and Settings\\"));
          my_strcat(DeskLink,user_name);
          my_strcat(DeskLink,_T("\\Desktop\\Strawberry Prolog.lnk"));
          my_strcpy(StartLink+i-7,_T("Documents and Settings\\"));
          my_strcat(StartLink,user_name);
          my_strcat(StartLink,_T("\\Start Menu\\Programs\\Strawberry Prolog.lnk"));
        }
        else
        {
          i=my_strlen(DeskLink);
          my_strcpy(DeskLink+i-7,_T("Documents and Settings"));
          my_strcat(DeskLink,_T("\\All Users\\Desktop\\Strawberry Prolog.lnk"));
          my_strcpy(StartLink+i-7,_T("Documents and Settings"));
          my_strcat(StartLink,_T("\\All Users\\Start Menu\\Programs\\Strawberry Prolog.lnk"));
        }
        DeleteFile(StartLink);
        DeleteFile(DeskLink);
        i=my_strlen(StartLink)-21+17; // 21==strlen("Strawberry Prolog.lnk")
        if (Installed!="")
        {
          j=my_strlen(DeskLink)-21;
          my_strcpy(DeskLink+j,Installed+_T(".lnk"));
          my_strcpy(StartLink+i-17,Installed+_T(".lnk"));
          DeleteFile(StartLink);
          DeleteFile(DeskLink);
        }
        my_strcpy(StartLink+i-17, _T("Strawberry Games\\"));
        for (j=0; j<EXE_FILES; j++)
        {
          my_strcpy(StartLink+i,EXEfiles[j]);
          my_strcat(StartLink+i,_T(".lnk"));
          DeleteFile(StartLink);
        }
        StartLink[i-1]=0;
        RemoveDirectory(StartLink);
      } 
    
#if PROF==2
      lr = RegOpenKeyEx(HKEY_LOCAL_MACHINE,_T("Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Strawberry Prolog 2.92 pro"), 0, KEY_READ, &hKey);
#elif PROF==1
      lr = RegOpenKeyEx(HKEY_LOCAL_MACHINE,_T("Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Strawberry Prolog 2.92 middle"), 0, KEY_READ, &hKey);
#else
      lr = RegOpenKeyEx(HKEY_LOCAL_MACHINE,_T("Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Strawberry Prolog 2.92 light"), 0, KEY_READ, &hKey);
#endif
      if(ERROR_SUCCESS == lr)
      {
        lr = RegQueryValueEx(hKey,_T("PrologDir"), 0, &dwType,(unsigned char *)PrologDir, &cbSize);
        RegCloseKey(hKey);
#if PROF==2
        RegDeleteKey(HKEY_LOCAL_MACHINE,_T("Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Strawberry Prolog 2.92 pro"));
#elif PROF==1
        RegDeleteKey(HKEY_LOCAL_MACHINE,_T("Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Strawberry Prolog 2.92 middle"));
#else
        RegDeleteKey(HKEY_LOCAL_MACHINE,_T("Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Strawberry Prolog 2.92 light"));
#endif
      } 
      else
        GetModuleFileName(NULL, PrologDir, MAX_PATH);
      res=FindResource(NULL,MAKEINTRESOURCE(IDR_UNINST),RT_RCDATA);
      ASSERT(res);
      size=SizeofResource(NULL,res);
      Exe=LoadResource(NULL,res);
      
      GetWindowsDirectory(WindowsDir,MAX_PATH);
      my_strcat(WindowsDir,_T("\\temp\\uninst.tmp "));
      ExeFile.Open(WindowsDir,CFile::modeCreate | CFile::modeWrite);
      ExeFile.Write(Exe,size);
      ExeFile.Close();
      my_strcat(WindowsDir,PrologDir);
      WinExec(make_short(WindowsDir),SW_SHOW); // chang with CreateProcess in 3 places
      if (!ProcessShellCommand(cmdInfo))
        return FALSE;
      return TRUE;
    }
    // Dispatch commands specified on the command line.  Will return FALSE if
    // app was launched with /RegServer, /Register, /Unregserver or /Unregister.
    if (!ProcessShellCommand(cmdInfo))
      return FALSE;
  }

  // The main window has been initialized, so show and update it
  pMainFrame->ShowWindow(SW_SHOWMAXIMIZED);
  if ((Environment&64)==0)
    pMainFrame->SendMessage(WM_COMMAND, ID_VIEW_TOOLBAR);
  if ((Environment&128)==0)
    pMainFrame->SendMessage(WM_COMMAND, ID_VIEW_STATUS_BAR);
  pMainFrame->SendMessage(WM_COMMAND, ID_WINDOW_TILE_VERT);
  pMainFrame->UpdateWindow();
  pMainFrame->SetTimer( 1, 700, NULL); // 1400
  return TRUE;
}

int CStrawberryApp::ExitInstance()
{
#if !defined(_WIN32_WCE) || defined(_CE_DCOM)
	_Module.RevokeClassObjects();
#endif
	if(pThread)
	{
		HANDLE hThread = pThread->m_hThread;
		pThread->PostThreadMessage(WM_USER+1, 0, 0); //OnKill
		::WaitForSingleObject(hThread,1000);//give it a chance to die
	}
	return CWinApp::ExitInstance();
}

// App command to run the dialog
void CStrawberryApp::OnAppAbout()
{
  CAboutDlg aboutDlg;
  aboutDlg.DoModal();
}

// CStrawberryApp message handlers

/////////////////////////////////////////////////////////////////////////////
// CStrawberryApp commands

void CStrawberryApp::OnFileOpenEx() 
{
  gl_open=1;
  CWinApp::OnFileOpen();
}
void CStrawberryApp::OnFileOpenSt() 
{
  gl_open=8;
  CWinApp::OnFileOpen();
}
void CStrawberryApp::OnFileOpenWith()
{
  gl_open=0;
  CdOpenWith open_withDlg;
  if (open_withDlg.DoModal()!=IDOK || gl_open==0)
    return;
  CWinApp::OnFileOpen();
  gl_open=0;
}
void CStrawberryApp::OnFileSaveWith()
{
  if(pMainFrame->MDIGetActive()==NULL) return;
  gl_open=2;
  CdOpenWith open_withDlg;
  if (open_withDlg.DoModal()!=IDOK || gl_open==0)
  {
    gl_open=0;
    return;
  }
  pMainFrame->MDIGetActive()->GetActiveView()->SendMessage(WM_COMMAND, ID_FILE_SAVE_AS);
  gl_open=0;
}

void CStrawberryApp::OnOptionsEnvironment() 
{
    CEnvironment Sheet(_T("Environment"), NULL, 0);
    Sheet.DoModal();
}

void CStrawberryApp::OnOptionsSettings() 
{
  pInfo=pActivePj->m_pInfo;
  CSettings Sheet(_T("Settings of ") + pActivePj->GetTitle(), NULL, 0);
  Sheet.DoModal();
}


void CStrawberryApp::OnOptionsDefault() 
{
  pInfo=&DefaultProject;
  CSettings Sheet(_T("Default Project"), NULL, 0);
  Sheet.DoModal();
}

void CStrawberryApp::OnTraceBreakPoint() 
{
  if (pActivePj && ((Environment&32) || pActivePj==pActiveFile)) // ExecOnlyPj
  {
    pInfo=pActivePj->m_pInfo;
    CSettings Sheet(_T("Settings of ") + pActivePj->GetTitle(), NULL, 2);
    Sheet.DoModal();
  }
  else
  {
    pInfo=&DefaultProject;
    CSettings Sheet(_T("Default Project"), NULL, 2);
    Sheet.DoModal();
  }
}

void CStrawberryApp::OnUpdateFileSave(CCmdUI* pCmdUI) 
{
  CMDIChildWnd *pWnd=pMainFrame->MDIGetActive();
  if (pWnd)
  {
    CStrawberryDoc *pDoc=(CStrawberryDoc*)pWnd->GetActiveDocument();
    if (pDoc->m_FileType==4 || pDoc->m_FileType==7) // exe or spex file
        pCmdUI->Enable(FALSE);
  }
}

void CStrawberryApp::OnUpdateOptionsSettings(CCmdUI* pCmdUI) 
{
  if (pActivePj && ((Environment&32) || pActivePj==pActiveFile)) // ExecOnlyPj
    pCmdUI->SetText(_T("Settings of ") + pActivePj->GetTitle());
  else
  {
    pCmdUI->SetText(_T("Settings of Project"));
    pCmdUI->Enable(FALSE);
  }
}

void CStrawberryApp::OnUpdateRunCompile(CCmdUI* pCmdUI) 
{
  if (status_fl&2)
  {
    pCmdUI->SetText(_T("Compile"));
    pCmdUI->Enable(FALSE);
  }
  else if (pActivePj && ((Environment&32) || pActivePj==pActiveFile)) // ExecOnlyPj
    pCmdUI->SetText(_T("Compile ") + pActivePj->GetTitle());
  else if (pActiveFile)
    pCmdUI->SetText(_T("Compile ") + pActiveFile->GetTitle());
  else
  {
    pCmdUI->SetText(_T("Compile"));
    pCmdUI->Enable(FALSE);
  }
}

void CStrawberryApp::OnUpdateRunRun(CCmdUI* pCmdUI) 
{
  if (!pActiveFile || (status_fl&2))
      pCmdUI->Enable(FALSE);
}
void CStrawberryApp::OnProofTree() 
{
  if (pProofTree!=NULL)
  {
    WINDOWPLACEMENT wp;
    pProofTree->BringWindowToTop();
    pProofTree->GetWindowPlacement(&wp);
    wp.showCmd=SW_RESTORE;
    pProofTree->SetWindowPlacement(&wp);
  }
  else
  {
    pProofTree=new CwProofTree;
    CRect rect(8, Screen.cy/2, Screen.cx-8, Screen.cy-8);
    my_sprintf(string3,_T("Proof Tree - step %u."), 0x10000*lSteps_br+Steps_br-Corection);
    pProofTree->CreateEx( ((Environment&0x1000)?WS_EX_TOPMOST:0),
     AfxRegisterWndClass( CS_DBLCLKS, theApp.LoadStandardCursor(IDC_ARROW),
      CreateSolidBrush(GetSysColor(COLOR_WINDOW)), theApp.LoadIcon(IDI_TREE) ),
      string3, WS_OVERLAPPEDWINDOW | WS_CAPTION | WS_SYSMENU
      | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_VSCROLL | WS_HSCROLL,
      rect, 0, NULL);
    pProofTree->ShowWindow(SW_SHOWNORMAL);
    pProofTree->UpdateWindow();
  }
}

void CStrawberryApp::OnToolsClasses() 
{
  CwClasses* pClasses=new CwClasses;
  CButton*   pButton= new CButton;
  CImageList *pImgList=new CImageList;
  HICON hIcon;

  CRect rect(Screen.cx/2, 8, Screen.cx-8, Screen.cy-8);
  pClasses->Create( AfxRegisterWndClass( 0, theApp.LoadStandardCursor(IDC_ARROW),
    CreateSolidBrush(GetSysColor(COLOR_WINDOW)), theApp.LoadIcon(IDI_ICON) ),
    _T("Classes"), WS_OVERLAPPEDWINDOW | WS_CAPTION | WS_SYSMENU
    | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX,
    rect, 0, NULL);
  pClasses->ShowWindow(SW_SHOWNORMAL);
  pClasses->UpdateWindow();
  CRect rect2(0, 45, Screen.cx/2-20, Screen.cy-48);
  pClasses->m_pTreeBox=new CTreeCtrl;
  pClasses->m_pTreeBox->Create(WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_BORDER
      | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS| WS_VSCROLL, rect2, pClasses, 1);

  pImgList->Create(16,16,ILC_COLOR4 | ILC_MASK,3,0);
  hIcon=::LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_OBJECT));
  pImgList->Add(hIcon);
  hIcon=::LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_PROPERTY));
  pImgList->Add(hIcon);
  pClasses->m_pTreeBox->SetImageList(pImgList, TVSIL_NORMAL);
  pClasses->AddClasses();

  CRect rect3(10, 10, 90, 35);
  pButton->Create( _T("Refresh"), WS_CHILD | WS_VISIBLE | WS_TABSTOP, rect3, pClasses, 100);
}

void CStrawberryApp::OnToolsSystemList() 
{
  ShowInformation(5);
}
void CStrawberryApp::OnToolsStack() 
{
  ShowInformation(6);
}
void CStrawberryApp::OnToolsVariabels() 
{
  ShowInformation(7);
}
void CStrawberryApp::OnHelpOperators() 
{
  ShowInformation(8);
}
void CStrawberryApp::OnToolsWindowObjects() 
{
  ShowInformation(11);
}
#if TR
void CStrawberryApp::OnToolsClosedTerms() 
{
  ShowInformation(1);
}
void CStrawberryApp::OnToolsOpenTerms() 
{
  ShowInformation(2);
}
void CStrawberryApp::OnToolsTree() 
{
  ShowInformation(3);
}
void CStrawberryApp::OnToolsGoodBlocks() 
{
  ShowInformation(4);
}
void CStrawberryApp::OnToolsConstants() 
{
  ShowInformation(9);
}
void CStrawberryApp::OnToolsKeyMap() 
{
  ShowInformation(10);
}
void CStrawberryApp::OnToolsHashBlocks() 
{
  ShowInformation(12);
}
void CStrawberryApp::OnToolsEkler() 
{
  ShowInformation(13);
}
void CStrawberryApp::OnToolsDField() 
{
  ShowInformation(14);
}
void CStrawberryApp::OnToolsPointers() 
{
  ShowInformation(15);
}
void CStrawberryApp::OnToolsFField() 
{
  ShowInformation(16);
}
void CStrawberryApp::OnToolsGoodFField() 
{
  ShowInformation(17);
}
#endif
/////////////////////////////////
void CStrawberryApp::OnRunCompile() 
{
  pThread->PostThreadMessage(WM_USER, 4, 0);
}

void CStrawberryApp::OnRunRun() 
{
  pThread->PostThreadMessage(WM_USER, 3, 0);
}

void CStrawberryApp::OnRunBuild(int Flag)
{
#if PROF==2
  pThread->PostThreadMessage(WM_USER, 5, Flag);
  //MessageBoxA(NULL, "Sorry but this option is not available in version 1.6.",
  //    "Strawberry Prolog", MB_OK | MB_ICONINFORMATION);
#elif PROF==1
  MessageBoxA(NULL, "Sorry but this option is available only in Strawberry Prolog - Professional edition.\nOur address is http://www.dobrev.com.",
      "Strawberry Prolog (Middle edition)", MB_OK | MB_ICONINFORMATION);
#else
  MessageBoxA(NULL, "Sorry but this option is available only in Strawberry Prolog - Professional edition.\nOur address is http://www.dobrev.com.",
      "Strawberry Prolog (Light edition)", MB_OK | MB_ICONINFORMATION);
#endif
}
void CStrawberryApp::OnRunBuildExe() 
{
  OnRunBuild(2); // exe
}
void CStrawberryApp::OnInstallation() 
{
  OnRunBuild(1); // spex
}
#if TR
void CStrawberryApp::OnToolsMake() 
{
  OnRunBuild(0);  // Standard.sys
}
void CStrawberryApp::OnToolsInfo() 
{
  DWORD i, k;
  
  sprintf(string2,"\r\nsv_sub= %d = 0x%x\r\n", sv_sub, sv_sub);
  MitiText(string2);    
  sprintf(string2,"MEMORY_S= %d = 0x%x\r\n", MEMORY_S, MEMORY_S);
  MitiText(string2);    
  sprintf(string2,"NEW_OBJ= %d = 0x%x\r\n", NEW_OBJ, NEW_OBJ);
  MitiText(string2);    
  sprintf(string2,"sv_c= %d = 0x%x\r\n", sv_c, sv_c);
  MitiText(string2);    
  sprintf(string2,"MEMORY_C= %d = 0x%x\r\n", MEMORY_C, MEMORY_C);
  MitiText(string2);    
  sprintf(string2,"PROGRAM_L= %d = 0x%x\r\n", PROGRAM_L, PROGRAM_L);
  MitiText(string2);    
  sprintf(string2,"sv_StStore= %d = 0x%x\r\n", sv_StStore, sv_StStore);
  MitiText(string2);    
  sprintf(string2,"STRING_STORE= %d = 0x%x\r\n", STRING_STORE, STRING_STORE);
  MitiText(string2);
  
  MitiText("\r\n");
      
  for (i=0; i<20; i++)    // all_op
  {
    if (i>15)
      k=8*(i-16)+34;  // 2+32
    else
    {
      if (i%4==3)        // Assoc .. 012 . x-xx . Left x-y . Right x-y . 2x-2xx
                              // 0 prefics, 1 sufics, 2 infics
        k=18+(i&12);// 2+16 4+8
      else if (i%4==1 && (i&8))     // prefics fy
        k=i+8;          // -8+16
      else
        k=i;
    }
    len=0;
    write_p(Definition[i+DF_FX], 4, 0);
    MitiText(string2, &cf_red);
    sprintf(string2, " =%d = 0x%x.\r\n", k+1, k+1);
    MitiText(string2);
  }
}
#endif // TR
void CStrawberryApp::OnTraceStep() 
{
  if (Trace)
    pThread->ResumeThread();
  else if (Environment&16) // One Step is always active
  {
    if (status_fl&1)
      pThread->PostThreadMessage(WM_USER, 0, 0); // From Next
    else
      pThread->PostThreadMessage(WM_USER, 2, 0); // First Step
  }
}

void CStrawberryApp::OnTraceTrace() 
{
  Trace=1;
  pMainFrame->SetWindowText(_T("StrProlog is TRACING."));
}

void CStrawberryApp::OnTraceStop() 
{
  Wait=Wait_d=0;
  ret_fl=10;
  Trace=2;
  pThread->ResumeThread();
  if (status_fl&4) // Waiting
    pMainFrame->PostMessage(WM_USER+1, ret_fl, 0); // OnEnd
}

void CStrawberryApp::OnTraceGo() 
{
  if (Trace==1)
  {
    if (pCompiled && pCompiled== // mnogo slojno
         (((Environment&32) && pActivePj)?pActivePj:pActiveFile))
      pMainFrame->SetWindowText(pCompiled->GetTitle()+ _T(" is running!"));
    else
      pMainFrame->SetWindowText(_T("Your program is running!"));
    Trace=0;
    pThread->ResumeThread();
  }
}

void CStrawberryApp::OnTraceStepOver() 
{
  int j;
  Trace=4;
  for (j=stack_br, StepOver=0; j!=0; j=(Stack[j]&MASKA2), StepOver++);
  pThread->ResumeThread();
}
void CStrawberryApp::OnTraceStepOut() 
{
  int j;
  Trace=4;
  for (j=stack_br, StepOver=0; j!=0; j=(Stack[j]&MASKA2), StepOver++);
  if (StepOver>0)
    StepOver--;
  pThread->ResumeThread();
}

void CStrawberryApp::OnRunNextAnswer() 
{
  pThread->PostThreadMessage(WM_USER, 1, 0);
}

void CStrawberryApp::OnRunLoopCheck() 
{
    CLoopCheck loopDlg;
    loopDlg.DoModal();
}

void CStrawberryApp::OnTraceFirstStep() 
{
  pThread->PostThreadMessage(WM_USER, 2, 0);
}

void CStrawberryApp::OnTraceFromNext() 
{
  pThread->PostThreadMessage(WM_USER, 0, 0);
}

void CStrawberryApp::OnUpdateTraceStop(CCmdUI* pCmdUI) 
{
  if (!(status_fl&2))
      pCmdUI->Enable(FALSE);
}

void CStrawberryApp::OnUpdateTraceTrace(CCmdUI* pCmdUI) 
{
  if ((Trace&3) || !(status_fl&2))
      pCmdUI->Enable(FALSE);
}

BOOL CStrawberryApp::PreTranslateMessage(MSG* pMsg)
{
    // CG: The following lines were added by the Splash Screen component.
    if (CSplashWnd::PreTranslateAppMessage(pMsg))
        return TRUE;

    return CWinApp::PreTranslateMessage(pMsg);
}
////////////////////////////////////////////////////////
// Angel

HRESULT CreateShortCut(LPCTSTR pszShortcutFile, LPTSTR pszLink, 
  LPTSTR pszDesc, LPTSTR pszWorkDir)   
{
    HRESULT hres;
    IShellLink* psl;
      void*    p;
    
//    hres=CoInitialize(NULL);

    hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
                            IID_IShellLink, &p);

    psl=static_cast<IShellLink*>(p);

    if (SUCCEEDED(hres))
    {
       IPersistFile* ppf;
       void* p; 
        
       hres = psl->QueryInterface(IID_IPersistFile, &p);

       ppf=static_cast<IPersistFile*>(p);

       if (SUCCEEDED(hres))
       {   
         wchar_t wsz[MAX_PATH];

         hres = psl->SetPath(pszShortcutFile);
         hres = psl->SetDescription(pszDesc);
         hres = psl->SetWorkingDirectory(pszWorkDir);
#ifdef UNICODE
         my_strcpy(wsz, pszLink);
#else
         MultiByteToWideChar(CP_ACP, 0, pszLink, -1, wsz, MAX_PATH);
#endif
         hres = ppf->Save(wsz, TRUE);
    
         ppf->Release();
       }
       psl->Release();
    }
    return hres;
}

#include "ComSupport/typeviewer/PlamTypeLibBrowserDlg.h" // Plamen

void CStrawberryApp::OnObjectBrowser() 
{
	ComSupport::CPlamTypeLibBrowserDlg Browser;
	Browser.DoModal();
}

