// not UNIX
// StrawberryDoc.cpp : implementation of the CStrawberryDoc class
//

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

#include "MainFrm.h"
#include "StrawberryDoc.h"
#include "StrawberryView.h"
#include "CntrItem.h"
#include "SrvrItem.h"
#include "Thread.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CStrawberryDoc

IMPLEMENT_DYNCREATE(CStrawberryDoc, CRichEditDoc)

BEGIN_MESSAGE_MAP(CStrawberryDoc, CRichEditDoc)
	// Enable default OLE container implementation
	ON_UPDATE_COMMAND_UI(ID_OLE_EDIT_LINKS, CRichEditDoc::OnUpdateEditLinksMenu)
	ON_COMMAND(ID_OLE_EDIT_LINKS, CRichEditDoc::OnEditLinks)
	ON_UPDATE_COMMAND_UI_RANGE(ID_OLE_VERB_FIRST, ID_OLE_VERB_LAST, CRichEditDoc::OnUpdateObjectVerbMenu)
	ON_COMMAND(ID_FILE_SEND_MAIL, OnFileSendMail)
	ON_UPDATE_COMMAND_UI(ID_FILE_SEND_MAIL, OnUpdateFileSendMail)
END_MESSAGE_MAP()

//BEGIN_DISPATCH_MAP(CStrawberryDoc, CRichEditDoc)
//  DISP_PROPERTY_NOTIFY_ID(CStrawberryDoc, "program", dispidprogram, m_program, OnprogramChanged, VT_BSTR)
//  DISP_FUNCTION_ID(CStrawberryDoc, "compile", dispidcompile, compile_method, VT_UI4, VTS_NONE)
//  DISP_PROPERTY_NOTIFY_ID(CStrawberryDoc, "predicate", dispidpredicate, m_predicate, OnpredicateChanged, VT_BSTR)
//  DISP_PROPERTY_NOTIFY_ID(CStrawberryDoc, "arguments", dispidarguments, m_arguments, OnargumentsChanged, VT_BSTR)
//  DISP_FUNCTION_ID(CStrawberryDoc, "call", dispidcall, call_method, VT_UI4, VTS_NONE)
//  DISP_PROPERTY_NOTIFY_ID(CStrawberryDoc, "result", dispidresult, m_result, OnresultChanged, VT_VARIANT)
//  DISP_FUNCTION_ID(CStrawberryDoc, "GetTypeInfoCount", dispidGetTypeInfoCount, GetTypeInfoCount, VT_EMPTY, VTS_PUI4)
//END_DISPATCH_MAP()
//
//// Note: we add support for IID_IStrawberry to support typesafe binding
////  from VBA.  This IID must match the GUID that is attached to the 
////  dispinterface in the .IDL file.
//
//// {225AE544-A2CE-11D1-A58A-444553540000}
////// {0579D504-2252-4C72-BB8B-DA24E0AB52A5} za triene
//static const IID IID_IStrawberry =
//{ 0x225ae544, 0xa2ce, 0x11d1, { 0xa5, 0x8a, 0x44, 0x45, 0x53, 0x54, 0x0, 0x0 } };
////{ 0x579D504, 0x2252, 0x4C72, { 0xBB, 0x8B, 0xDA, 0x24, 0xE0, 0xAB, 0x52, 0xA5 } };
//
//BEGIN_INTERFACE_MAP(CStrawberryDoc, CRichEditDoc)
//	INTERFACE_PART(CStrawberryDoc, IID_IStrawberry, Dispatch)
//END_INTERFACE_MAP()


// CStrawberryDoc construction/destruction

CStrawberryDoc::CStrawberryDoc()
{
	// TODO: add one-time construction code here
  m_Star=6;// New
  m_FileType=3;            // For empty documents,
  m_CharSet=0x80+ch_set; 
  m_pInfo=&DefaultProject; // no serialization in them

	//EnableAutomation();
	//AfxOleLockApp();
}

CStrawberryDoc::~CStrawberryDoc()
{
	//AfxOleUnlockApp();
}

BOOL CStrawberryDoc::OnNewDocument()
{
	if (!CRichEditDoc::OnNewDocument())
		return FALSE;

	// TODO: add reinitialization code here
	// (SDI documents will reuse this document)
  if (FileType==5) // Output
  {
    m_FileType=5;
    FileType=3;
  }
  else if (GetDocTemplate()==pDocTemplate1)
  {
    m_FileType=1;
    pActiveFile=pActivePj=this;
    m_pInfo=new CProjectInfo;
    m_pInfo->STACK_start=DefaultProject.STACK_start;
    m_pInfo->STACK_max=DefaultProject.STACK_max;
    m_pInfo->BUDA_start=DefaultProject.BUDA_start;
    m_pInfo->BUDA_max=DefaultProject.BUDA_max;
    m_pInfo->BUDA_S_start=DefaultProject.BUDA_S_start;
    m_pInfo->BUDA_S_max=DefaultProject.BUDA_S_max;
    m_pInfo->m_Settings=DefaultProject.m_Settings;
    m_pInfo->m_Break_point=DefaultProject.m_Break_point;
    m_pInfo->m_Colors=DefaultProject.m_Colors;
    m_pInfo->m_AddFile=DefaultProject.m_AddFile;
    m_pInfo->m_DefFile=DefaultProject.m_DefFile;
    m_pInfo->m_ExeFileName=DefaultProject.m_ExeFileName;
    m_pInfo->m_Comments=DefaultProject.m_Comments;
    m_pInfo->m_GetMethod=DefaultProject.m_GetMethod;
    m_pInfo->m_PostMethod=DefaultProject.m_PostMethod;
    m_pInfo->m_ProgArg=DefaultProject.m_ProgArg;
    int i=0, j=DefaultProject.m_FilesList.GetSize();
    for ( ; i<j; m_pInfo->m_FilesList.Add(DefaultProject.m_FilesList[i++]) );
    for (i=0; i<744; m_pInfo->m_Icon[i]=DefaultProject.m_Icon[i], i++);
    m_pInfo->m_lf=DefaultProject.m_lf;
  }
  else
  {
    m_FileType=3;
    pActiveFile=this;
    m_pInfo=&DefaultProject;
  }
	return TRUE;
}
CRichEditCntrItem* CStrawberryDoc::CreateClientItem(REOBJECT* preo) const
{
	return new CStrawberryCntrItem(preo, const_cast<CStrawberryDoc*>(this));
}


// CStrawberryDoc server implementation

COleServerItem* CStrawberryDoc::OnGetEmbeddedItem()
{
	// OnGetEmbeddedItem is called by the framework to get the COleServerItem
	//  that is associated with the document.  It is only called when necessary.

	CStrawberrySrvrItem* pItem = new CStrawberrySrvrItem(this);
	ASSERT_VALID(pItem);
	return pItem;
}


// CStrawberryDoc Active Document server implementation

CDocObjectServer *CStrawberryDoc::GetDocObjectServer(LPOLEDOCUMENTSITE pDocSite)
{
	return new CDocObjectServer(this, pDocSite);
}


static DWORD CALLBACK MyStreamOutCallback(DWORD dwCookie, LPBYTE pbBuff, LONG cb, LONG *pcb)
{
  DWORD i, j, read, code;
  
  if (ch_set>0)
  {
    for( i=0; pbBuff[i]<128 && i< (DWORD)cb; i++);
    for( j=i; j< (DWORD)cb; i++)
    {
      if (pbBuff[j]<128)
        pbBuff[i]=pbBuff[j++];
      else
      {
        j+=read=readUTF8(pbBuff + j, &code);
        if (read==0) // error
        {
          j++;
          pbBuff[i]=(BYTE)default_char; //'#'
          gl_flag|=4;
        }
        else if ((code=char_set(code, 0, ch_set))==0)
        {
          pbBuff[i]=(BYTE)default_char; //'#'
          gl_flag|=2;
        }
        else
          pbBuff[i]= (BYTE)code;
      }
    }
  }
  else
    i=cb;
  CArchive* pArchive = (CArchive*) dwCookie;
  pArchive->Write(pbBuff, i);
  *pcb = cb;
  return 0;
}

// CStrawberryDoc serialization

void CStrawberryDoc::Serialize(CArchive& ar)
{
	if (ar.IsStoring())
	{ // TODO: add storing code here
	  if (m_Star!=2)
        m_Star=3;
    if (m_FileType!=2 && m_FileType!=4 && m_FileType!=7)
    {
      if (gl_open&4)
      {
        ch_set=(gl_open&0x7e0000)/0x20000;
        default_char=(gl_open&0x10000)?'#':'?';
        m_CharSet&=0xffffff80;
        m_CharSet|=ch_set+64*(default_char=='#');
      }
      else
      {
        ch_set=(m_pInfo->m_Settings&0x7e0000)/0x20000;
        default_char=(m_pInfo->m_Settings&0x10000)?'#':'?';
        if (ch_set!=(m_CharSet&63))
        {
          CString ch_set_str;
          if (m_FileType==1)
            ch_set_str+=_T("The new char set is:\n");
          else
            ch_set_str+=_T("The default char set is:\n");
          ch_set_str+=Char_Sets[ch_set];
          ch_set_str+=_T("\n\nDo you want to use it instead of the char set:\n");
          ch_set_str+=Char_Sets[m_CharSet&63];
          if (m_FileType!=1)
            ch_set_str+=_T("\n\n(If you save this file as a project (*.SPJ) then it will remember its char set.)");
          if (IDYES==pMainFrame->MessageBox(ch_set_str, _T("The char set is different"), MB_ICONQUESTION | MB_YESNO))
          {
            m_CharSet&=0xffffff80;
            m_CharSet|=ch_set+64*(default_char=='#');
          }
          else
          {
            ch_set=m_CharSet&63;
            default_char=(m_CharSet&64)?'#':'?';
          }
        }
      }
    }
    if (m_FileType==1)
    {
      m_pInfo->m_Settings&=M1^0x7fff0000;
      m_pInfo->m_Settings|=0x20000*ch_set+0x10000*(default_char=='#');
      if(m_pInfo->m_lf.lfItalic)
        m_pInfo->m_Settings|=0x40000000;
      if(m_pInfo->m_lf.lfUnderline)
        m_pInfo->m_Settings|=0x20000000;
      if(m_pInfo->m_lf.lfStrikeOut)
        m_pInfo->m_Settings|=0x10000000;
      if(m_pInfo->m_lf.lfCharSet)
        m_pInfo->m_Settings|=0x8000000;
      if(m_pInfo->m_lf.lfOutPrecision)
        m_pInfo->m_Settings|=0x4000000;
      if(m_pInfo->m_lf.lfClipPrecision)
        m_pInfo->m_Settings|=0x2000000;
      if(m_pInfo->m_lf.lfQuality)
        m_pInfo->m_Settings|=0x1000000;
      if(m_pInfo->m_lf.lfPitchAndFamily)
        m_pInfo->m_Settings|=0x800000;
      ar<<(BYTE)1; // warning // 14 DWORD
      ar<<(BYTE)2; // version  //  1 CString  ! three pleases for change
      ar<<(BYTE)14;
      ar<<(BYTE)8;
      ar<<m_pInfo->m_Settings;
      ar<<m_pInfo->m_Break_point;
      ar<<m_pInfo->m_Colors;
      ar<<m_pInfo->STACK_start;
      ar<<m_pInfo->BUDA_start;
      ar<<m_pInfo->BUDA_S_start;
      ar<<m_pInfo->STACK_max;
      ar<<m_pInfo->BUDA_max;
      ar<<m_pInfo->BUDA_S_max;
      ar<<m_pInfo->m_lf.lfHeight;
      ar<<m_pInfo->m_lf.lfWidth;
      ar<<m_pInfo->m_lf.lfEscapement;
      ar<<m_pInfo->m_lf.lfOrientation;
      ar<<m_pInfo->m_lf.lfWeight;
      ar<<(CString)m_pInfo->m_lf.lfFaceName;
      ar<<m_pInfo->m_AddFile;
      ar<<m_pInfo->m_DefFile;
      ar<<m_pInfo->m_ExeFileName;
      ar<<m_pInfo->m_Comments;
      ar<<m_pInfo->m_GetMethod;
      ar<<m_pInfo->m_PostMethod;
      ar<<m_pInfo->m_ProgArg;
      int j=0, i=m_pInfo->m_FilesList.GetSize();
      for (ar<<i; j<i; ar<<m_pInfo->m_FilesList[j++]);
      for (i=0; i<744; ar<<m_pInfo->m_Icon[i++]);
      { // for fp
        ar.Flush();
        CFile* fp = ar.GetFile();
        m_Head=(DWORD)fp->GetPosition();
      }
    }
    if (m_FileType==2) // different if spj is rtf
    {
      m_bRTF=TRUE;
      CRichEditDoc::Serialize(ar);
    }
    else if (m_FileType!=4 && m_FileType!=7)
    {
      m_bRTF=FALSE;

	  // Calling the base class CRichEditDoc enables serialization
	  //  of the container document's COleClientItem objects.
	  
      CHARRANGE Selection;
      int EventMask;
      EDITSTREAM es;
      
      pActiveFile=this; // ? for sure

      CRichEditCtrl *pEdit=&(GetView()->GetRichEditCtrl());
      gl_flag=0;
      es.dwCookie = (DWORD) &ar;
      es.pfnCallback = MyStreamOutCallback; 
      pEdit->GetSel(Selection);
      EventMask=pEdit->SetEventMask(ENM_NONE);
      pEdit->SetOptions(ECOOP_XOR, ECO_AUTOVSCROLL);
      pEdit->SetOptions(ECOOP_XOR, ECO_AUTOHSCROLL);
      pEdit->HideSelection(TRUE, FALSE);
      pEdit->SetSel(0, M1);
      
      pEdit->StreamOut((CP_UTF8 << 16) | SF_USECODEPAGE | SF_TEXT | SFF_SELECTION, es);
      
      pEdit->SetSel(Selection);
      pEdit->HideSelection(FALSE, FALSE);
      pEdit->SetOptions(ECOOP_XOR, ECO_AUTOVSCROLL);
      pEdit->SetOptions(ECOOP_XOR, ECO_AUTOHSCROLL);
      pEdit->SetEventMask(EventMask);
      if (gl_flag&6)
      {
        CString ch_set_str=_T("");
        sprintf(string2,"\n\n(The errors are replaced with the symbol \'%c\')", default_char);
        if (gl_flag&4)
        {
          ch_set_str+="Your file was not saved correctly.";
          ch_set_str+=string2;
          pMainFrame->MessageBox(ch_set_str, _T("This is a system problem"), MB_ICONSTOP | MB_OK);
        }
        else
        {
          ch_set_str+="This file was not saved correctly because contains symbols which cannot fit in:\n";
          ch_set_str+=Char_Sets[ch_set];
          ch_set_str+="\n\nSave it again in Unicode or in other char set.";
          ch_set_str+=string2;
          pMainFrame->MessageBox(ch_set_str, _T("Unknown characters"), MB_ICONWARNING | MB_OK);
        }
      }
    }
	}
	else
	{ // TODO: add loading code here
      CFile* fp = ar.GetFile();
      CString end=fp->GetFileName().Right(4);
      if (end.CompareNoCase(_T(".spj"))==0)
        m_FileType=1;
      else if (end.CompareNoCase(_T(".rtf"))==0)
        m_FileType=2;
      else if (end.CompareNoCase(_T(".exe"))==0)
        m_FileType=4;
      else if (end.CompareNoCase(_T("spex"))==0)
        m_FileType=7;
      else if (end.CompareNoCase(_T(".add"))==0)
        m_FileType=6;
      else
        m_FileType=3;
      if (m_FileType==1)
      {
        m_pInfo=new CProjectInfo;
        BYTE ch_warn, ch_ver, num_int, num_str;

        ar>>ch_warn;
        ar>>ch_ver;
        if (ch_ver==1)
        {
          num_int=14;
          num_str=1;
        }
        else if (ch_ver==2)
        {
          if (ch_warn>1)
          {
            MitiText("Warning: ", &cf_green);
            MitiText("This project file is made on a newer version of Strawberry Prolog.\r\n");
          }
          ar>>num_int;
          ar>>num_str;
        }
        else
        {
          MitiText("Error: This project file cannot be open. It is made on a newer version of Strawberry Prolog.\r\n\r\n", &cf_red);
          return;
        }
        ar>>m_pInfo->m_Settings;
        m_pInfo->m_Settings&=M1^6; // Active Break Point and St. is full as fail
        ar>>m_pInfo->m_Break_point;
        ar>>m_pInfo->m_Colors;
        ar>>m_pInfo->STACK_start;
        ar>>m_pInfo->BUDA_start;
        ar>>m_pInfo->BUDA_S_start;
        ar>>m_pInfo->STACK_max;
        ar>>m_pInfo->BUDA_max;
        ar>>m_pInfo->BUDA_S_max;
        ar>>m_pInfo->m_lf.lfHeight;
        ar>>m_pInfo->m_lf.lfWidth;
        ar>>m_pInfo->m_lf.lfEscapement;
        ar>>m_pInfo->m_lf.lfOrientation;
        ar>>m_pInfo->m_lf.lfWeight;
        int i;
        for (; num_int-->14; ar>>i);
        { // for st
         CString st;
         ar>>st;
         my_strcpy(m_pInfo->m_lf.lfFaceName, st);
        }
        if (ch_ver==2)
        {
          ar>>m_pInfo->m_AddFile;
          ar>>m_pInfo->m_DefFile;
          ar>>m_pInfo->m_ExeFileName;
          ar>>m_pInfo->m_Comments;
          if (num_str>5)
          {
            ar>>m_pInfo->m_GetMethod;
            ar>>m_pInfo->m_PostMethod;
            ar>>m_pInfo->m_ProgArg;
          }
          else
          {
            m_pInfo->m_GetMethod="new";
            m_pInfo->m_PostMethod="new";
            m_pInfo->m_ProgArg="";
          }
          CString st;
          for ( ; num_str-->8; ar>>st);
          for (ar>>i; i-->0; ar>>st, m_pInfo->m_FilesList.Add(st) );
          for (i=0; i<744; ar>>m_pInfo->m_Icon[i++]);
        }
        { // for fp
         ar.Flush();
         CFile* fp = ar.GetFile();
         m_Head=(DWORD)fp->GetPosition();
        }
        if (m_pInfo->STACK_start<8)
          m_pInfo->STACK_start=8;
        if (m_pInfo->BUDA_start<MAX_VARS+2048)
          m_pInfo->BUDA_start=MAX_VARS+2048;
        if (m_pInfo->BUDA_S_start<MAX_VARS)
          m_pInfo->BUDA_S_start=MAX_VARS;
        m_pInfo->m_lf.lfItalic=(m_pInfo->m_Settings&0x40000000)!=0;
        m_pInfo->m_lf.lfUnderline=(m_pInfo->m_Settings&0x20000000)!=0;
        m_pInfo->m_lf.lfStrikeOut=(m_pInfo->m_Settings&0x10000000)!=0;
        m_pInfo->m_lf.lfCharSet=(m_pInfo->m_Settings&0x8000000)!=0;
        m_pInfo->m_lf.lfOutPrecision=(m_pInfo->m_Settings&0x4000000)!=0;
        m_pInfo->m_lf.lfClipPrecision=(m_pInfo->m_Settings&0x2000000)!=0;
        m_pInfo->m_lf.lfQuality=(m_pInfo->m_Settings&0x1000000)!=0;
        m_pInfo->m_lf.lfPitchAndFamily=(m_pInfo->m_Settings&0x800000)!=0;
#if PROF==0
        if (m_pInfo->m_Settings&512) // Not for Light
        {
          CHARFORMAT cf;
          cf.crTextColor=c_green;
          cf.dwMask=CFM_COLOR;
          cf.dwEffects=0;
          GetView()->GetRichEditCtrl().SetDefaultCharFormat(cf);
        }
        else
#endif
        if (!(m_pInfo->m_Settings&16)) // Use Def. Font
        {
          CHARFORMAT cf;
          cf.crTextColor=m_pInfo->m_Colors;
          my_strcpy(cf.szFaceName, m_pInfo->m_lf.lfFaceName);
          cf.yHeight=-m_pInfo->m_lf.lfHeight*15;
          if (cf.yHeight <190) cf.yHeight=190; //plamen test
          cf.dwMask=CFM_COLOR | CFM_FACE | CFM_SIZE | CFM_BOLD | CFM_ITALIC | CFM_STRIKEOUT | CFM_UNDERLINE;
          cf.dwEffects=0;
          if (m_pInfo->m_lf.lfWeight>500)
            cf.dwEffects|=CFE_BOLD;
          if (m_pInfo->m_lf.lfItalic)
            cf.dwEffects|=CFE_ITALIC;
          if (m_pInfo->m_lf.lfUnderline)
            cf.dwEffects|=CFE_STRIKEOUT;
          if (m_pInfo->m_lf.lfStrikeOut)
            cf.dwEffects|=CFE_UNDERLINE;
          GetView()->GetRichEditCtrl().SetDefaultCharFormat(cf);
        }
      }
      else if (m_FileType==4 || m_FileType==7)
      {
        DWORD Head, i;
        WORD st_ver1, st_ver2;
        CString ExeName, ExeFrom, ExeProdID, ExeComments, str_ver, TypeFile;
        CRichEditCtrl *pExeWindow=&(GetView()->GetRichEditCtrl());
        pExeWindow->SetOptions(ECOOP_OR, ECO_READONLY);
        ar.Flush();
        CFile *pFile = ar.GetFile();

        if (m_FileType==7)
        {
          TypeFile="SPEX";
          pFile->Seek(-8, CFile::end);
        }
        else
        {
          TypeFile="EXE";
          pFile->Seek(-4, CFile::end);
        }
        pFile->Read(&Head, 4);
        pFile->Seek(Head, CFile::begin);

        CHARFORMAT cf;
        ar>>i;
        cf.crTextColor=RGB(255, 0, 0);
        cf.dwMask=CFM_COLOR;
        cf.dwEffects=0; // not CFE_AUTOCOLOR
        if (i!=0x9e56f78a)
          goto ET4;
        ar>>ExeName;
        ar>>ExeFrom;
        ar>>ExeProdID;
        ar>>ExeComments;
        ar>>i; // nothing
        ar>>st_ver1;
        ar>>st_ver2; // x1000
        my_sscanf(ExeProdID.Mid(13, 5), _T("%d"), &i);
        if (ExeProdID.GetLength()!=18)
        {
ET4:      pExeWindow->SetWindowText(_T("Error\r\n\r\nThis ")+TypeFile+_T(" file is not written on Strawberry Prolog or it is corrupt."));
          pExeWindow->SetSel(0, 5);
          pExeWindow->SetSelectionCharFormat(cf);
        }
        else
        {
          if (st_ver2==0)
            str_ver.Format(_T("%d.0"), st_ver1);
          else
            str_ver.Format(_T("%g"), (float)st_ver1+(float)st_ver2/1000);
          if (ExeComments!="")
            ExeComments=_T("\r\n\r\nComments:\r\n\r\n")+ExeComments;
          pExeWindow->SetWindowText(
           _T("This program is written on Strawberry Prolog\r\nversion ")
           + str_ver + _T("\r\nWith the compiler licensed to:\r\n\r\n")
           + ExeName + _T("\r\n") + ExeFrom + _T("\r\nProduct ID: ")
           + ExeProdID + _T("\r\n") + ExeComments);
          pExeWindow->SetSel(27, 44);
          pExeWindow->SetSelectionCharFormat(cf);
          cf.crTextColor=RGB(0, 0, 255);
          pExeWindow->SetSel(53, 53+str_ver.GetLength());
          pExeWindow->SetSelectionCharFormat(cf);
          cf.crTextColor=RGB(255, 0, 0);
          i=str_ver.GetLength() + ExeName.GetLength() + ExeFrom.GetLength() + 100;
          pExeWindow->SetSel(i, i+18);
          pExeWindow->SetSelectionCharFormat(cf);
          if (ExeComments!="")
          {
            cf.crTextColor=RGB(0, 0, 255);
            pExeWindow->SetSel(i+21, i+21+9);
            pExeWindow->SetSelectionCharFormat(cf);
          }
        }
        pExeWindow->SetSel(0, 0);
        m_pInfo=&DefaultProject;
      }
      else
        m_pInfo=&DefaultProject;
#if PROF==2
      GetView()->GetRichEditCtrl().SetUndoLimit(2400);
#elif PROF==1
      GetView()->GetRichEditCtrl().SetUndoLimit(800);
#else
      GetView()->GetRichEditCtrl().SetUndoLimit(40);
#endif
      //GetView()->GetRichEditCtrl().SetOptions(ECOOP_XOR, ECO_WANTRETURN);
#if PROF
      if (m_pInfo->m_Settings&1024) // Don't edit this project
#else
      if (m_pInfo->m_Settings&(1024|512)) // Don't edit this project | Not Light edition
#endif
        GetView()->GetRichEditCtrl().SetOptions(ECOOP_OR, ECO_READONLY);
      if (m_FileType==2) // different if spj is rtf
      {
        m_bRTF=TRUE;
        CRichEditDoc::Serialize(ar);
      }
      else if (m_FileType!=4 && m_FileType!=7)
	    {
	    // Calling the base class CRichEditDoc enables serialization
	    //  of the container document's COleClientItem objects.
	    
        pActiveFile=this;
        pAr=&ar;
        if ((Environment&0x10000)==0)
        {  
          m_bRTF=TRUE;
          pMainFrame->SyntaxColoring(61); // 61 is the read Flag
        }
        else
        {
          m_bRTF=FALSE;
          pMainFrame->SyntaxColoring(0); // 0 is no read
        }
      }    

	    // Calling the base class CRichEditDoc enables serialization
	    //  of the container document's COleClientItem objects.
	    // TODO: set CRichEditDoc::m_bRTF = FALSE if you are serializing as text
	}
}


// CStrawberryDoc diagnostics

#ifdef _DEBUG
void CStrawberryDoc::AssertValid() const
{
	CRichEditDoc::AssertValid();
}

void CStrawberryDoc::Dump(CDumpContext& dc) const
{
	CRichEditDoc::Dump(dc);
}
#endif //_DEBUG


// CStrawberryDoc commands
BOOL CStrawberryDoc::SaveModified() 
{
	if (pOutput == &(GetView()->GetRichEditCtrl()) )
	{
      pOutput=NULL;
      return TRUE;
    }
    else
	  return CRichEditDoc::SaveModified();
}
//////////////////////////////////////////////////////////////////////
// CProjectInfo Class - Construction/Destruction
//////////////////////////////////////////////////////////////////////
CProjectInfo::CProjectInfo()
{
  m_Settings=1;
}
CProjectInfo::~CProjectInfo()
{
}

ULONG CStrawberryDoc::compile_method(void)
{
  AFX_MANAGE_STATE(AfxGetAppModuleState());
  my_strcpy(namef, m_program);
  if (m_program.Right(4)==".exe" || m_program.Right(4)=="spex")
  {
    pInfo2=new CProjectInfo;
    status_fl=64; // Run Directly
    if (load_exe(m_program.Right(4)=="spex")==0)
      return(-1);
    else
      return 1;
  }
#if PROF==2
  if (0) //(!(status_fl&128)) // Not Registered
#endif
  {
    MessageBoxA(NULL,
      "To use the method \"compile\" you need a registrated copy of the profesional edition or compiled EXE file.",
        "Strawberry Prolog Server",MB_OK | MB_ICONHAND);
    return(-1);
  }
  if (m_program.Right(4)==".spj")
  {
    pInfo2=new CProjectInfo;
    status_fl=64; // Run Directly
  }
  else
    pInfo2=&DefaultProject;
  compile(0);
  if (error==0)
    return 1;
  else
  {
    my_sprintf(string3,_T("You have %d errors in %s."), error, namef);
    MessageBox(NULL,string3,_T("Error in compilation"),MB_OK | MB_ICONHAND);
    return 0;
  }
}

ULONG CStrawberryDoc::call_method(void)
{
  AFX_MANAGE_STATE(AfxGetAppModuleState());
  if (error)
  {
    MessageBoxA(NULL, "You cannot run anything before the compilation.",
        "Strawberry Prolog Server",MB_OK | MB_ICONHAND);
    return(-1);
  }
  DWORD i, j, t, k, p;
  strcpy(string, make_short(m_arguments));
  len=strlen(string);
  i_poin=0;
  f_end=len+3;
  strcpy(string+len, " . ");
  if (read_n(&k, 2)==0)
  {
    error=0;
    return(0); 
  }
  if (k>=MEMORY_c256)
  {
    j=sv_subv;
    for (i=list_br; i; i--, Link[sv_subv++]=buda_br++);
    Buda1[buda_br+1]=k;
    Buda2[buda_br+1]=j;
  }
  else if (k==TT_VAR)
  {
    Buda2[buda_br+1]=Buda2[buda_br];
    Buda1[buda_br+1]=Buda1[buda_br];
  }
  else
    Buda1[buda_br+1]=k;
  a1=buda_br++;

  strcpy(string, make_short(m_predicate));
  len=strlen(string);
  i_poin=0;
  f_end=len+3;
  strcpy(string+len, " . ");
  if (read_n(&t, 2)==0 || t>=MEMORY_c256 || t==TT_VAR)
  {
    error=0;
    return(0); 
  }
  Buda1[buda_br++ -1]=t;

  status_fl&=M1^4;
  i=stack_br;
  Stack[stack_br]|=HALF;
  Ekler[++ekler_br]=4; // 1
  Stack[stack_br+3]=ekler_br;
  my_gl2=1;
  j=call(2);
  Stack[i]&=HALFM;
  status_fl|=4;
  for(p=0; Buda1[p]==TT_LINK; p=Buda2[p]);
  if (Buda1[p]==TT_STR)
  {
    CString str(make_long(StringStore+Buda2[p]));
    m_result.vt=VT_BSTR;
    m_result.bstrVal=str.AllocSysString();
  }  
  else if (Buda1[p]==TT_INT)
  {
    m_result.vt=VT_I4;
    m_result.intVal=(int)Buda2[p];
  }  
  else if (Buda1[p]==TT_FLOAT)
  {
    m_result.vt=VT_R4;
    m_result.fltVal=*(float*)&Buda2[p];
  }  
  else if (Buda1[p]==TT_OBJ
   && (SUBTYPE(ObjectStore[Buda2[p]],CLASS_SYSTEM_ActiveX) || SUBTYPE(ObjectStore[Buda2[p]],C_S_WIN_Embedded)))
  {
		COleDispatchDriver *DispTml=(COleDispatchDriver*)( ObjectStore[Buda2[p]+7] ); 
		IDispatch* pDisp=DispTml->m_lpDispatch;
    m_result.vt=VT_DISPATCH;
    m_result.pdispVal=pDisp;
  }  
  else if (Buda1[p]==TT_VAR)
    m_result.vt=VT_EMPTY;
  else if (Buda1[p]==Definition[DF_TRUE])
  {
    m_result.vt=VT_BOOL;
    m_result.boolVal=true;
  }  
  else if (Buda1[p]==Definition[DF_FALSE])
  {
    m_result.vt=VT_BOOL;
    m_result.boolVal=false;
  }  
  else
  {
    len=0;
    write_p( TT_VAR, 6, 0);
    CString str(make_long((BYTE *)string2));
    m_result.vt=VT_BSTR;
    m_result.bstrVal=str.AllocSysString();
  }  
  if (j>1)
    return -1;
  else
    return j;
}
