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

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

[OnInit]
	define DocEnd {run.section(Origin.OGS,DocEnd);};
	%A="CoxPHM!AvailableDataLBX";
	run.section(DBRoutines,PopLBXwNonTextData,"%A" "Survival");
	CoxPHM!AvailableDataLBX.multSel=2;
	CoxPHM!TimeDataEBX$="";
	CoxPHM!CensorDataEBX$="";
	CoxPHM!CovariatesLBX.reset();
	CoxPHM!CovariatesLBX.multsel=2;
	CoxPHM!CensorValueEBX$="";
	CoxPHM!NotCensorValueEBX$="";
	CoxPHM!AdvancedCHKBX=1;
	CoxPHM!WorksheetCHKBX=0;
	CoxPHM!PlotCHKBX=0;
	return 0;

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

[ToolBar.AddCensorDataBTN.OnClick]
	run.section(,ToolBar.RemoveCensorDataBTN.OnClick);
	%A=CoxPHM!AvailableDataLBX.v$(CoxPHM!AvailableDataLBX.Choice)$;
	CoxPHM!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)
		CoxPHM!AvailableDataLBX.Del(CoxPHM!AvailableDataLBX.Choice);

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

	return 0;

[CreateSurvivalWKS]
	create.wksName$="Survival";
	create.enumwks=1;
	create.template$="CREATE";
	create.numtypes=9;
	create.type1=4;
	loop(ii,2,9)
	{
		create.type$(ii)=1;
	}
	create.wks(Time CENSOR Survival Covariate ParamEst StdError ChiSq PValue Hazard);
	%T=create.wksName$;
	loop(ii,1,9)
	{
		%T!wks.col$(ii).width=10;
	}
	%T!wks.col4.width=25;
	%T!wks.labels(0);
	return 0;

[GetCensorValues]
	%T_CENSOR=data(1,1,Cnpts);
	%W="";
	%V=%A[1]$;
	loop(ii,2,Cnpts)
	{
		%B=%A[ii]$;
		if("%B"!="%V")
		{
			%W=%B;
			%T_CENSOR[ii]=0;
			break;
		}
	}
	loop(jj,ii,Cnpts)
	{
		%B=%A[jj]$;
		if("%B"=="%V")
			continue;
		else if("%B"=="%W")
		{
			%T_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=CoxPHM!CensorDataEBX$;
	if("%A"!="")
		CoxPHM!AvailableDataLBX.Add(%A);
	CoxPHM!CensorDataEBX$="";
	CoxPHM!CensorValueEBX$="";
	CoxPHM!NotCensorValueEBX$="";
	%V="";
	%W="";
	if(exist(%T)==2)
		win -cd %T;
	%A="CoxPHM!AvailableDataLBX";
	run.section(DBRoutines,SortLBXorCMBX,"%A" "LBX");
	return 0;

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

[ToolBar.AddCovariatesBTN.OnClick]
	CoxPHM!CovariatesLBX.MoveSel(CoxPHM!AvailableDataLBX);
	return 0;
	
[ToolBar.RemoveCovariatesBTN.OnClick]
	CoxPHM!AvailableDataLBX.MoveSel(CoxPHM!CovariatesLBX);
	%A="CoxPHM!AvailableDataLBX";
	run.section(DBRoutines,SortLBXorCMBX,"%A" "LBX");
	return 0;

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

[CheckSettings]
	%A=CoxPHM!CensorDataEBX$;	
	%B=$SurvivalAnalysis.NoCensorDataset;
	if(exist(%T_CENSOR)!=1)
	{
		if(exist(%T)==2)
			win -cd %T;
		run.section(,RecreateSurvivalWKS);
	}
	if(run.section(DBRoutines.OGS,CheckDatasetExists,"%B" "%T_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=CoxPHM!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;
	}

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

	get %T_CENSOR -e Cnpts;
	get %T_Time -e Tnpts;
	if(Tnpts!=Cnpts)
	{
		run.section(DBRoutines.OGS,ReportError,$SurvivalAnalysis.DataPtsNotSame);
		return 1;
	}

	numCovars=CoxPHM!CovariatesLBX.numItems;
	if(numCovars<1)
	{
		run.section(DBRoutines.OGS,ReportError,$SurvivalAnalysis.TooFewCovariates);
		return 1;
	}

	// Loop on all Covariates copying to temporary worksheet %T and checking existence and npts 
	loop(ii,1,numCovars)
	{
		%A=CoxPHM!CovariatesLBX.V$(ii)$;
		%B=$SurvivalAnalysis.NoCovariateData;
		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 COVnpts;
		if(COVnpts!=Cnpts)
		{
			run.section(DBRoutines.OGS,ReportError,$SurvivalAnalysis.COVDataPtsNotSame);
			return 1;
		}
		%U=COVAR$(ii);
		%T!wks.col=2+ii;
		%T!wks.insert(%U);
		%T!wks.col$(2+ii).width=10;		
		%T_%U=treplace(%A,0,0,2);    // This makes masked values become missing values 
                                     //  when copying the %A dataset to %T_%U where as 
                                     //  vector assignment does not handle masking
        %B=$SurvivalAnalysis.NoCovariateData;
		if(run.section(DBRoutines.OGS,CheckDatasetExists,"%B" "%T_%U")!=0)
			return 1;
	}
	
	// Loop on all Covariates again removing masked and missing values with set -e command 
	nMissingVals=0; // Count rows of paired data removed due to missing values
	loop(ii,1,numCovars)
	{
		%U=COVAR$(ii);
		run.section(,SortSurvivalWKS); // Sort temporary worksheet on %U putting missing values at bottom of worksheet
		run.section(,RemoveMissingAndMaskedValues); // Remove rows containing missing and masked values from temporary worksheet 
	}	

	// Remove masked and missing values in Time column  
	%U="Time";	
	run.section(,SortSurvivalWKS);
	run.section(,RemoveMissingAndMaskedValues);
	
	// Check again after removing missing value rows
	get %T_CENSOR -e Cnpts;
	get %T_Time -e Tnpts;
	if(Tnpts!=Cnpts)
	{
		run.section(DBRoutines.OGS,ReportError,$SurvivalAnalysis.DataPtsNotSame);
		return 1;
	}
	
	run.section(,AskOutputSAFunction);
	Results=Results +
	        CoxPHM!WorksheetCHKBX*2 +
	        CoxPHM!PlotCHKBX*4;
	        
	if(run.section(DBRoutines.OGS,LoadSurvivalAnalysisWorkspace)!=0)
		return 1;

	return 0;

[SortSurvivalWKS]
	get %T_%U -e npts;
	sort.wksName$=%T;
	sort.cname1$="A: %U";
	sort.missing=1; // Put missing values at bottom of worksheet
	sort.c1=1;
	sort.c2=2+numCovars;
	sort.r1=1;
	sort.r2=npts;
	sort.wks();
	return 0;

[RemoveMissingAndMaskedValues]
	get %T_%U -e npts;
	sum(%T_%U);
	if(npts-sum.n)
	{
		nMissingVals+=(npts-sum.n);
		set %T -e sum.n;
	}
	return 0;

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

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

[CoxPHM]
	ii=saCoxPHM(Cnpts,numCovars,Results,%T);
	if(ii!=0)
	{
		run.section(DBRoutines.OGS,ReportError,$SurvivalAnalysis.CoxPHMError);
		if(exist(%T)==2)
			win -cd %T;
		run.section(,RecreateSurvivalWKS);
		return ii;
	}
	if(Results>1)									// Finish Worksheet
	{
		run.section(,FinishSurvivalWks);
		if(Results&2)								// Show worksheet
			win -a %T;
		if(Results&4)								// Create Plot
		{
			%L=%H;
			run.section(,MakeSurvivalPlot);
			win -a %L;
		}
	}
	else
	{
		if(exist(%T)==2)
			win -cd %T;
	}
	run.section(,RecreateSurvivalWKS);
	dialog.SaveSettingsToOPS(OStat.DLL,CoxPHM);
	return 0;

[FinishSurvivalWks]
	loop(ii,2,2+numCovars)
	{
		%A=%T!wks.col2.name$;
		delete %T_%A;
	}
	%B=$SurvivalAnalysis.CoxPHMModel;
	%A=CoxPHM!TimeDataEBX$;
	%B=%B %A;
	%A=CoxPHM!CensorDataEBX$;
	%B=%B, %A;
	%A=$SurvivalAnalysis.CensorValue;
	%B=%B, %A;	
	%A=CoxPHM!CensorValueEBX$;
	%B=%B%A;
	%T!wks.col3.type=4;
	%T!wks.col3.format=2;
	%T!page.label$=%B;
	%T!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 SurvivalCOX %B;
			break;
		}
	}
	win -a %B;
	%A=$SurvivalAnalysis.CoxPHMModel;
	page.label$=%A %T;
	page.title=3;
	layer -i %T_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;

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

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

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

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