//////////////////////////////////////////////////////////////////////
// Filename:	KaplanMeier.OGS
// Purpose:		Event handlers for KaplanMeier dialog box
// Creation:	by GJL, 6/20/01
// Modification Log:
//////////////////////////////////////////////////////////////////////

[OnOpen]
	dialog.start(OStat.DLL,KaplanMeier,KaplanMeier.OPS);
	return 0;


[OnInit]
	define DocEnd {run.section(Origin.OGS,DocEnd);};
	%A="KaplanMeier!AvailableDataLBX";
	run.section(DBRoutines,PopLBXwNonTextData,"%A" "Survival");
	KaplanMeier!AvailableDataLBX.multSel=0;
	KaplanMeier!ConfidenceLevelEBX$=$(95/100,.2);
	KaplanMeier!TimeDataEBX$="";
	KaplanMeier!CensorDataEBX$="";
	KaplanMeier!CensorValueEBX$="";
	KaplanMeier!NotCensorValueEBX$="";
	KaplanMeier!AdvancedCHKBX=1;
	KaplanMeier!WorksheetCHKBX=0;
	KaplanMeier!PlotCHKBX=0;
	KaplanMeier!PlotErrorsCHKBX=0;
	return 0;

[ToolBar.AddTimeDataBTN.OnClick]
	run.section(,ToolBar.RemoveTimeDataBTN.OnClick);
	%A=KaplanMeier!AvailableDataLBX.v$(KaplanMeier!AvailableDataLBX.Choice)$;
	KaplanMeier!TimeDataEBX$=%A;
	KaplanMeier!AvailableDataLBX.Del(KaplanMeier!AvailableDataLBX.Choice);
	return 0;
	
[ToolBar.RemoveTimeDataBTN.OnClick]
	%A=KaplanMeier!TimeDataEBX$;
	if("%A"!="")
	{
		KaplanMeier!AvailableDataLBX.Add(%A);
		KaplanMeier!TimeDataEBX$="";
	}
	%A="KaplanMeier!AvailableDataLBX";
	run.section(DBRoutines,SortLBXorCMBX,"%A" "LBX");
	return 0;

[ToolBar.AddCensorDataBTN.OnClick]
	run.section(,ToolBar.RemoveCensorDataBTN.OnClick);
	%A=KaplanMeier!AvailableDataLBX.v$(KaplanMeier!AvailableDataLBX.Choice)$;
	KaplanMeier!CensorDataEBX$=%A;
	if("%A"=="")
		return 1;

	%B=$SurvivalAnalysis.NoCensorDataset;
	if(run.section(DBRoutines.OGS,CheckDatasetExists,"%B" %A)!=0)
	{
		run.section(,ToolBar.RemoveCensorDataBTN.OnClick);
		return 1;
	}

	/// GJL 4/11/02 QA70-1404 UPDATE_ORIGIN_FOR_EXCEL_WORKBOOK
	%B=%[%A,'_'];
	if(%B!page.extInfo==1) // If data set is in Excel workbook update Origin
	{
		win -o %B
		{
			layer -s;
			set %B -ui;
		}
	}
	/// GJL 4/11/02 QA70-1404 End UPDATE_ORIGIN_FOR_EXCEL_WORKBOOK

	get %A -e Cnpts;
	if(Cnpts<2)
	{
		run.section(DBRoutines.OGS,ReportError,$SurvivalAnalysis.TooFewDataPts);
		run.section(,ToolBar.RemoveCensorDataBTN.OnClick);
		return 1;
	}

	run.section(,CreateSurvivalWKS);
	if(run.section(,GetCensorValues)!=1)
		KaplanMeier!AvailableDataLBX.Del(KaplanMeier!AvailableDataLBX.Choice);

	KaplanMeier!CensorValueEBX$=%V;
	KaplanMeier!NotCensorValueEBX$=%W;

	return 0;

[CreateSurvivalWKS]
	create.wksName$="Survival";
	create.enumwks=1;
	create.template$="CREATE";
	create.numtypes=10;
	create.type1=4;
	loop(ii,2,10)
	{
		create.type$(ii)=1;
	}
	create.type7=4;
	create.wks(Time CENSOR Survival StdError SurLLim SurULim Percent Estimate PerLLim PerULim);
	%S=create.wksName$;
	loop(ii,1,10)
	{
		%S!wks.col$(ii).width=10;
	}
	%S!wks.labels(0);
	return 0;

[GetCensorValues]
	%S_CENSOR=data(1,1,Cnpts);
	%W="";
	%V=%A[1]$;
	loop(ii,2,Cnpts)
	{
		%B=%A[ii]$;
		if("%B"!="%V")
		{
			%W=%B;
			%S_CENSOR[ii]=0;
			break;
		}
	}
	loop(jj,ii,Cnpts)
	{
		%B=%A[jj]$;
		if("%B"=="%V")
			continue;
		else if("%B"=="%W")
		{
			%S_CENSOR[jj]=0;
			continue;
		}
		else
		{
			run.section(DBRoutines.OGS,ReportError,$SurvivalAnalysis.OneTwoCensorValues);
			run.section(,ToolBar.RemoveCensorDataBTN.OnClick);
			return 1;
		}
	}
	/// GJL 5/06/02 QA70-1691 SUPPORT_NO_CENSORED_ITEMS
	if("%W"=="")
	{
		if(%[%V])
			%W="--";
		else
		{
			run.section(DBRoutines.OGS,ReportError,$SurvivalAnalysis.OneTwoCensorValues);
			run.section(,ToolBar.RemoveCensorDataBTN.OnClick);
			return 1;
		}
	}
	/// GJL 5/06/02 QA70-1691 End SUPPORT_NO_CENSORED_ITEMS
	return 0;

[ToolBar.RemoveCensorDataBTN.OnClick]
	%A=KaplanMeier!CensorDataEBX$;
	if("%A"!="")
		KaplanMeier!AvailableDataLBX.Add(%A);
	KaplanMeier!CensorDataEBX$="";
	KaplanMeier!CensorValueEBX$="";
	KaplanMeier!NotCensorValueEBX$="";
	%V="";
	%W="";
	if(exist(%S)==2)
		win -cd %S;
	%A="KaplanMeier!AvailableDataLBX";
	run.section(DBRoutines,SortLBXorCMBX,"%A" "LBX");
	return 0;

[ToggleCensorValueBTN.OnClick]
	%V=KaplanMeier!CensorValueEBX$;
	KaplanMeier!CensorValueEBX$=KaplanMeier!NotCensorValueEBX$;
	KaplanMeier!NotCensorValueEBX$=%V;
	if(exist(%S_CENSOR)==1)
		%S_CENSOR=mod(%S_CENSOR+1,2);	
	return 0;

[ComputeBTN.OnClick]
	run.section(DBRoutines.OGS,SaveAndSetAtOC);
	if(run.section(,CheckSettings)==0)
	{
		run.section(,OpenAndDirectOutputToResultsLog);
		run.section(,KaplanMeier);
		run.section(,CloseAndRedirectOutput);
		run.section(,CleanUp);
	}
	run.section(DBRoutines.OGS,RestoreAtOC);
	return 0;

[CheckSettings]
	%A=KaplanMeier!ConfidenceLevelEBX.v1$;	
	%B=$SurvivalAnalysis.ConLevelGT0LT1;
	if(run.section(DBRoutines.OGS,CheckSingleNumericGTandLT,"%B" 0 1 %A)!=0)
		return 1;
	ConLevel=%A;
	
	%A=KaplanMeier!CensorDataEBX$;	
	%B=$SurvivalAnalysis.NoCensorDataset;
	if(exist(%S_CENSOR)!=1)
	{
		if(exist(%S)==2)
			win -cd %S;
		run.section(,RecreateSurvivalWKS);
	}
	if(run.section(DBRoutines.OGS,CheckDatasetExists,"%B" "%S_CENSOR")!=0)
		return 1;
	/// GJL 4/11/02 QA70-1404 UPDATE_ORIGIN_FOR_EXCEL_WORKBOOK
	%B=%[%A,'_'];
	if(%B!page.extInfo==1) // If data set is in Excel workbook update Origin
	{
		win -o %B
		{
			layer -s;
			set %B -ui;
		}
	}
	/// GJL 4/11/02 QA70-1404 End UPDATE_ORIGIN_FOR_EXCEL_WORKBOOK
	get %A -e Cnpts;
	
	%A=KaplanMeier!TimeDataEBX$;
	%B=$SurvivalAnalysis.NoTimeDataset;
	if(run.section(DBRoutines.OGS,CheckDatasetExists,"%B" %A)!=0)
		return 1;
	/// GJL 4/11/02 QA70-1404 UPDATE_ORIGIN_FOR_EXCEL_WORKBOOK
	%B=%[%A,'_'];
	if(%B!page.extInfo==1) // If data set is in Excel workbook update Origin
	{
		win -o %B
		{
			layer -s;
			set %B -ui;
		}
	}
	/// GJL 4/11/02 QA70-1404 End UPDATE_ORIGIN_FOR_EXCEL_WORKBOOK
	get %A -e Tnpts;

	if(Tnpts!=Cnpts)
	{
		run.section(DBRoutines.OGS,ReportError,$SurvivalAnalysis.DataPtsNotSame);
		return 1;
	}	
	
	%S_Time=treplace(%A,0,0,2);    // This makes masked values become missing values 
                                   //  when copying the current dataset to %S_Time where as 
                                   //  vector assignment does not handle masking	
	run.section(,SortSurvivalWKS);
	run.section(,RemoveMissingAndMaskedTimeValues);
	
	%B=$SurvivalAnalysis.NoTimeDataset;
	if(run.section(DBRoutines.OGS,CheckDatasetExists,"%B" "%S_Time")!=0)
		return 1;

	get %S_Time -e Tnpts;
	get %S_CENSOR -e Cnpts;
	if(Tnpts!=Cnpts)
	{
		run.section(DBRoutines.OGS,ReportError,$SurvivalAnalysis.DataPtsNotSame);
		return 1;
	}
	
	run.section(,AskOutputSAFunction);
	Results=Results +
	        KaplanMeier!WorksheetCHKBX*2 +
	        KaplanMeier!PlotCHKBX*4 +
	        KaplanMeier!PlotCHKBX*KaplanMeier!PlotErrorsCHKBX*8;
	        
	if(run.section(DBRoutines.OGS,LoadSurvivalAnalysisWorkspace)!=0)
		return 1;
	
	return 0;

[SortSurvivalWKS]
	get %S_Time -e Tnpts;
	sort.wksName$=%S;
	sort.cname1$="A: Time";
	sort.missing=1; // Treat missing values as largest number for removal with set -e command 
	sort.c1=1;
	sort.c2=2;
	sort.r1=1;
	sort.r2=Tnpts;
	sort.wks();
	return 0;

[RemoveMissingAndMaskedTimeValues]
	get %S_Time -e Tnpts;
	sum(%S_Time);
	nMissingVals=Tnpts-sum.n;
	if(nMissingVals)
		set %S -e sum.n;
	return 0;	

[AskOutputSAFunction]
	get %S_CENSOR -e Cnpts;
	if(KaplanMeier!AdvancedCHKBX==1 && Cnpts>300)
	{
		Results=0;
		Type -n $SurvivalAnalysis.AskOutputSAFunction; // Break here on command error if anser is No
	}
	Results=KaplanMeier!AdvancedCHKBX;
	return 0;

[OpenAndDirectOutputToResultsLog]	
	SaveRedirection=type.Redirection(16,3);	// SDB 1/7/99 v6.0148 REPORT_TO_OUTPUTLOG
	%A=KaplanMeier!TimeDataEBX$;
	%B=%[%A,'_'];
	win -o %B {type.BeginResults()}; // RKM 12/10/98 v6.0141 REPORT_TO_OUTPUTLOG
	return 0;

[KaplanMeier]
	ii=saKaplanMeier(Cnpts,Results,ConLevel,%S);
	if(ii!=0)
	{
		run.section(DBRoutines.OGS,ReportError,$SurvivalAnalysis.KaplanMeierError);
		if(exist(%S)==2)
			win -cd %S;
		run.section(,RecreateSurvivalWKS);
		return ii;
	}
	if(Results>1)									// Finish Worksheet
	{
		run.section(,FinishSurvivalWks);
		if(Results&2)								// Show worksheet
			win -a %S;
		if(Results&4)								// Create Plot
		{
			%L=%H;
			run.section(,MakeSurvivalPlot);
			if(Results&8)							// Add Errrs to Plot
				run.section(,AddErrorsToSurvivalPlot);
			win -a %L;
		}
	}
	else
	{
		if(exist(%S)==2)
			win -cd %S;
	}
	run.section(,RecreateSurvivalWKS);
	dialog.SaveSettingsToOPS(OStat.DLL,KaplanMeier);
	return 0;

[FinishSurvivalWks]
	delete %S_CENSOR;
	%B=$SurvivalAnalysis.KMEstimator;
	%A=KaplanMeier!TimeDataEBX$;
	%B=%B %A;
	%A=KaplanMeier!CensorDataEBX$;
	%B=%B, %A;
	%A=$SurvivalAnalysis.CensorValue;
	%B=%B, %A;
	%A=KaplanMeier!CensorValueEBX$;
	%B=%B%A;
	%S!page.label$=%B;
	%S!page.title=3;
	return 0;

[MakeSurvivalPlot]
	doc -cp SurvivalPlot;
	for(ii=count+1;0<1;ii++)
	{
		%B=SurvivalPlot$(ii);
		if(exist(%B)!=3)
		{
			win -t plot SurvivalKM %B;
			break;
		}
	}
	win -a %B;
	%A=$SurvivalAnalysis.KMEstimator;
	page.label$=%A %S;
	page.title=3;
	layer -i %S_Survival;
	layer -at; // layer.x.rescaleMargin=2 stored in template
	layer.x.to=110*layer.x.to/102; // make right Y axis have 10% margin
	return 0;

[AddErrorsToSurvivalPlot]
	win -a %B;
	layer -i %S_SurLLim;
	layer -i %S_SurULim;
	layer -at; // layer.x.rescaleMargin=2 stored in template
	layer.x.to=110*layer.x.to/102; // make right Y axis have 10% margin
	%A=Key.text$;
	%B=$SurvivalAnalysis.ConfidenceBand;
	%A=%A
\L(2) %B; 
	key.text$=%A;
	return 0;

[RecreateSurvivalWKS]
	%S="";
	%A=KaplanMeier!CensorDataEBX$;
	get %A -e Cnpts;
	run.section(,CreateSurvivalWKS);
	run.section(,GetCensorValues);
	%W=KaplanMeier!CensorValueEBX$;
	if("%V"!="%W")
		%S_CENSOR=mod(%S_CENSOR+1,2);	
	return 0;

[CloseAndRedirectOutput]
	type.EndResults();
	type.Redirection=SaveRedirection; // restore previous redirection.
	return 0;

[OnCancel]
	if(exist(%S_CENSOR)==1)
		win -cd %S;
	%S="";
	run.section(,CleanUp);
	return 0;

[CleanUp]
	delete -v nMissingVals;
	delete -v count;
	delete -v ConLevel;
	delete -v Results;
	delete -v SaveRedirection;
	delete -v Cnpts;
	delete -v Tnpts;
	delete -v ii;
	delete -v jj;
	%A="";%B="";%L="";
	%V="";%W="";
	return 0;