////////////////////////////////////////////////////////////////////////////////
// Filename:    plot.ogs
// Creation:    8/12/1995
// Purpose:     To generate plots from menu or from 2D toolbar
// Modifications:
// JMP v3.85 11/03/95 				Rewrite most parts to be used from either wks or graph
// LAS  v4.0 01/16/96	STORE_OBJ 		Box Chart now allows dots in the worksheet name
// JMP v4.12 07/23/96	LINESERIES_MULTIX	Use multiX setting when adding LineSeries Data
// JMP v4.13 07/27/96	COLUMN_RENAME		Rename UIM Status property from Column to WksCol to avoid starting with 'c'
// CPY v4.986 5/15/97	TERNAY_NO_Y_COL		force plot id to 245 to prevent Y colum in plto
// JMP v4.995 6/06/97	USE_FDLOG_TO_TRACK	Use FDLOG object to use template path and to track user for template path
// SFX 6/4/98 v6.0123 ADD_FLOW_VECTOR_PLOT_TYPE
// CPY 7/28/98 v6.0127 b4098 CNTRL_SEL_COL_NEED_SCRIPT_CHANGE
// ML 8/6/98 v6.0127 SCRIPT_CHANGE_FOR_FLOW_VECTOR
// SFX 10/28/98 v6.0135 FLOATING_BAR_AND_COLUMN_ARE_SWAPED
// RB	11/4/98 v6.0135 RESTORE_FLOATING_BAR_AND_COLUMN
// SDB 2/1/99 v.6.0151 HIST_PROB_UPDATE
// CPY 3/19/99 v6.0176 t5596 MOVE_COMPLEX_PLOT_NOT_FROM_SCRIPT
// CPY v6.0190 4/26/99
/// SFX 5/24/99 v6.0205 t6484 ZOOM_PLOT_CAUSES_CRASH
// CPY 10/28/99 t7082 v6.0236 PLOT_TO_TEMPLATE_CHECK_GROUP
// CPY 06/26/2001 t6834 v6.9018 ADD_SMITH_CHART_PLOT_HOOK_UP
// CPY v7.0311 QA70-1736 5/24/02 ARG_COPY_COL_LABEL_OTHER_LAYERS
// JJ 10/29/2001 t9578 SMITH_CHART_IMPROVMENTS
//YuI 9/19/03 v7.5700 SYSTEM_THEME_IS_NOT_APPLIED_TO_SOME_PLOTS
////////////////////////////////////////////////////////////////////////////////
// Standard Origin Plots
// For Customer Modifications:
//	For customized plotting routine for any of the basic graph types, 
//	replace the code calling the General section with your custom code
//	which you may model after the General section.
////////////////////////////////////////////////////////////////////////////////

[General]
	////////////////////////////////////////////////////////////////////////
	// General Plotting of data for Worksheet or Graph
	// Assumes 3 arguments: 1st=Plot Type, 2nd=Template, 3rd=Restore/Exchange Axes
	////////////////////////////////////////////////////////////////////////
	if (exist(%H)==2)
	{
		worksheet -P %1 %2;
		Legend;
		return 0;
	}
	if (exist(%H)==3)
	{
		layer -b x %3;           //Restore/Exchange Axes if 0/1 respectively
		layer -i%1 %C;
		return 0;
	}	



[Line]
	run.section(,general,200 Line 0);

[Scatter]
	run.section(,general,201 Scatter 0);

[LineSymbol]
	run.section(,general,202 LineSymb 0);

[Column]
	run.section(,general,203 Column 0);

[StackCol]
	run.section(,general,213 Column 0);

[Bar]
	run.section(,general,215 Bar 1);

[StackBar]
	run.section(,general,216 Bar 1);

[Area]
	run.section(,general,214 Area 0);

[pClamp]
	run.section(,general,200 pCLAMP 0);

[Pie]
	run.section(,general,225 Pie 0);

[PiecePie]
	worksheet -Plot 225 Pie;
	return 0;

[HiLoClose]
	run.section(,general,205 HLClose 0);

////////////////////////////////////////////////////////////////////////////////
// Floating Column Plots
////////////////////////////////////////////////////////////////////////////////
[FloatColumn]
	run.section(,general,207 FloatCol 0);

////////////////////////////////////////////////////////////////////////////////
// Floatting Bar Plots
////////////////////////////////////////////////////////////////////////////////
[FloatBar]
	//Plot the selected region with at least two y columns as floating bars
	run.section(,general,207 FloatBar 0);

////////////////////////////////////////////////////////////////////////////////
// Vector Plots
////////////////////////////////////////////////////////////////////////////////
[Vector]
	run.section(,general,208 vector 0);

////////////////////////////////////////////////////////////////////////////////
// FlowVector Plots
////////////////////////////////////////////////////////////////////////////////
[FlowVector]
	run.section(,general,218 VectXYXY 0);
	
////////////////////////////////////////////////////////////////////////////////
// Line
////////////////////////////////////////////////////////////////////////////////
[LineSeries]
	//New Line Series code
	//uses new BREAK object
	//JMP 09/15/1995
	if (exist(%H)!=2)
	{
		type -b $general.BadGraphType;
		return 1;
	}

	NumYs = %(%H,@Y#,2);
	if (NumYs != wks.iscolsel() || NumYs!=2 && NumYs!=3) 
	{
		type -b $general.Only2or3YColumns;
		break 1;
	} 

	create.wksName$="LineSeries";
	create.enumwks=1;
	create.wkslabel$=$Plot.LineSeriesLabel;
	create.template$="CREATE";
	create.npts=30;				//Use something common for default - columns will expand as necessary
	create.enumerate=1;
	create.numtypes=2;			
	create.type1=4;				//Only explicitly specify 1st type as X
	create.type2=1;				//Set TypeN=Y column type
	create.wks(Series Values);
	
	%A=create.data1$;			//X data (Series)
	%B=create.data2$;			//Y data (Values)

	break.open(Constructing new columns..);
	break.min=beg;break.max=end;
	count=%(%H,@Y#,2);
	xx=1;
	loop(ii,wks.r1,wks.r2)
	{
		break.set(ii);
		kk=0;
		loop(jj,1,count)
		{
			kk=%(%H,@YS,kk+1);
			%A[xx]=jj;
			%B[xx]=wcol(kk)[ii];
			xx+=1;
		}
	}			
	break.close();

	%A=create.wksname$;
	win -oa %A {
		worksheet -s;
		worksheet -s (%A!wks.ncols-1) 0 (%A!wks.ncols) 0;
		worksheet -P ? LSer$(count);
	}

	delete -v kk;
	delete -v xx;
	delete -v NumYs;

	return 0;

[FillArea]
	run.section(,general,249 FillArea 0);

[DoseRespFit]
	///This code is to satisfy people who are used to plotting into the old DOSERESP.OTP plot
	if (exist(%H)==2)
	{
		worksheet -P 201 scatter;
		layer.x.space=2;                //Set X axis to Log10
		layer -a;                       //Rescale
		dotool -w sr;                   //Activate Sigmoidal Regression tool
		return 0;
	}
	if (exist(%H)==3)
	{
		dotool -w sr;
		return 0;
	}

////////////////////////////////////////////////////////////////////////////////
// Double Y (Line/Symbol)
////////////////////////////////////////////////////////////////////////////////
[DoubleY]
	//Create a double Y line chart by putting the last selected Y column into the 2nd layer
	if (exist(%H)!=2)
	{
		type -b $general.BadGraphType;
		return 1;
	}

	if( %(%H,@Y#,2) < 2 ) 
	{
		type -b $general.doubleYError;
		return 1;
	} 

	rone=wks.r1;
	rtwo=wks.r2;

	if (exist(%H)!=2)
	{
		type -b $general.BadGraphType;
		return 1;
	}

	//reject selection if it does not start with X or Y
	if (wks.col$(wks.c1).type!=1 && wks.col$(wks.c1).type!=4)
	{
		type -b $general.selectionXY;
		return 1;
	}

	jj=0;
	count=wks.iscolsel();
	create _tempPos -t 1;
	tempPos=1;
	loop(ii,1,count)
	{
		jj=wks.c1+%(%H,@O,ii-1);
		//pass valid column types (X,Y,YERR,XERR,L)
		if(mod(wks.col$(jj).type,2)!=0 && wks.col$(jj).type!=4)
		{
			_tempPos[tempPos]=jj;		//save positions in temp dataset
			tempPos+=1;			
		}
	};

	%W=%H;
	jj=%(%H,@Y-,wks.c2);
	jj=list(jj,_tempPos);
	worksheet -ps;
	win -t plot doubleY;

	loop(ii,jj,tempPos-1)
	{
		layer -wd %W _tempPos[ii] rone _tempPos[ii] rtwo ?;
	}

	page.active=1;
	loop(ii,1,jj-1)
	{
		layer -wd %W _tempPos[ii] rone _tempPos[ii] rtwo ?;
	}

	del -v rone;del -v rtwo;del -v tempPos;
	del _tempPos;

	label -r legend;
	%Z="";

	//CPY v7.0311 QA70-1736 5/24/02 ARG_COPY_COL_LABEL_OTHER_LAYERS
	// \L($(page.active).$(ii)) %[%C,>'_']; was the old line, which only shows column name
	//the new one will generate things like "\(2.1) %(2.1)"	which will correctly show column label
	// from another layer
	doc -e LW
	{
		ii=1;
		doc -e D {
			%Z=%Z
\L($(page.active).$(ii)) %%($(page.active).$(ii));
			ii++;
		}
	}
	//CPY v7.0311 QA70-1736 5/24/02 ARG_COPY_COL_LABEL_OTHER_LAYERS
	// add link to variables
	//label -p 100 (-18) -s -sa -n legend %Z;
	label -p 100 (-18) -s -sl -sa -n legend %Z;
	//
	legend.background=1;
	legend.top=150;
	/// YuI 9/19/03 v7.5700 SYSTEM_THEME_IS_NOT_APPLIED_TO_SOME_PLOTS
	ApplySystemThemeToActivePage();
	/// end SYSTEM_THEME_IS_NOT_APPLIED_TO_SOME_PLOTS
	doc -uw;
	return 0;

////////////////////////////////////////////////////////////////////////////////
// Water Fall (XY offset)
////////////////////////////////////////////////////////////////////////////////
[WaterFall]

	//Plot the selected columns as a water fall line graph
	if (exist(%H)!=2)
	{
		type -b $general.BadGraphType;
		return 1;
	}

	worksheet -P ? Waterfal;
	return 0;

////////////////////////////////////////////////////////////////////////////////
// Polar Plot
////////////////////////////////////////////////////////////////////////////////
[Polar]
	//Plot selected columns as polar graph
	if (exist(%H)!=2)
	{
		type -b $general.BadGraphType;
		return 1;
	}

	worksheet -P ? Polar;
	Legend;
	return 0;

//---------  CPY 06/26/2001 t6834 v6.9018 ADD_SMITH_CHART_PLOT_HOOK_UP
////////////////////////////////////////////////////////////////////////////////
// Smith Chart Plot
////////////////////////////////////////////////////////////////////////////////
[SmithChart]
	//Plot selected columns as Smith Chart graph
	if (exist(%H)!=2)
	{
		type -b $general.BadGraphType;
		return 1;
	}	

	worksheet -P ? SmithCht;
	
	layer -b ps 1; // check to convert to Smith Chart layer if not already so
	Legend;
	
	
	return 0;	
//---------	end CPY 06/26/2001

////////////////////////////////////////////////////////////////////////////////
// Ternary Plot
////////////////////////////////////////////////////////////////////////////////
[Ternary]
	//Plot selected columns as polar graph
	if (exist(%H)!=2)
	{
		type -b $general.BadGraphType;
		return 1;
	}
	if (%(%H,@Z#,2)!=1)
	{
		type -b $general.Only1ZColumn;
		break 1;
	}

	//CPY 5/15/97 TERNAY_NO_Y_COL, explicit id will prevent Y columns added to layer
	//worksheet -P ? Ternary;  
	worksheet -P 245 Ternary;
	Legend;
	return 0;

////////////////////////////////////////////////////////////////////////////////
// Box Chart
////////////////////////////////////////////////////////////////////////////////
[BoxChart]
	//Create a Box chart for the selected columns
	//JMP modified 08/30/1995
	//Main code taken from old STAT.TXT file

	if(run.section(,CheckBinCreate)==0)
		type -c $Histogram.PrevCreated;

	if (exist(%H)!=2)
	{
		type -b $general.BadGraphType;
		return 1;
	}

	if (%(%H,@Y#,2) < 1) 
	{
		type -b $general.singleYError;
		break 1;
	}
	
	worksheet -p 206 Box;
	get %C -nhwc A;
	win -o %A {win -h 1;}
	legend;
	return 0;

[UpdateBoxChart]

	%W=store.wksname$;//capture worksheet name stored in the storage object
	for (j=1,i=store.selc1;i<=store.selc2;j+=1,i+=1) 
	{
		sum(%(%W,i));
		%(%H,1,j)       = %(%W,@Col,i);
		col(mean)[j]    = sum.mean;
		col(max)[j]     = sum.max;
		col(min)[j]     = sum.min;
		col(sd)[j]      = sum.sd;
		dummy={1,99};
		dummy=percentile(%(%W,i),dummy);
		col(P1)[j]      = dummy[1];
		col(P99)[j]     = dummy[2];
	}
	del dummy;
	return 0;

////////////////////////////////////////////////////////////////////////////////
// Histogram from Matrix window
////////////////////////////////////////////////////////////////////////////////
[MatrixHistogram]
	matrix -id; // check if data is available, if not, convert to data first
	worksheet -p 219 MHisto;
	get %C -nhwc A;
	get %C -se v1;// get internal data size = 1,2,4,8,
	if(v1==1) // byte data, must be image histogram, 0-255
	{
		if(x1 < 0)
			x1 = 0;
		if(x2 > 255)
			x2 = 255;
	}
	win -o %A {win -h 1;};
	legend;

////////////////////////////////////////////////////////////////////////////////
// Histogram
////////////////////////////////////////////////////////////////////////////////
[Histogram]
	//------------ CPY 10/11/01 v6.9103 t9576 HISTOGRAME_FROM_MATRIX
	if(exist(%H)==5) // from a matrix
	{
		run.section(,MatrixHistogram);
		return 0;
	}
	//------------
	/// GCJ 7/21/98 v6.0125 t1320 DRAW_HISTOGRAM_PLOT
	if(run.section(,CheckBinCreate)==0)
		type -c $Histogram.PrevCreated;


	if (exist(%H)!=2)
	{
		type -b $general.BadGraphType;
		return 1;
	}

	
	if(wks.iscolsel()!=%(%H,@Y#,2)) 
	{
		type -b $general.RangeYColumns;
		break 1;
	}
	
	
	worksheet -p 219 Hist;
	get %C -nhwc A;
	win -o %A {win -h 1;};
	legend;
	return 0;

////////////////////////////////////////////////////////////////////////////////
// Stacked Histogram
////////////////////////////////////////////////////////////////////////////////
[StackHist]
	if(run.section(,CheckBinCreate)==0)
		type -c $Histogram.PrevCreated;

	/// SDB 2/3/99 v6.0156 
	if (exist(%H)!=2)
	{
		type -b $general.BadGraphType;
		return 1;
	}

	if(wks.iscolsel()==0 || %(%H,@Y#,2)==0)
	{
		type -b $general.selectionXY;
		return 1;
	}

	if(wks.iscolsel()!=%(%H,@Y#,2)) 
	{
		type -b $general.RangeYColumns;
		break 1;
	}

	%W=%H;					//Save the current worksheet name
	%Z="";ii=0;
	count=%(%W,@Y#,2);
	loop(jj,1,count)
	{
		ii=%(%W,@YS,ii+1);
		%Z=%Z $(ii);
	};

	win -t plot Hist;				//Get the Origin.OTP template

	layer -i219 %(%W,%[%Z,#1]);			//Include the first Y column
	get %(%W,%[%Z,#1]) -nhwc A;
	win -o %A {win -h 1;};

	loop(ii,2,count)
	{
		page -l Hist;
		layer -i219 %(%W,%[%Z,#ii]);		//Include Y column
		get %(%W,%[%Z,#ii]) -nhwc A;
		win -o %A {win -h 1;};
		label -r XB;				//Remove the X axis label for all but the first layer
	};

	xGap=10;
	yGap=5;
	Left=25;
	Right=5;
	Bottom=10;
	Top=10;
	page -o p;

	ArrangeLayers page.nlayers 1;

	queue {
		doc -e L {
			rescale;
		};
	};
	return 0;

////////////////////////////////////////////////////////////////////////////////
// Histogram + Probabilities
////////////////////////////////////////////////////////////////////////////////
[HistProb]
	//Creates a histogram from the selected data and performs a cumulative count of the data
	if(run.section(,CheckBinCreate)==0)
		type -c $Histogram.PrevCreated;

	if (exist(%H)!=2)
	{
		type -b $general.BadGraphType;
		return 1;
	}

	if (%(%H,@Y#,2)!=1||wks.iscolsel()!=1)
	{
		type -b $general.Only1YColumn;
		return 1;
	}
	
	sum(%(%H,%(%H,@YS,1)));
	///SDB 2/1/99 REDIRECT_TO_RESULTS_LOG
	SaveRedirection=type.Redirection(16,3);	// SDB 1/7/99 REPORT_TO_OUTPUTLOG
	type.BeginResults();		/// RKM 12/10/98 v6.0141 REPORT_TO_OUTPUTLOG

	type $histogram.Title;                                  //Histogram & Probabilities
	type;                                                   //Blank Line
	type $histogram.ParaHeader1;
	separator 5;
	type "$(sum.mean)\t$(sum.sd)\t$(sum.max)\t$(sum.min)\t$(sum.n)";

	type.EndResults();
	type.Redirection=SaveRedirection; // restore previous redirection.
	delete -v SaveRedirection;
	doc -cp HistProb;
	%B=%(%H,%(%H,@YS,1));
	win -t Plot HistCumu HistProb$(count+1);
	queue {
		layer -o 1 {rescale;}
	}
	layer -o 1 {
		layer -i219 %B;
		get %C -nhwc A;
		win -o %A {win -h 1;};
	};
	layer -o 2 {
		layer -i201 %(%A,4);
		rescale;
	};
	return 0;

[CheckBinCreate]
	get %C -nhw A;
	return 0;	

////////////////////////////////////////////////////////////////////////////////
// QC (X bar R) Chart
////////////////////////////////////////////////////////////////////////////////
[QCchart]
	//Plots the selected data into the Quality Control template
	if (exist(%H)!=2)
	{
		type -b $general.BadGraphType;
		return 1;
	}

	if (exist(%C)!=1) 
	{
		type -b $general.selectionError;
		break 1;
	} 

	if (wks.iscolsel()!=(wks.c2-wks.c1+1)) 
	{
		type -b $general.ContiguousError;
		break 1;
	} 

	%W=%H;
	%B=%(%H,wks.c1);
	getenumwks QC;
	qc.worksheet$=%W;

	//JMP COLUMN_RENAME
	//qc.column1=%W!wks.c1;
	qc.WksCol1=%W!wks.c1;
	qc.WksCol2=%W!wks.c2;

	qc.plot$="";
	worksheet -Link %B;
	if(qc.WksCol2 - qc.WksCol1 >= 1) 
	{
		qc.groupsize=qc.WksCol2-qc.WksCol1 + 1;
		type -c $plot.QCHeader1;
	}
	else 
		getn -s $plot.qcchartSubgroup qc.groupsize $plot.qcchartTitle;
	qc.run();
	return 0;

////////////////////////////////////////////////////////////////////////////////
// Template
////////////////////////////////////////////////////////////////////////////////
[Template]
	//Pick a template file and plot all selected columns into it
	dialog.start(OTools.dll,TemplateLibrary);
	ini.get.filename$=template.ini;
	ini.getsection(categories);
	jj=TemplateLibrary!Categories.Choice;
	loop(ii,2,ini.keynum)
	{
		%A=ini.keyvalue$(ii)$;
		TemplateLibrary!Categories.v$(ii-1)$=%A;
	}
	TemplateLibrary!Categories.Choice=jj;
	jj=TemplateLibrary!Templates.Choice;
	ini.get.filename$=template.ini;
	%A=TemplateLibrary!Categories.s1$;
	ini.getsection(%A);
	TemplateLibrary!CatEdit.v1$="%A";
	loop(ii,1,ini.keynum)
	{
		%B=ini.keyname$(ii)$;
		TemplateLibrary!Templates.v$(ii)$=%B;
	}
	%K=TemplateLibrary!Templates.v$(jj)$;
	TemplateLibrary!Templates.Choice=jj;
	TemplateLibrary!TemEdit.v1$=%K.otp;
	if(run.LoadOC("OriginLab\TemplateLibrary",4)!=0)	
	{
		run.section(DBRoutines.OGS,ReportError,$Regression.CFileNoLoad);
		return 1;
	}
	run.section(DBRoutines,SaveAndSetAtOC);
	ini.getstr(W,,%K,%A,template.ini);
	%A=system.path.program$;
	if(%[%W]<=1)
		%W=%A;
	TemplateLibrary!NoPreview.show=0;

	if(OpenTemplate(%W%K))
	{
		TemplateLibrary!BMP.display(%Atemplatepict.bmp);
	}
	else
	{
		if(exist(%ATemplates\Previews\%K.bmp)==-1)
		{
			TemplateLibrary!BMP.display();
			TemplateLibrary!NoPreview.show=1;
		}
		else
		{
			TemplateLibrary!BMP.display(%ATemplates\Previews\%K.bmp);
		}
	}
	run.section(DBRoutines,RestoreAtOC);
	return 0;

////////////////////////////////////////////////////////////////////////////////
// Bring up the Zoom template and Initialize it
////////////////////////////////////////////////////////////////////////////////
//
// CPY v6.0190 4/26/99 change plot type from 201 into 200, as we should use line plots
//
[zoom]
	rone=wks.r1;
	rtwo=wks.r2;

	if (exist(%H)!=2)
	{
		type -b $general.BadGraphType;
		return 1;
	}

	//reject selection if it does not start with X or Y
	if (wks.col$(wks.c1).type!=1 && wks.col$(wks.c1).type!=4)
	{
		type -b $general.selectionXY;
		return 1;
	}

	if(wks.iscolsel()==0 || %(%H,@Y#,2)==0)
	{
		type -b $general.selectionXY;
		return 1;
	}

	/// SFX 5/24/99 v6.0205 t6484 ZOOM_PLOT_CAUSES_CRASH
	worksheet -ps;
	/// end ZOOM_PLOT_CAUSES_CRASH

	count=wks.iscolsel();
	create _tempPos -t 1;
	tempPos=1;
	loop(ii,1,count)
	{
		jj=wks.c1+%(%H,@O,ii-1);
		//pass valid column types (X,Y,YERR,XERR,L)
		if(mod(wks.col$(jj).type,2)!=0 && wks.col$(jj).type!=4)
		{
			_tempPos[tempPos]=jj;		//save positions in temp dataset
			tempPos+=1;
		}
	};

	%W=%H;
	win -t plot zoom1;
	loop(ii,1,tempPos-1)
	{
		/// SFX 5/24/99 v6.0205 t6484 ZOOM_PLOT_CAUSES_CRASH
		//layer -s 2;layer -w %W _tempPos[ii] rone _tempPos[ii] rtwo 200;
		//layer -s 1;layer -w %W _tempPos[ii] rone _tempPos[ii] rtwo 200;
		layer -s 2;layer -wd %W _tempPos[ii] rone _tempPos[ii] rtwo 200;
		layer -s 1;layer -wd %W _tempPos[ii] rone _tempPos[ii] rtwo 200;
		/// end ZOOM_PLOT_CAUSES_CRASH
	}
	page.active=2;
	layer -g;
	page.active=1;
	layer -g;

	del -v rone;del -v rtwo;del -v tempPos;
	del _tempPos;

	queue
	{
		limit %C;
		zoomrect.x=limit.xmin;
		zoomrect.y=%C(limit.xmin);
		zoomrect.run();
	};
	return 0;

