// TDR_admp.cp
// TDR parameters administration
// 測定やデータ処理に関連するパラメータの管理を行う

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

#include "CustomFileDialog.h"
#include "debugs.h"
#include "inputdialog.h"
#include "datautils.h"
#include "showlist.h"
#include "TDR.h"

static void DrawDlgRect(Rect *r);
static void DrawDlgLine(Rect *r);


// initialize parameters 
// １度に１組のデータを処理することを想定している
//　従って、パラメータの構造体のオブジェクトは１つしか存在しない
void TDRInit(void)
{
	GrafPtr cptr;
	extern int done;	/* in TDR.cp */

	// メモリ共通領域の確保
	if((TA = (double *)malloc(N_DATA * sizeof(double))) == NULL){
		showstop("\pTDRInit: cannot allocate memory for TA", "\p", "\p", "\p");
		done = true;
	}
	if((RS = (double *)malloc(N_DATA * sizeof(double))) == NULL){
		showstop("\pTDRInit: cannot allocate memory for RS", "\p", "\p", "\p");
		done = true;
	}
	if((RB = (double *)malloc(N_DATA * sizeof(double))) == NULL){
		showstop("\pTDRInit: cannot allocate memory for RB", "\p", "\p", "\p");
		done = true;
	}
	if((RC = (double *)malloc(N_DATA * sizeof(double))) == NULL){
		showstop("\pTDRInit: cannot allocate memory for RC", "\p", "\p", "\p");
		done = true;
	}
	if((RX = (double *)malloc(N_DATA * sizeof(double))) == NULL){
		showstop("\pTDRInit: cannot allocate memory for RX", "\p", "\p", "\p");
		done = true;
	}
	if((dC = (double *)malloc(N_DATA * sizeof(double))) == NULL){
		showstop("\pTDRInit: cannot allocate memory for dC", "\p", "\p", "\p");
		done = true;
	}
	if((dR = (double *)malloc(N_DATA * sizeof(double))) == NULL){
		showstop("\pTDRInit: cannot allocate memory for dR", "\p", "\p", "\p");
		done = true;
	}
	if((Rdt = (double *)malloc(N_DATA * sizeof(double))) == NULL){
		showstop("\pTDRInit: cannot allocate memory for Rdt", "\p", "\p", "\p");
		done = true;
	}
	if((Rpp = (double *)malloc(N_DATA * sizeof(double))) == NULL){
		showstop("\pTDRInit: cannot allocate memory for Rpp", "\p", "\p", "\p");
		done = true;
	}
	if((dR_dt = (double *)malloc(N_DATA * sizeof(double))) == NULL){
		showstop("\pTDRInit: cannot allocate memory for dR_dt", "\p", "\p", "\p");
		done = true;
	}
	if((MEM1 = (double *)malloc(N_DATA * sizeof(double))) == NULL){
		showstop("\pTDRInit: cannot allocate memory for MEM1", "\p", "\p", "\p");
		done = true;
	}
	if((MEM2 = (double *)malloc(N_DATA * sizeof(double))) == NULL){
		showstop("\pTDRInit: cannot allocate memory for MEM2", "\p", "\p", "\p");
		done = true;
	}
	if((MEM3 = (double *)malloc(N_DATA * sizeof(double))) == NULL){
		showstop("\pTDRInit: cannot allocate memory for MEM3", "\p", "\p", "\p");
		done = true;
	}
	if((CHAN1 = (double *)malloc(N_DATA * sizeof(double))) == NULL){
		showstop("\pTDRInit: cannot allocate memory for MEM3", "\p", "\p", "\p");
		done = true;
	}

	if((fa = (double *)malloc(N_DATA * sizeof(double))) == NULL){
		showstop("\pTDRInit: cannot allocate memory for fa", "\p", "\p", "\p");
		done = true;
	}
	if((lfa = (double *)malloc(N_DATA * sizeof(double))) == NULL){
		showstop("\pTDRInit: cannot allocate memory for lfa", "\p", "\p", "\p");
		done = true;
	}
	if((spect = (complex<double> *)malloc(N_DATA * sizeof(complex<double>))) == NULL){
		showstop("\pTDRInit: cannot allocate memory for spect", "\p", "\p", "\p");
		done = true;
	}
	if((calimag = (double *)malloc(N_DATA * sizeof(double))) == NULL){
		showstop("\pTDRInit: cannot allocate memory for calimag", "\p", "\p", "\p");
		done = true;
	}
	if((n_it = (short *)malloc(N_DATA * sizeof(short))) == NULL){
		showstop("\pTDRInit: cannot allocate memory for n_it", "\p", "\p", "\p");
		done = true;
	}
	if((standard_eps = (complex<double> *)malloc(N_DATA * sizeof(complex<double>))) == NULL){
		showstop("\pTDRInit: cannot allocate memory for standard_eps", "\p", "\p", "\p");
		done = true;
	}

	
	EPInit(&ep, TDR_PARAMWIN_ID, TDRSetItems);
	TDR_InitContrls(ep.w);
	GetPort(&cptr);
	SetPort(ep.w);
	TDR_New();
	ShowWindow(ep.w);
	SetPort(cptr);
		
	PLInit(&plx,  PLOT_WINDOW_ID);
	PLInit(&plc, PLOT_WINDOW_ID);
	PLSetDrawParms(&plx);
	PLSetDrawParms(&plc);
	
	PLSetData(&plx, TA, dR, N_DATA);
	PLScrlInit(&plx, PLOT_VSCRL_ID, PLOT_HSCRL_ID);
	
	PLSetData(&plc, TA, dC, N_DATA);
	PLScrlInit(&plc, PLOT_VSCRL_ID, PLOT_HSCRL_ID);
	
	SLInit(&sl, LIST_WINDOW_ID);		
	SLInit(&slstd, LIST_WINDOW_ID);
	
	strcpy(op_name, "");
	strcpy(op_comment, "");

	
	WaitCurHandle = GetCCursor(TDR_WAITCSR_ID);
	

}

//　処理パラメータの初期化をする
void TDR_New(void)
{
	short i;
	
	for(i = 0 ; i < ep.inum ; i++){		// 表示の初期化
		TESetText("", 0, ep.item[i].te);
	}
	
	// 数値データなどの初期化
	tdrparam.fs_dfile1.sfr.sfGood = false;
	tdrparam.fs_dfile2.sfr.sfGood = false;
	tdrparam.fs_dfile3.sfr.sfGood = false;
	tdrparam.fs_param.sfr.sfGood = false;
	tdrparam.fs_spec.sfr.sfGood = false;

	tdrparam.fs_dfile1.typelist[0] = 'TEXT';
	tdrparam.fs_dfile2.typelist[0] = 'TEXT';
	tdrparam.fs_dfile3.typelist[0] = 'TEXT';
	
	tdrparam.baseXs = 0;
	tdrparam.baseXe = 0;
	tdrparam.cutXs = 0;
	tdrparam.cutXe = 0;
	tdrparam.baseCs = 0;
	tdrparam.baseCe = 0;
	tdrparam.cutCs = 0;
	tdrparam.cutCe = 0;
	
	SetControlValue(Cstandards, 1);

	tdrparam.dt = 0.0;
	tdrparam.limit_nit = 60;
	tdrparam.condition_done = 1.0e-5;
	
	strcpy(tdrparam.comment, "");
	
	for(i = 0 ; i < N_DATA ; i++){
		*(TA + i) = 0.0;
		*(RS + i) = 0.0;
		*(RB + i) = 0.0;
		*(RC + i) = 0.0;
		*(RX + i) = 0.0;

		*(dR + i) = 0.0;
		*(Rdt + i) = 0.0;
		*(Rpp + i) = 0.0;
		
		*(fa + i) = 0.0;
		*(lfa + i) = 0.0;
		*(n_it + i) = 0;
		
		*(spect + i) = complex<double>(0.0,0.0);
		*(standard_eps + i) = complex<double>(0.0, 0.0);
		*(calimag + i) = 0.0;
	}
	tdrparam.n_spec = 0;

	TDR_ClearPreamble(&pre);
		
	EPDraw(&ep);		//初期化された画面を表示する
	DrawControls(ep.w);

	tdrparam.launch_flag = LAUNCH_BY_CL;	// double clicked
	
	isCalcDialog = false;	// calc dialog is not displayed.
}	
	
	
// return EdiI item number
// use EdtI resource
short TDRSetItems(EditItem ei[])
{
	short i;
	short offset = 65;	//これの調整で、全体に上下させることができるのであえて残す
	Handle dh;
	Str255 tmpstr;
	
	for(i = 0 ; i < TDR_EDTI_NUMBER ; i++){
		dh = Get1Resource(EDTI_RESTYPE, TDR_EDTI_START_ID + i);
		ei[i].lx = (**(EdtIHandle)dh).lx;	
		ei[i].ly = (**(EdtIHandle)dh).ly + offset;
		BlockMoveData((**(EdtIHandle)dh).label, tmpstr, (Size)(**(EdtIHandle)dh).label[0]+1);
		strcpy(ei[i].label, PtoCstr(tmpstr));
		ei[i].ex = (**(EdtIHandle)dh).ex;	
		ei[i].ey = (**(EdtIHandle)dh).ey;
		ei[i].f_rect = (**(EdtIHandle)dh).f_rect;
		ei[i].t_rect = (**(EdtIHandle)dh).t_rect;
		BlockMoveData((**(EdtIHandle)dh).format, tmpstr, (Size)((**(EdtIHandle)dh).format[0] + 1));
		strcpy(ei[i].format, PtoCstr(tmpstr));
		
		ei[i].f_rect.top += offset; ei[i].f_rect.bottom += offset;
		ei[i].t_rect.top += offset; ei[i].t_rect.bottom += offset;
		
		ReleaseResource(dh);
	}

	// プルダウンの分の間をあける
	for(i = 13 ; i < TDR_EDTI_NUMBER ; i++){
		ei[i].ly += 30;
		ei[i].f_rect.top += 30; ei[i].f_rect.bottom += 30;
		ei[i].t_rect.top += 30; ei[i].t_rect.bottom += 30;
	}
	
	for(i = 0 ; i < TDR_EDTI_NUMBER ; i++){
		ei[i].te = TENew(&(ei[i].t_rect), &(ei[i].t_rect));
	}
	
	return TDR_EDTI_NUMBER;
}

// Initialize Controls
// Initialize grobal handles
void TDR_InitContrls(WindowPtr w)
{
	GrafPtr cptr;
	
	GetPort(&cptr);
	SetPort(w);
	Cdatafile1 = GetNewControl(TDR_DFILE1_ID, w);
	Cdatafile2 = GetNewControl(TDR_DFILE2_ID, w);
	Cdatafile3 = GetNewControl(TDR_DFILE3_ID, w);
	Cstandards = GetNewControl(TDR_STANDARD_ID, w);
	
	SetPort(cptr);
}

void TDR_ControlClick(WindowPtr w,  EventRecord ev)
{
	ControlHandle ccntrl;
	Point mouse;
	long part;
	GrafPtr cptr;
	short format;
	char valbuf[256];
	char path[256];	// test
	
	GetPort(&cptr);
	SetPort(w);
	mouse = ev.where;
	GlobalToLocal(&mouse);
	
	part = FindControl(mouse, w, &ccntrl);
	format = tdrenv.output_ftype;
	
	if(ccntrl == Cdatafile1){	// datafile1 button
		if(TrackControl(ccntrl, mouse, NULL) != NULL){
			CustomOpen(NULL, 1, tdrparam.fs_dfile1.typelist, &(tdrparam.fs_dfile1.sfr),&format);
			if(tdrparam.fs_dfile1.sfr.sfGood){  // reading not cancelled...
				// Specifying the 1st file means the start of new analysis. So, clear status.
				TDR_New();
				// restore
				tdrparam.fs_dfile1.sfr.sfGood=true;
				//
				tdrenv.input_ftype = format;
				tdrparam.flag_dfile1=format;
				tdrparam.fs_dfile1.fss = tdrparam.fs_dfile1.sfr.sfFile;
				// DoRead
				SetCCursor(WaitCurHandle);
				TDR_readDatafile(&tdrparam);
				if(TDR_QueryResourceExists(&(tdrparam.fs_dfile1.fss), TDR_PRM_RESTYPE, TDR_PRM_RESID)){
					InitCursor();
					if(TDR_ShowRestoreParmsDialog()){
						TDR_ReadParmsFromResouce(&(tdrparam.fs_dfile1.fss), &(tdrparam));
						TDR_SetParamToEditPanel(&ep, &tdrparam);
					}
				}
				//
				TDR_Setdispdata();
				PLSetScrlRange(&plx);
				PLSetScrlRange(&plc);
				sprintf(valbuf, ep.item[TDR_EDTI_N_TINTERVAL].format, tdrparam.dt);
				EPSetContent(&ep, TDR_EDTI_N_TINTERVAL, valbuf);
				sprintf(valbuf, oinfo.operation_comment);
				EPSetContent(&ep, TDR_EDTI_N_COMMENT, valbuf);
				EPDraw(&ep);
				InitCursor();

// test
path[0] = 0;
GetPathName(tdrparam.fs_dfile1.fss, path);

			}
		}
	}
	else if(ccntrl == Cdatafile2){
		if(TrackControl(ccntrl, mouse, NULL) != NULL){
			CustomOpen(NULL, 1, tdrparam.fs_dfile2.typelist, &(tdrparam.fs_dfile2.sfr),&format);
			if(tdrparam.fs_dfile2.sfr.sfGood){
				tdrparam.flag_dfile2=format;
				tdrparam.fs_dfile2.fss = tdrparam.fs_dfile2.sfr.sfFile;
				// DoRead
				SetCCursor(WaitCurHandle);
				TDR_readDatafile(&tdrparam);
				TDR_Setdispdata();
				PLSetScrlRange(&plx);
				PLSetScrlRange(&plc);
				InitCursor();
			}
		}
	}
	else if(ccntrl == Cdatafile3){
		if(TrackControl(ccntrl, mouse, NULL) != NULL){
			CustomOpen(NULL, 1, tdrparam.fs_dfile3.typelist, &(tdrparam.fs_dfile3.sfr), &format);
			if(tdrparam.fs_dfile3.sfr.sfGood){
				tdrparam.flag_dfile3 = format;
				tdrparam.fs_dfile3.fss = tdrparam.fs_dfile3.sfr.sfFile;
				// DoRead
				SetCCursor(WaitCurHandle);
				TDR_readDatafile(&tdrparam);
				//
				if(TDR_QueryResourceExists(&(tdrparam.fs_dfile3.fss), TDR_PRM_RESTYPE,TDR_PRM_RESID)){
					if(TDR_ShowRestoreParmsDialog()){
						TDR_ReadParmsFromResouce(&(tdrparam.fs_dfile3.fss), &(tdrparam));
					}
				}
				// display dt
				sprintf(valbuf, ep.item[TDR_EDTI_N_TINTERVAL].format, tdrparam.dt);
				EPSetContent(&ep, TDR_EDTI_N_TINTERVAL, valbuf);

				//
				TDR_Setdispdata();
				PLSetScrlRange(&plx);
				PLSetScrlRange(&plc);
				EPDraw(&ep);
				InitCursor();
			}
		}
	}
	else if(ccntrl == Cstandards){
		TDR_Parampopup(mouse, ccntrl);
	}
	else{
		// void
	}
	SetPort(cptr);
}

// submenu popup		
void TDR_Parampopup(Point mouse, ControlHandle ctrl)
{
	long part;
	
	part = TrackControl(ctrl, mouse, (ControlActionUPP)-1);
}	

// set display data
void TDR_Setdispdata(void)
{
	short i;

	// TA[] is already exist.(read from file or make from dt value.)	
	for(i = 0 ; i < N_DATA ; i++){
		*(dR + i) = *(RS + i) - *(RX + i);
		*(dC + i) = *(RB + i) - *(RC + i);
	}
	PLSetData(&plx, TA, dR, N_DATA);
	PLSetData(&plc, TA, dC, N_DATA);
	
	PLSetScrlRange(&plx);
	PLSetScrlRange(&plc);
}


/******************************************************/
// Causion! Parameter window has no scrollbars
// Growing parameter window
void TDR_ParamGrow(EditPanel *ep, EventRecord ev)
{
	long growth;
	Rect growarea;
	GrafPtr cptr;
	
	GetPort(&cptr);
	SetPort(ep->w);
	SetRect(&growarea, 40, 40, 650, 650);
	
	growth = GrowWindow(ep->w, ev.where, &growarea);
	if(growth != 0){
		SizeWindow(ep->w, LoWord(growth), HiWord(growth), true);
		EraseRect(&(ep->w->portRect));
		InvalRect(&(ep->w->portRect));
	}
	SetPort(cptr);
}


// Zooming parameter window
void TDR_ParamZoom(EditPanel *ep, EventRecord ev)
{
	Point mouse;
	short part;
	WindowPtr win;
	GrafPtr cptr;
	
	GetPort(&cptr);
	mouse = ev.where;
	part = FindWindow(ev.where, &win);
	SetPort(win);
	
	if(TrackBox(win, mouse, part)){
		ZoomWindow(win, part, false);
		EraseRect(&(ep->w->portRect));
	}
	
	SetPort(cptr);
}

// Set Parameters to TDR_PARAMETER structure
// Use grabal variable of control handles in TDR.h
void TDR_SetParamToStruct(EditPanel *ep, TDR_PARAMETER *p)
{
	char buf[256];
	short i;


	// Editable region	
	i = 0;
	EPGetContent(ep, i, buf);  p->baseXs = atoi(buf);  i++;
	EPGetContent(ep, i, buf);  p->baseXe = atoi(buf);  i++;
	EPGetContent(ep, i, buf);  p->cutXs = atoi(buf);  i++;
	EPGetContent(ep, i, buf);  p->cutXe = atoi(buf);  i++;

	EPGetContent(ep, i, buf);  p->baseCs = atoi(buf);  i++;
	EPGetContent(ep, i, buf);  p->baseCe = atoi(buf);  i++;
	EPGetContent(ep, i, buf);  p->cutCs = atoi(buf);  i++;
	EPGetContent(ep, i, buf);  p->cutCe = atoi(buf);  i++;

	EPGetContent(ep, i, buf); p->dt = atof(buf);  i++;

	EPGetContent(ep, i, buf); p->d = atof(buf);  i++;
	EPGetContent(ep, i, buf); p->gd = atof(buf);  i++;

	EPGetContent(ep, i, buf); p->gX = atof(buf);  i++;
	EPGetContent(ep, i, buf); p->gC = atof(buf);  i++;

	p->id_standard = GetControlValue(Cstandards);
	p->id_standard = p->id_standard - 1; 		// convert to index of array
	
	EPGetContent(ep, i, buf); p->temperature = atof(buf);  i++;

	EPGetContent(ep, i, buf); p->DCf = atof(buf);  i++;

	EPGetContent(ep, i, buf); p->lfs = atof(buf);  i++;
	EPGetContent(ep, i, buf); p->lfe = atof(buf);  i++;
	EPGetContent(ep, i, buf); p->dlf = atof(buf);  i++;

	EPGetContent(ep, i, buf); strcpy(p->comment, buf); i++;
		
	if(p->limit_nit <= 0 || p->limit_nit >60) p->limit_nit = 60;
	if(p->condition_done > 0.01 || p->condition_done < 0.0) p->condition_done = 0.00001;

}

// set contens of TDR_PARAMETER to EditPanel and related Controls
// Use grabal variable of control handles in TDR.h
void TDR_SetParamToEditPanel(EditPanel *ep, TDR_PARAMETER *p)
{
	char buf[256];
	short i;

	i = 0;
	sprintf(buf, ep->item[i].format, p->baseXs); EPSetContent(ep, i, buf); i++;
	sprintf(buf, ep->item[i].format, p->baseXe); EPSetContent(ep, i, buf); i++;
	sprintf(buf, ep->item[i].format, p->cutXs); EPSetContent(ep, i, buf); i++;
	sprintf(buf, ep->item[i].format, p->cutXe); EPSetContent(ep, i, buf); i++;

	sprintf(buf, ep->item[i].format, p->baseCs); EPSetContent(ep, i, buf); i++;
	sprintf(buf, ep->item[i].format, p->baseCe); EPSetContent(ep, i, buf); i++;
	sprintf(buf, ep->item[i].format, p->cutCs); EPSetContent(ep, i, buf); i++;
	sprintf(buf, ep->item[i].format, p->cutCe); EPSetContent(ep, i, buf); i++;

	sprintf(buf, ep->item[i].format, p->dt); EPSetContent(ep, i, buf); i++;

	sprintf(buf, ep->item[i].format, p->d); EPSetContent(ep, i, buf); i++;
	sprintf(buf, ep->item[i].format, p->gd); EPSetContent(ep, i, buf); i++;

	sprintf(buf, ep->item[i].format, p->gX); EPSetContent(ep, i, buf); i++;
	sprintf(buf, ep->item[i].format, p->gC); EPSetContent(ep, i, buf); i++;

	sprintf(buf, ep->item[i].format, p->temperature); EPSetContent(ep, i, buf); i++;

	sprintf(buf, ep->item[i].format, p->DCf); EPSetContent(ep, i, buf); i++;

	sprintf(buf, ep->item[i].format, p->lfs); EPSetContent(ep, i, buf); i++;
	sprintf(buf, ep->item[i].format, p->lfe); EPSetContent(ep, i, buf); i++;
	sprintf(buf, ep->item[i].format, p->dlf); EPSetContent(ep, i, buf); i++;

	sprintf(buf, ep->item[i].format, p->comment); EPSetContent(ep, i, buf); i++;

	SetControlValue(Cstandards, p->id_standard+1); // convert to control #

}
// show error messages about parameter setting error
void TDR_paramerr(unsigned char *str0, unsigned char *str1, unsigned char *str2, unsigned char *str3)
{
	ParamText((unsigned char *)str0,
	          (unsigned char *)str1,
			  (unsigned char *)str2,
			  (unsigned char *)str3);
	Alert(TDR_ALERT_PRM_ID, NULL);
}

// get data from PlotFormat and set to EditPanel
// use global value in TDR.h
void TDR_MarkToParam(void)
{
	char valbuf[256];
	short i;

	i = 0;
	sprintf(valbuf, ep.item[i].format, plx.marknum[0]);
	EPSetContent(&ep, i, valbuf); i++;
	sprintf(valbuf, ep.item[i].format, plx.marknum[1]);
	EPSetContent(&ep, i, valbuf); i++;
	sprintf(valbuf, ep.item[i].format, plx.marknum[2]);
	EPSetContent(&ep, i, valbuf); i++;
	sprintf(valbuf, ep.item[i].format, plx.marknum[3]);
	EPSetContent(&ep, i, valbuf); i++;

	sprintf(valbuf, ep.item[i].format, plc.marknum[0]);
	EPSetContent(&ep, i, valbuf); i++;
	sprintf(valbuf, ep.item[i].format, plc.marknum[1]);
	EPSetContent(&ep, i, valbuf); i++;
	sprintf(valbuf, ep.item[i].format, plc.marknum[2]);
	EPSetContent(&ep, i, valbuf); i++;
	sprintf(valbuf, ep.item[i].format, plc.marknum[3]);
	EPSetContent(&ep, i, valbuf); i++;
}

void TDR_ShowMoreInformation(TDR_PARAMETER *pr)
{
	DialogPtr dlg;
	short itemtype, item;
	Rect box;
	Handle itemH;
	char datastr[256];
	GrafPtr cptr;
	
	GetPort(&cptr);
	dlg = GetNewDialog(TDR_MOREINFDLG_ID, nil, (WindowPtr)-1);
	SetPort(dlg);
	
	// display information
	// # of data
	GetDialogItem(dlg, 3, &itemtype, &itemH, &box);
	sprintf(datastr, "%4d", pr->n_data);
	SetDialogItemText(itemH, C2PStr(datastr));
	// # of calib
	GetDialogItem(dlg, 5, &itemtype, &itemH, &box);
	sprintf(datastr, "%4d", pr->n_cdata);
	SetDialogItemText(itemH, C2PStr(datastr));
	// # of spectrum
	GetDialogItem(dlg, 7, &itemtype, &itemH, &box);
	sprintf(datastr, "%4d", pr->n_spec);
	SetDialogItemText(itemH, C2PStr(datastr));
	// sample DC
	GetDialogItem(dlg, 9, &itemtype, &itemH, &box);
	sprintf(datastr, "%5.4e", pr->dcx);
	SetDialogItemText(itemH, C2PStr(datastr));
	// calibration dc
	GetDialogItem(dlg, 11, &itemtype, &itemH, &box);
	sprintf(datastr, "%5.4e", pr->dcc);
	SetDialogItemText(itemH, C2PStr(datastr));
	// sigma/eps(sample)
	GetDialogItem(dlg, 13, &itemtype, &itemH, &box);
	sprintf(datastr, "%5.4e", pr->sbex);
	SetDialogItemText(itemH, C2PStr(datastr));
	// sigma/eps(calib)
	GetDialogItem(dlg, 15, &itemtype, &itemH, &box);
	sprintf(datastr, "%5.4e", pr->sbec);
	SetDialogItemText(itemH, C2PStr(datastr));

	while(1){
		ModalDialog(0, &item);
		if(item == 1){		// OK button
			break;
		}
	}
	DisposeDialog(dlg);
	SetPort(cptr);
}

void TDR_SetItCondition(TDR_PARAMETER *pr)
{
	DialogPtr dlg;
	short itemtype, item;
	Rect box;
	Handle itemH;
	Str255 buf;
	char datastr[256];
	GrafPtr cptr;
	double cond;
	short nit;
	
	GetPort(&cptr);
	dlg = GetNewDialog(TDR_CONVCONDDLG_ID, nil, (WindowPtr)-1);
	SetPort(dlg);
	
	// display information
	// # of iteration
	GetDialogItem(dlg, 3, &itemtype, &itemH, &box);
	sprintf(datastr, "%d", pr->limit_nit);
	SetDialogItemText(itemH, C2PStr(datastr));
	// convergence condition of iteration
	GetDialogItem(dlg, 5, &itemtype, &itemH, &box);
	sprintf(datastr, "%5.4e", pr->condition_done);
	SetDialogItemText(itemH, C2PStr(datastr));
	
	while(1){
		ModalDialog(0, &item);
		if(item == 1){		// OK button
			// get number of iteration
			GetDialogItem(dlg, 3, &itemtype, &itemH, &box);
			GetDialogItemText(itemH, buf);
			nit = atoi(P2CStr(buf));
			// get escape condition
			GetDialogItem(dlg, 5, &itemtype, &itemH, &box);
			GetDialogItemText(itemH, buf);
			cond = atof(P2CStr(buf));
			if(nit > 0 ) pr->limit_nit = nit;
			if(cond > 0.0 && cond < 1.0) pr->condition_done = cond;
			break;
		}
	}
	DisposeDialog(dlg);
	SetPort(cptr);
}

// use globals in TDR.h
// EditPanel ep, TDR_PARAMETER tdrparam 
void doTDRCalc(void)
{
	char valbuf[256];
	
	TDR_SetParamToStruct(&ep, &tdrparam);
	if(StartCalc(&tdrparam) == 0){			/* success! */
		// display conductivity
		sprintf(valbuf, ep.item[TDR_EDTI_N_COND_C].format, tdrparam.gC);
		EPSetContent(&ep, TDR_EDTI_N_COND_C, valbuf);
		sprintf(valbuf, ep.item[TDR_EDTI_N_COND_X].format, tdrparam.gX);
		EPSetContent(&ep, TDR_EDTI_N_COND_X, valbuf);
		// save dielectric data
		TDR_saveSpectr(&tdrparam);
		// save processing parameter to reflected wave file
		TDR_SaveParmsToResouce(current_fss, &tdrparam);
	}
}

void TDR_ShowPreamble(TDR_PREAMBLE *p)
{
	DialogPtr dlg;
	short itemtype, item;
	Rect box;
	Handle itemH;
	char datastr[256];
	GrafPtr cptr;
	
	GetPort(&cptr);
	dlg = GetNewDialog(TDR_PREAMBLDLG_ID, nil, (WindowPtr)-1);
	SetPort(dlg);

	GetDialogItem(dlg, 4, &itemtype, &itemH, &box);
	sprintf(datastr, "%d", p->format);
	SetDialogItemText(itemH, C2PStr(datastr));
	GetDialogItem(dlg, 6, &itemtype, &itemH, &box);
	sprintf(datastr, "%d", p->type);
	SetDialogItemText(itemH, C2PStr(datastr));
	GetDialogItem(dlg, 8, &itemtype, &itemH, &box);
	sprintf(datastr, "%d", p->points);
	SetDialogItemText(itemH, C2PStr(datastr));
	GetDialogItem(dlg, 10, &itemtype, &itemH, &box);
	sprintf(datastr, "%d", p->count);
	SetDialogItemText(itemH, C2PStr(datastr));

	GetDialogItem(dlg, 12, &itemtype, &itemH, &box);
	sprintf(datastr, "%8.6e", p->xincrement);
	SetDialogItemText(itemH, C2PStr(datastr));
	GetDialogItem(dlg, 14, &itemtype, &itemH, &box);
	sprintf(datastr, "%8.6e", p->xorigin);
	SetDialogItemText(itemH, C2PStr(datastr));
	GetDialogItem(dlg, 16, &itemtype, &itemH, &box);
	sprintf(datastr, "%8.6e", p->xreference);
	SetDialogItemText(itemH, C2PStr(datastr));

	GetDialogItem(dlg, 18, &itemtype, &itemH, &box);
	sprintf(datastr, "%8.6e", p->yincrement);
	SetDialogItemText(itemH, C2PStr(datastr));
	GetDialogItem(dlg, 20, &itemtype, &itemH, &box);
	sprintf(datastr, "%8.6e", p->yorigin);
	SetDialogItemText(itemH, C2PStr(datastr));
	GetDialogItem(dlg, 22, &itemtype, &itemH, &box);
	sprintf(datastr, "%8.6e", p->yreference);
	SetDialogItemText(itemH, C2PStr(datastr));
	GetDialogItem(dlg, 24, &itemtype, &itemH, &box);
	sprintf(datastr, "%8.6e", p->yrange);
	SetDialogItemText(itemH, C2PStr(datastr));

	while(1){
		ModalDialog(0, &item);
		if(item == 1){		// OK button
			break;
		}
	}
	DisposeDialog(dlg);
	SetPort(cptr);
}

void TDR_ClearPreamble(TDR_PREAMBLE *pr)
{
	pr->format = 0;
	pr->type = 0;
	pr->points = 0;
	pr->count = 0;
	pr->xincrement = 0.0;
	pr->xorigin = 0.0;
	pr->xreference = 0.0;
	pr->yincrement = 0.0;
	pr->yorigin = 0.0;
	pr->yreference = 0.0;
	pr->yrange = 0.0;
}


// Restore parameters dialog
// if "Restore" selected, return true, else return false.
Boolean TDR_ShowRestoreParmsDialog(void)
{
	DialogPtr dlg;
	short item;
	Boolean status;
	GrafPtr cptr;
	
	GetPort(&cptr);
	dlg = GetNewDialog(TDR_RESTOREPARMS_ID, nil, (WindowPtr)-1);
	SetPort(dlg);
	
	while(1){
		ModalDialog(0, &item);
		if(item == 1){		// Restore parameters
			status = true;
			break;
		}
		if(item == 3){		// start with new parameters
			status = false;
			break;
		}
	}
	DisposeDialog(dlg);
	SetPort(cptr);

	return status;
}

void TDR_RestoreMarkerPos(void)
{
	int sample_mkpos[N_PLOTMARK], calib_mkpos[N_PLOTMARK];

	sample_mkpos[0]=tdrparam.baseXs; sample_mkpos[1]=tdrparam.baseXe;
	sample_mkpos[2]=tdrparam.cutXs; sample_mkpos[3]=tdrparam.cutXe;
	calib_mkpos[0]=tdrparam.baseCs; calib_mkpos[1]=tdrparam.baseCe;
	calib_mkpos[2]=tdrparam.cutCs; calib_mkpos[3]=tdrparam.cutCe;
	PLSetInirialMarkPos(&plx, sample_mkpos);
	PLSetInirialMarkPos(&plc, calib_mkpos);
}

void TDR_StoreMarkerPosToParam(void)
{
	tdrparam.baseXs = plx.marknum[0]; tdrparam.baseXe = plx.marknum[1];
	tdrparam.cutXs = plx.marknum[2]; tdrparam.cutXe = plx.marknum[3];
	tdrparam.baseCs = plc.marknum[0]; tdrparam.baseCe = plc.marknum[1];
	tdrparam.cutCs = plc.marknum[2]; tdrparam.cutCe = plc.marknum[3];
}

void TDR_SetEnvironment(TDR_ENV *env)
{
	DialogPtr dlg;
	short itemtype, item;
	short result;
	Rect box;
	Handle itemH;
	char datastr[256];
	Str255 text;
	GrafPtr cptr;
	MenuHandle mh;
	
	GetPort(&cptr);
	dlg = GetNewDialog(TDR_ENVDLG_ID, nil, (WindowPtr)-1);
	SetPort(dlg);
	
	// draw box and line
	GetDialogItem(dlg, 30, &itemtype, &itemH, &box);
	DrawDlgRect(&box);
	GetDialogItem(dlg, 31, &itemtype, &itemH, &box);
	DrawDlgRect(&box);
	GetDialogItem(dlg, 32, &itemtype, &itemH, &box);
	DrawDlgRect(&box);
	DrawDlgLine(&box);
	GetDialogItem(dlg, 33, &itemtype, &itemH, &box);
	DrawDlgRect(&box);
	DrawDlgLine(&box);
	GetDialogItem(dlg, 34, &itemtype, &itemH, &box);
	DrawDlgRect(&box);


	// set current value
	GetDialogItem(dlg, 3, &itemtype, &itemH, &box);
	sprintf(datastr, "%s", env->GPIB_addr);
	SetDialogItemText(itemH, C2PStr(datastr));

	GetDialogItem(dlg, 5, &itemtype, &itemH, &box);
	mh = GetMenuHandle(myOpenDialogID);
	if(env->input_ftype > 0 && env->input_ftype <= CountMItems(mh)){
		SetControlValue((ControlHandle)itemH, env->input_ftype);
	}
	else{
		SetControlValue((ControlHandle)itemH, 1);
	}
	DisposeMenu(mh);
	
	GetDialogItem(dlg, 7, &itemtype, &itemH, &box);
	mh = GetMenuHandle(mySaveAsDialogID);
	if(env->output_ftype > 0 && env->output_ftype <= CountMItems(mh)){
		SetControlValue((ControlHandle)itemH, env->output_ftype);
	}
	else{
		SetControlValue((ControlHandle)itemH,1);
	}

	GetDialogItem(dlg, 9, &itemtype, &itemH, &box);
	sprintf(datastr, "%s", env->rawfile_basename);
	SetDialogItemText(itemH, C2PStr(datastr));

	GetDialogItem(dlg, 11, &itemtype, &itemH, &box);
	sprintf(datastr, "%d", env->rawfile_startnum);
	SetDialogItemText(itemH, C2PStr(datastr));

	GetDialogItem(dlg, 12, &itemtype, &itemH, &box);
	sprintf(datastr, "%s", env->rawfile_pathname);
	SetDialogItemText(itemH, C2PStr(datastr));

	GetDialogItem(dlg, 15, &itemtype, &itemH, &box);
	sprintf(datastr, "%s", env->spfile_basename);
	SetDialogItemText(itemH, C2PStr(datastr));

	GetDialogItem(dlg, 17, &itemtype, &itemH, &box);
	sprintf(datastr, "%d", env->spfile_startnum);
	SetDialogItemText(itemH, C2PStr(datastr));

	GetDialogItem(dlg, 18, &itemtype, &itemH, &box);
	sprintf(datastr, "%s", env->spfile_pathname);
	SetDialogItemText(itemH, C2PStr(datastr));

	GetDialogItem(dlg, 21, &itemtype, &itemH, &box);
	sprintf(datastr, "%s", env->spfile_freqbname);
	SetDialogItemText(itemH, C2PStr(datastr));

	GetDialogItem(dlg, 23, &itemtype, &itemH, &box);
	sprintf(datastr, "%s", env->spfile_realbname);
	SetDialogItemText(itemH, C2PStr(datastr));

	GetDialogItem(dlg, 25, &itemtype, &itemH, &box);
	sprintf(datastr, "%s", env->spfile_imagbname);
	SetDialogItemText(itemH, C2PStr(datastr));

	GetDialogItem(dlg, 26, &itemtype, &itemH, &box);
	SetControlValue((ControlHandle)itemH,env->freqdup_flag);

	GetDialogItem(dlg, 28, &itemtype, &itemH, &box);
	sprintf(datastr, "%d", env->wave_startnum);
	SetDialogItemText(itemH, C2PStr(datastr));

	GetDialogItem(dlg, 29, &itemtype, &itemH, &box);
	SetControlValue((ControlHandle)itemH,env->numsave_flag);

	while(1){
		ModalDialog(0, &item);
		if(item == 1){		// OK button
			GetDialogItem(dlg, 3, &itemtype, &itemH, &box);
			GetDialogItemText(itemH, text);
			strcpy(env->GPIB_addr, PtoCstr(text));
			GPIBAddress = atoi(env->GPIB_addr);

			GetDialogItem(dlg, 5, &itemtype, &itemH, &box);
			env->input_ftype = GetControlValue((ControlHandle)itemH);

			GetDialogItem(dlg, 7, &itemtype, &itemH, &box);
			env->output_ftype = GetControlValue((ControlHandle)itemH);

			GetDialogItem(dlg, 9, &itemtype, &itemH, &box);
			GetDialogItemText(itemH, text);
			strcpy(env->rawfile_basename, PtoCstr(text));
	
			GetDialogItem(dlg, 11, &itemtype, &itemH, &box);
			GetDialogItemText(itemH, text);
			env->rawfile_startnum = atoi(PtoCstr(text));

			GetDialogItem(dlg, 15, &itemtype, &itemH, &box);
			GetDialogItemText(itemH, text);
			strcpy(env->spfile_basename, PtoCstr(text));

			GetDialogItem(dlg, 17, &itemtype, &itemH, &box);
			GetDialogItemText(itemH, text);
			env->spfile_startnum = atoi(PtoCstr(text));

			GetDialogItem(dlg, 21, &itemtype, &itemH, &box);
			GetDialogItemText(itemH, text);
			strcpy(env->spfile_freqbname, PtoCstr(text));

			GetDialogItem(dlg, 23, &itemtype, &itemH, &box);
			GetDialogItemText(itemH, text);
			strcpy(env->spfile_realbname, PtoCstr(text));

			GetDialogItem(dlg, 25, &itemtype, &itemH, &box);
			GetDialogItemText(itemH, text);
			strcpy(env->spfile_imagbname, PtoCstr(text));
			
			GetDialogItem(dlg, 26, &itemtype, &itemH, &box);
			env->freqdup_flag = GetControlValue((ControlHandle)itemH);
			
			GetDialogItem(dlg, 28, &itemtype, &itemH, &box);
			GetDialogItemText(itemH, text);
			env->wave_startnum = atoi(PtoCstr(text));
			
			TDR_WriteEnv(env);
			break;
		}
		if(item == 26){ // check box
			GetDialogItem(dlg, 26, &itemtype, &itemH, &box);
			result = (GetControlValue((ControlHandle)itemH) + 1) % 2;
			SetControlValue((ControlHandle)itemH, result);
			env->freqdup_flag = result;
		}
		if(item == 29){ // check box
			GetDialogItem(dlg, 29, &itemtype, &itemH, &box);
			result = (GetControlValue((ControlHandle)itemH) + 1) % 2;
			SetControlValue((ControlHandle)itemH, result);
			env->numsave_flag = result;
		}

	}
	DisposeDialog(dlg);
	SetPort(cptr);
}

static void DrawDlgRect(Rect *r)
{
	PenState currpen;
	Pattern pat;
	
	GetPenState(&currpen);
	PenNormal();

	GetIndPattern(&pat, 0, 4);
	PenPat(&pat);	
	FrameRect(r);
	
	SetPenState(&currpen);
}

static void DrawDlgLine(Rect *r)
{
	PenState currpen;
	RGBColor currcol;
	
	GetPenState(&currpen);
	GetForeColor(&currcol);
	PenNormal();

	RGBForeColor(&PLOT_RGBs[PLOT_BLUE]);
	MoveTo(r->left+5, r->bottom-5);
	LineTo(r->right-5, r->bottom-5);
	
	RGBForeColor(&currcol);	
	SetPenState(&currpen);
}


void TDR_SetOPInfo(void)
{
	DialogPtr dlg;
	short itemtype, item;
	Rect box;
	Handle itemH;
	Str255 buf;
	char datastr[256];
	GrafPtr cptr;
	
	GetPort(&cptr);
	dlg = GetNewDialog(TDR_OPERATORDLG_ID, nil, (WindowPtr)-1);
	SetPort(dlg);
	
	// display information
	// operator name
	GetDialogItem(dlg, 3, &itemtype, &itemH, &box);
	strcpy(datastr, op_name);
	SetDialogItemText(itemH, C2PStr(datastr));
	// comment for measurement
	GetDialogItem(dlg, 5, &itemtype, &itemH, &box);
	strcpy(datastr, op_comment);
	SetDialogItemText(itemH, C2PStr(datastr));
	
	while(1){
		ModalDialog(0, &item);
		if(item == 1){		// OK button
			// get operator name
			GetDialogItem(dlg, 3, &itemtype, &itemH, &box);
			GetDialogItemText(itemH, buf);
			strcpy(op_name, P2CStr(buf));
			// get comment
			GetDialogItem(dlg, 5, &itemtype, &itemH, &box);
			GetDialogItemText(itemH, buf);
			strcpy(op_comment, P2CStr(buf));
			break;
		}
	}
	DisposeDialog(dlg);
	SetPort(cptr);
}

// for HP54750A
void TDR_SetTimebase(TDR_PARAMETER *pr)
{
	DialogPtr dlg;
	short itemtype, item;
	short result;
	char datastr[256];
	Rect box;
	Handle itemH;
	Str255 text;
	GrafPtr cptr;
	MenuHandle mh;
	short i;
	Boolean cancelled;
	
	GetPort(&cptr);
	dlg = GetNewDialog(TDR_TIMEBASEDLG_ID, nil, (WindowPtr)-1);
	SetPort(dlg);
	
	// set current value
	GetDialogItem(dlg, 3, &itemtype, &itemH, &box);
	sprintf(datastr, "%d", pr->timebase_points);
	SetDialogItemText(itemH, C2PStr(datastr));

	GetDialogItem(dlg, 5, &itemtype, &itemH, &box);
	sprintf(datastr, "%e", pr->timebase_lasttime);
	SetDialogItemText(itemH, C2PStr(datastr));

	InitCursor();
	
	while(1){
		ModalDialog(0, &item);
		if(item == 1){		// OK button
			// get No. of time axis
			GetDialogItem(dlg, 3, &itemtype, &itemH, &box);
			GetDialogItemText(itemH, text);
			pr->timebase_points = atoi(PtoCstr(text));		
			// get end time of reflected wave
			GetDialogItem(dlg, 5, &itemtype, &itemH, &box);
			GetDialogItemText(itemH, text);
			pr->timebase_lasttime = atof(PtoCstr(text));
			cancelled = false;		
			break;
		}
		if(item == 7){		// Cancel button
			cancelled = true;
			break;
		}
	}
	DisposeDialog(dlg);
	SetPort(cptr);
	
	if(cancelled == false){
		// make time axis
		if(pr->timebase_points >= 0.0 && pr->timebase_lasttime >= 0.0){
			for(i = 0 ; i < pr->timebase_points ; i++){
				*(TA + i) = pr->timebase_lasttime / (double)(pr->timebase_points) * (double)i;
			}
			/* and set dt */
			pr->dt = pr->timebase_lasttime / (double)(pr->timebase_points);
		}
		sprintf(datastr, ep.item[TDR_EDTI_N_TINTERVAL].format, pr->dt);
		EPSetContent(&ep, TDR_EDTI_N_TINTERVAL, datastr);

		// change display condition
		TDR_Setdispdata();
	}
}

