// Filename:    TEMPLATE.OGS
// Creation:    by Joe Przechocki, 3/31/97
// Purpose:     Modularized Code for performing template routines
// Modifications:
//
// CPY v6.0135 11/8/98 t4354 WKS_COL_SEL_CMD_FIX to apply to col stats
/// SFX 3/23/99 v6.0176 t5712 QC_LOSES_DROPLINE_WHEN_REDRAWING
//	CPY v6.0291 t5913 6/19/00 UIM_OBJ_NAMES_IGNORE_NONE_ALPHANUMERIC
//	CPY v6.1030 t8410 8/18/00 NO_X_COL_STAT_EMPTY, add limit -s to ignore plotting relations
//	JCG 06/11/2002 tQA70-1671 v7.0317 TABLE_VALUE_QCD2_PLUS_N<2_OR_N>25_ISSUE
// GJL 8/5/02 ER7.0360 QA2356 ADD_COEFFICENT_OF_VARIATION
// JCG 08/15/2002 tQA70-1671 v7.0372 ADD_CONDITION_TO_CHECK_SUBGROUP_SIZE
// SDB 07/28/2003 ER7.0635 QA4907 RESET_RANGE_AFTER_CALCULATION
// SDB 09/18/2003 ER7.5699 QA5196 SET_RANGE_FOR_STAT_ON_COLUMNS
// SDB 04/5/2004 ER7.5851 QA5855 ADD_POLAR_SCRIPT_TO_OGS
// Echo 7/12/07 ASSOCIATE_DATASET_TO_SHEET

[Function]
	/////////////////////////////////////////////////////////////////////
	// FUNCTION.OTP
	/////////////////////////////////////////////////////////////////////
	switch(index) 
	{
	case 1:
		;{	//Need semicolon to delay executing following codes till current script finished
			NewFunction;
		}	 	
		break;
	case 2:
		%B=%C;
		GetStr -s $Template.FunctionNewName %B;
		set %C -n %B;
		clr;
		break;
	case 3:
		layer -c;
		;{	//Need semicolon to delay executing following codes till current script finished
			page -T %1;
			layer -i;
			layer -i %Z;
			queue {layer -a};	//Need to queue rescale because function must be included before Origin knows ranges
		}
		break;
	case 4:
		layer -all ask;
	}
	return 0;

[Waterfal]
	switch(index)
	{
	case 1:
		layer -y ?;
		%A=$waterfal.EnableDisable;
		getn $waterfal.XYoffset i:A $waterfal.totalY y $waterfal.totalX x;
		if (i==1) {layer -y $(x),$(y)} else {layer -y !$(x),$(y)};
		break;
	case 2:
		layer -r;
		break;
	case 3:
		get %(1,@D) -cf ii;	//Check fill color setting
		get %(1,@D) -pf jj;	//Check fill enable/disable
		get %(1,@D) -ss v1;
		ii=ii<=0||ii==(0/0)?1:ii;
		getn 
		$Waterfal.AskFill jj:2
		$Waterfal.AskColor ii:@C 
		$Waterfal.AskLines v1:2;
	
		doc -e data 
		{
			set %C -cf ii;
			set %C -pf jj;
			set %C -ss v1;
		};
	
		break;
	}	
	return 0;

[Colstat]
	//--------------- CPY v6.0135 11/8/98 t4354 WKS_COL_SEL_CMD_FIX
	//
	%W=store.v1$;
	if(exist(%W)!=2)
	{
		type -b $WksStat.NoWks;
		return 1;
	}
	win -o %W {doc -uw};
	if(exist(%H_CIL)==1)
		delete %H_CIL;
	if(exist(%H_CIU)==1)
		delete %H_CIU;
	if(exist(%H_P25)==1)
		delete %H_P25;
	if(exist(%H_P75)==1)
		delete %H_P75;
	if(exist(%H_IQR)==1)
		delete %H_IQR;
	if(exist(%H_Median)==1)
		delete %H_Median;
	if(exist(%H_VAR)==1)
		delete %H_VAR;
	if(exist(%H_CoefVar)==1) // GJL 8/5/02 ER7.0360 QA2356 ADD_COEFFICENT_OF_VARIATION
		delete %H_CoefVar;
	if(exist(%H_Kurt)==1)
		delete %H_Kurt;
	for(ii=1;ii<=wks.ncols;ii+=1)
	{
		%A=wks.col$(ii).name$;
		if(%[%A,1:1]=="P")
			delete col($(ii));
	}
 
	if(Advanced.v1!=0)
	{
		wks.col=colnum(se)+1;
		wks.insert(CIL CIU P25 P75 IQR P$(percentile.v1));
		wks.col=colnum(sum)+1;
		wks.insert(Median Var CoefVar Kurt); // GJL 8/5/02 ER7.0360 QA2356 ADD_COEFFICENT_OF_VARIATION
		wks.col$(colnum(CIL)).label$=$Statistics.LCL;
		wks.col$(colnum(CIU)).label$=$Statistics.UCL;
		wks.col$(colnum(P25)).label$=$Statistics.Percentile25;
		wks.col$(colnum(P75)).label$=$Statistics.Percentile75;
		wks.col$(colnum(IQR)).label$=$Statistics.IQR;
		wks.col$(colnum(P$($(percentile.v1)))).label$=$Statistics.PercentileN;
		wks.col$(colnum(Median)).label$=$Statistics.Median;
 		wks.col$(colnum(VAR)).label$=$Statistics.Variance;
 		wks.col$(colnum(CoefVar)).label$=$Statistics.CoefVariance; // GJL 8/5/02 ER7.0360 QA2356 ADD_COEFFICENT_OF_VARIATION		
		wks.col$(colnum(Kurt)).label$=$Statistics.Kurtosis;
	}

	get %(%H,1) -e jj;		
	type -qp 0;/* internal i= msg off*/
	loop(ii,1,jj)
	{
		stat.reset();
		%A=%(%H,1,ii);
		%B=%(%H,2,ii);
		if(exist(%W_%A)!=1)
		{
			type -b $General.ColumnError;
			continue;
		}
		if(%B[ii]==0/0)
		{
			get %W_%A -b bd;
			get %W_%A -e ed;
			wcol(2)[ii]$="[$(bd):$(ed)]";
		}
		// SDB 07/28/2003 ER7.0635 QA4907 RESET_RANGE_AFTER_CALCULATION
		// SDB 09/18/2003 ER7.5699 QA5196 SET_RANGE_FOR_STAT_ON_COLUMNS
		//get %W_%A -b svBegData;
		//get %W_%A -e svEndData;
		if(Range.Choice==1)
		{
			get %W_%A -b bd;
			get %W_%A -e ed;
			wcol(2)[ii]$ = "[$(bd):$(ed)]";
			doc -uw;
		}
		else
		{
			bd=%[%B,":"];
			ed=%[%B,>":"];
		}
		if(ed<bd)
			continue;
		set %W_%A -bs bd;
		set %W_%A -es ed;
		stat.ds.more=1;
		stat.ds.data$=%W_%A;
		limit -s %W_%A;
		stat.ds.conflev=.95;
		stat.ds.interpolate=system.graph.percinterp;
		stat.ds();
		// SDB 07/28/2003 ER7.0635 QA4907 RESET_RANGE_AFTER_CALCULATION
		// SDB 09/18/2003 ER7.5699 QA5196 SET_RANGE_FOR_STAT_ON_COLUMNS
		//set %W_%A -b svBegData;
		//set %W_%A -e svEndData;
		col(mean)[ii] = stat.ds.mean;
		col(sd)[ii] = stat.ds.sd;
		col(se)[ii] = stat.ds.se;
		col(min)[ii] = stat.ds.min;
		col(imin)[ii] = limit.imin;
		col(max)[ii] = stat.ds.max;
		col(imax)[ii] = limit.imax;
		col(range)[ii] = stat.ds.range;
		col(n)[ii] = stat.ds.size;
		col(sum)[ii] = stat.ds.sum;
		if(Advanced.v1!=0)
		{
			stat.ds.more=1;
			col(CIL)[ii]=stat.ds.cil;
			col(CIU)[ii]=stat.ds.ciu;
			col(P25)[ii]=stat.ds.quartl25;
			col(P75)[ii]=stat.ds.quartl75;
			col(IQR)[ii] = col(P75)[ii] - col(P25)[ii];
			stat.ds.percent=percentile.v1;
			stat.ds.interpolate=system.graph.percinterp;
			stat.ds();
			col(p$(percentile.v1))[ii]=stat.ds.percentile;
			col(median)[ii] = stat.ds.median;
			col(var)[ii] = stat.ds.var;
			col(CoefVar)[ii] = stat.ds.sd / stat.ds.mean; // GJL 8/5/02 ER7.0360 QA2356 ADD_COEFFICENT_OF_VARIATION	
			col(kurt)[ii] = stat.ds.kurt;
		};
	}
	StatLabel.text$=$WksStat.StatLabel;
	type -qp 1;/* restore internal i= msg */
	delete -v bd;
	delete -v ed;

/////////////////////////////////////////////////////////////////////
//  QC chart begin
/////////////////////////////////////////////////////////////////////

[QC]
	%W=qc.worksheet$;
	
	///Echo 7/12/07 ASSOCIATE_DATASET_TO_SHEET
	//%B=%(%W,qc.WksCol1);	
	range r = [%W]%(wksheet$)!$(qc.WksCol1);
	int nVal = range2uid([r]);
	%B=uid2name(nVal)$;
	///END ASSOCIATE_DATASET_TO_SHEET
	
	set %H -e 0;
	
	if(qc.WksCol2 == qc.WksCol1)
	{
		col(mean)=ave(%B,qc.groupsize);
	}
	else
	{
		sum(%W,qc.WksCol1,qc.WksCol2);
		/* stat results in 
		 * _MEAN, _SD, _MAX, _MIN, _RANGE, _NPTS
		 */
		qc.groupsize=qc.WksCol2-qc.WksCol1+1;
		col(Mean)=_MEAN;
	};
	
	col(R) = _Range;
	col(Sigma)=_SD;
	col(R)=col(mean)==0/0?0/0:col(R);
	col(Sigma)=col(mean)==0/0?0/0:col(Sigma);
	
	%W=%H;
	%B=qc.plot$;
	
	if(exist(%B,3))
	{
		win -a %B;page.active=1;win -e;page.active=2;win -e
	}
	else
	{
		GetEnumWin XbarR;
		%W!qc.plot$=%H;
	};

	page.active=2;/* choose layer 2 */
	
	QCupdate.worksheet$=%W;
	queue {doc -uw};
	QCupdate.run();

[QCUpdate]
	/* Assume QC object in worksheet and column mean, R
	 * QC.groupSize, QC.NumSigma
	 */
	/* layer 2 is the layer that contain this obj */

	%W=qcupdate.worksheet$;/* worksheet name that contains the mean and R data and QC obj */
	win -o %W
	{
		sum(col(mean));
		x = sum.mean;
		sum(col(R));
		get col(R) -e ii;
		y = sum.mean;
		if(qc.WksCol2>qc.WksCol1)
		{
			%A="$(qc.WksCol1)-$(qc.WksCol2)";
		}
	else
	{
		%A="$(qc.WksCol1)";
	}
	};
	
	qcupdate.columns$=%A;  //was qcupdate.column(s)$=%A; CPY v6.0291 t5913 6/19/00
	qcupdate.XBar=x;
	qcupdate.RBar=y;
	qcupdate.NumPoints=ii;
	
	x=%W!qc.groupsize;

	qcupdate.Sigma=qcupdate.Rbar/(QCd2(x) * sqrt(x));
	y=(%W!qc.NumSigma+1) * qcupdate.Sigma * 1.2;/* axis limits */
	x=qcupdate.xBar;

	/* layer 2 */
	layer -w %W 1 0 1 0 201;
	/// SFX 3/23/99 v6.0176 t5712 QC_LOSES_DROPLINE_WHEN_REDRAWING
	set %C -lv 1;
	/// end QC_LOSES_DROPLINE_WHEN_REDRAWING
	/* 
	 * 202 is line/symbol graph
	 */
	y1 = x - y;/* set axes limits */
	y2 = x + y;

	count = qcupdate.NumPoints;
	y=qcupdate.Rbar;
	x=%W!qc.groupSize;
	
	// JCG 08/15/2002 tQA70-1671 v7.0372 ADD_CONDITION_TO_CHECK_SUBGROUP_SIZE
	/// JCG 06/11/2002 tQA70-1671 v7.0317 TABLE_VALUE_QCD2_PLUS_N<2_OR_N>25_ISSUE
	//	type -b $Statistics.NLimitsAtt;
	/// end TABLE_VALUE_QCD2_PLUS_N<2_OR_N>25_ISSUE
	if(x < 2 || x > 25 )
		type -b $Statistics.NLimitsAtt;
	// end ADD_CONDITION_TO_CHECK_SUBGROUP_SIZE

	layer -o 1
	{
	/* layer 1 is the bottom layer in this template */
		layer -i203 %W_R;
		/* column graph */
		y1=0;x1=0;x2= 1 + count;

		UCL=QCD4(x) * y;
		LCL=QCD3(x) * y;

		y2 = 1.5 * UCL;
		/* the QCLines macro assume UCL and LCL */
		QCLines y;
	};
	qcupdate.RangeUCL=UCL;
	qcupdate.RangeLCL=LCL;

	/* we delay drawing the labels because
	 * we want to have the correct position
	 * set by layer 1
	 */
	x = qcupdate.Xbar;
	y = %W!qc.NumSigma*qcupdate.Sigma;
	
	UCL=x+y;
	LCL=x-y;
	QCLines qcupdate.Xbar;
	qcupdate.UpperControlLimit=UCL;
	qcupdate.LowerControlLimit=LCL;

/////////////////////////////////////////////////////////////////////
//  QC chart end
/////////////////////////////////////////////////////////////////////


/////////////////////////////////////////////////////////////////////
//  Histogram begin
/////////////////////////////////////////////////////////////////////

[Hist]
	/* script for histbut in histogram worksheet window */
	/* assume wks name is in %W */
	store.v1$=%W;	/* orig wks name */
	store.v2$=%H;	/* bin wks name */
	

	store.v1 = %w!wks.c1;
	store.v2 = %w!wks.c2;
	/* to store selection range in Status Object:store */

	%B=%H;
	store.v3=1.11;	/* first time */
	label -s -n title "Frequency counts for %W";
	win -o %W
	{
		tot=wks.c2-wks.c1+1;
		if (tot>20){type -b $Template.Hist20col;};
		for (ij=1;ij<=tot;ij+=1)
		{
			j=wks.c2-tot+ij;
        		%A=%(%W,@C,j);
			sum(col(%A));
			%B!mean.v$(ij)=sum.mean;	/* assign the variables */
			%B!sd.v$(ij)=sum.sd;
			%B!mins.v$(ij)=sum.min;
			%B!maxs.v$(ij)=sum.max;
			%B!n.v$(ij)=sum.n;
	/* We need to find the overall maximum and minimum */
			if (j==wks.c1){min=sum.min;max=sum.max};
			if (sum.min<min){min=sum.min};
			if (sum.max>max){max=sum.max};
		};
		i = nint(sqrt(sum.n));
		limit -r min max i inc; /* smooths the max/min values*/
		min-=inc/2;/* extend half unit outside */
		max+=inc/2;
	};

	GetNumber 
	$Template.HistMin min 
	$Template.HistMax max 
	$Template.HistStep inc 
	$Template.HistCount;
	run.section(,Calc);
	if (page.nlayers==1)
	{
		gauslay.enable=0;	//Don't allow the user to change the layers, since there is only one
	}
	else
	{
		gauslay.max=page.nlayers;
	}
[Calc]
	/* script for calcbut in histogram worksheet */
	%W=store.v1$;		/* orig wks name */
	first=store.v3;		/* first time? */
	fcol = store.v1;
	scol = store.v2;

	/* to read in selection range stored in Status Oject:store */

	/* If it is the first time through some calcuations *
	 * need to be performed that don't need to be *
	* done for recalculation */
	col(1)=data(min+0.5*inc,max+0.5*inc,inc);
	/*  X column for the new worksheet. Note that this must
	 *  be done before the sum function is called again.
	 *  Also, this actually may create one more point than
	 * is needed.
	 */
	for(i=fcol;i<=scol;i+=1)
	{
		%A=%(%W,@C,i);
	 	worksheet -v %A;
 		col(%A)=histogram(%(%W,@D,i),inc,min,max);
	};
	ncols = scol - fcol + 1;
	%W=store.v2$; 		/* store bin wks name */
	if (first!=1.11){run.section(,Replot);break 1;};
	store.v3=0.00;

	win -T Plot Histgm %HPlot;

	doc -cl %H;/* count number of layers, result in count */

	if(count > nCols)
	{
		repeat (count - nCols) (layer -s (nCols+1);layer -d)
	}	
	else
	{
		if( nCols > count)
		{
			repeat (nCols - count) (layer -n;plot -L)
		}
	};
	doc -cl %H;
	CheckMargins;/* see def in Page.CNF */
	if (count<=8){ArrangeLayers nCols 1};
	if (count>8)
	{
		type -b $Template.HistArrange;
	};

	for(i=1,j=2;i<=nCols;i+=1,j+=1)
	{
		layer -s i;
	 	%A=%(%W,@C,j);
		layer -i203 %W_%A;rescale;
	};
	layer -s 1;
	bin.v1$=%w;		/* store bin window name */
	%W!store.v3$=%H;	/* store plot window name */
	%B=%W!store.v1$;
	bin.v2$=%B;		/* store orig wks name */ 
	%B=bin.v1$;/* get worksheet name */
	bin.v3$=%H;
	v1=min;v2=max;v3=inc;
	draw -n bin -v set;	/* store these variables in the plot */
	x1=min;x2=max;
	

[Replot]
	%A=store.v3$;
	win -o %A
	{
	doc -each LW {rescale;layer.y.from=0;}
	/* the plot is still the active window
	 * -LW is for each layer in the window
	 */
	layer -s 1;
	x1=min;
	x2=max;
	}
	win -a %A;

[Bin]
	if(index>0)
	{
	draw -z get index;
	getn -s (%Z) This.v$(index);
	return;
	};
	%B=bin.v1$;/* get worksheet name */

	draw -n bin -v g;/* get the variables from bin label */
	min=v1;max=v2;inc=v3;
	nCols=%(%B,@#);/* in the histgm wks */
	set %B -e 0;/* reset wks size to zero */
	win -a %B;
	run.section(,Calc);

[Norm]
	/* generate gaussian curve for each layer
	 * from mean and sd of relevant layer
	 */

	%B=bin.v2$; /* Original wks */
	%W=bin.v1$; /* bin wks */
	//%K=Gaussian worksheet
	if ((exist(Gaussian))==2)
	{	/* check for wks */
		set Gaussian -e 0;	/* if exist - delete it */
		win -c Gaussian;
	};

	doc -cw Gaussian; win -T Wks Gauss Gaussian$(count+1);

	%K=%H;
	tot=%B!wks.c2-%B!wks.c1+1;
	for (ij=1;ij<=tot;ij+=1)
	{
		worksheet -v range$(ij);
		kol=colnum(range$(ij));
		wks.col$(kol).type=4;
		worksheet -v gauss$(ij);
		min=%W!mins.v$(ij);	/* read data in */
		max=%W!maxs.v$(ij);
		mean=%W!mean.v$(ij);
		sd=%W!sd.v$(ij);
		n=%W!n.v$(ij);
		col(range$(ij))=data(min-inc,max+inc,.01*(max-min));
	
		col(gauss$(ij))=gauss(col(range$(ij)),0,mean,2*sd,n*inc);
		///RKM 2/20/97 v 4.92 Redirect to Notes
		Redirect=type.redirection;
		if(type.redirection&2==2) %K=type.notes$;
		if (exist(Results)!=9)
		{
			win -n notes Results;
		}
		type.notes$=system.notes.created$;
		type.redirection=6;

		repeat 2 {type};                        //Skip some spaces
		type "$(@D,D9)";                        //Type out date and time
		type;

		type $Template.HistNorm;
		type $Template.HistHeading;
		type "$(mean,*5)\t$(sd,*5)\t$(n*inc,*5)";
		type.redirection=Redirect;
		if((type.redirection&2==2) && (exist(%K)==9)) 
			type.notes$=%K;
		else
			type.redirection=5;
		del Redirect;
	};
	

	win -a %Wplot;	/* goto plot window */

	for (ij=1;ij<=tot;ij+=1)
	{
		layer -s ij;
		layer -i %K_gauss$(ij);
		set %K_gauss$(ij) -l 1;	/* line */
		set %K_gauss$(ij) -k 0;	/* no symbol */
		set %K_gauss$(ij) -c 1;	/* black */
		set %K_gauss$(ij) -d 0;	/* solid */
		rescale;
		layer.y.from=0;
        };
	layer -s 1;
	x1=bin.v1;x2=bin.v2; 	/* reset the horiz axis */

/////////////////////////////////////////////////////////////////////
//  Histogram end
/////////////////////////////////////////////////////////////////////


/////////////////////////////////////////////////////////////////////
//  Polar begin
// 	SDB 04/5/2004 ER7.5851 QA5855 ADD_POLAR_SCRIPT_TO_OGS
/////////////////////////////////////////////////////////////////////
[SetAngularUnit]
	getn 
	$Template.FunctionFrom x1 
	$Template.FunctionTo x2 
	$Template.FunctionIncrement x3 
	$Template.FunctionAngRange;
	return 0;

[SetStartPosition]
	layer -b pr (this.choice-1);
	return 0;
	
[SetRadiusRange]
	if(layer.y.type > 1)
	   this.choice=2;
	layer -b polar (this.choice-1);
	return 0;
	
/////////////////////////////////////////////////////////////////////
//  Polar end
/////////////////////////////////////////////////////////////////////
