// TDR.cp
// TDR processing program of beta version
//   				by apj.
//
#define TDR_MAIN_PROCESS

#include <complex.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <Strings.h>

#include <AppleEvents.h>
#include <AEObjects.h>
#include <AEPackObject.h>

#include "debugs.h"
#include "fileio.h"
#include "inputdialog.h"
#include "datautils.h"
#include "showlist.h"
#include "TDR.h"
#include "templateobj.h"

#define ALERT_DIED_ID	990
// common data area
AEAddressDesc gSELF;
int done;



// functions
pascal short AEHandleOpenApplication(const AEDesc *theAppleEvent, AEDesc *reply, long handlerRefcon);
pascal short AEHandleOpenDocument(const AEDesc *theAppleEvent, AEDesc *reply, long handlerRefcon);
pascal short AEHandlePrintDocument(const AEDesc *theAppleEvent, AEDesc *reply, long handlerRefcon);
pascal short AEHandleQuitApplication(const AEDesc *theAppleEvent, AEDesc *reply, long handlerRefcon);
pascal short AEHandleStartApplication(const AEDesc *theAppleEvent, AEDesc *reply, long HandlerRefcon);
pascal short AEHandleCloseDocument(const AEDesc *theAppleEvent, AEDesc *reply, long handlerRefcon);

void InitToolBox(void);
void InitApplication(void);
void TDR_DoMenu(long sel);
void TDR_DoFileMenu(short mitem);
void TDR_DoSettingsMenu(short mitem);
void TDR_DoBrowsMenu(short mitem);
void TDR_DoCalcMenu(short mitem);
void TDR_DoConnectMenu(short mitem);

void DoClientNew(void);
void DoServerNew(void);
void DoClientOpen(void);
void DoClientPrint(void);
void DoServerPrint(SFReply *sfr);
void DoClientQuit(void);
void DoServerQuit(void);
void DoClientCloseDocument(void);
void DoServerCloseDocument(void);
void DoSave(void);
void DoAdjustMenu(void);
pascal Boolean AboutDialogFilter(DialogPtr theDialog, EventRecord *theEvent, short *itemHit);
void DoAbout(void);

void died (char desc[255], int code, int ref);


//**************************************************************************/
// AppleEvent Handlers
pascal short AEHandleOpenApplication(const AEDesc *theAppleEvent, AEDesc *reply, long handlerRefcon)
{
	DoServerNew();
	return noErr;
}

// open document
pascal short AEHandleOpenDocument(const AEDesc *theAppleEvent, AEDesc *reply, long handlerRefcon)
{
	AEDescList	docList;
	AEKeyword	keywd;
	DescType	rtype;
	Size		acsize;
	OSErr 		err;
	FSSpec		fss;
	short i;
	
	odoc_count = 0;
	
	/* open document apple event */
	err = AEGetParamDesc (theAppleEvent, keyDirectObject, typeAEList, &docList);
	if (err) died ("Error Processing Apple Event", err, 14);
	
	/* count number of document to be opened */
	err = AECountItems (&docList, &odoc_count);
	if (err) died ("Error Processing Apple Event", err, 15);
	if (odoc_count < 1) died ("No File for OpenDoc Apple Event", 0, 16);

	/* allocate memory for odoc_fss(FSSpec *) */
	odoc_fss = (FSSpec *)malloc(sizeof(FSSpec) * odoc_count);
	if(odoc_fss == NULL){
		showmsgs("\pCan't allocate memory for so many files", NULL, NULL, NULL);
		ExitToShell();
	}
	
	/* get FSS record of all document */
	for(i = 0 ; i < odoc_count ; i++){
		err = AEGetNthPtr (&docList, i+1, typeFSS, &keywd, &rtype,
			(Ptr)&fss, sizeof(FSSpec), &acsize);
		if (err) died ("Error Processing Apple Event", err, 17);
		BlockMove(&fss, odoc_fss+i, acsize);
	}
	
	/* get rid of storage */
	err = AEDisposeDesc (&docList);
	if (err) died ("Error Processing Apple Event", err, 18);
	
	/* open the passed file and do processing */
	TDR_AutomaticFT(odoc_fss, odoc_count);
	
	return noErr;
}


// print contents of file
pascal short AEHandlePrintDocument(const AEDesc *theAppleEvent, AEDesc *reply, long handlerRefcon)
{
	SFReply sfr;
	Size	actualSize;
	AEDescList docList;
	long itemsInList;
	long index;
	AEKeyword returnedKeywd;
	DescType returnedType;
	
	AEError(AEGetParamDesc(theAppleEvent, keyDirectObject, typeAEList, &docList));
	AEError(AECountItems(&docList, &itemsInList));

	AEError(AEGetNthPtr(&docList, index, typeFSS, &returnedKeywd, &returnedType,
				(Ptr)&sfr, sizeof(SFReply), &actualSize));
	DoServerPrint(&sfr);

	AEError(AEDisposeDesc(&docList));
	return noErr;
}

pascal short AEHandleQuitApplication(const AEDesc *theAppleEvent, AEDesc *reply, long handlerRefcon)
{
	/* quit apple event - set the done flag */
	/* Don't make the mistake of calling ExitToSHell() from */
	/* inside the Quit Application Handler. If you do so, 	*/
	/* your handler will never return to the Apple Event	*/
	/* Manager. */
	done = true;
	return noErr;
}


pascal short AEHandleCloseDocument(const AEDesc *theAppleEvent, AEDesc *reply, long handlerRefcon)
{
	AEDesc aObject;
	AEDesc aToken;
	
	AEError(AEGetParamDesc(theAppleEvent, keyDirectObject, typeObjectSpecifier, &aObject));
	AEError(AEResolve(&aObject,   kAEIDoMinimum, &aToken));

	DoServerCloseDocument();
	
	return noErr;    /* apj */
}


pascal short AEHandleStartApplication(const AEDesc *theAppleEvent, AEDesc *reply, long HandlerRefcon)
{
	/* startup apple event - ask for an input file */
//	GetUserFile();
	return noErr;
}



// functions

void InitToolBox(void)
{
	EventRecord tempEvent;
	
	/* Initialize Managers */
	InitGraf (&qd.thePort);
	InitFonts ();
    FlushEvents(everyEvent - osMask - diskMask, 0);
	InitWindows ();
	InitMenus ();
	TEInit ();
	InitDialogs (nil);
	InitCursor ();
    MaxApplZone();
    MoreMasters();
    
	EventAvail(everyEvent, &tempEvent);
	EventAvail(everyEvent, &tempEvent);
	EventAvail(everyEvent, &tempEvent);
	
	/* メニューのセットアップ　アプリケーションによって多少異なる */
	applemenu = GetMenu(AppleMenuID);	/* TDR.h */
	if (applemenu == NULL) died ("Can't find Apple Menu Resource", 0, 001);
	AppendResMenu(applemenu, 'DRVR');
	filemenu = GetMenu(TDR_MFILE_ID); /* TDR.h */
	editmenu = GetMenu(TDR_MEDIT_ID); /* TDR.h */
	setmenu = GetMenu(TDR_MSET_ID);	/* TDR.h */
	browsmenu = GetMenu(TDR_MBROWS_ID);	/* TDR.h */
	calcmenu = GetMenu(TDR_MCONN_ID); /* TDR.h */
	connectmenu = GetMenu(TDR_MEDIT_ID); /* TDR.h */
	InsertMenu(applemenu, 0);
	InsertMenu(filemenu, 0);
	InsertMenu(editmenu, 0);
	InsertMenu(setmenu, 0);
	InsertMenu(browsmenu, 0);
	InsertMenu(calcmenu, 0);
	InsertMenu(connectmenu, 0);
	DrawMenuBar();
	
}
//************************************************************************

void died (char desc[255], int code, int ref)
{
	/* nasty error has occurred - report it and quit */
	int go;
	char a[50], b[50];
	
	CtoPstr (desc);
	NumToString (code, (StringPtr)a);
	NumToString (ref, (StringPtr)b);
	ParamText ((StringPtr)desc, (StringPtr)a, (StringPtr)b, NULL);
	go = Alert(ALERT_DIED_ID, NULL);
	ExitToShell();
}


void InitApplication(void)
{
	long aGestaltResponse;
	Handle aMenuBar;
	ProcessSerialNumber aProcessSerialNumber;
	AEEventHandlerUPP OPENAPae, OPENae, QUITae, STARTae, PRINTae, CLOSEae;
	
	if(Gestalt(gestaltAppleEventsAttr, &aGestaltResponse) != noErr)
		ExitToShell();
	
	AEError(AEObjectInit());
	
	aMenuBar = GetNewMBar(TDR_MENUBAR_ID);
	SetMenuBar(aMenuBar);
	DisposeHandle(aMenuBar);
	DrawMenuBar();
		
	AEError(GetCurrentProcess(&aProcessSerialNumber));
	AEError(AECreateDesc(typeProcessSerialNumber, (Ptr)&aProcessSerialNumber,
						 sizeof(ProcessSerialNumber), (AEDesc *)&gSELF));
						 
	/* must use these for PPC proc pointers */				 
	OPENAPae = NewAEEventHandlerProc ( &AEHandleOpenApplication);
	OPENae = NewAEEventHandlerProc ( &AEHandleOpenDocument);
	QUITae = NewAEEventHandlerProc ( &AEHandleQuitApplication);
	STARTae = NewAEEventHandlerProc ( &AEHandleStartApplication);
	PRINTae = NewAEEventHandlerProc ( &AEHandlePrintDocument);
	CLOSEae = NewAEEventHandlerProc ( &AEHandleCloseDocument);

	AEError(AEInstallEventHandler(kCoreEventClass, kAEOpenApplication, 
								  OPENAPae, 0, false));
	AEError(AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments, 
								  OPENae, 0, false));
	AEError(AEInstallEventHandler(kCoreEventClass, kAEPrintDocuments, 
								  PRINTae, 0, false));
	AEError(AEInstallEventHandler(kCoreEventClass, kAEQuitApplication, 
								  QUITae, 0, false));
	AEError(AEInstallEventHandler(kCoreEventClass, kAEOpenApplication, 
								  STARTae, 0, false));
	AEError(AEInstallEventHandler('core', 'clos',
								  CLOSEae, 0, false));
	
}

void TDR_DoMenu(long sel)
{
	unsigned short aMenuID;
	unsigned short aMenuItem;
	int DAstat;
	Str255 DAname;
	
	aMenuID = HiWord(sel);
	aMenuItem = LoWord(sel);
	
	switch(aMenuID){
		case AppleMenuID:
			switch(aMenuItem){
				case TDR_MITEM_ABOUT:
					DoAbout();
					break;
				default:
					GetMenuItemText(GetMenuHandle(AppleMenuID), aMenuID, DAname);
					DAstat = OpenDeskAcc(DAname);
					break;
			}
			break;
		case TDR_MFILE_ID:
			TDR_DoFileMenu(aMenuItem);
			break;
		case TDR_MEDIT_ID:
			break;
		case TDR_MSET_ID:
			TDR_DoSettingsMenu(aMenuItem);
			break;
		case TDR_MBROWS_ID:
			TDR_DoBrowsMenu(aMenuItem);
			break;
		case TDR_MCALC_ID:
			TDR_DoCalcMenu(aMenuItem);
			break;
		case TDR_MCONN_ID:
			TDR_DoConnectMenu(aMenuItem);
			break;
	}
	HiliteMenu(0);
	DoAdjustMenu();
}

// Subroutine foe menuitems
void TDR_DoFileMenu(short mitem)
{
	CursHandle curh;

	switch(mitem){
		case TDR_MITEM_NEW:
			DoClientNew();
			break;
		case TDR_MITEM_OPEN:
			//DoClientOpen();
			break;
		case TDR_MITEM_CLOSE:
			//DoClientCloseDocument();
			break;
		case TDR_MITEM_SAVE:
			DoSave();
			break;
		case TDR_MITEM_SAVESET:
			curh = GetCursor(watchCursor);
			SetCursor(*curh);
			TDR_WritePrefs(&tdrparam);
			TDR_WriteEnv(&tdrenv);
			InitCursor();
			break;
		case TDR_MITEM_LOADSET:
			curh = GetCursor(watchCursor);
			SetCursor(*curh);
			if((TDR_ReadPrefs(&tdrparam) != 0) || TDR_ReadEnv(&tdrenv)){
				showmsgs("\pCannot open Preference File : TDRpreference", "\p","\p","\p");
				// set default value
			 	strcpy(tdrenv.GPIB_addr, TDR_DEFAULT_GPIBADDR);
			 	tdrenv.input_ftype = TDR_DEFAULT_IFTYPE;
				tdrenv.output_ftype = TDR_DEFAULT_OFTYPE;
			 }
			 EPDraw(&ep);
			 InitCursor();
			 break;
		case TDR_MITEM_PRINT:
			//DoClientPrint();
			break;
		case TDR_MITEM_QUIT:	/* Do not save preferences !!! */
			DoClientQuit();
			ExitToShell();     /* apj */
			break;
	}

}

void TDR_DoSettingsMenu(short mitem)
{
	
	switch(mitem){
		case TDR_MITEM_SPARAM:
			ShowWindow(ep.w);
			SelectWindow(ep.w);
			break;
		case TDR_MITEM_SSAMPL:
			TDR_RestoreMarkerPos();
			ShowWindow(plx.w);
			SelectWindow(plx.w);
			break;
		case TDR_MITEM_SCALIB:
			TDR_RestoreMarkerPos();
			ShowWindow(plc.w);
			SelectWindow(plc.w);
			break;
		case TDR_MITEM_SMOREINFO:
			TDR_SetItCondition(&tdrparam);
			break;
		case TDR_MITEM_SHOWENV:
			TDR_SetEnvironment(&tdrenv);
			break;
		case TDR_MITEM_STIMEBASE:
			TDR_SetTimebase(&tdrparam);
			break;
	}
}



void TDR_DoBrowsMenu(short mitem)
{
	char buf[256];
	short i;
	
	switch(mitem){
		case TDR_MITEM_SSPEC:
			SLClearCell(&sl, tdrparam.n_spec);
			for(i = 0 ; i < tdrparam.n_spec ; i++){
				sprintf(buf, "% 4.3f % 6.4e  %10.8e  %10.8e  %3d",
						*(lfa + i), *(fa + i), real(*(spect + i)), 
						imag(*(spect + i)), *(n_it + i));
				SLSet1Data(&sl, buf);
			}
			ShowWindow(sl.w);
			SelectWindow(sl.w);
			break;
		case TDR_MITEM_FTRSLT:
			TDR_ShowMoreInformation(&tdrparam);
			break;
		case TDR_MITEM_SPREAMBL:
			TDR_ShowPreamble(&pre);
			break;
		case TDR_MITEM_SSTANDARD:
			SLClearCell(&slstd, tdrparam.n_spec);
			for(i = 0 ; i < tdrparam.n_spec ; i++){
				sprintf(buf, "% 4.3f % 6.4e  %10.8e  %10.8e",
						*(lfa + i), *(fa + i), real(*(standard_eps + i)), 
						imag(*(standard_eps + i)));
				SLSet1Data(&slstd, buf);
			}
			ShowWindow(slstd.w);
			SelectWindow(slstd.w);
			break;
	}
}

void TDR_DoCalcMenu(short mitem)
{
	Str255 datestr, timestr;
	unsigned long secs;
	short i;
	char buf[256];	
		
	switch(mitem){
		case TDR_MITEM_CCALC:
			SetCCursor(WaitCurHandle);
			/* get processing start time */
			GetDateTime(&secs);
			IUDateString(secs, abbrevDate, datestr);
			IUTimeString(secs, true, timestr);
			strcpy(oinfo.processing_time, PtoCstr(datestr));
			strcat(oinfo.processing_time, PtoCstr(timestr));

			doTDRCalc();
			InitCursor();
			break;
		case TDR_MITEM_STDCALC:
			TDR_SetParamToStruct(&ep, &tdrparam);
			CalcStandard(&tdrparam);
			SLClearCell(&slstd, tdrparam.n_spec);
			for(i = 0 ; i < tdrparam.n_spec ; i++){
				sprintf(buf, "% 4.3f % 6.4e  %10.8e  %10.8e",
						*(lfa + i), *(fa + i), real(*(standard_eps + i)),
						imag(*(standard_eps + i)));
				SLSet1Data(&slstd, buf);
			}
			ShowWindow(slstd.w);
			SelectWindow(slstd.w);
			break;
	}
}

void TDR_DoConnectMenu(short mitem)
{
	FileIO fs;
	
	// オペレータの名前の入力なしに測定をしようとしたときは、強制的に入力させる
	if(mitem != TDR_MITEM_OP && strlen(op_name) == 0){
		TDR_SetOPInfo();
		return;
	}
	
	switch(mitem){
		case TDR_MITEM_MES2:	//オシロのmemory1,memory2の内容を読み出してセーブする
			if(TDR_Get2Data(&pre, &oinfo) == 0){
				StandardPutFile("\pOutput file name", "\pUntitled", &(fs.sfr));
				write2sample(&fs, TA, RS, RX, pre.points, &pre, &oinfo);
				tdrparam.dt = pre.xincrement;
			}
			break;
		case TDR_MITEM_MES3:	//オシロのmemory1,memory2,memory3の内容を読み出してセーブする
			if(TDR_Get3Data(&pre, &oinfo) == 0){
				StandardPutFile("\pOutput file name", "\pUntitled", &(fs.sfr));
				write3sample(&fs, TA, RS, RC, RX, pre.points, &pre, &oinfo);
				tdrparam.dt = pre.xincrement;
			}
			break;
		case TDR_MITEM_M2M3:	//オシロのmemory2,memory3の内容を読み出してセーブする
			if(TDR_GetM2M3Data(&pre, &oinfo) == 0){
				StandardPutFile("\pOutput file name", "\pUntitled", &(fs.sfr));
				write2sample(&fs, TA, RS, RX, pre.points, &pre, &oinfo);
				tdrparam.dt = pre.xincrement;
			}
			break;
		case TDR_MITEM_M1:	//オシロのmemory1の内容を読み出してセーブする
			if(TDR_Get1Data(1, &pre, &oinfo) == 0){
				StandardPutFile("\pOutput file name", "\pUntitled", &(fs.sfr));
				write1sample(&fs, TA, CHAN1, pre.points, &pre, &oinfo);
				tdrparam.dt = pre.xincrement;
			}
			break;
		case TDR_MITEM_M2:	//オシロのmemory2の内容を読み出してセーブする
			if(TDR_Get1Data(2, &pre, &oinfo) == 0){
				StandardPutFile("\pOutput file name", "\pUntitled", &(fs.sfr));
				write1sample(&fs, TA, CHAN1, pre.points, &pre, &oinfo);
				tdrparam.dt = pre.xincrement;
			}
			break;
		case TDR_MITEM_M3:	//オシロのmemory3の内容を読み出してセーブする
			if(TDR_Get1Data(3, &pre, &oinfo) == 0){
				StandardPutFile("\pOutput file name", "\pUntitled", &(fs.sfr));
				write1sample(&fs, TA, CHAN1, pre.points, &pre, &oinfo);
				tdrparam.dt = pre.xincrement;
			}
			break;
		case TDR_MITEM_OP:	//オペレータの情報
			TDR_SetOPInfo();
			break;
	}
}

/**************************** Client & Server *******************************/

void DoClientNew(void)
{
	AppleEvent aAppleEvent;
	AppleEvent aReply;
		
	AEError(AECreateAppleEvent(kCoreEventClass, kAEOpenApplication, &gSELF,
							   kAutoGenerateReturnID, kAnyTransactionID, &aAppleEvent));
	AEError(AESend(&aAppleEvent, &aReply, kAENoReply, kAENormalPriority, 0,
				   nil, nil));
}

void DoServerNew(void)
{
	TDR_New(); 
}


void DoClientOpen(void)
{
	SFReply sfr;
	AppleEvent aAppleEvent;
	AppleEvent aReply;
	AEDescList aDocList;
	AEDesc aDocDesc;
	Point where;

	where.h = 100; where.v = 50;
	SFGetFile(where, "\pSelect a  File", 0, -1, 0, 0, &sfr);

	if(sfr.good){
		AEError(AECreateAppleEvent(kCoreEventClass, kAEOpenDocuments, &gSELF,
									kAutoGenerateReturnID, kAnyTransactionID, &aAppleEvent));
		AEError(AECreateDesc(typeFSS, (Ptr)&sfr, sizeof(SFReply), &aDocDesc));
		AEError(AECreateList((Ptr)nil, 0, false, &aDocList));
		AEError(AEPutDesc(&aDocList, 1, &aDocDesc));
		AEError(AEPutParamDesc(&aAppleEvent, keyDirectObject, &aDocList));
		AEError(AESend(&aAppleEvent, &aReply, kAENoReply, kAENormalPriority, 0,
			               nil, nil));
	}
}



void DoClientPrint(void)
{
	// void
}

void DoServerPrint(SFReply *sfr)
{

}

void DoClientQuit(void)
{
	AppleEvent	aAppleEvent;
	AppleEvent aReply;
	
	AEError(AECreateAppleEvent(kCoreEventClass, kAEQuitApplication, &gSELF,
							   kAutoGenerateReturnID, kAnyTransactionID, &aAppleEvent));
	AEError(AESend(&aAppleEvent, &aReply, kAENoReply, kAENormalPriority, 0,
			       nil, nil));

	// メモリ共通領域の解放
	free(TA);
	free(RS);
	free(RB);
	free(RC);
	free(RX);
	free(dC);
	free(dR);
	free(Rdt);
	free(Rpp);
	free(dR_dt);
	free(MEM1);
	free(MEM2);
	free(MEM3);
	free(CHAN1);
	free(fa);
	free(lfa);
	free(spect);
	free(calimag);
	free(n_it);
	free(standard_eps);

}


void DoServerQuit(void)
{
	// メモリ共通領域の解放
	free(TA);
	free(RS);
	free(RB);
	free(RC);
	free(RX);
	free(dC);
	free(dR);
	free(Rdt);
	free(Rpp);
	free(MEM1);
	free(MEM2);
	free(MEM3);
	free(CHAN1);
	free(fa);
	free(lfa);
	free(spect);
	free(calimag);
	free(n_it);
	free(standard_eps);

	ExitToShell();

}



void DoClientCloseDocument(void)
{
	AEDesc dNull;
	AEDesc dDocument;
	AEDesc dDocumentKeyForm;
	long aDocumentAbsolutePosition;
	AppleEvent aAppleEvent;
	AppleEvent aReply;
	
	AEError(AECreateDesc(typeNull, nil, 0, &dNull));
	aDocumentAbsolutePosition = 1;
	AEError(AECreateDesc(typeLongInteger, (Ptr)&aDocumentAbsolutePosition, sizeof(long),
						 &dDocumentKeyForm));
	AEError(CreateObjSpecifier('docu', &dNull, formAbsolutePosition,
							&dDocumentKeyForm, true, &dDocument));
	AEError(AECreateAppleEvent('core', 'clos',  &gSELF, kAutoGenerateReturnID,
							   kAnyTransactionID,  &aAppleEvent));
	AEError(AEPutParamDesc(&aAppleEvent, keyDirectObject,  &dDocument));
	AEError(AESend(&aAppleEvent, &aReply, kAENoReply, kAENormalPriority, 0,
				   nil, nil));

}

void DoServerCloseDocument(void)
{
// void
	
}

/******************************************************************************/
/* Save is not AppleEvent in this case */
void DoSave(void)
{
	WindowPtr wp;
	long oPtr;
	FileIO fio;
	
	wp = FrontWindow();
	if(wp == nil) return;
	
	oPtr = oPtr = GetWRefCon(wp);
	
	if(((Identifier *)oPtr)->id == 'EDTO'){
		TDR_SetParamToStruct(&ep, &tdrparam);
		TDR_saveParam(&tdrparam);
	}
	else if(((Identifier *)oPtr)->id == 'LSTO'){
		SLDoSave((ShowList *)oPtr, &fio);
		TDR_saveIcon(&fio, 204);		// アイコンをつける
	}

}

/*********************   another menu ***************************/

void DoAdjustMenu(void)
{
	// void
}


pascal Boolean AboutDialogFilter(DialogPtr theDialog, EventRecord *theEvent, short *itemHit)
{
	MoveWindow((WindowPtr)theDialog, ((TickCount()/5) % 200) + 40, 50, true);
	return false;
}

void DoAbout(void)
{
	TDR_About();
}



/********************************************************************************/

void main(void)
{
	EventRecord aEvent;
	WindowPtr aWhichWindow, updatewindow;
	short wincode;
	GrafPtr cptr;
	long oPtr;
	
	InitToolBox();
	InitApplication();

	GetPort(&cptr);

	// load minimum information from preference
	if(TDR_ReadEnv(&tdrenv) != 0){
		strcpy(tdrenv.GPIB_addr, TDR_DEFAULT_GPIBADDR);
		GPIBAddress = atoi(tdrenv.GPIB_addr);
		tdrenv.input_ftype = TDR_DEFAULT_IFTYPE;
		tdrenv.output_ftype = TDR_DEFAULT_OFTYPE;
	}
	
	TDRInit();	
	
	SetPort(cptr);	
	
	done = false;
	while( !done ){
		EPDoMouseMove(&ep, aEvent);
		PLDoMouseMove(&plx, aEvent);
		PLDoMouseMove(&plc, aEvent);

		
		if(WaitNextEvent(everyEvent, &aEvent, 20, 0) == true){
			wincode = FindWindow(aEvent.where, &aWhichWindow);

			if(IsDialogEvent(&aEvent)){
				DoDialogEvent(&aEvent);
			}
			
			switch(aEvent.what){
				case nullEvent:
					break;
				case updateEvt:
						updatewindow = (WindowPtr)aEvent.message;
						GetPort(&cptr);
						SetPort(updatewindow);
						BeginUpdate(updatewindow);
						oPtr = GetWRefCon(updatewindow);
						if(((Identifier *)oPtr)->id == 'EDTO'){
							DrawControls(updatewindow);
							DrawGrowIcon(updatewindow);
							EPDraw((EditPanel *)oPtr);
						}
						if(((Identifier *)oPtr)->id == 'PLTO'){
							((PlotFormat *)oPtr)->n = tdrparam.n_rawdata;
							PLFullDraw((PlotFormat *)oPtr);
						}
						if(((Identifier *)oPtr)->id == 'LSTO'){
							SLDoUpdate((ShowList *)oPtr);
						}
						EndUpdate(updatewindow);
						SetPort(cptr);
						break;
				case mouseDown:
						GetPort(&cptr);
						if(!aWhichWindow) aWhichWindow = FrontWindow();
						if(aWhichWindow) SetPort(aWhichWindow);
					switch(wincode){

						case inMenuBar:
							EPDeactivate(&ep);
							TDR_DoMenu(MenuSelect(aEvent.where));
							break;
						case inContent:
							SelectWindow(aWhichWindow);
							oPtr = GetWRefCon(aWhichWindow);
							if(((Identifier *)oPtr)->id == 'EDTO'){
								EPDeactivate((EditPanel *)oPtr);
								EPClicked((EditPanel *)oPtr, aEvent);
								TDR_ControlClick(aWhichWindow, aEvent);
							}
							if(((Identifier *)oPtr)->id == 'PLTO'){
								PLContentClick((PlotFormat *)oPtr, aEvent);
							}
							if(((Identifier *)oPtr)->id == 'LSTO'){
								SLContentClick((ShowList *)oPtr, aEvent);
							}
							break;
						case inDrag:
							oPtr = GetWRefCon(aWhichWindow);
							if(((Identifier *)oPtr)->id == 'EDTO'){
								EPDeactivate((EditPanel *)oPtr);
								DragWindow(aWhichWindow, aEvent.where, &qd.screenBits.bounds);
							}
							if(((Identifier *)oPtr)->id == 'PLTO'){
								DragWindow(aWhichWindow, aEvent.where, &qd.screenBits.bounds);
								PLSetDrawParms((PlotFormat *)oPtr);
							}
							if(((Identifier *)oPtr)->id == 'LSTO'){
								DragWindow(aWhichWindow, aEvent.where, &qd.screenBits.bounds);
							}
							break;
						case inGoAway:
							oPtr = GetWRefCon(aWhichWindow);
							if(((Identifier *)oPtr)->id == 'EDTO'){
								EPDeactivate((EditPanel *)oPtr);
								EPGoAway((EditPanel *)oPtr, aEvent);
							}
							if(((Identifier *)oPtr)->id == 'PLTO'){
								PLGoAway((PlotFormat *)oPtr, aEvent);
								TDR_MarkToParam();
								TDR_StoreMarkerPosToParam();

							}
							if(((Identifier *)oPtr)->id == 'LSTO'){
								SLHideList((ShowList *)oPtr, aEvent);
							}
							break;
						case inGrow:
							oPtr = GetWRefCon(aWhichWindow);
							if(((Identifier *)oPtr)->id == 'EDTO'){
								TDR_ParamGrow((EditPanel *)oPtr, aEvent);
							}
							if(((Identifier *)oPtr)->id == 'PLTO'){
								PLDoGrow((PlotFormat *)oPtr, aEvent);
							}
							break;
						case inZoomIn:
						case inZoomOut:
							oPtr = GetWRefCon(aWhichWindow);
							if(((Identifier *)oPtr)->id == 'EDTO'){
								TDR_ParamZoom((EditPanel *)oPtr, aEvent);
							}
							if(((Identifier *)oPtr)->id == 'PLTO'){
								PLDoZoom((PlotFormat *)oPtr, aEvent);
							}
							break;
					}
					SetPort(cptr);
					break;
				case keyDown:
					if(aEvent.modifiers & cmdKey){
						TDR_DoMenu(MenuKey(aEvent.message & charCodeMask));
					}
					else{					
						oPtr = GetWRefCon(aWhichWindow);
						if(((Identifier *)oPtr)->id == 'EDTO'){
							EPHandleKeyDown((EditPanel *)oPtr, aEvent);
						}
					}
					break;
				case kHighLevelEvent:
					AEError(AEProcessAppleEvent(&aEvent));
					break;
			}
			
		}
	}
	DoServerQuit();

}

