// Filename:    Baseline.ogs
// Purpose:     Peak picking, baseline creation and integration
// Modifications:
// LAS 4/18/02 v7.0283 OPEN_WORKSHEET_FOR_OGG
////////////////////////////////////////////////////////////////////////////////

[Tab.BaseLn.OnInit]
	Baseline!Tab.BaseLn.Auto=1;
	Baseline!Tab.BaseLn.NumPoints.v1=10;
	Baseline!Tab.BaseLn.Fittype.v1$=$Baseline.EndWeighted;
	Baseline!Tab.BaseLn.Fittype.v2$=$Baseline.EntireDataNoSmooth;
	Baseline!Tab.BaseLn.Fittype.v3$=$Baseline.EntireDataWithSmooth;
	Baseline!Tab.BaseLn.Fittype.v4$=$Baseline.PositiveAlgorithm;
	Baseline!Tab.BaseLn.Fittype.choice=1;

[Tab.Peaks.OnInit]
	Baseline!Tab.Peaks.MinWidth.v1=5;
	Baseline!Tab.Peaks.MaxWidth.v1=40;
	Baseline!Tab.Peaks.MinHeight.v1=5;
	Baseline!Tab.Peaks.Labels=1;
	Baseline!Tab.Peaks.CenterMarker=1;
	Baseline!Tab.Peaks.BaseMarker=1;

[Tab.Area.OnInit]
	Baseline!Tab.Area.IntCurve.choice=1;

[Initialize]
	if (%C=="") 
	{
		type -b $Baseline.NoValidData;
		return 1;
	}
	if(Layer.is3D==1)
	{
		type -b $General.2DGraphsOnly;
		return 1;
	}
	else
	{
		curve.data$=%C;					//Active Dataset
		curve.worksheet$=%[%C,'_'];			//Worksheet containing Active Dataset
		//BEGIN OPEN_WORKSHEET_FOR_OGG
		if(exist(%[%C,'_']) != 2)
		{
			edit %C;	//open worksheet
			win -ch 1;  //hide
		}
		//END OPEN_WORKSHEET_FOR_OGG
		curve.plotname$=%H;				//Active plot window
		return 0;
	}

[Check]
	%B=%C;
	%A="";
	%A=$Baseline.PageLabel;
	doc -e W {
		if(page.label$=="%A")
		{
			%A=%H;
			Break;
		}
	}
	if(run.section(,CheckBase,%A)==0)
	{
		run.section(,Supp,%A);		//If it is a dataset, run the Supp section
	}
	else
		return 1;
		
[Tab.BaseLn.Create.OnClick]
	switch(Baseline!Tab.BaseLn.Auto.choice)
	{
		case 1:
			run.section(,AutoBaseline);
			break;
		case 2:
			run.section(,UserDefined);
			break;
		case 3:
			run.section(,ExistingDataset);
			break;
	};
	return 0;

[AutoBaseline]
	if(Baseline!Tab.BaseLn.NumPoints.v1==0)
	{
		type -b $Baseline.Points;
		return 1;
	}
	run.section(,Create);
	curve.basey$=%A_basey; 
	curve.baseX$=%A_basex;
	curve.base$=%A_basey;
	curve.baselinepts=Baseline!Tab.BaseLn.NumPoints.v1;
	curve.minpeakrange=Baseline!Tab.Peaks.MinWidth.v1;
	curve.maxpeakrange=Baseline!Tab.Peaks.MaxWidth.v1;
	curve.minheight=Baseline!Tab.Peaks.MinHeight.v1;

	curve.baseline.fittype=Baseline!Tab.BaseLn.FitType.choice-1;

	if(curve.baseline()==0/0)
	{
		limit %C;
		stat.makeX.fitnpts=Baseline!Tab.BaseLn.NumPoints.v1;
		stat.fitxdata$=%A_basex;
		stat.makex.fitx1=limit.xmin;
		stat.makex.fitx2=limit.xmax;
		stat.makex();
		set %A_basey -e Baseline!Tab.BaseLn.NumPoints.v1;
		curve.basey$=%A_basey; 
		curve.baseX$=%A_basex;
		curve.base$=%A_basey;
		%i=curve.base$; 
		%B=curve.data$;
		limit %B;
		(%i)=limit.ymin;
		layer -i200 %i;			//include the baseline data	
		layer -a;
		set %i -c 2;
	}
	%i=curve.base$; 
	%B=curve.data$;
	limit %B;
	(%i)=%i>limit.ymax?limit.ymax:%i;
	(%i)=%i<limit.ymin?limit.ymin:%i;
	(%i)=%i==0/0?limit.ymin:%i;
	layer -i200 %i;			//include the baseline data	
	set %i -c 2;
	layer -a;
	return;

[UserDefined]
	run.section(,Create);
	limit %C;
	stat.makeX.fitnpts=Baseline!Tab.BaseLn.NumPoints.v1;
	stat.fitxdata$=%A_basex;
	stat.makex.fitx1=limit.xmin;
	stat.makex.fitx2=limit.xmax;
	stat.makex();
	set %A_basey -e Baseline!Tab.BaseLn.NumPoints.v1;
	curve.basey$=%A_basey; 
	curve.baseX$=%A_basex;
	curve.base$=%A_basey;
	%i=curve.base$; 
	%B=Baseline!Tab.BaseLn.YEquals$;
	Usereq(x)=%B;
	%A_Basey=Usereq(%A_basex);
	%B=curve.data$;
	limit %B;
	(%i)=%i==0/0?limit.ymin:%i;
	layer -i200 %i;			//include the baseline data	
	set %i -c 2;
	layer -a;
	delete usereq;
	return;

[ExistingDataset]
	%W=Baseline!Tab.BaseLn.Dataset$;
	if(exist(%W)!=1)
	{
		type -b $Baseline.NoBaseData;
		break;
	};
	run.section(,Create);
	%B=create.wksname$;
	%B_basey=%W;
	%B_basex=xof(%W);
	curve.basey$=%B_basey; 
	curve.baseX$=%B_basex;
	curve.base$=%B_basey;
	%i=curve.base$; 

	layer -i200 %i;			//include the baseline data	
	layer -a;
	return 0;		

[Create]
	if(run.section(,Initialize)!=0) break;
	%B=%C;	
	%A="";
	doc -e W {
		%A=$Baseline.PageLabel;
		if(page.label$=="%A")
		{
			%A=%H;
			Break;
		}
	}
	if (exist(%A)==2)
	{
		win -o %A
		{		
			create.wksName$=%A;
			create.enumwks=0;
			loop(ii,1,%A!wks.ncols)
			{
				del col(1);
			}
			if(page.extinfo==1)
			{
				type -b $Baseline.NoExcelWks;
				return 1;
			}
		}
	}
	else
	{
		create.wksName$="Base";
		create.enumwks=1;
	}

	create.wkslabel$=$Baseline.PageLabel;
	create.template$="CREATE";
	create.type1=4;
	create.type2=1;
	create.wks(basex basey);
	%A=create.wksname$;
	return;				//Origin stores the baseline data in %i


[Supp]
	%B=%C;	
	%i=curve.basey$;
	if (%i!="")
	{   
		if (exist(%i)==1) 
			curve.base$=%i; 
		else
		{
			ty -b $baseline.novaliddata;
			return 1;
		}
	}
	else
	{
		ty -b $baseline.nodataset;
		return 1;
	}

	layer -i200 %i;						//include the baseline data in the layer
	set %i -c 2;
	layer -a;
	return 0;

[Tab.BaseLn.Subtract.OnClick]
	if(run.section(Baseline,Check)==1)
		return 1;
	if(run.section(,Initialize)!=0) return 1;
	if(run.section(,CheckI)==1);
	%A=curve.basey$;
	if (exist(%A)==1)
	{
		copy %A %A_bk;  				
		%A=curve.data$;
		copy %A %A_bk;				//backup the original data
		layer -e %i;				//take the baseline out of the layer
		%A --O %i;
			%i --O %i;
		layer -i200 %i;
		set %i -c 2;
		layer -a;
		%B=curve.markerindex$;					
		doc -e S
		{
			if("%[%c,>'_']"=="pky" || "%[%c,>'_']"=="PosPkL" || "%[%c,>'_']"=="NegPkL" || "%[%c,>'_']"=="BMkY")	
				layer -e %c;
		};
		layer -a;						//rescale

		Baseline!StoreBaseline$=%i;					//store the baseline and active dataset 
		Baseline!StoreString$=curve.data$;				//for undo checking
	}
	else
		type -b $Baseline.NoBaselineData;

[Tab.BaseLn.UndoSubtr.OnClick]
	run.section(Baseline,Check);
	if(run.section(,Initialize)!=0) break;
	run.section(,CheckI);
	doc -e S
	{
		if("%[%c,>'_']"=="pky" || "%[%c,>'_']"=="PosPkL" || "%[%c,>'_']"=="NegPkL" || "%[%c,>'_']"=="BMkY")	
			layer -e %c;
	};
	layer -a;						//rescale
	%A=curve.basey$;
	%B=curve.data$;
	if(exist(%A_bk)!=1||exist(%B_bk)!=1)
	{
		ty -b $baseline.nobackup;
		return;
	}
	else
	{
		copy %B_bk %B;
		copy %A_bk %A;
		layer -a;
		delete %A_bk;
		delete %B_bk;
		%i=Baseline!StoreBaseline$;
	};
	return 0;

[Tab.BaseLn.Modify.OnClick]
	run.section(Baseline,Check);
	dotool 0;
	%B=%C;	
	%A="";
	doc -e W {
		%A=$Baseline.PageLabel;
		if(page.label$=="%A")
		{
			%A=%H;
			Break;
		}
	}
	if(exist(%A)==2)
	{
		set %i -m 1;
		mvpts %i;  
	}
	else
	{
		type -b $Baseline.NoBaselineData;
	}
	
[Tab.Peaks.FindPeaks.OnClick]
	doc -uw;
	%B=%C;	
	%A="";
	doc -e W {
		%A=$Baseline.PageLabel;
		if(page.label$=="%A")
		{
			%A=%H;
			Break;
		}
	}
	if(exist(%A)!=2)
	{	
		if(run.section(,CheckBase)!=0)
			break;
	}
	else
	{
		curve.basey$=%A_basey; 
		curve.baseX$=%A_basex;
		curve.base$=%A_basey;
	}
	if(run.section(,Initialize)!=0) break;
	%J=%C;

	%B=%C;
	%A="";
	doc -e W {
		%A=$Baseline.BasePeaks;
		if(page.label$=="%A")
		{
			%A=%H;
			Break;
		}
	}
	if (exist(%A)==2)
	{
		win -o %A
		{		
			create.wksName$=%A;
			create.enumwks=0;
			loop(ii,1,%A!wks.ncols)
			{
				del col(1);
			}
			if(page.extinfo==1)
			{
				type -b $Baseline.NoExcelWks;
				return 1;
			}
		}
	}
	else
	{
		create.wksName$="BsPeak";
		create.enumwks=1;
	}

	create.wkslabel$=$Baseline.BasePeaks;
	create.template$="CREATE";
	create.type1=2;
	create.type2=2;
	create.type3=4;
	create.type4=1;
	create.type5=5;
	create.type6=5;
	create.type7=2;
	create.type8=4;
	create.type9=1;
	create.wks(PkIndex PkDir Pkx Pky PosPkL NegPkL BMkIndex BMkX BMkY);
	%A=create.wksname$;
	curve.markerindex$=%A_BMkIndex;
	curve.peakindex$=%A_PkIndex;
	curve.peakdirection$=%A_PkDir;   		

	if(exist(%A)==2)
	{
		win -o %A
		{		
			if(page.extinfo==1)
			{
				type -b $Baseline.NoExcelWks;
				return 1;
			}
		}
	}

	Baseline!StoreString$=%A;
	

	if(Baseline!Tab.Peaks.MinWidth.v1<0 || Baseline!Tab.Peaks.MinWidth.v1>100) 
	{
		type -b $baseline.minpercent;	//minimum width must be between 0 and 100
		return;
	} 

	if(Baseline!Tab.Peaks.MaxWidth.v1<0 || Baseline!Tab.Peaks.MaxWidth.v1>100) 
	{
		type -b $baseline.maxpercent;	//maximum width must be between 0 and 50
		return;
	} 

	curve.minpeakrange=(Baseline!Tab.Peaks.MinWidth.v1)/100;
	curve.maxpeakrange=(Baseline!Tab.Peaks.MaxWidth.v1)/100;
	curve.minheight=(Baseline!Tab.Peaks.MinHeight.v1)/100;
	if (curve.pickpeaks()==0/0) run.section(,ErrSec);
	win -o %A
	{
		get %A_PkIndex -e end;			
		for(ii=1;ii<=end;ii+=1)
		{
			index=%A_pkindex[ii];		
			%A_Pkx[ii]=xvalue(index,%j);		//find the peak's x and y values in the active dataset
			%A_Pky[ii]=%j[index];			
		} 
		if (Baseline!Tab.Peaks.BaseMarker==1)
		{
			curve.markerindex$=%A_BMkIndex;
			get %A_BMkIndex -e end;
			for(i=1;i<=end;i+=1)
			{
				index=%A_BMkindex[i];
				%A_BMkX[i]=xvalue(index,%j);	//find the x and y values for the base markers
				%A_BMky[i]=%j[index];
			} 

		} 
	};

	win -o %A
	{
		get %h_PkY -b beginIndx;
		get %h_PkY -e EndIndx;
		range = EndIndx-beginIndx+1;
		for(i=1;i<=range;i+=1;)
		{
			%A=($(col(Pkx)[i]));
			if(col(PkDir)[i]$=="POS")
				col(PosPkL)[i]$=%A;	//set values for positive labels
			else
				col(NegPkL)[i]$=%A;	//set values for positive labels
		} 
	};

	%A=Baseline!StoreString$;
	if(Baseline!Tab.Peaks.Labels)
	{
		%B=%A_PosPkL;
		layer -i %B;					//Add labels
		set %B -ty 70;					//Offset in the y direction by 70 percent
		set %B -tj 1;					//Left Alignment
		f=font(arial);
		set %B -tf f;					//set the font to Arial
		%B=%A_NegPkL;
		layer -i %B;					//Add labels
		set %B -ty -70;					//Offset in the y direction by 70 percent
		set %B -tj 1;					//Left Alignment
		f=font(arial);
		set %B -tf f;					//set the font to Arial
		layer -a;
	} 

	if(Baseline!Tab.Peaks.CenterMarker)
	{
		%B=%A_Pky;
		layer -i201 %B;					//add Peak Centers
		set %B -c 2;					//Set the color to red
		set %B -k 6;					//Set the data point symbol to vertical line |
		set %B -z 8;					//point size to 15
		set %B -l 0;					//line connection to none
		layer -a;
	} 

	if(Baseline!Tab.Peaks.BaseMarker)
	{
		%A=curve.markerindex$;        
		%B=%[%A, '_'];
		%B=%B_BMkY;
		layer -i201 %B;					//Add Base markers
		set %B -c 4;					
		set %B -k 10;
		set %B -z 12;
		set %B -l 0;
		layer -a;
	} 
	return;

[DelPeaks]

	%A=curve.peakindex$;
	%A=%[%A,'_'];
	%A=%A_pky;

	if(exist(%A)==1)
	{
		Mark -x %A;
		def EndToolbox [;i1=_indx[1];undo -dr %A i1 i1; Mark -d %A -b i1 -e i1];
		GetPts 1 $Baseline.ClkPtsDel;
	}    
	else
	{
		ty -b $baseline.createpeak;
		return 1;
	} 

	win -o %A
	{

		if(Baseline!Tab.Peaks.BaseMarker)
		{
			if(exist(col(MrkIndx)))
			{
				wks.col=colnum(MrkIndx);
				hadcolm=1;
				delete col(MrkIndx);
			} 
        		if(exist(col(BMkX)))
			{
				wks.col=colnum(BMkX);
				delete col(BMkX);
       			} 
			if(exist(col(BMkY)))
				delete col(BMkY);
        		if(hacolm!=1)
				wks.col=wks.ncols+1;
			hadcolm=0;
        		wks.insert(MrkIndx BMkX BMkY);
        		n=colnum(BMkX);
        		wks.col$(n).type=4;			//set to X column
        		curve.markerindex$=%A_MrkIndx; 
		}
	};


	win -o %A
	{
		get %h_PkY -b beginIndx;
		get %h_PkY -e EndIndx;
		range = EndIndx-beginIndx+1;
		for(i=1;i<=range;i+=1;)
		{
			%A=($(col(Pkx)[i]),$(col(Pky)[i]));
			col(pKlabel)[i]$=%A;
		}
	};


	if(Baseline!Tab.Peaks.Labels)
	{
		layer -i201 %A;
		set %A -c 10;
		set %A -k 1;
		set %A -z 10;
		set %A -l 0;
		layer -a;
	}

	if(Baseline!Tab.Peaks.CenterMarker)
	{
		%B=%[%A, '_'];
		%A=%B_Pklabel;
		layer -i %A;
//		set %A -z 8;
		set %A -c 8;
		layer -a;
	}

	if(Baseline!Tab.Peaks.BaseMarker)
	{
		%A=curve.markerindx$;        
		%B=curve.data$;
		set %B -y %A;
		layer -i201 %A;
		set %A -c 4;
		set %A -k 7;
		set %A -z 15;
		set %A -l 0;
		layer -a;
	}

[CheckBase]
	if(exist(%1_BaseY)!=1)
	{
		type -n $Baseline.CreateBase;
		run.section(,AutoBaseline);
	}
	else
	{
		curve.basey$=%1_BaseY;
		return 0;
	}

[Modi]
	%A=curve.markerindex$;

	if(exist(%A))
	{
		set %A -m 1;   
		mvpts %A;
		//def EndToolBox {Runtool base follow;};   
	}    
	else
	{
		ty -b $baseline.createmark;
		return 1;
	}
	
[Tab.Area.UseBaseLn.OnClick]
	if(run.section(,Check)==0)
		run.section(,Integ,1);

[Tab.Area.FromY.OnClick]
	run.section(,Integ,2);
	return 0;

[Integ]
	if(run.section(,Initialize)!=0) break;
	curve.show=1;
	if(Baseline!Tab.Area.BaseMarker==1)
	{
		
		if (run.section(,CheckMark)!=0)
		{
			type -b $Baseline.CreateMark;
			return 1;
		}
	}

	switch (%1)
	{
	case 1:
		if (run.section(,CheckI)!=0)
		{
			type -b $Baseline.NoBaselineData;
			return 1;
		}
		break;
	case 2:
		curve.base$="";			//No baseline for integration
		break;
	};

	if(Baseline!Tab.Area.BaseMarker==1)
	{
		%B=%C;	
		%A=$Baseline.BasePeaks;
		doc -e W {
			if(page.label$=="%A")
			{
				%A=%H;
				Break;
			}
		}

		Baseline!StoreString$=%A;

		win -o %A
		{ 
			if(exist(%H_area))
			{
				wks.col=colnum(Area);
				delete %H_Area;
				hadcolm=1;
			}
			if(exist(%H_Hwidth))
				delete %H_Hwidth;
			if(exist(%H_Center)))
				delete %H_Center;
			if(exist(%H_Height)))
				delete %H_Height;
			wks.multix=1;
			if(hadcolm!=1)
				wks.col=wks.ncols+1;
			hadcolm=0;
			n=colnum(BMkIndex);
			wks.col=n;
			wks.insert(Area Center Height Hwidth); 
			curve.areas$=%h_Area; 
			curve.halfwidths$=%h_Hwidth;
			curve.centers$=%h_Center;
			curve.Heights$=%h_Height;
		};
		%a=curve.markerindex$;
		err=curve.mrkintegrate();
		run.section(,Output,1);
	}


	/// not integral curve and not using markers
	if(Baseline!Tab.Area.IntCurve.choice==1 && $(Baseline!Tab.Area.BaseMarker)!=1)
	{
		curve.result$="";
		err=curve.integrate();
		run.section(,Output,0);
	}

	if(Baseline!Tab.Area.IntCurve.choice==2 || Baseline!Tab.Area.IntCurve.choice==3)
	{
		%A=curve.worksheet$;
       		win -o %A
       		{
       			%B=curve.data$;
       			wks.col=colnum(%B);
			%B=%[%B,>'_'];
       			for (;1;)
			{
				if (wks.col$(wks.col+1).type==3)
					wks.col+=1;
				else
					break;
			}

			wks.col+=1;     				//Insert after Y or any Error Bar data...
			wks.insert(Integ);
			curve.result$=%(%H,wks.col);
			%A=%(%H,wks.col);
		};
		err=curve.integrate();
		if(Baseline!Tab.Area.IntCurve.choice==3)
		{
			;win -t plot line;	
			queue
			{
				layer -i200 %A;
				set %A -c 4;
				layer -A;
			}
		}
		else
		{
			layer -i200 %A;
			set %A -c 4;
			layer -A;
		}
		run.section(,Output,0);
	}
	
	if(exist(%i)==1)
		curve.base$=%i;

	if (MkS1>=0) 
	{
		i1=MkS1;
		i2=MkS2;
	}
	else 
	{
		get %C -b i1;
		get %C -e i2;
	}

[Output]
	SaveRedirection=type.Redirection(16,3);	// SDB 1/7/99 v6.0148 REPORT_TO_OUTPUTLOG
	type.BeginResults();		/// RKM 12/10/98 v6.0141 REPORT_TO_OUTPUTLOG

	if (%1==0)
	{						//integrate with no markers
		type $baseline.Results;
		separator 3;
		type "$(Curve.integrate.Area)\t$(Curve.integrate.Center)\t$(Curve.integrate.height)";
		separator 3;
	}
	else
	{						//integrate with markers
		%A=curve.peakindex$;
		get %A -e end;
		type $baseline.Results2;
		separator 5;
		for(i=1;i<=end;i+=1)
		{
			%A=%[%A,'_'];	
			type "Peak $(i)\t$(%A_area[i])\t$(%A_Center[i])\t$(%A_height[i])\t$(%A_hwidth[i])";
		}
		separator 5;
	} 	

	type.EndResults();
	type.Redirection=SaveRedirection; // restore previous redirection.
	delete -v SaveRedirection;
	return 0;

[ErrSec]
	switch (curve.lasterrid())
	{
	case 849:
		type -b;				//Beep
		type -b $Baseline.MinWidth;		//Minimum width is too small
		type -q;				//Clear up the status bar
		break;                                  
	case 850:
		type -b;
		type -b $Baseline.Maxwidth;		//Maximum width is too small
		type -q;	
		break;
	};

////////////////////////////////////////////////////
//Verifies that the baseline data is in the layer //
////////////////////////////////////////////////////
[CheckI]
	%B=%C;	
	%A=curve.basey$;

	if(exist(%A)==1)
	{
		%I=%A;
		return 0;
	}
	else
		return 1;

[CheckMark]
	%B=%C;
	%A="";
	doc -e W {
		%A=$Baseline.BasePeaks;	
		if(page.label$=="%A")
		{
			%A=%H;
			Break;
		}
	}
	if(exist(%A)==2)
	{
		%B=%A_bmky;
		curve.markerindex$=%A_bmkindex;
		curve.peakindex$=%A_pkindex;
		curve.areas$=%A_area;
		curve.halfwidths$=%A_hwidth;
		curve.centers$=%A_Center;
		curve.heights$=%A_Height;
		return 0;
	}
	else
		return 1;

[Tab.Area.BaseMarker.OnClick]
	Baseline!Tab.Area.IntCurve.choice=Baseline!Tab.Area.BaseMarker==1?1:0;
	
