/*

  This is a part of the Project Frontier's Source code.

  Copyright (C) 1994-1998 Francis Gastellu
                      aka Lone Runner/Aegis

  This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License
  as published by the Free Software Foundation; either version 2
  of the License, or (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

*/

#define Uses_TApplication
#define Uses_TButton
#define Uses_TCheckBoxes
#define Uses_TSItem
#define Uses_TInputLine
#define Uses_TEditWindow
#define Uses_TDeskTop
#define Uses_TDialog
#define Uses_TKeys
#define Uses_MsgBox
#define Uses_TStaticText
#define Uses_TRect
#define Uses_TFileEditor
#define Uses_TFileDialog
#define Uses_TChDirDialog
#define Uses_fpstream
#define Uses_TScreen
#define Uses_THistory
#define Uses_TColorGroup
#define Uses_TColorItem
#define Uses_TColorDialog
#define Uses_TLabel
#define Uses_TSystemError
#define Uses_TEventQueue

#define Uses_TView
#define Uses_TStatusLine
#define Uses_TStatusDef
#define Uses_TStatusItem
#define Uses_TEvent
#define Uses_TWindow
#define Uses_TListBox

#include <tv.h>

#include <errno.h>
#include "pp.h"
#include "tvcmds.h"

#include <stdlib.h>
#include <stdarg.h>
#include <strstrea.h>
#include <iomanip.h>
#include <conio.h>
#include <dos.h>
#include <stdio.h>
#include <io.h>
#include <process.h>
#include "calc.h"
#include "calendar.h"
#include "ascii.h"
#include "pcbcolor.h"
#include "help.h"
#include "pphlp.h"
#include "gadgets.h"
#include <spawno.h>
#include <fcntl.h>
#include <ctype.h>
#include "ctxt.h"
#include "fileview.h"
#include "exevalid.h"
#include "break.h"
#include <time.h>
#include <alloc.h>

#define NUMBER_OF_TOPICS_IN_HELPFILE 409

#if !defined( __STRING_H )
#include <String.h>
#endif  // __STRING_H

#if !defined( __FSTREAM_H )
#include <Fstream.h>
#endif  // __FSTREAM_H

#if !defined( __DIR_H )
#include <Dir.h>
#endif  // __DIR_H

#if !defined( __MESSAGE_H )
#include "message.h"
#endif  // __MESSAGE_H

#if !defined( __TAGGER_H )
#include "tagger.h"
#endif  // __TAGGER_H

#undef cpColor

#define cpColor \
	"\x71\x70\x78\x74\x20\x28\x24\x17\x1F\x1A\x31\x31\x1E\x71\x00" \
	"\x31\x3F\x3A\x13\x13\x31\x21\x00\x1F\x1F\x1B\x17\x1C\x1B\x1D\x1A" \
	"\x4F\x7F\x7A\x13\x13\x70\x70\x7F\x7E\x20\x2B\x2F\x78\x2E\x70\x30" \
	"\x3F\x3E\x1F\x2F\x1A\x20\x72\x31\x31\x30\x2F\x3E\x31\x13\x00\x00"

#define cpOldColor \
	"\x71\x70\x78\x74\x20\x28\x24\x17\x1F\x1A\x31\x31\x1E\x71\x00" \
	"\x37\x3F\x3A\x13\x13\x31\x21\x00\x1F\x1F\x1B\x17\x1C\x1B\x1D\x1A" \
	"\x4F\x7F\x7A\x13\x13\x70\x70\x7F\x7E\x20\x2B\x2F\x78\x2E\x70\x30" \
	"\x3F\x3E\x1F\x2F\x1A\x20\x72\x31\x31\x30\x2F\x3E\x31\x13\x00\x00"


TPalette *oldPalette = (TPalette *)cpOldColor;
int attribwin(void);
void createMsgFile();
char *strnchr(char *str, char c, int len);
void defaultDesktop();
int isProjectFile(const char *file);
void reminder(int chance);
extern "C" unsigned long int crc32file(char *name);
void screenSaver();
void saveConfig();
void giveUpTimeSlice();
void checkDesqView();
void processEmacsHeader(const char *FileName);
void createEmacsHeader(const char *FileName);
void readKeyFile(char *str);
int checkPPLdebug();

extern "C" {
void codeSize(int line, long size);
void yywarning(char *msg);
void yymessage(char *msg);
void yyerror(char *msg);
void writeLines(int line);
void libSize(int line, long size);
void linking(int line);
}

int keytype;
int pass1, pass2, pass3, pass4, pass5, pass6, pass7;
int entercount=0;
int viewerType;

int alwaysflat;
int flat;
int flatxnn;

int Disarr;
int Nouvar;
char curfilename[MAXPATH] = "";
enum Boolean compileok = False;
int winused[100];
TFileEditor *Editor[100];
int mainNumber;
unsigned long crcEditor[100];
static int winnum;
static int nocommandline = False;
Boolean viewer = False;
static int viewerwin;
Boolean Tagger = False;
int curtag=0;
static int Taggerwin;
static char filetoload[MAXPATH];
static Boolean MsgCreated = False;
Boolean EGAmode = False;
char SysPath[MAXPATH];
char lastPPECreated[MAXPATH+MAXFILE];
char drive[MAXDRIVE];
char dir[MAXDIR];
char fname[MAXFILE];
char ext[MAXEXT];
int thisnumber;
int runProcedure;
static Boolean desqViewRunning;
float desqViewVersion;
char cancelExit;
char cracked;
int compilecount=0;
eEXEValidResult crcchk;
TCollection *tagList;
unsigned int screenSaverTimeout=0;

int wantToTrace=0;


char regtype[5][30]={
	{"NORMAL"},
	{"BETA TESTER"},
	{"PROFESSIONAL"},
	{"-"},
	{"-"}};

char compileDest[128];
char creatPPE;
char creatBAK;
char saveBefore;
char SwapCompil;
char SwapShell;
char SwapRun;
char autoSaveDesktop;
char autoLoadDesktop;
char emacsHeader;
char serialNumber[16];
char firstName[36];
char lastName[36];
char tabLen;

char userFirstName[16];
char userLastName[16];
char userPassword[13];
char argumentList[128];
char *userScreen;
char *backScreen=NULL;
char *ppScreen;
int backCursX;
int backCursY;
int userCursX;
int userCursY;

char registered;
char PPCPathName[128];
//char RUNPathName[128];
char PPDPathName[128];
int autoindentmode;

int inMacro = 0;
int inMacro2 = 0;

char messageFile[256];
char desktopFile[256];
char configFile[256];

const bcReSelectEditor = 1609;
const bcSelectWindow = 1610;
int noFlip=0;

TEditWindow *clipWindow;
TMessageViewer *messageViewer;
TTaggerWindow *TaggerWindow;
TView *messageView;
TView *TaggerView;
TDialog *TagDialog;
TDialog *ZippyResult;
TLineCollection *collection;
TListBox *listbox;
TMouse *mouseObject;

time_t lastActionTime;


void createMsgFile()
{
FILE *msg;

if ((msg = fopen(messageFile, "wt")) == NULL)
{
   messageBox("\003Cannot create Message windowFile !",mfError|mfOKButton);
   MsgCreated = False;
}
fputc(0,msg);
fclose(msg);
MsgCreated = True;
}


int attribwin(void)
{
for(int i=1;i<100;i++)
{
	if (!winused[i])
		{
		winused[i] = True;
		return (i);
		}
}
return(0);
}

TEditWindow *TEditorApp::openEditor( const char *fileName, Boolean visible )
{
    if (!registered && visible) reminder(3);
    TRect r = deskTop->getExtent();
	if (visible) winnum = attribwin(); else winnum = 0;
	TView *p = validView( new TEditWindow( r, fileName, winnum ) );
	if (p)
		{
	    if( !visible )
		p->hide();
	    if (winnum != 0)
		{
		TRect r = getExtent();
		//if (!EGAmode) r.b.y = r.b.y - 9; else r.b.y = r.b.y - 17;
		r.b.y -= 2;
		if (winnum < 10) r.a.y = r.a.y + winnum - 1; else r.a.y = r.a.y + 9;
		if (winnum < 10) r.a.x = r.a.x + winnum - 1; else r.a.x = r.a.x + 9;
		p->locate(r);
		}
	    p->setState(sfShadow,False);
		deskTop->insert( p );
		return (TEditWindow *)p;
	    }
    else
	{
	winused[winnum] = False;
	return 0;
	}
}

void reminder(int chance)
{
if (random(chance-1) == 0)
	messageBox("\003Did you forget to send your postcard ?",mfInformation|mfOKButton);
}

void defaultDesktop()
{
	strcpy(desktopFile, SysPath);
	if (desktopFile[strlen(desktopFile)-1] != '\\') strcat(desktopFile, "\\");
	strcat(desktopFile, "DESKTOP.PP");
	strcpy(configFile, SysPath);
    if (configFile[strlen(configFile)-1] != '\\') strcat(configFile, "\\");
    strcat(configFile, "PP.CFG");
}

void checkParamList( int argc, char *argv[] )
{
    int fok=0;
	fnsplit(argv[0], drive, dir, fname, ext);
	strcpy(SysPath,drive);
	strcat(SysPath,dir);
	strcpy(messageFile, SysPath);
	if (messageFile[strlen(messageFile)-1] != '\\') strcat(messageFile, "\\");
	strcat(messageFile, "MESSAGES");
	defaultDesktop();

	for (int a = 1;a<argc;a++)
	{
	if (!strcmpi(argv[a],"/NOFLIP"))
	{
	noFlip = True;
	continue;
	}

	strcpy(filetoload,argv[a]);
	if (!strchr(filetoload,'.')) strcat(filetoload,".PPS");
	argv[a] = filetoload;

    if (access( argv[a], 4 ) != 0 && !fok) // check for read permission
	nocommandline = True;
	else
	fok = True;
    }
}

void TEditorApp::saLoadConfig()
{
FILE *savefile;
int aa;
if (access(configFile,4) != 0) return;
if ((savefile = fopen(configFile, "rb")) == NULL)
	messageBox("\003Enable to load init file options !",mfError);
else
	{
	char a;
	fseek(savefile,0,SEEK_END);
	if (ftell(savefile) == 833) screenSaverTimeout = 120; else screenSaverTimeout = 0;
	fseek(savefile,0,SEEK_SET);
	a = fgetc(savefile);
	if (a != 0) Disarr = False; else Disarr = True;
	a = fgetc(savefile);
	if (a != 0) Nouvar = False; else Nouvar = True;
	a = fgetc(savefile);
	ushort newMode = TScreen::screenMode ^ TDisplay::smFont8x8;
	if (a != 0)
		{
		TRect t=getExtent();
		if (!(t.b.y > 25))
			{
			setScreenMode(newMode);
			}
		EGAmode = True;
		}
	else
		{
		TRect t=getExtent();
		if (t.b.y > 25)
			{
			setScreenMode(newMode);
			}
		EGAmode = False;
		}
	TPalette *p = &getPalette();
	fread(p->data,64,1,savefile);

//	if (memcmp(p->data+1, oldPalette->data+1,63))
//		{
//		memcpy(p->data+1, cpColor, 63);
//		deskTop->setState( sfVisible, False );
//		deskTop->setState( sfVisible, True );
//        }

	fread(compileDest,128,1,savefile);
	fread(PPCPathName,128,1,savefile);
	creatPPE=fgetc(savefile);
	creatBAK=fgetc(savefile);
	saveBefore=fgetc(savefile);
	autoindentmode=fgetc(savefile);
	SwapCompil=fgetc(savefile);
	SwapShell=fgetc(savefile);
	autoSaveDesktop = fgetc(savefile);
	autoLoadDesktop = fgetc(savefile);
	fseek(savefile, 29+29+14, SEEK_CUR);
//	fread(serialNumber,14,1,savefile);
//	fread(firstName,29,1,savefile);
//	fread(lastName,29,1,savefile);
	fread(userPassword,12,1,savefile);
	fread(userFirstName,15,1,savefile);
	fread(userLastName,15,1,savefile);
	fread(argumentList,127,1,savefile);
//	fread(RUNPathName,128,1,savefile);
	fseek(savefile, 128, SEEK_CUR);
	fread(PPDPathName,128,1,savefile);
	SwapRun=fgetc(savefile);
	tabLen=fgetc(savefile);
	emacsHeader=fgetc(savefile);
	alwaysflat=fgetc(savefile);
	flatxnn=fgetc(savefile);
	if (screenSaverTimeout == 0) fread(&screenSaverTimeout,2,1,savefile);
    fgetc(savefile);
    if (!feof(savefile))
    	{
        fseek(savefile, -1, SEEK_CUR);
        for (aa=0;aa<128;aa++)
        	fread(&breakPoint[aa], 2, 1, savefile);
        }
    else
        for (aa=0;aa<128;aa++)
        	breakPoint[aa]=0;
	fclose(savefile);
	deskTop->setState( sfVisible, False );
	deskTop->setState( sfVisible, True );
				TEvent event;
		event.what = evBroadcast;
		event.message.command = 1549;
		putEvent(event);
	}
}

void TEditorApp::loadConfig()
{
int aa;
FILE *savefile;
userScreen = (char *)calloc(4000,1);
userCursX=1;
userCursY=1;
randomize();
registered = 0;
if (access(configFile,4) != 0) return;
if ((savefile = fopen(configFile, "rb")) == NULL)
	messageBox("\003Enable to load init file options !",mfError);
else
	{
	char a;
	fseek(savefile,0,SEEK_END);
	if (ftell(savefile) == 833) screenSaverTimeout = 120; else screenSaverTimeout = 0;
	fseek(savefile,0,SEEK_SET);
	a = fgetc(savefile);
	if (a != 0) Disarr = False; else Disarr = True;
	a = fgetc(savefile);
	if (a != 0) Nouvar = False; else Nouvar = True;
	a = fgetc(savefile);
	ushort newMode = TScreen::screenMode ^ TDisplay::smFont8x8;
	if (a != 0)
		{
		TRect t=getExtent();
		if (!(t.b.y > 25))
			{
			setScreenMode(newMode);
			}
		EGAmode = True;
		}
	else
		{
		TRect t=getExtent();
		if (t.b.y > 25)
			{
			setScreenMode(newMode);
			}
		else
			{
			if (!noFlip)
				{
				setScreenMode(newMode);
				ushort newMode2 = TScreen::screenMode ^ TDisplay::smFont8x8;
				setScreenMode(newMode2);
				}
			}
		EGAmode = False;
		}
	TPalette *p = &getPalette();
	fread(p->data,64,1,savefile);

//	if (memcmp(p->data+1, oldPalette->data+1,63))
//		{
//		memcpy(p->data+1, cpColor, 63);
//		deskTop->setState( sfVisible, False );
//		deskTop->setState( sfVisible, True );
//        }

	fread(compileDest,128,1,savefile);
	fread(PPCPathName,128,1,savefile);
	creatPPE=fgetc(savefile);
	creatBAK=fgetc(savefile);
	saveBefore=fgetc(savefile);
	autoindentmode=fgetc(savefile);
	SwapCompil=fgetc(savefile);
	SwapShell=fgetc(savefile);
	autoSaveDesktop = fgetc(savefile);
	autoLoadDesktop = fgetc(savefile);
	fseek(savefile, 29+29+14, SEEK_CUR);
//	fread(serialNumber,14,1,savefile);
//	fread(firstName,29,1,savefile);
//	fread(lastName,29,1,savefile);
	fread(userPassword,12,1,savefile);
	fread(userFirstName,15,1,savefile);
	fread(userLastName,15,1,savefile);
	fread(argumentList,127,1,savefile);
//	fread(RUNPathName,128,1,savefile);
	fseek(savefile, 128, SEEK_CUR);
	fread(PPDPathName,128,1,savefile);
	SwapRun=fgetc(savefile);
	tabLen=fgetc(savefile);
	emacsHeader=fgetc(savefile);
	alwaysflat=fgetc(savefile);
	flatxnn=fgetc(savefile);
	if (screenSaverTimeout == 0) fread(&screenSaverTimeout,2,1,savefile);
    fgetc(savefile);
    if (!feof(savefile))
    	{
        fseek(savefile, -1, SEEK_CUR);
        for (aa=0;aa<128;aa++)
        	fread(&breakPoint[aa], 2, 1, savefile);
        }
    else
        for (aa=0;aa<128;aa++)
        	breakPoint[aa]=0;
	fclose(savefile);
	deskTop->setState( sfVisible, False );
	deskTop->setState( sfVisible, True );
		TEvent event;
		event.what = evBroadcast;
		event.message.command = 1549;
		putEvent(event);
	}
}

void TEditorApp::calculator()
{
    TCalculator *calc = (TCalculator *) validView(new TCalculator);

    if(calc != 0)
    {
	deskTop->insert(calc);
    }
}

void TEditorApp::calendar()
{
    TCalendarWindow *cal = (TCalendarWindow *) validView(new TCalendarWindow);

    if(cal != 0)
	{
	deskTop->insert( cal );
    }
}

void TEditorApp::ascii()
{
	TAsciiChart *chart = (TAsciiChart *) validView(new TAsciiChart);

	if(chart != 0)
	{
	deskTop->insert(chart);
	}
}

void TEditorApp::colorchart()
{
	TColorChart *chart = (TColorChart *) validView(new TColorChart);

	if(chart != 0)
	{
	deskTop->insert(chart);
	}
}

void processUnallowedChars( const char *filename)
{
FILE *in, *out;

if ((in = fopen(filename, "rb")) == NULL)
{
   messageBox("\003Cannot open result file ! (pUC)\n", mfError | mfOKButton);
   return;
}

if ((out = fopen("MSGTEMP.$$$", "wb")) == NULL)
{
/*   struct REGPACK reg;

   reg.r_ax = 0x5900;
   reg.r_bx = 0;
   intr(0x21, &reg);

   messageBox(mfError|mfOKButton, "\003Classe de l'erreur : %d", (reg.r_bx & 0xFF00) >> 8);
   messageBox(mfError|mfOKButton, "\003Action propos‚e : %d", reg.r_bx & 0xFF);
   messageBox(mfError|mfOKButton, "\003Code Erreur : %d", reg.r_ax );*/
   messageBox("\003Cannot open temp file (msg) !\n", mfError | mfOKButton);
   exit(255);
   return;
}
int a;
int b=0;
while (!feof(in))
   {
   a=fgetc(in);
   if (!((((a == '/') || (a == '-') || (a == '\\') || (a == '|')) && (b == '\b')) || (a == '\b')))
	fputc(a, out);
   b = a;
   }
fclose(in);
fclose(out);
unlink(filename);
rename("MSGTEMP.$$$",filename);
return;
}

void processTempFile( const char *filename, const char *newfile)
{
FILE *in, *out;

if ((in = fopen(filename, "rb")) == NULL)
{
   messageBox("\003Cannot open result file ! (pTF)\n", mfError | mfOKButton);
   return;
}

if ((out = fopen("MSGTEMP.$$$", "wb")) == NULL)
{
   messageBox("\003Cannot open temp file (msg) ! (pTF)\n", mfError | mfOKButton);
   exit(255);
   return;
}
int c = strlen("__TEMP__.$$$");
char a[20];
long b;
int i;
a[c] = 0;
while (!feof(in))
   {
   b = ftell(in);
   fread(&a, c, 1, in);
   if (!strcmp(a,"__TEMP__.$$$"))
	for (i=0;i<strlen(newfile);i++)
		fputc(newfile[i],out);
   else
	   {
	   fseek(in, b, SEEK_SET);
	   fputc(fgetc(in), out);
	   }
   }
fclose(in);
fclose(out);
unlink(filename);
rename("MSGTEMP.$$$",filename);
return;
}


void TEditorApp::openMessages( const char *fileName, int num)
{
	if (viewer)
	{
	messageView->makeFirst();
	return;
	}
	processUnallowedChars(fileName);
	if (num == 0) viewerwin = attribwin(); else
		{
		viewerwin = num;
		winused[num] = True;
		}
	TView *w = validView( new TMessageWindow( fileName, viewerwin ) );
	TRect r = getExtent();
	if (!EGAmode) r.a.y = r.b.y - 9; else r.a.y = r.b.y - 17;
	r.b.y = r.b.y - 2;
	w->locate(r);
	  if( w != 0 )
	w->setState(sfShadow,False);
	deskTop->insert(w);
	messageView = w;
	viewer = True;
}

void TEditorApp::openTags(int num)
{
	if (Tagger)
	{
	TaggerView->makeFirst();
	return;
	}
	if (num == 0) Taggerwin = attribwin(); else
		{
		Taggerwin = num;
		winused[num] = True;
		}
	TView *w = validView(TaggerWindow = new TTaggerWindow( Taggerwin ) );
	TRect r = getExtent();
	if (!EGAmode) r.a.y = r.b.y - 9; else r.a.y = r.b.y - 17;
	r.b.y = r.b.y - 2;
	w->locate(r);
	  if( w != 0 )
	w->setState(sfShadow,False);
	deskTop->insert(w);
	TaggerView = w;
	Tagger = True;
}


TEditorApp::TEditorApp( int argc, char *argv[] ) :
	TProgInit( TEditorApp::initStatusLine,
		   TEditorApp::initMenuBar,
		   TEditorApp::initDeskTop
		 ),
	TApplication()
{

	TCommandSet ts;
	ts.enableCmd( cmSave );
	ts.enableCmd( cmSaveAs );
	ts.enableCmd( cmCut );
	ts.enableCmd( cmCopy );
	ts.enableCmd( cmPaste );
	ts.enableCmd( cmClear );
	ts.enableCmd( cmUndo );
	ts.enableCmd( cmFind );
	ts.enableCmd( cmReplace );
	ts.enableCmd( cmSearchAgain );
	disableCommands( ts );

int a=0;
heap = NULL;

tagList = new TLineCollection(5, 5);

	loadConfig();

	TEditor::editorDialog = doEditDialog;
	clipWindow = openEditor( 0, False );
	message(clipWindow, evBroadcast, 1520, &getPalette());
	if( clipWindow != 0 )
	{
	TEditor::clipboard = clipWindow->editor;
	TEditor::clipboard->canUndo = False;
	}
	createMsgFile();
//    if (MsgCreated) openMessages(messageFile);

	char fn[255]="";
	struct ffblk ffblk;
	char full[255];
	int al=False;

//	serialNotOK();
char infos[255]="";
readKeyFile(infos);

strncpy(firstName,infos,35);
strncpy(lastName,&infos[36],35);
while (firstName[0] == ' ')
	strcpy(firstName,&firstName[1]);

while (lastName[0] == ' ')
	strcpy(lastName,&lastName[1]);

keytype = infos[118];

	if (!findfirst("*.PRJ", &ffblk, 0))
	{
	strcpy(fn,ffblk.ff_name);
	if (findnext(&ffblk))
		{
		strcpy(desktopFile, fn);
		fnsplit(fn, drive, dir, fname, ext);
		strcpy(configFile,fname);
		strcat(configFile,".PRC");
		saLoadConfig();
		}
	else
		fn[0] = 0;
	}

	if (registered && (!pass1 || !pass2 || !pass3 || !pass4 || !pass5 || !pass6 || !pass7))
		cracked = 1;

	if ((argc >= 2) && !nocommandline )
	{
	a = 1;
	if (!strcmpi(argv[a],"/NOFLIP")) a++;
	if (argv[a] != NULL)
		{
		strcpy(fn,argv[a]);
		if (strchr(fn,'.') == NULL) strcat(fn,".");
		}
	}

	for (a=0;a<strlen(fn);a++)
	fn[a] = toupper(fn[a]);

	if (fn[0] != 0 && isProjectFile(fn))
	{
	strcpy(desktopFile, fn);
	retrieveDesktop();
	goto checkSerial;
	}

	if (autoLoadDesktop) retrieveDesktop();

	fnsplit(fn, drive, dir, fname, ext);

	if (drive[0] == 0)
	{
	drive[0]=getdisk()+'A';
	drive[1]=':';
	}
	if (dir[0] == 0)
	{
	getcurdir(0,&dir[1]);
		dir[0]='\\';
	}

	fnmerge(full,drive,dir,fname,ext);

	for (a=0;a<100;a++)
		if (Editor[a] != NULL)
			if (!strcmp(Editor[a]->fileName,full)) al = True;

	if (fn[0] != 0 && !al)
	openEditor( fn, True);
	else
	if (!autoLoadDesktop) showAbout();

checkSerial:
if (keytype == 2)
	{
	TRect r = getExtent();                            // Create the heap view.
	r.a.x = r.b.x - 9;     r.b.y = r.a.y + 1;
	heap = new THeapView( r );
	insert(heap);
	}
}

void readKeyFile(char *str)
{

FILE *in;
int a;
unsigned int seed;
unsigned int sum=0;
unsigned int siz=0;
unsigned char c;
unsigned char e;
unsigned char f;
char *d = "X";
char hdr[19];

pass1 = 1;
char filen[MAXPATH+MAXFILE];

strcpy(filen, SysPath);
if (filen[strlen(filen)-1] != '\\') strcat(filen, "\\");
strcat(filen,"PP.KEY");

if ((in = fopen(filen, "rb"))
	== NULL)
{
	messageBox("\003See FREE.NFO to get your\n"
			   "\003*FREE* keyfile !"
			   ,mfInformation|mfOKButton);
   return;
}

fread(&hdr, 17, 1, in);
hdr[17]=0;
if (!strcmp(hdr,"PowerPPL KeyFile "))
	{
	fread(&seed, sizeof(seed), 1, in);
	srand(seed);
	pass2 = 1;
	}
else
	randomize();


fread(&siz, sizeof(siz), 1, in);

for (a=0;a < siz;a++)
	{
	c = (unsigned char)random(95)+33;
	pass3 = 1;
	if (c > 80)
		{
		while (1)
			{
			if (fgetc(in) != random(95)+33)
				while (1)
					if (random(50) == 6) break;
			if (random(30) == 6) break;
			}
		c = (unsigned char)random(95)+33;
		}
	pass4 = 1;
	if (c > 50 && c < 100)
		c += random(95)+33;
	lp2:
	if (c <= 32)
		c += random(95)+33;
	if (c >= 127)
		c -= random(95)+33;
	if (c <= 32)
		goto lp2;
	f = fgetc(in);
	e = getc(in)-33;
	for (;e > 0;e--)
		f -= random(95)+33;

	d[0] = f ^ c;
	pass5 = 1;
	sum += d[0];
	if (feof(in) || strlen(str) > 250)
		break;
	strcat(str, d);
	}

f = fgetc(in);
e = getc(in)-33;
for (;e > 0;e--)
	f -= random(95)+33;

pass6 = 1;
siz = f << 8;

f = fgetc(in);
e = getc(in)-33;
for (;e > 0;e--)
	f -= random(95)+33;

siz += f;

fclose(in);
if (siz != sum)
	{
	registered = 0;
	messageBox("\003See FREE.NFO to get your\n"
			   "\003*FREE* keyfile !"
			   ,mfInformation|mfOKButton);
	}
else
	registered = 1;
pass7 = 1;
return;
}

void TEditorApp::userInfo()
{
    TDialog *d = new TDialog( TRect( 0, 0, 60, 15 ), "User Informations" );

    d->options |= ofCentered;

	TView *firstname = new TInputLine( TRect( 3, 4, 57, 5 ), 16);
	d->insert(firstname);

    d->insert(
	new TLabel( TRect (3,3,35,4), "~F~irst Name", firstname ));

    TView *lastname = new TInputLine( TRect( 3, 7, 57, 8 ), 16);
	d->insert(lastname);

	d->insert(
	new TLabel( TRect (3,6,35,7), "~L~ast Name", lastname));

    TView *password = new TInputLine( TRect( 3, 10, 57, 11 ), 13);
	d->insert(password);

    d->insert(
	new TLabel( TRect (3,9,35,10), "~P~assword", password));

    d->insert(
	new TButton( TRect( 35, 12, 45, 14 ), "O~K~", cmOK, bfDefault ) );
	d->insert(
	new TButton( TRect( 47, 12, 57, 14 ), "~C~ancel", cmCancel, bfNormal ) );

    d->selectNext( False );

	// we save the dialog data:
    firstname->setData(&userFirstName);
    lastname->setData(&userLastName);
    password->setData(&userPassword);

    ushort control = deskTop->execView( d );

    if( control != cmCancel )
	{
		firstname->getData(&userFirstName);
		lastname->getData(&userLastName);
		password->getData(&userPassword);
	}

	destroy( d );
}


void TEditorApp::argumentLine()
{
    ushort histId=1;

    TDialog *d = new TDialog( TRect( 0, 0, 60, 9 ), "Program Arguments" );

	d->options |= ofCentered;

    TInputLine *arglist = new TInputLine( TRect( 3, 4, 55, 5 ), 127);
	d->insert(arglist);

    d->insert(
	new TLabel( TRect (3,3,35,4), "~A~rguments", arglist ));

    d->insert( new THistory( TRect( 55, 4, 58, 5 ), arglist, histId ) );

	d->insert(
	new TButton( TRect( 35, 6, 45, 8 ), "O~K~", cmOK, bfDefault ) );
    d->insert(
	new TButton( TRect( 47, 6, 57, 8 ), "~C~ancel", cmCancel, bfNormal ) );

    d->selectNext( False );

	// we save the dialog data:
    arglist->setData(&argumentList);

	ushort control = deskTop->execView( d );

    if( control != cmCancel )
	{
		arglist->getData(&argumentList);
	}

    destroy( d );
}

void TEditorApp::setTabLen()
{
    TDialog *d = new TDialog( TRect( 0, 0, 27, 9 ), "Tabulation length" );

    d->options |= ofCentered;

    TInputLine *tablen = new TInputLine( TRect( 3, 4, 24, 5 ), 3);
	d->insert(tablen);

    d->insert(
	new TLabel( TRect (3,3,25,4), "~T~abulation length", tablen ));

    d->insert(
	new TButton( TRect( 1, 6, 11, 8 ), "O~K~", cmOK, bfDefault ) );
	d->insert(
	new TButton( TRect( 15, 6, 25, 8 ), "~C~ancel", cmCancel, bfNormal ) );

    d->selectNext( False );

	// we save the dialog data:

	char temp[6]="";
	itoa(tabLen, temp, 10);

    tablen->setData(&temp);

    ushort control = deskTop->execView( d );

    if( control != cmCancel )
		{
		tablen->getData(&temp);
		tabLen = atoi(temp);
		deskTop->setState( sfVisible, False );
		deskTop->setState( sfVisible, True );
		}

    destroy( d );
}



int isProjectFile(const char *file)
{
char signature[30]="";

fpstream *f = new fpstream(file, ios::in|ios::binary);
f->readBytes(signature, strlen(CTXT_HEADER));
delete(f);
if (strncmp(signature,CTXT_HEADER,strlen(CTXT_HEADER)-7))
	return(0);
else
	return(1);
}


void TEditorApp::fileOpen()
{
    char fileName[MAXPATH];
	strcpy( fileName, "*.PPS" );

	if( execDialog( new TFileDialog( "*.PPS", "Open file",
		"~N~ame", fdOpenButton, 100 ), fileName) != cmCancel )
	openEditor( fileName, True );
}

void TEditorApp::doZippySearch()
{
	char tofind[255];

	if (!registered) reminder(1);

	TDialog *d = new TDialog( TRect( 0, 0, 60, 8 ), "Zippy Search" );

	d->options |= ofCentered;

	TView *keyword = new TInputLine( TRect( 3, 3, 57, 4 ), 128);
	d->insert(keyword);

	d->insert(
	new TLabel( TRect (3,2,35,3), "~W~ord(s) to search for", keyword ));

	d->insert(
	new TButton( TRect( 35, 5, 45, 7 ), "O~K~", cmOK, bfDefault ) );
	d->insert(
	new TButton( TRect( 47, 5, 57, 7 ), "~C~ancel", cmCancel, bfNormal ) );

	d->selectNext( False );

	ushort control = deskTop->execView( d );
	keyword->getData(&tofind);
	destroy( d );

	if( control == cmCancel || tofind[0] == 0)
		return;

	TDialog *d3 = new TDialog( TRect( 0, 0, 60, 6 ), "Zippy Search In Progress" );

	d3->options |= ofCentered;

	d3->selectNext( False );

	deskTop->insert( d3 );

	ZippyResult = new TDialog( TRect( 0, 0, 60, 13 ), "Zippy Search Results" );

	TScrollBar *scrl = new TScrollBar( TRect ( 56,2,57,11) );

	ZippyResult->insert(scrl);

	listbox = new TListBox( TRect (3, 2, 56, 11), 1, scrl);

	ZippyResult->insert(listbox);

	ZippyResult->options |= ofCentered;
	ZippyResult->selectNext( False );

	collection = new TLineCollection(5, 5);

	TDrawBuffer b;
	b.moveStr( 0, "°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°", 0x13);
	d3->writeLine( 3, 3, 54, 1, b );

	THelpFile *hFile;
	fpstream *helpStrm;
	THelpTopic *helpTopic;

	char hlpfile[MAXPATH];
	strcpy(hlpfile, SysPath);
	strcat(hlpfile, "PPHLP.HLP");
	helpStrm = new fpstream(hlpfile, ios::in|ios::binary);
	hFile = new THelpFile(*helpStrm);

	int a;
	int c;
	int e;
	int f;
	int g;
	char line[256];
	char temp[255];
	helpTopic = hFile->getTopic(1);

	for (a=0,f=0;f<=NUMBER_OF_TOPICS_IN_HELPFILE-1;a++)
		{
		if (helpTopic != 0)
			delete helpTopic;
		helpTopic = hFile->getTopic(a);
		if (!hFile->validTopic(a)) continue;
		f++;
		helpTopic->setWidth(200);
		g = (54 * f) / NUMBER_OF_TOPICS_IN_HELPFILE;
		b.moveChar( 0, 'Ű', 0x13, g);
		d3->writeLine( 3, 3, g, 1, b );
		e = helpTopic->numLines()-1;
		for (c=1;c<=e;c++)
			{
			strcpy(line, helpTopic->getLine(c));
			if (strstr(strupr(line),strupr(tofind)) != NULL)
				{
				itoa(a,temp,10);
				strcat(temp, ",");
				for (g=5-strlen(temp);g>0;g--)
					strcat(temp, " ");
				strcpy(line,helpTopic->getLine(2));
				strcat(temp,&line[2]);
				collection->insert(newStr(temp));
				break;
				}
			}
		}
	delete hFile;
	delete helpTopic;


	listbox->newList(collection);

	TEditorApp::deskTop->remove(d3);
	destroy(d3);

	TListViewer *l = listbox;

	if (l->range == 0)
		{
		destroy( ZippyResult );
		destroy( collection );
		messageBox("\003There are no item containing this string.",mfInformation | mfOKButton);
		}
	else
    	deskTop->insert( ZippyResult );
}


void TEditorApp::pathOptions()
{
if (!registered) reminder(5);
	TDialog *d = new TDialog( TRect( 0, 0, 60, 14 ), "Directories" );

	d->options |= ofCentered;

	TView *output = new TInputLine( TRect( 3, 3, 57, 4 ), 128);
	d->insert(output);

	d->insert(
	new TLabel( TRect (3,2,35,3), "~O~utput Directory", output ));

    TView *ppcpathname = new TInputLine( TRect( 3, 6, 57, 7 ), 128);
	d->insert(ppcpathname);

	d->insert(
	new TLabel( TRect (3,5,35,6), "~P~PC.EXE PathName", ppcpathname));

/*    TView *runtimepathname = new TInputLine( TRect( 3, 9, 57, 10 ), 128);
	d->insert(runtimepathname);

    d->insert(
	new TLabel( TRect (3,8,35,9), "~R~UN.EXE PathName", runtimepathname));*/

	TView *ppdpathname = new TInputLine( TRect( 3, 9, 57, 10 ), 128);
	d->insert(ppdpathname);

	d->insert(
	new TLabel( TRect (3,8,35,9), "PP~D~.EXE PathName", ppdpathname));

	d->insert(
	new TButton( TRect( 35, 11, 45, 13 ), "O~K~", cmOK, bfDefault ) );
	d->insert(
	new TButton( TRect( 47, 11, 57, 13 ), "~C~ancel", cmCancel, bfNormal ) );


	d->selectNext( False );

	// we save the dialog data:
	output->setData(&compileDest);
	ppcpathname->setData(&PPCPathName);
//	runtimepathname->setData(&RUNPathName);
	ppdpathname->setData(&PPDPathName);

	ushort control = deskTop->execView( d );

	// and read it back when the dialog box is successfully closed
	if( control != cmCancel )
	{
	output->getData(&compileDest);
	ppcpathname->getData(&PPCPathName);
//	runtimepathname->getData(&RUNPathName);
	ppdpathname->getData(&PPDPathName);
	}

	destroy( d );
}



void TEditorApp::openProject()
{
    if (!registered) reminder(2);
    char fileName[MAXPATH];

	strcpy( fileName, "*.PRJ" );

    if( execDialog( new TFileDialog( "*.PRJ", "Open Project File",
	    "~O~pen Project File", fdOpenButton, 100 ), fileName) != cmCancel )
    {
	if (autoSaveDesktop) saveDesktop();
	if (cancelExit) return;
    strcpy(desktopFile,fileName);
	fnsplit(fileName, drive, dir, fname, ext);
	fnmerge(configFile, drive, dir, fname, ".PRC");
	if (access(configFile,0) == 0) saLoadConfig();
	retrieveDesktop();

    if (!saveBefore)
	{
	messageBox("\003Projects need the \"Save all\" option "
		   "to run correctly. This option has been "
		   "automatically turned on...",
		   mfInformation|mfOKButton);
	saveBefore = True;
	}
	}
}


/*void TEditorApp::doDecompile()
{
	char fileName[MAXPATH];
	char ppxname[MAXPATH];

	strcpy( fileName, "*.PPE" );

	if( execDialog( new TFileDialog( "*.PPE", "Decompile File",
		"~D~ecompile File", fdOpenButton, 100 ), fileName) != cmCancel )
	{


	TDialog *d = new TDialog( TRect( 0, 0, 40, 9 ), "Compiling" );

	d->options |= ofCentered;

	fnsplit(fileName, drive, dir, name, ext);
//	strcpy(









	}

}*/

void TEditorApp::fileNew()
{
	openEditor( 0, True );
}

void TEditorApp::changeDir()
{
	execDialog( new TChDirDialog( cdNormal, 0 ), 0 );
}

void TEditorApp::dosShell()
{
    suspend();
    system("cls");
    int save;
    save = getdisk();
	dir[0] = '\\';
    getcurdir(0,&dir[1]);
	cout << "Type EXIT to return...\n";
    char *commandcom = getenv( "COMSPEC");
	if (SwapShell) spawnlpeo(P_WAIT, commandcom, commandcom,NULL,environ); else spawnlpe(P_WAIT, commandcom, commandcom,NULL,environ);
    setdisk(save);
    chdir(dir);
    resume();
    redraw();
	lastActionTime = time(NULL);
}

void TEditorApp::showAbout()
{
	TDialog *d = new TDialog( TRect( 0, 0, 70, 12 ), "About" );

	d->options |= ofCentered;

char message[1024];

if (registered)
	{
	if (keytype == 1)
		sprintf(message,"\003Power PPL v3.00 For Frontier\n\003\n"
						"\003(C) 1994,95,96,97 The Aegis Corporation\n"
						"\n"
						"\003This version belongs to %s %s\n\003\n",
						firstName,
						lastName);
	else
		sprintf(message,"\003Power PPL v3.00 For Frontier\n\003\n"
						"\003(C) 1994,95,96,97 The Aegis Corporation\n"
						"\n"
						"\003This version belongs to %s %s\n\003\n",
						firstName,
						lastName,
						regtype[keytype-1]);
	}
else
	sprintf(message,"\003Power PPL v3.00 For Frontier\n\003\n"
					"\003(C) 1994,95,96,97 The Aegis Corporation\n"
					"\n"
					"\003Please, send us a postcard to get your FREE Keyfile\n\003\n");

	d->insert(
	new TStaticText( TRect (2,2,68,8), message));
	d->insert(
	new TButton( TRect( 29, 9, 39, 11 ), "O~K~", cmOK, bfDefault ) );

	d->selectNext( False );

	deskTop->execView( d );
	destroy( d );
}


void TEditorApp::runPPE()
{
if (autoSaveDesktop) saveDesktop();
if (cancelExit) return;
char command[512];
char filename[256];
char temp[128];
char *p[25];
int	pi;
int s;
char *t;
FILE *out;
//int bakdrive;
//char newpath[128]="";

	strcpy(filename,curfilename);


    char fullPPEName[256]="";
    char basename[15]="";
    int i;

    char c[2]="X";

	int taking=0;
	if (!strcmp(&desktopFile[strlen(desktopFile)-10], "DESKTOP.PP"))
		{
		for(i=strlen(filename);i>=0;i--)
			{
			if (!taking && (filename[i] != '.')) continue;
			taking = True;
			if (filename[i] == '\\') break;
			c[0]=filename[i];
			strcat(basename,c);
			}
		}
		else
		{
		for(i=strlen(desktopFile);i>=0;i--)
			{
			if (!taking && (desktopFile[i] != '.')) continue;
			taking = True;
			if (desktopFile[i] == '\\') break;
			c[0]=desktopFile[i];
			strcat(basename,c);
			}
		}
	strrev(basename);
	basename[strlen(basename)-1]=0;

    if (strcmp(compileDest,""))
	strcpy(fullPPEName,compileDest);
	else
	{
	temp[0] = getdisk()+'A';
	temp[1] = ':';
	temp[2] = '\\';
	getcurdir(0,&temp[3]);
	strcat(temp,"\\");
	strcpy(fullPPEName,temp);
	}
    if ((fullPPEName[strlen(fullPPEName)-1] != '\\') && strcmp(compileDest,"")) strcat(fullPPEName, "\\");
    strcat(fullPPEName,basename);
	strcat(fullPPEName,".PPE");

if (!wantToTrace)
	{
/*	if (strstr(PCBOARDPathName, "PCBOARD") != NULL)
	    sprintf(command, "%s \"/RUNPPE;%s;%s;PWRD:%s;PPE:%s %s\"",
			     PCBOARDPathName,
			     userFirstName,
			     userLastName,
			     userPassword,
			     fullPPEName,
			     argumentList);
    else*/
/*     if (breakPoint[0] == 0)
	    sprintf(command, "%s %s %s\"",
			     RUNPathName,
			     fullPPEName,
			     argumentList);
     else*/
	    sprintf(command, "%s /PPRUN %s.PPS %s %s\"",
			     PPDPathName,
                 basename,
			     fullPPEName,
			     argumentList);
    }
else
	    sprintf(command, "%s /PP %s.PPS %s %s\"",
			     PPDPathName,
                 basename,
			     fullPPEName,
			     argumentList);

    s = strlen(command);
    pi = NULL;

    for (i = 0; i < 25; i++)
	{
	p[i] = &command[0]+pi;
	t = strnchr(command+pi,' ',s);
	if (t == NULL) break;
#pragma warn -sig
	pi = (t-command)+1;
#pragma warn .sig
	if (pi>s) break;
	command[pi-1] = 0;
	}
    for (i = i+1; i < 25; i++)
	p[i] = NULL;

suspend();
textcolor(7);
textbackground(0);
clrscr();

/*bakdrive = getdisk();
for (i=0;i<strlen(PCBDATPath);i++)
	PCBDATPath[i] = toupper(PCBDATPath[i]);

if (strstr(PCBDATPath,":"))
	setdisk(PCBDATPath[0]-'A');

for (i=strlen(PCBDATPath);i>=0;i--)
	{
	c[0] = PCBDATPath[i];
	if (c[0] == ':') break;
	strcat(newpath,c);
	}
strrev(newpath);
if (newpath[0] != '\\')
	{
	strcpy(temp,newpath);
	strcpy(newpath,"\\");
	strcat(newpath,temp);
	}
temp[0] = '\\';
getcurdir(bakdrive+1,&temp[1]);
chdir(newpath);*/

if (!SwapRun) i = spawnvp(P_WAIT, command, p); else i = spawnvpo(P_WAIT, command, p);

wantToTrace=0;
gettext(1,1,80,25,userScreen);
userCursX = wherex();
userCursY = wherey();

//chdir(temp);
//setdisk(bakdrive);

resume();
redraw();

saLoadConfig();
lastActionTime = time(NULL);

if (i == -1)
	{
	if (access(messageFile,0) == 0) unlink(messageFile);
	out = fopen(messageFile,"wt");
	if (errno == ENOENT)
		fprintf(out, "PCBOARD.EXE not found in location specified !\n");
	if (errno == E2BIG)
		fprintf(out, "Internal error ! E2BIG\n");
	if (errno == EINVAL)
		fprintf(out, "Internal error ! EINVAL\n");
	if (errno == ENOEXEC)
		fprintf(out, "Exec format error !\n");
	if (errno == ENOMEM)
		fprintf(out, "Not enough memory to run PPE...\n");
	fclose(out);

    showError:

	if (!viewer)
		openMessages(messageFile,0);
	else
		{
		deskTop->remove(messageView);
		destroy(messageView);
		winused[viewerwin] = False;
		viewer = False;
		openMessages(messageFile,0);
		}
	}

}

void TEditorApp::doCompile()
{

	if (cracked)
		{
		compilecount++;
		if (compilecount == 6)
			{
			coucou:
			goto coucou;
			}
		}

	char filename[255];
	char command[512];

	strcpy(filename,curfilename);

	TDialog *d = new TDialog( TRect( 0, 0, 40, 9 ), "Compiling" );

	d->options |= ofCentered;
	char sentence[255]="";
	char shortname[13]="";
	char basename[9]="";
	char c[2]="X";
	for(int i=strlen(filename)-1;i>=0;i--)
	{
	if (filename[i] == '\\') break;
	c[0]=filename[i];
	strcat(shortname,c);
	}
	strrev(shortname);

	int taking=0;
	if (!strcmp(&desktopFile[strlen(desktopFile)-10], "DESKTOP.PP"))
		{
		for(i=strlen(filename);i>=0;i--)
			{
			if (!taking && (filename[i] != '.')) continue;
			taking = True;
			if (filename[i] == '\\') break;
			c[0]=filename[i];
			strcat(basename,c);
			}
		}
		else
		{
		for(i=strlen(desktopFile);i>=0;i--)
			{
			if (!taking && (desktopFile[i] != '.')) continue;
			taking = True;
			if (desktopFile[i] == '\\') break;
			c[0]=desktopFile[i];
			strcat(basename,c);
			}
		}
	strrev(basename);
	basename[strlen(basename)-1]=0;


	if (basename[0] == 0)
	sprintf(sentence,"Main file   : Untitled",shortname);
	else
	sprintf(sentence,"Main file   : %s",shortname);
   d->insert( new TStaticText( TRect( 3, 2, 38, 6 ), sentence ) );
	if (creatPPE && basename[0] != 0)
		sprintf(sentence,"Destination : %s.PPE",basename);
	else
	sprintf(sentence,"Destination : Memory",basename);


	int bx = 3 + strlen(sentence)+1;
	d->insert( new TStaticText( TRect( 3, 3, bx, 6 ), sentence ) );

	TCommandSet ts;
	ts.enableCmd( cmClose );
	disableCommands( ts );

	TEditorApp::deskTop->insert( d );

	TDrawBuffer b;
	b.moveStr( 0, "            Please, wait...           ", 0x13);
	d->writeLine( 1, 7, 38, 1, b );

	char ppename[255];
	strcpy(ppename,compileDest);
	if ((ppename[strlen(ppename)-1] != '\\') && strcmp(compileDest,"")) strcat(ppename, "\\");
    strcat(ppename,basename);
    strcat(ppename,".PPE");

    char tmpname[255];
    strcpy(tmpname,SysPath);
	strcat(tmpname,"__TEMP__.$$$");

    char tmpppename[255];
    strcpy(tmpppename,SysPath);
    strcat(tmpppename,"__TEMP__.PPE");

    strcpy(command,PPCPathName);
    strcat(command," ");
    strcat(command,tmpname);
//    if (Disarr) strcat(command," /DISARR");
//    if (Nouvar) strcat(command," /NOUVAR");

    char *p[25];
    int	pi = NULL;
    int s = strlen(command);
    char *t;


    for (i = 0; i < 25; i++)
	{
	p[i] = &command[0]+pi;
	t = strnchr(command+pi,' ',s);
	if (t == NULL) break;
#pragma warn -sig
	pi = (t-command)+1;
#pragma warn .sig
	if (pi>s) break;
	command[pi-1] = 0;
	}
    for (i = i+1; i < 25; i++)
	p[i] = NULL;

//Michel

int handle;
int sauve;

if ((handle = open(messageFile, O_TRUNC | O_RDWR)) == -1)
{
   perror("Error:");
   return;
}

asm{
mov ah,0x45
mov bx,1
int 0x21
mov sauve,ax

mov ah,0x46
mov bx,handle
mov cx,1
int 0x21
}

fige();

if (!SwapCompil) i = spawnvp(P_WAIT, command, p); else i = spawnvpo(P_WAIT, command, p);

defige();

asm {
mov ah,0x46
mov bx, sauve
mov cx,1
int 0x21
}

close(handle);
close(sauve);

lastActionTime = time(NULL);

processTempFile(messageFile, shortname);

if (i == 0 || i == 1)
	crcEditor[mainNumber] = crc32file(tmpname);

if (i == -1)
	{
	if (access(messageFile,0) == 0) unlink(messageFile);
	FILE *out = fopen(messageFile,"wt");
	if (errno == ENOENT)
		fprintf(out, "PPLC not found in location specified !\n");
	if (errno == E2BIG)
		fprintf(out, "Internal error ! E2BIG\n");
	if (errno == EINVAL)
		fprintf(out, "Internal error ! EINVAL\n");
	if (errno == ENOEXEC)
		fprintf(out, "Exec format error !\n");
	if (errno == ENOMEM)
		fprintf(out, "Not enough memory to compile...\n");
	fclose(out);
	}


if (creatPPE && basename[0] != 0)
	{
	if (access(ppename,0) == 0) unlink(ppename);
	if (access(tmpppename,0) == 0) rename(tmpppename, ppename);
	}
else
	if (access(tmpppename,0) == 0) unlink(tmpppename);

if (access(tmpname,0) == 0) unlink(tmpname);

if (i == 0 && creatPPE && (access(ppename,0) == -1) && basename[0] != 0)
	{
	FILE *out = fopen(messageFile,"at");
		fprintf(out, "\nError : Could not create %s.\n",ppename);
		fprintf(out, "Please, check drive, directory & Read-Only status...\n",ppename);
	fclose(out);
	i = 4;
	}

strcpy(lastPPECreated,ppename);

    switch(i)
	{
	case 0:
		b.moveStr( 0, "  Success          :   ", 0x13 );
		d->writeLine( 1, 7, 23, 1, b );
		b.moveStr( 0, "Press any key  ", 0x93);
		d->writeLine( 24, 7, 15, 1, b );
		break;
	case 1:
		b.moveStr( 0, "  Warnings         :   ", 0x13 );
		d->writeLine( 1, 7, 23, 1, b );
		b.moveStr( 0, "Press any key  ", 0x93);
		d->writeLine( 24, 7, 15, 1, b );
		break;
	default:
		b.moveStr( 0, "  Errors           :   ", 0x13 );
		d->writeLine( 1, 7, 23, 1, b );
		b.moveStr( 0, "Press any key  ", 0x93);
		d->writeLine( 24, 7, 15, 1, b );
		runProcedure = False;
		break;
	}

	if (runProcedure && (i == 0 || i == 1))
	{
	TEditorApp::deskTop->remove(d);

	destroy(d);

	ts.enableCmd( cmClose );
	enableCommands( ts );

	TEvent e;
	e.what = evCommand;
	e.message.command = cmRunPPE;
	putEvent(e);
	return;
	}

	int j;
	int fnc=False;

	j = getch();

	if (j == 0)
	{
	j = getch();
	fnc = True;
	}

	TEditorApp::deskTop->remove(d);

	destroy(d);

	if (j == 102 && fnc)
	{
	TEvent event;
	event.what = evCommand;
	event.message.command = cmRunPPE;
	putEvent(event);
	}

	if (j == 67 && fnc)
	{
	TEvent event;
	event.what = evCommand;
	event.message.command = cmCompile;
	putEvent(event);
	}

    ts.enableCmd( cmClose );
    enableCommands( ts );

    if (i == 0)
	{
	if (viewer)
		{
//		messageViewer->removeAll();
		messageViewer->update(messageFile);
		}
	}
    else
	{
	if (viewer)
		{
		deskTop->remove(messageView);
		destroy(messageView);
		winused[viewerwin] = False;
		viewer = False;
		}
	openMessages(messageFile,0);
	}

/*    if (i == 0)
	{
	TEvent event;
	event.what = evBroadcast;
	event.message.command = bcReSelectEditor;
	putEvent(event);
	}*/
}


void TEditorApp::showClip()
{
    clipWindow->select();
    clipWindow->show();
}

void TEditorApp::tile()
{
    deskTop->tile( deskTop->getExtent() );
}

void TEditorApp::cascade()
{
    deskTop->cascade( deskTop->getExtent() );
}

TPalette& TEditorApp::getPalette() const
{
    static TPalette newcolor ( cpColor cHelpColor, sizeof( cpColor cHelpColor )-1 );
    static TPalette newblackwhite( cpBlackWhite cHelpBlackWhite, sizeof( cpBlackWhite cHelpBlackWhite)-1 );
    static TPalette newmonochrome( cpMonochrome cHelpMonochrome, sizeof( cpMonochrome cHelpMonochrome)-1 );
    static TPalette * far palettes[] =
	{
	&newcolor,
	&newblackwhite,
	&newmonochrome
	};
    return *(palettes[appPalette]);

}

void TEditorApp::idle()
{
    TProgram::idle();
	if (keytype==2)
		if (heap != NULL)
			heap->update();

	if (entercount > 35)
		{
		struct REGPACK reg;
		reg.r_ax = 0x0500;
		reg.r_bx = 0;
		if (random(10) == 1)
			reg.r_cx = 0x000D;
		else
			reg.r_cx = random(95)+33;
		intr(0x16, &reg);
		}

time_t t;
t = time(NULL);

if ((screenSaverTimeout != 0) && (t - lastActionTime >= screenSaverTimeout))
	{
	int bakx = wherex();
	int baky = wherey();
	fige();
	char *sauvegarde;
	sauvegarde = (char *)calloc(4000,1);
	gettext(1,1,80,25,sauvegarde);

	char ld,lf;

	asm{
	mov ah,0x0F
	int 0x10
	mov ah,0x03
	int 0x10
	mov ld,ch
	mov lf,cl
	}

	screenSaver();

	puttext(1,1,80,25,sauvegarde);
	free(sauvegarde);
	gotoxy(bakx,baky);

	asm{
	mov ah,0x01
	mov ch,ld
	mov cl,lf
	int 0x10
	}

	defige();
	lastActionTime = time(NULL);
	}


	giveUpTimeSlice();
}

void TEditorApp::openHelp( int helpContext)
{
    TWindow *w;
    THelpFile *hFile;
	fpstream *helpStrm;
	static Boolean helpInUse = False;

if (helpInUse == False)
	{
	helpInUse = True;
	char hlpfile[MAXPATH];
	strcpy(hlpfile, SysPath);
	strcat(hlpfile, "PPHLP.HLP");
	helpStrm = new fpstream(hlpfile, ios::in|ios::binary);
	hFile = new THelpFile(*helpStrm);
	if (!helpStrm)
		{
		messageBox("\003Unable to open help file", mfError | mfOKButton);
		delete hFile;
		}
	else
		{
		w = new THelpWindow(getExtent(), hFile, helpContext);
		if (validView(w) != 0)
		{
		execView(w);
		destroy( w );
		}
		}
	helpInUse = False;
	}
}

void TEditorApp::defaultcolors()
{

if (messageBox("\003This will restore default colors !", mfOKButton | mfCancelButton | mfWarning) == 10)
	{
	TPalette *p = &getPalette();
	memcpy(p->data+1, cpColor, 63);
	deskTop->setState( sfVisible, False );
	deskTop->setState( sfVisible, True );
	}
}


void TEditorApp::handleEvent( TEvent& event )
{
    TApplication::handleEvent( event );
    if (event.what == evCommand)
    {
    switch( event.message.command )
	    {
	    case  cmHelp:
	    case  cmHelpContents:
		if (!registered) reminder(5);
		openHelp(getHelpCtx());
		break;

	    case cmOpenProject:
		openProject();
		break;

	    case cmCloseProject:
		if (strstr(desktopFile, "DESKTOP.PP")) break;
		if (autoSaveDesktop) saveDesktop();
		if (cancelExit) break;
		defaultDesktop();
		retrieveDesktop();
		saLoadConfig();
		break;

	    case cmOpen:
		fileOpen();
		break;

	    case cmNew:
		fileNew();
		break;

	    case cmChangeDrct:
		changeDir();
		break;

	    case cmDosShell:
		if (!registered) reminder(3);
		dosShell();
		break;

	    case cmShowClip:
		showClip();
		break;

	    case cmTile:
		tile();
		break;

	    case cmCascade:
		cascade();
		break;

	    case cmParams:
		selectParams();
		break;

	    case cmAbout:
		showAbout();
		break;

		case cmAscii:
		if (!registered) reminder(3);
		ascii();
		break;

		case cmColor:
		if (!registered) reminder(2);
		colorchart();
		break;

	    case cmCalendar:
		if (!registered) reminder(5);
		calendar();
		break;

	    case cmCalc:
		if (!registered) reminder(5);
		calculator();
		break;

	    case cmVideoMode:
		if (!registered) reminder(5);
		ushort newMode = TScreen::screenMode ^ TDisplay::smFont8x8;
		setScreenMode(newMode);
		EGAmode = Boolean(!EGAmode);
		if (viewer)
			{
			TRect r = getExtent();
			if (!EGAmode) r.a.y = r.b.y - 9; else r.a.y = r.b.y - 17;
			r.b.y = r.b.y - 2;
			messageView->locate(r);
			}
		break;

/*		case cmDecompile:
		doDecompile();
		break;*/

	    case cmColorCmd:
		if (!registered) reminder(5);
		colors();
		break;

	    case cmDefCols:
		defaultcolors();
		break;

	    case cmMessage:
		openMessages(messageFile,0);
		break;

		case cmTags:
		openTags(0);
		break;

		case cmDirOptions:
		pathOptions();
		break;

	    case cmFileOptions:
		fileOptions();
		break;

		case cmSaveDesktop:
		if (!registered) reminder(5);
		saveDesktop();
		break;

	    case cmRetrieveDesktop:
		if (!registered) reminder(5);
		retrieveDesktop();
		break;

	    case cmQuit:
		if (!registered) reminder(1);
		if (autoSaveDesktop) saveDesktop();
		if (cancelExit) break;
		saveConfig();
		event.what = evBroadcast;
		event.message.command = 1538;
		putEvent(event);
		break;

		case cmHelpIndex:
		if (!registered) reminder(5);
		openHelp(hcHelpIndex);
		break;

	    case cmPreviousTopic:
		if (!registered) reminder(5);
		openHelp(0xFFFF);
		break;

	    case cmUserInfo:
		userInfo();
		break;

	    case cmArguments:
		argumentLine();
		break;

		case cmUserScreen:
		int bakx = wherex();
		int baky = wherey();
		fige();
		char *sauvegarde;
		sauvegarde = (char *)calloc(4000,1);
		gettext(1,1,80,25,sauvegarde);
		puttext(1,1,80,25,userScreen);
		gotoxy(userCursX,userCursY);
		getch();
		puttext(1,1,80,25,sauvegarde);
		free(sauvegarde);
		gotoxy(bakx,baky);
		defige();
		lastActionTime = time(NULL);
		break;

	    case cmTabLen:
		setTabLen();
		break;

		case cmZippySearch:
		doZippySearch();
		break;

	    default:
		return ;
	    }
    clearEvent( event );
    }
    if (event.what == evKeyDown)
    {
	switch (event.message.command)
		{
		case kbAltF1:
		if (!registered) reminder(5);
		openHelp(0xFFFF);
		break;

		case kbShiftF1:
		if (!registered) reminder(5);
		openHelp(hcHelpIndex);
		break;

		case kbAltY:
		if (flatxnn) flatxnn = 0; else flatxnn = 1;
		deskTop->setState( sfVisible, False );
		deskTop->setState( sfVisible, True );
		clearEvent(event);
		event.what = evBroadcast;
		event.message.command = 1549;
		putEvent(event);
		break;

		default:
		return;
		}
	}

	if (event.what == evBroadcast)
	{
	switch (event.message.command)
	    {
	    case 1015:
		openHelp(event.message.infoInt);
		break;

	    case 1001:
		thisnumber = event.message.infoInt;
		doCompile();
		break;

		case 1700:
		runPPE();
		break;

		case 1546:
		openHelp( event.message.infoInt);
		break;

		default:
		return;
		}
    clearEvent( event );
    }
}

void TEditorApp::fige()
{
    TSystemError::suspend();
    TEventQueue::suspend();
}

void TEditorApp::defige()
{
    TEventQueue::resume();
    TSystemError::resume();
}

void TEditorApp::colors()
{

    TColorGroup &group1 =
	*new TColorGroup("Desktop") +
	    *new TColorItem("Color",             1)+

	*new TColorGroup("Menus") +
	    *new TColorItem("Normal",            2)+
	    *new TColorItem("Disabled",          3)+
	    *new TColorItem("Shortcut",          4)+
	    *new TColorItem("Selected",          5)+
	    *new TColorItem("Selected disabled", 6)+
	    *new TColorItem("Shortcut selected", 7
	);

    TColorGroup &group2 =
	*new TColorGroup("Dialogs/Calc") +
	    *new TColorItem("Frame/background",  33)+
	    *new TColorItem("Frame icons",       34)+
	    *new TColorItem("Scroll bar page",   35)+
	    *new TColorItem("Scroll bar icons",  36)+
	    *new TColorItem("Static text",       37)+

	    *new TColorItem("Label normal",      38)+
	    *new TColorItem("Label selected",    39)+
            *new TColorItem("Label shortcut",    40
        );

    TColorItem &item_coll1 =
        *new TColorItem("Button normal",     41)+
	*new TColorItem("Button default",    42)+
        *new TColorItem("Button selected",   43)+
        *new TColorItem("Button disabled",   44)+
	*new TColorItem("Button shortcut",   45)+
	*new TColorItem("Button shadow",     46)+
	*new TColorItem("Cluster normal",    47)+
	*new TColorItem("Cluster selected",  48)+
	*new TColorItem("Cluster shortcut",  49
	);

    TColorItem &item_coll2 =
	*new TColorItem("Input normal",      50)+
	*new TColorItem("Input selected",    51)+
        *new TColorItem("Input arrow",       52)+

        *new TColorItem("History button",    53)+
        *new TColorItem("History sides",     54)+
	*new TColorItem("History bar page",  55)+
	*new TColorItem("History bar icons", 56)+

	*new TColorItem("List normal",       57)+
	*new TColorItem("List focused",      58)+
	*new TColorItem("List selected",     59)+
	*new TColorItem("List divider",      60)+

	*new TColorItem("Information pane",  61
	);

     group2 = group2 + item_coll1 + item_coll2;

     TColorGroup &group3 =
	 *new TColorGroup("Text Windows") +
	     *new TColorItem("Frame passive",      8)+
	     *new TColorItem("Frame active",       9)+
	     *new TColorItem("Frame icons",       10)+
	     *new TColorItem("Scroll bar page",   11)+
	     *new TColorItem("Scroll bar icons",  12)+
	     *new TColorItem("Normal Text",       13)+
	     *new TColorItem("Selected Text",     14)+
	     *new TColorItem("BreakPoint",        32)+

	     *new TColorItem("Reserved Words",    24)+
	     *new TColorItem("Symbols",           25)+
	     *new TColorItem("Numbers",           26)+
	     *new TColorItem("Comments",          27)+
	     *new TColorItem("Strings",           28)+
	     *new TColorItem("Predefined Vars",   29)+
	     *new TColorItem("Labels",            30)+
	     *new TColorItem("Directives",        31
	 );


     TColorGroup &group4 =
	 *new TColorGroup("Calendar/Ascii") +
		 *new TColorItem("Frame passive",     16)+
	     *new TColorItem("Frame active",      17)+
	     *new TColorItem("Frame icons",       18)+
	     *new TColorItem("Scroll bar page",   19)+
	     *new TColorItem("Scroll bar icons",  20)+
	     *new TColorItem("Normal text",       21)+
	     *new TColorItem("Current day",       22
	 );


    TColorGroup &group5 = group1 + group2 + group3 + group4;

    TColorDialog *c = new TColorDialog((TPalette*)0, &group5 );

    if( validView( c ) != 0 )
	{
	c->helpCtx = hcNoContext;  // set context help constant
	c->setData(&getPalette());
	if( deskTop->execView( c ) != cmCancel )
	    {
		getPalette() = *(c->pal);
	    deskTop->setState( sfVisible, False );
	    deskTop->setState( sfVisible, True );
	    }
	destroy( c );
	}

}

//
// retrieveDesktop() function ( restores the previously stored Desktop )
//

void TEditorApp::retrieveDesktop()
{
	struct ffblk ffblk;
	fpstream *f;

	if (findfirst(desktopFile, &ffblk, 0))
	{
	f = new fpstream(desktopFile, ios::out|ios::binary);
	f->writeBytes(CTXT_HEADER,strlen(CTXT_HEADER));
	for (int a=0;a<10;a++)
		*f << 0;
	f->writeWord(0);
	f->writeWord(0);
	f->writeWord(0);
	f->writeWord(0);
	delete(f);
	}
	f = new fpstream(desktopFile, ios::in|ios::binary);
	if( !f )
	messageBox("\003Could not open desktop file", mfOKButton | mfError);
	else
	   {
	   TEditorApp::loadDesktop(*f);
	   if( !f )
	   messageBox("\003Error reading desktop file", mfOKButton | mfError);
	   }
	delete f;
}

//
// saveDesktop() function ( saves the DeskTop by calling storeDesktop function )
//

void TEditorApp::saveDesktop()
{
	saveConfig();
	cancelExit = 0;
	for (int a=1; a < 100; a++)
		if (Editor[a] != NULL)
			if (Editor[a]->valid(1) == False)
				{
				cancelExit = 1;
				return;
				}

	if (access(desktopFile, 0)==0) unlink(desktopFile);
	fpstream *f = new fpstream(desktopFile, ios::out|ios::binary);

	if( f )
	{
	TEditorApp::storeDesktop(*f);
	if( !f )
		{
		messageBox("\003Could not create desktop file.", mfOKButton | mfError);
		delete f;
		::remove(desktopFile);
		return;
		}
	}
	delete f;
}

//
// writeView() function ( writes a view object to a resource file )
//

static void writeView(TView *p, void *strm)
{
   if (p == messageView || p == clipWindow || p == TaggerView)  return;
   fpstream *s = (fpstream *) strm;
   if (p != TProgram::deskTop->last)
	  *s << p;
}

//
// storeDesktop() function ( stores the Desktop in a resource file )
//

void TEditorApp::storeDesktop(fpstream& s)
{
  s.writeBytes(CTXT_HEADER,strlen(CTXT_HEADER));
  for (int a=0;a<10;a++)
	if (a == viewerwin)
		s << 0;
	else
		s << winused[a];
  TRect r;
  if (viewer)
	{
	s << viewerwin;
	r = messageView->getBounds();
	s << r.a.x;
	s << r.a.y;
	s << r.b.x;
	s << r.b.y;
	}
  else
	s << 0;
  if (Tagger)
	{
	s << Taggerwin;
	r = TaggerView->getBounds();
	s << r.a.x;
	s << r.a.y;
	s << r.b.x;
	s << r.b.y;
	}
  else
	s << 0;
  int c = (int)tagList->getCount();
  s << c;
  for (a=0;a<c;a++)
	s.writeString((char *)tagList->at(a));

  deskTop->forEachReverse(::writeView, &s);
  s << 0;
}

int main( int argc, char *argv[] )
{
#ifndef IDE
	crcchk = ValidateEXE(argv[0]);
#endif
//setdisk(3);
	if (!strcmp(getenv("INPP"),"Y"))
		{
		cout << "PowerPPL is already running. Type EXIT to return...\n";
		backScreen = (char *)calloc(4000,1);
		if (mouseObject)
			{
			mouseObject->hide();
			mouseObject->hide();
			}
		gettext(1,1,80,25,backScreen);
		if (mouseObject)
			{
			mouseObject->show();
			mouseObject->show();
			}
		backCursX = wherex();
		backCursY = wherey();
		return 0;
		}

	cout << "PowerPPL v3.00 For Frontier\n(C) 1994,95,96,97 The Aegis Corporation.\n";

	putenv("INPP=Y");

	backScreen = (char *)calloc(4000,1);
	ppScreen = (char *)calloc(4000,1);
	if (mouseObject)
		{
		mouseObject->hide();
		mouseObject->hide();
		}
	gettext(1,1,80,25,backScreen);
	if (mouseObject)
		{
		mouseObject->show();
		mouseObject->show();
		}
	backCursX = wherex();
	backCursY = wherey();

	checkParamList(argc, argv);
	checkDesqView();
	if (access("__TEMP__.$$$",0) == 0) unlink("__TEMP__.$$$");
	if (access("__TEMP2_.$$$",0) == 0) unlink("__TEMP2_.$$$");
	if (access("__TEMP__.PPE",0) == 0) unlink("__TEMP__.PPE");
	if (access("MSGTEMP.$$$",0) == 0) unlink("MSGTEMP.$$$");
	if (access(messageFile,0) == 0) unlink (messageFile);
	lastActionTime = time(NULL);
	TEditorApp editorApp( argc, argv );
	editorApp.run();
	free(userScreen);
	if (access(messageFile,0) == 0) unlink (messageFile);
	if (access("__TEMP__.$$$",0) == 0) unlink("__TEMP__.$$$");
	if (access("__TEMP2_.$$$",0) == 0) unlink("__TEMP2_.$$$");
	if (access("__TEMP__.PPE",0) == 0) unlink("__TEMP__.PPE");
	if (access("MSGTEMP.$$$",0) == 0) unlink("MSGTEMP.$$$");
	putenv("INPP=");
	return(0);
}


TScreen::~TScreen()
{
	suspend();
//	if (backScreen)
//		{
		puttext(1,1,80,25,backScreen);
		free(backScreen);
		gotoxy(backCursX, backCursY);
//		}
}

char *strnchr(char *str, char c,int len)
{
int i;

for(i=0;i<len;i++)
	if (str[i] == c) return(str+i);

return(NULL);
}

void giveUpTimeSlice()
{
struct REGPACK reg;

if (desqViewRunning)
	{
	reg.r_ax = 0x1000;
	intr(0x15, &reg);
	}
}

void checkDesqView()
{
struct REGPACK reg;

reg.r_ax = 0x2B01;
reg.r_cx = 0x4445;
reg.r_dx = 0x5351;
intr(0x21, &reg);

if ((reg.r_ax & 0xFF) != 0xFF)
	{
	desqViewRunning = True;
	desqViewVersion = (reg.r_bx & 0xFF00) >> 8;
	desqViewVersion += (float(reg.r_bx & 0xFF))/100;
	printf("Running under DesqView v%g\n",desqViewVersion);
	printf("Page flipping disabled...\n");
	noFlip = True;
	delay(300);
	}
}

void TEditorApp::saveConfig()
{
int a;
FILE *savefile;
if ((savefile = fopen(configFile, "r+b")) == NULL)
    {
	if ((savefile = fopen(configFile, "w+b")) == NULL)
		{
		messageBox("\003Enable to save Init File Options !",mfError);
	    return;
        }
    }

	if (Disarr) fputc(0,savefile); else fputc(1,savefile);
	if (Nouvar) fputc(0,savefile); else fputc(1,savefile);
	if (EGAmode) fputc(1,savefile); else fputc(0,savefile);
	TPalette *p = &getPalette();
	fwrite(p->data,64,1,savefile);
	fwrite(compileDest,128,1,savefile);
	fwrite(PPCPathName,128,1,savefile);
	if (creatPPE) fputc(1,savefile); else fputc(0,savefile);
	if (creatBAK) fputc(1,savefile); else fputc(0,savefile);
	if (saveBefore) fputc(1,savefile); else fputc(0,savefile);
	if (autoindentmode) fputc(1,savefile); else fputc(0,savefile);
	if (SwapCompil) fputc(1,savefile); else fputc(0,savefile);
	if (SwapShell) fputc(1,savefile); else fputc(0,savefile);
	if (autoSaveDesktop) fputc(1,savefile); else fputc(0,savefile);
	if (autoLoadDesktop) fputc(1,savefile); else fputc(0,savefile);
	fwrite(serialNumber,14,1,savefile);
	fwrite(firstName,29,1,savefile);
	fwrite(lastName,29,1,savefile);
	fwrite(userPassword,12,1,savefile);
	fwrite(userFirstName,15,1,savefile);
	fwrite(userLastName,15,1,savefile);
	fwrite(argumentList,127,1,savefile);
//	fwrite(RUNPathName,128,1,savefile);
	fseek(savefile, 128, SEEK_CUR);
	fwrite(PPDPathName,128,1,savefile);
	if (SwapRun) fputc(1,savefile); else fputc(0,savefile);
	fputc(tabLen,savefile);
	if (emacsHeader) fputc(1,savefile); else fputc(0,savefile);
	if (alwaysflat) fputc(1,savefile); else fputc(0,savefile);
	if (flatxnn) fputc(1,savefile); else fputc(0,savefile);
	fwrite(&screenSaverTimeout,2,1,savefile);
    for (a=0;a<128;a++)
        fwrite(&breakPoint[a],2,1,savefile);
    fgetc(savefile);
    if (feof(savefile))
        for (a=0;a<128;a++)
        	fputc(0, savefile);
	fclose(savefile);
}

void processEmacsHeader(const char *FileName)
{
if (!registered) return;

if (strstr(FileName,".PPS") == NULL) return;

char buf[256];
FILE *in, *out;
char Hdr[3] = {0,0,0};
char ln;
int cnt=0;
long b;
char Str[3][19] = {
	{"; File           :"},
	{"; Original by    :"},
	{"; Last update by :"}
	};
int lineCount;
unsigned char c;
int lc2;


if ((in = fopen(FileName, "rt")) == NULL)
	{
	return;
	}
if ((out = fopen("TEMP.$_", "wt")) == NULL)
	{
	messageBox("\003Cannot create temp file ! (hdr)",mfError|mfOKButton);
	return;
	}

for (ln = 0; ln < 3; ln++)
	{
	lineCount=0;

	fseek(in,0,SEEK_SET);

	while (!feof(in))
		{
		lineCount++;

		b = ftell(in);
		fread(&buf, 18, 1, in);
		buf[18] = 0;

		if (!strcmpi(Str[ln],buf))
			{
			Hdr[ln] = 1;
			break;
			}
		fseek(in,b,SEEK_SET);
		while (fgetc(in) != '\n')
			if (feof(in))
				break;
		cnt++;
		if (cnt > 10) break;
		}
	}

fseek(in,0,SEEK_SET);
struct date d;
getdate(&d);
struct  time t;
gettime(&t);



if (!Hdr[0])
	{
	fputs(";----------------------------------------------PowerPPL v3.00 For Frontier---\n",out);
	fnsplit(FileName,drive,dir,fname,ext);
	fprintf(out,"%s %s%s\n",Str[0],fname,ext);
	}
if (!Hdr[1])
	fprintf(out,"%s %s %s on %02d/%02d/%04d at %2d:%02d:%02d\n",Str[1],
																strupr(firstName),
																strupr(lastName),
																d.da_mon,
																d.da_day,
																d.da_year,
																t.ti_hour,
																t.ti_min,
																t.ti_sec);
if (!Hdr[2])
	{
	fprintf(out,"%s %s %s on %02d/%02d/%04d at %2d:%02d:%02d\n",Str[2],
																strupr(firstName),
																strupr(lastName),
																d.da_mon,
																d.da_day,
																d.da_year,
																t.ti_hour,
																t.ti_min,
																t.ti_sec);
	fputs(";----------------------------------------------------------------------------\n\n",out);
	}

lc2=1;
while(1)
	{
	if (Hdr[2])
		if (lc2 == lineCount)
			{
			lc2++;
			while (fgetc(in) != '\n')
				if (feof(in))
					break;
			fprintf(out,"%s %s %s on %02d/%02d/%04d at %2d:%02d:%02d\n",Str[2],
																		strupr(firstName),
																		strupr(lastName),
																		d.da_mon,
																		d.da_day,
																		d.da_year,
																		t.ti_hour,
																		t.ti_min,
																		t.ti_sec);
			}
	c = fgetc(in);
	if (feof(in))
		break;
	if (c == '\n')
		lc2++;
	fputc(c,out);
	}

fclose(in);
fclose(out);

unlink(FileName);
rename("TEMP.$_",FileName);

}

void createEmacsHeader(const char *FileName)
{

if (!registered) return;

if (strstr(FileName,".PPS") == NULL) return;

char buf[256];
FILE *in, *out;
char Hdr[3] = {0,0,0};
char ln;
int cnt=0;
unsigned char c;
long b;
char Str[3][19] = {
	{"; File           :"},
	{"; Original by    :"},
	{"; Last update by :"}
	};

if ((in = fopen(FileName, "rt")) == NULL)
	{
	return;
	}
if ((out = fopen("TEMP.$_", "wt")) == NULL)
	{
	messageBox("\003Cannot create temp file ! (hdr)",mfError|mfOKButton);
	return;
	}

for (ln = 0; ln < 3; ln++)
	{
	fseek(in,0,SEEK_SET);

	while (!feof(in))
		{
		b = ftell(in);
		fread(&buf, 18, 1, in);
		buf[18] = 0;

		if (!strcmpi(Str[ln],buf))
			{
			Hdr[ln] = 1;
			break;
			}
		fseek(in,b,SEEK_SET);
		while (fgetc(in) != '\n')
			if (feof(in))
				break;
		cnt++;
		if (cnt > 10) break;
		}
	}

fseek(in,0,SEEK_SET);
struct date d;
getdate(&d);
struct  time t;
gettime(&t);

if (!Hdr[0])
	{
	fputs(";----------------------------------------------PowerPPL v3.00 For Frontier---\n",out);
	fnsplit(FileName,drive,dir,fname,ext);
	fprintf(out,"%s %s%s\n",Str[0],fname,ext);
	}
if (!Hdr[1])
	fprintf(out,"%s %s %s on %02d/%02d/%04d at %2d:%02d:%02d\n",Str[1],
																strupr(firstName),
																strupr(lastName),
																d.da_mon,
																d.da_day,
																d.da_year,
																t.ti_hour,
																t.ti_min,
																t.ti_sec);
if (!Hdr[2])
	{
	fprintf(out,"%s %s %s on %02d/%02d/%04d at %2d:%02d:%02d\n",Str[2],
																strupr(firstName),
																strupr(lastName),
																d.da_mon,
																d.da_day,
																d.da_year,
																t.ti_hour,
																t.ti_min,
																t.ti_sec);
	fputs(";----------------------------------------------------------------------------\n\n",out);
	}

while(1)
	{
	c = fgetc(in);
	if (feof(in))
		break;
	fputc(c,out);
	}

fclose(in);
fclose(out);

unlink(FileName);
rename("TEMP.$_",FileName);

}

TMouse::TMouse()
{
	show();
	mouseObject = this;
}

int checkPPLdebug()
{
unsigned char *p = (unsigned char *)(long)0x000003C6;
p = (unsigned char *)MK_FP(p[0]+(p[1]<<8), 0x400);
return (p[0] == 0xBA && p[1] == 0xAB);
}
