///////////////////////////////////////////////////////////////////////////////////////////
// File:	FIT.OGS
// Purpose:	Parameter Initialization for Menu Fitting
//Modification Log:
///////////////////////////////////////////////////////////////////////////////////////////
/// HYYU v4.11 7/11/96 ADD_CHECK_DATA_TYPE
/// RKM 7/22/96 added pv2=0 (pv2=X0) in all ExpDecay sections to take care of the X0 A1 dependancy
/// RKM also changed the report format for ExpDecay per Tom's suggestion
/// RKM also changed all %X to %A
/// ML v4.12 7/22/96 B874 ENABLE_NEGATIVE_COEFFICIENTS
/// JMP v4.133 9/19/96 PkHeightConditon Correct for token pass check...token is really Gauss, but now allow for Gauss or Gaussian..
/// RKM v4.92 2/19/97 REPORT_REDIRECT_TO_NOTES redirect report to Notes window 
/// JMP 2/21/97 v4.92 APPROX_FULLWIDTH_DIVIDED_BY_10
/// CPY 7/28/97 v4.9996 b2840 DOUBLE_FIT_CURVE_FOR_EXPDECAY2
/// RKM 12/10/98 v6.0141 REPORT_TO_OUTPUTLOG
/// SDB 1/7/99 v6.0148 REPORT_TO_OUTPUTLOG
/// RB 3/30/99 v6.0179 PASTETOLOG
/// RKM 5/18/99	ADD_ERROR_BAR_WEIGHTING
/// SDB 7/7/20 INIT_XBEGIN_XEND
/// LAS 9/14/01 PARAM_INIT
/// IV 10/17/2001 CONFIDENCE_LIMITS
/// GRD 2001.12.31 6.1_DECAY_FIT_INIT
/// GRD 2002.01.14 CANCEL_OLD_DIALOG
/// YuI 6/28/02 v7.0332 QA70-2194 UNINITIALIZE_NLSF_RUNTIME_ERROR
/// CPY v7.0361 QA70-2574 NLAFWIZ_1234_RESULT_WKS_NAME_NO_RESULTS
/// Kyle 12/14/2009 QA80-14832 GRAPH_ANALYSIS_QUICK_FIT_DYNA_MENU
/// Folger 01/14/09 QA81-14832 SUPPORT_QUICK_FIT_THEME_WITH_PREFERENCE_SETTINGS
///////////////////////////////////////////////////////////////////////////////////////////

[CheckData]
/* check the dataset type */
	if(%C=="")
	{
		type -b $FIT.NoData;	
		return 1;
	}
	
	/// check plot type

	if (exist(%H)==2)
		worksheet -p 200;
		
	get %C -pt plottype;
	if( plottype == 231 )  /// plot type is error bar 
	{
		type -b $FIT.ErrorBar;
		return 1;
	}
	
	if( plottype == 232 )  /// plot type is text
	{
		type -b $FIT.TextData;
		return 1;
	}	
	/// plot type ok, might still have other consideration later

	return 0;

/// end HYYU v4.11 7/11/96 ADD_CHECK_DATA_TYPE


[WeightAsError]
	///RKM 5/18/99	ADD_ERROR_BAR_WEIGHTING
	%B=errof(%C);
	if (exist(%B)==1)
	{
		nlsf.wType=1;
		nlsf.w$=%B;
		nlsf.chisqrerr=0;	//Don't Scale Errors with Standard Deviation
	}
	else
	{
		nlsf.wType=0;
		nlsf.w$="";
		nlsf.chisqrerr=1;	//Scale Errors with Standard Deviation
	}


[EXPDECAY1]

/* Exponential decay 1 							*/
/* -------------------------------------------------------------*/
/*Fit y0+A1*e^(-(x-x0)/t1) to %C */ 

/// HYYU check the type for fitting
	if( run.section(,CheckData) )
		return 1;
	
	nlsf.init();
	nlsf.func$=ExpDec1;
	/// YuI 6/28/02 v7.0332 QA70-2194 UNINITIALIZE_NLSF_RUNTIME_ERROR
	//	nlsf.execute(parainit); // LAS 9/14/01 PARAM_INIT
	/// end UNINITIALIZE_NLSF_RUNTIME_ERROR

	run.section(,WeightAsError);
	if(run.section(,AutoNLSF)==1)
		return 1;
	/* queue changed to type t1 instead of t     */
	/* this will now be consistant with manuals  */
	/* Modified 4/28/94 by JMP Keyword tt1       */
	queue 
	{
		SaveRedirection=type.Redirection(16,3);	// SDB 1/7/99 REPORT_TO_OUTPUTLOG
		type.BeginResults();		/// RKM 12/10/98 v6.0141 REPORT_TO_OUTPUTLOG
		type $Fit.Expdecay1function;
		///RKM 5/18/99	ADD_ERROR_BAR_WEIGHTING
		%B=errof(%C);
		if (exist(%B)==1)
			type $regression.UsingWeight;
		type;
		type $fit.Chisqr;
		type $fit.Rsquare;
		type;
		type $Regression.ShortParaHeader1;
		Separator 3;
		type "y0\t$(y0)\t$(nlsf.e1)";
		type "A1\t$(A1)\t$(nlsf.e2)";
		type "t1\t$(t1)\t$(nlsf.e3)";
		Separator 3;
		type.EndResults();
		type.Redirection=SaveRedirection; // restore previous redirection.
		delete -v SaveRedirection;
	};

	return	0;


[EXPDECAY2]

/* Exponential decay 2 							*/
/* -------------------------------------------------------------*/ 
 
/// HYYU check the type for fitting
	if( run.section(,CheckData) )
		return 1;
/// HYYU end check data type

	#Fit y0 + A1e^(-(x-x0)/t1) + A2e^(-(x-x0)/t2) to %C
	nlsf.init();
	nlsf.func$=ExpDec2;
	
	/// YuI 6/28/02 v7.0332 QA70-2194 UNINITIALIZE_NLSF_RUNTIME_ERROR
	//	nlsf.execute(parainit); // LAS 9/14/01 PARAM_INIT
	/// end UNINITIALIZE_NLSF_RUNTIME_ERROR


/// GRD 2001.12.31 : Remove the comment characters (//)
/// from the next line to restore the 6.X "Verify Initial Guesses" dialog
//	if(run.section(, OldFitInit, Decay2) == 1) return;	/* 6.1_DECAY_FIT_INIT */
		
	run.section(,WeightAsError);
	if(run.section(,AutoNLSF)==1)
		return 1;
	queue 
	{
		SaveRedirection=type.Redirection(16,3);	// SDB 1/7/99 REPORT_TO_OUTPUTLOG
		type.BeginResults();		/// RKM 12/10/98 v6.0141 REPORT_TO_OUTPUTLOG
		type $Fit.ExpDecay2Function;
		///RKM 5/18/99	ADD_ERROR_BAR_WEIGHTING
		%B=errof(%C);
		if (exist(%B)==1)
			type $regression.UsingWeight;
		type;
		type $fit.Chisqr;
		type $fit.Rsquare;
		type;
		type $Regression.ShortParaHeader1;
		Separator 3;
		type "y0\t$(y0)\t$(nlsf.e1)";
		type "A1\t$(A1)\t$(nlsf.e2)";
		type "t1\t$(t1)\t$(nlsf.e3)";
		type "A2\t$(A2)\t$(nlsf.e4)";
		type "t2\t$(t2)\t$(nlsf.e5)";
		Separator 3;
		type.EndResults();
		type.Redirection=SaveRedirection; // restore previous redirection.
		delete -v SaveRedirection;
	}; 


	return	0;


[EXPDECAY3]

/* Exponential decay 3 */
/* -------------------------------------------------------------*/ 
/// HYYU check the type for fitting
	if( run.section(,CheckData) )
		return 1;
/// HYYU end check data type

	#Fit y0 + A1e^(-(x-x0)/t1) + A2e^(-(x-x0)/t2) + A3e^(-(x-x0)/t3) to %C
	nlsf.init();
	nlsf.func$=ExpDec3;
	
	/// YuI 6/28/02 v7.0332 QA70-2194 UNINITIALIZE_NLSF_RUNTIME_ERROR
	//	nlsf.execute(parainit); // LAS 9/14/01 PARAM_INIT
	/// end UNINITIALIZE_NLSF_RUNTIME_ERROR


/// GRD 2001.12.31 : Remove the comment characters (//)
/// from the next line to restore the 6.X "Verify Initial Guesses" dialog
//	if(run.section(, OldFitInit, Decay3) == 1) return;	/* 6.1_DECAY_FIT_INIT */

	run.section(,WeightAsError);
	if(run.section(,AutoNLSF)==1)
		return 1;
	queue 
	{
		SaveRedirection=type.Redirection(16,3);	// SDB 1/7/99 REPORT_TO_OUTPUTLOG
		type.BeginResults();		/// RKM 12/10/98 v6.0141 REPORT_TO_OUTPUTLOG
		type $Fit.ExpDecay3Function;
		///RKM 5/18/99	ADD_ERROR_BAR_WEIGHTING
		%B=errof(%C);
		if (exist(%B)==1)
			type $regression.UsingWeight;
		type;
		type $fit.Chisqr;
		type $fit.Rsquare;
		type;
		type $Regression.ShortParaHeader1;
		Separator 3;
		type "y0\t$(y0)\t$(nlsf.e1)";
		type "A1\t$(A1)\t$(nlsf.e2)";
		type "t1\t$(t1)\t$(nlsf.e3)";
		type "A2\t$(A2)\t$(nlsf.e4)";
		type "t2\t$(t2)\t$(nlsf.e5)";
		type "A3\t$(A3)\t$(nlsf.e6)";
		type "t3\t$(t3)\t$(nlsf.e7)";
		Separator 3;
		type.EndResults();
		type.Redirection=SaveRedirection; // restore previous redirection.
		delete -v SaveRedirection;
	};


	return	0;


[SetXYoffset]
	/* this macro is used in initializing various
	 * fitting functions
	 * The parameters in limit.??? is assumed
	 * set x0, y0 accordingly
	 */

	/* CPY v3.53 add argument */
	minoffset = %1;
		/* consider zero offset if 5% from zero */
	x0 = limit.xmin;
	if(abs(x0/(limit.xmax-x0)) < minoffset) 
		x0 = 0;		
	y0 = limit.ymin;
	if(abs(y0/(limit.ymax-y0)) < minoffset)
		y0 = 0;
	del -v minoffset;
	#!x0=;
	#!y0=;

/* CPY v3.493 EXPG */


[TypeBasicParam]
	/* type out Chisqr and x0,y0 */
	SaveRedirection=type.Redirection(16,3); 
	type.BeginResults();		/// RKM 12/10/98 v6.0141 REPORT_TO_OUTPUTLOG
	Separator 3;
	type "X offset (x0) = $(x0)";
	type "Y offset (y0) = $(y0)";
	Separator 3;
	type "Chi^2 = $(nlsf.Chisqr)";
	type.EndResults();
	type.Redirection=SaveRedirection; // restore previous redirection.
	delete -v SaveRedirection;
	return	0;



[FitExpGrowth] 
/// HYYU check the type for fitting
	if( run.section(,CheckData) )
		return 1;
/// HYYU end check data type

	#Fit y0 + Ae^(x/t) to %C
	nlsf.init();
	nlsf.func$=ExpGro1;
			       /* ExpGrow function can be double exponential
				* so we restrict it to single by
			 	* using only the first 4 parameters.
			 	* params:y0 x0 A1 t1. Must define function first
			 	*/
	/// YuI 6/28/02 v7.0332 QA70-2194 UNINITIALIZE_NLSF_RUNTIME_ERROR
	//	nlsf.execute(parainit); // LAS 9/14/01 PARAM_INIT
	/// end UNINITIALIZE_NLSF_RUNTIME_ERROR

	
	run.section(,WeightAsError);
	if(run.section(,AutoNLSF)==1)
		return 1;
	queue 
	{
		SaveRedirection=type.Redirection(16,3);	// SDB 1/7/99 REPORT_TO_OUTPUTLOG
		type.BeginResults();		/// RKM 12/10/98 v6.0141 REPORT_TO_OUTPUTLOG
		type $Fit.EXPGROWFunction;
		///RKM 5/18/99	ADD_ERROR_BAR_WEIGHTING
		%B=errof(%C);
		if (exist(%B)==1)
			type $regression.UsingWeight;
		type;
		type $fit.Chisqr;
		type $fit.Rsquare;
		type;
		type $Regression.ShortParaHeader1;
		Separator 3;
		type "y0\t$(y0)\t$(nlsf.e1)";
		type "A\t$(A1)\t$(nlsf.e2)";
		type "t\t$(t1)\t$(nlsf.e3)";
		Separator 3;
		type.EndResults();
		type.Redirection=SaveRedirection; // restore previous redirection.
		delete -v SaveRedirection;
	}; 


	return	0;


[Fit1Peak]
	/* The Fit1Peak macro is used for both Gaussian and
	 * Lorentzian fit. The macro does not need to be defined
	 * before the menu, but it is clearer to put them
	 * together.
	 */  
	/// HYYU check the type for fitting
	if( run.section(,CheckData) )
		return 1;
	/// HYYU end check data type

	NumPeaks = 1;		/* Gauss,Lorentz functions are multi-peaks functions */
	
	integ -q %C;
	nlsf.init();
	if( !%1 )
		nlsf.func$="Gauss";
	else
		nlsf.func$="Lorentz";

	nlsf.numReplica=0;
				/* %1 is the argument passed to the macro */
	/// YuI 6/28/02 v7.0332 QA70-2194 UNINITIALIZE_NLSF_RUNTIME_ERROR
	//	nlsf.execute(parainit); // LAS 9/14/01 PARAM_INIT
	/// end UNINITIALIZE_NLSF_RUNTIME_ERROR


	run.section(,WeightAsError);
	if(run.section(,AutoNLSF)==1)
		return 1;					/* the generic macro for iterating 10 times */
	queue 	 			/* CPY v3.43 peakheight fix */
	{
		%A=nlsf.func$;
		SaveRedirection=type.Redirection(16,3);	// SDB 1/7/99 REPORT_TO_OUTPUTLOG
		type.BeginResults();		/// RKM 12/10/98 v6.0141 REPORT_TO_OUTPUTLOG
		%A=nlsf.func$;
		if(%A=="Gauss") 
			x = P4/(P3*sqrt(pi/2));		/* peak height */
		
		else 
			x = 2*P4/(Pi*P3);

		type "%A fit to %C:";
		///RKM 5/18/99	ADD_ERROR_BAR_WEIGHTING
		%B=errof(%C);
		if (exist(%B)==1)
			type $regression.UsingWeight;
		type;
		type $fit.Chisqr;
		type $fit.Rsquare;
		type;
		type $fit.HeaderInfo;
		Separator 5;
		type "$(P4,*5)\t$(P2,*5)\t$(P3,*5)\t$(P1,*5)\t$(x,*5)";
		type;

		del -s _integ_area;
					/* *5 if a formatting statement for 5 significant digits */
		type.EndResults();
		type.Redirection=SaveRedirection; // restore previous redirection.
		delete -v SaveRedirection;
	};


	return	0;


[FitSigmoidal] 
	if (run.section(,CheckData))
		return 1;	/// HYYU check the type for fitting

	#Sigmoidal fit to %C
	axis -pget X Scale ScaleType;
	if(ScaleType==1) 
		%S = Logistic;
	else 
		%S = Boltzmann;
	nlsf.init();
	nlsf.func$=%S;
	
	/// YuI 6/28/02 v7.0332 QA70-2194 UNINITIALIZE_NLSF_RUNTIME_ERROR
	//	nlsf.execute(parainit); // LAS 9/14/01 PARAM_INIT
	/// end UNINITIALIZE_NLSF_RUNTIME_ERROR


	run.section(,WeightAsError);
	if(run.section(,AutoNLSF)==1)
		return 1;		/* the generic macro for iterating 12 times */
	queue 
	{
		SaveRedirection=type.Redirection(16,3);	// SDB 1/7/99 REPORT_TO_OUTPUTLOG
		type.BeginResults();		/// RKM 12/10/98 v6.0141 REPORT_TO_OUTPUTLOG
		type $Sigmoidal.SigFit;
		///RKM 5/18/99	ADD_ERROR_BAR_WEIGHTING
		%B=errof(%C);
		if (exist(%B)==1)
			type $regression.UsingWeight;
		type;
		type $Sigmoidal.Chisqr;
		type $fit.Rsquare;
		type;
		Separator 3;
		type $Sigmoidal.Init;
		type $Sigmoidal.Final;
		type $Sigmoidal.XatY50;
		if(ScaleType==1) 			/* log scale, must be logistic */
		{
			type $Sigmoidal.Power;
			Separator 3;
			type $Sigmoidal.XatY20Log;
			type $Sigmoidal.XatY80Log;
		}
		else 
		{
			type $Sigmoidal.Width;
			Separator 3;
			type $Sigmoidal.XatY20;
			type $Sigmoidal.XatY80;
		}
							/* *5 if a formatting statement for 5 significant digits */
		type.EndResults();
		type.Redirection=SaveRedirection; // restore previous redirection.
		delete -v SaveRedirection;
	};
	
	
	return	0;


[FitNPeaks]
	/* %1 is the argument passed to the macro */  
/// HYYU check the type for fitting
	if( run.section(,CheckData) )
		return 1;
/// HYYU end check data type

	nlsf.init();
	nlsf.func$=%1;
/// SDB 7/7/20 INIT_XBEGIN_XEND
	nlsf.xBegin = 0/0;
	nlsf.xEnd = 0/0;

	run.section(,WeightAsError);
	/* CPY v3.534J add check numPeaks */
/// RJT : 4/29/02 : AMPO 7750 : changed 12 to 30
	if (NumPeaks<=0 || NumPeaks>30) 
		NumPeaks=2;
	GetNumber -s $Fit.FitNPeaksnumpeaks NumPeaks;
	nlsf.numReplica=NumPeaks-1;
	SaveParaInit=nlsf.ParaInit;
	nlsf.ParaInit=0;
/// RJT : 4/29/02 : AMPO 7750 : changed 12 to 30
	if(NumPeaks > 30) 
	{
		ty -b $Peaks.PeakErr;
		break 1;
	}

	del _Peak_Y;
	create _Peak_Y -X 20;
	
	integ -q %C;

	if(integ.dx < 0) 
	{
		integ.dx *=-1;
		integ.area *= -1;
	}
	/* if x is in descending order, we need to turn these around */

	def QuitFit [del _Peak_Y];

	limit %C;
	run.section(,SetXYoffset,0.05);/* CPY v3.53 */
	/* integration was carried out from zero, we need
	 * to remove the offset */
	integ.area -= y0*(limit.xmax-limit.xmin);
	integ.area/=NumPeaks;
	integ.dx/=NumPeaks;
	GetNumber -s $Fit.FitNPeakshalfwidth integ.dx;
	loop(i,1,NumPeaks) 
	{
		if (NumPeaks==1)
		{
			A=integ.area;
			W=integ.dx;
		}
		else
		{
			A$(i)=integ.area;
			w$(i)=integ.dx;
		}

	} 


	if(y0==0) 
		pv1=0;			/* y0 is the 1st parameter, hold it if zero */
	def EndToolbox 
	{
		doTool 0;		/* reset toolbox */
		loop(i,1,NumPeaks) 
		{
			if (NumPeaks==1)
				XC=_Peak_A[i];
			else
				XC$(i)=_Peak_A[i]; 
		}
		nlsf.fitdata$=%C;
		noFitCurve=-1;		/* we will generate the fit cureves by script */
		nlsf -v 0 1 3;		/* hold all xc's constant */
		nlsf.datastep*=2;
		if(nlsf.iterate(2)==-1)
			return 1;
		nlsf.datastep/=2;
		nlsf.iterate(2);	/* carry out four iterations */
		nlsf.datastep/=2;
		nlsf.iterate(2);
		
		nlsf -v 1 1 3;		/* release all holds on xc's */
		nlsf.datastep*=2;
		nlsf.iterate(2);
		nlsf.datastep/=2;
		nlsf.iterate(5);
		nlsf.end(8);		/* terminate fit */
		SaveRedirection=type.Redirection(16,3);	// SDB 1/7/99 REPORT_TO_OUTPUTLOG
		type.BeginResults();		/// RKM 12/10/98 v6.0141 REPORT_TO_OUTPUTLOG
		type "%1($(NumPeaks)) fit to %C:";
		///RKM 5/18/99	ADD_ERROR_BAR_WEIGHTING
		%B=errof(%C);
		if (exist(%B)==1)
			type $regression.UsingWeight;
		type;
		type $fit.Chisqr;
		type $fit.Rsquare;
		type;
		type "Peak\tArea\tCenter\tWidth\tHeight";
		Separator 5;
		loop(i,1,NumPeaks) 
		{
			x = NumPeaks==1?A:A$(i);
			y=NumPeaks==1?XC:Xc$(i);
			t=NumPeaks==1?W:w$(i);
			/* Cao v3.4 PkHeight */
			/* Joe v4.1 PkHeightConditon check correction */
			if("%[%1,6]"=="Gauss") 
				z = x/(t*sqrt(pi/2));	/* peak height */
			else 
				z = 2*x/(pi*t);
			ty "$(i)\t$(x,*5)\t$(y,*5)\t$(t,*5)\t$(z,*5)";
		}
		Separator 5;
		type "Yoffset = $(y0)";
		type;
		del -s _integ_area;
		type.EndResults();
		type.Redirection=SaveRedirection; // restore previous redirection.
		nlsf.ParaInit=SaveParaInit;
		delete -v SaveRedirection;
		delete -v SaveParaInit;
	};

	GetPts -n _Peak_Y NumPeaks [Double-click (or strike Enter) to set Peak$(1+GetPts.count)];

	return	0;

[ParaConf]
	break.open(Please wait for parameter calculation...);
	break.min=0;
	break.max=100;

	stat.name(1,%1);
	%K=stat.name.worksheet$;
	win -t data Origin %K;
	//---- CPY v7.0361 QA70-2574 NLAFWIZ_1234_RESULT_WKS_NAME_NO_RESULTS
	// %K might not be valid wks name, or already existed, so new wks name might be
	// diff, so need to update %K
	%K=%H;
	//---- end QA70-2574
	loop(ii,1,wks.ncols)
	{
		delete %(%H,wks.ncols);
	}
	work -v Name;
	work -v Value;
	work -v Err;
	work -v Vary;
	work -v LLimit;
	work -v ULimit;
	work -v Depend;
	work -v ConfIntv;
	work -v LConfLimit;    //IV 10/17/2001 CONFIDENCE_LIMITS
	work -v UConfLimit ;    //IV 10/17/2001 CONFIDENCE_LIMITS

	loop(ii,1,wks.ncols)
	{
		wks.col$(ii).type=2;
	}
	
	break.set(20);
	win -o %K 
	{
		wks.col$(colnum(Name)).format=2;
		wks.col$(colnum(Vary)).format=2;
	};

	for(i=1; i<=nlsf.npara; i+=1) 
	{
	    %L=nlsf.n$(i)$;
	    %K_Name[i]$=%L;
	    %K_LLimit[i] = PL$(i);
	    %K_Value[i] = P$(i);
	    %K_ULimit[i] = PU$(i);
	    %K_Err[i]=PE$(i);
	    %K_Depend[i] = nlsf.d$(i);
	    %K_ConfIntv[i] = nlsf.c$(i);
	    %K_LConfLimit[i] = P$(i) - nlsf.c$(i);    //IV 10/17/2001 CONFIDENCE_LIMITS
	    %K_UConfLimit[i] = P$(i) + nlsf.c$(i);     //IV 10/17/2001 CONFIDENCE_LIMITS
	    if(PV$(i)==1) 
	        %K_Vary[i]$="Floating";
	    else 
	        %K_Vary[i]$="Fixed";
	}
	break.set(40);
	
	i=nlsf.npara+1;
	run.section(Fit,SetParamValue,i " Chi^2/DoF" chisqr);
	run.section(Fit,SetParamValue,i "SSR" ssr);   
	run.section(Fit,SetParamValue,i "Correlation" cor);
	run.section(Fit,SetParamValue,i "COD(R^2)" cod);
	run.section(Fit,SetParamValue,i "MuFinal" Mu);
	break.set(50);
	run.section(Fit,SetParamValue,i "MuMin" mumin);
	run.section(Fit,SetParamValue,i "DerivStep" derivstep);
	run.section(Fit,SetParamValue,i "ParaChange" parachange);
	run.section(Fit,SetParamValue,i "Tolerance" Tolerance);
	break.set(60);
	run.section(Fit,SetParamValue,i "Confidence" conf);
	run.section(Fit,SetParamValue,i "Iterations" niter);
	run.section(Fit,SetParamValue,i "Range1" databegin);
	run.section(Fit,SetParamValue,i "Range2" dataend);
	run.section(Fit,SetParamValue,i "Step" datastep);
	break.set(70);
	run.section(Fit,SetParamValue,i "DataPoints" npoints);
	run.section(Fit,SetParamValue,i "DOF" dof);
	run.section(Fit,SetParamValue,i "Constr" nconstr);
	run.section(Fit,SetParamValue,i "ConstrEff" nconstreff);
	break.set(80);

	nlsf.paraconf();
	for(i=1; i<=nlsf.npara; i+=1) 
	{
		%K_LLimit[i] = PL$(i);
		%K_ULimit[i] = PU$(i);
	}
	break.close();	

	return	0;

[SetParamValue]
	%1+=1;
	%K_Name[%1]$=%2;
	%K_Value[%1] = nlsf.%3;
	return	0;


[SetFitMarkers]
	if(%1) 
	{
		mks1=mks1_x;
		mks2=mks2_x;
		del -v mks1_x;
		del -v mks2_x;
	} 
	else 
	{
		mks1_x=mks1;
		mks2_x=mks2;
	}

	return	0;

[AutoNLSF]
	nlsf.xBegin = 0/0;
	nlsf.xEnd = 0/0;
	nlsf.cleanupfitdata();
	nlsf.fitdata$=%C;
	nlsf.execute(parainit);
	if(nlsf.iterate(1)==-1)
		return 1;
	nlsf.iterate(2);
	nlsf.iterate(3);
	if(nlsf.datastep > 4) 
	{
		nlsf.datastep/=2;
		nlsf.iterate(1);
		nlsf.iterate(2);
	}
	if(nlsf.datastep > 1) 
	{
		nlsf.datastep=1;
		nlsf.iterate(2);
	}
	nlsf.iterate(50);
	nlsf.end(8);
	legend;
	return	0;

////////////////////////////////////////////////////////////
// New Gaussian Fit to Histogram Section
// JMP v3.83 9/20/1995 - Created
// JMP v3.84 9/21/1995 - Cleaned-up and simplified
////////////////////////////////////////////////////////////
[HistogramGaussian] 
/// HYYU check the type for fitting
	if( run.section(,CheckData) )
		return 1;
/// HYYU end check data type

	NumPeaks = 1;		/* Gauss,Lorentz functions are multi-peaks functions */

	/* parameters:
	 * y0 = P1
	 * xc = P2
	 * w  = P3
	 * A  = P4
	 */
	
	integ -q %C;
	nlsf.init();
	nlsf.func$ = Gauss;
	nlsf.numReplica=0;

	if(integ.dx < 0) 
	{
		integ.dx *=-1;
		integ.area *= -1;
	}
	/* if x is in descending order, we need to turn these around */

	P1=0;					//Set P1 to 0 and hold 
	PV1=0;	

	limit %C;				//Initialize P2
	%A=xof(%C);
	maxfraction=(%A[limit.imax]-limit.xmin)/(limit.xmax-limit.xmin);   /* find where is maximum */
	minfraction=(%A[limit.imin]-limit.xmin)/(limit.xmax-limit.xmin);   /* find where is minimum */
	maxfraction-=0.5;
	minfraction-=0.5;
	if(abs(maxfraction)<=abs(minfraction))
		P2 = %A[limit.imax];
	else
		P2 = %A[limit.imin];
	del -v 	maxfraction;
	del -v 	minfraction;

	P4 = integ.Area;			//Initialize P4
	P3=abs(2*P4/(limit.ymax-limit.ymin));	//Initialize P3 as f(P4)

	del dummy;				/* incase it was not deleted from other parts */
	dummy={1,1};
	dummy[1]=nlsf.PasteToPlot;			//Get current output settings
	
	/// RB 3/30/99 v6.0179 PASTETOLOG
	//dummy[2]=nlsf.PasteToScript;
	dummy[2]=nlsf.PasteToLog;
	///

	/// RB 3/30/99 v6.0179 PASTETOLOG
	//nlsf.PasteToScript=0;
	nlsf.PasteToLog=0;
	///

	if(run.section(,AutoNLSF)==1)
		return 1;		/* the generic macro for iterating 10 times */

	nlsf.PasteToPlot=dummy[1];			//Reset NLSF output parameters

	/// RB 3/30/99 v6.0179 PASTETOLOG
	//nlsf.PasteToScript=dummy[2];
	nlsf.PasteToLog=dummy[2];
	/// 

	del dummy;

	return	0;

[VarCovarMatrix]
	for(ii=1;1==1;ii++) 
	{
		if(exist(%A$(ii))==0)
			break;
	};	
	win -t matrix matrix %A$(ii);
	matrix -ps dim nlsf.npara nlsf.npara;
	return 0;


/// GRD 2001.12.31
// The following code is only used if you have removed the comments from
// the lines marked with:
// 6.1_DECAY_FIT_INIT

[OldFitInit]

	run.section(,KineticInit,0.05);
	run.section(,FitGuess);
	// GRD 2002.01.14 CANCEL_OLD_DIALOG
	result = run.section(,OldFitDialog%1);
	return result;


[OldFitDialogDecay2]
	t1 = prec(t1,1);			// just the order of magnitude
	A2 = 0.5*A1;t2=10*t1;
	GetNum 
		$Fit.EXPDECAY2firstDecay t1
		$Fit.EXPDECAY2secondDecay t2
		$Fit.EXPDECAY2initial x0
		$Fit.EXPDECAY2inittime pv2:2
		$Fit.EXPDECAY2YOffset y0
		$Fit.EXPDECAY2YOffsetVar pv1:2
		$Fit.EXPDECAY2Verify;
	pv5=1;pv6=1;/* turn on A2 and t2 variables */


[OldFitDialogDecay3]
	t1 = prec(t1,1);			/* just the order of magnitude */
	A2=0.5*A1;t2=10*t1;A3=0.5*A2;t3=10*t2;
	GetNum 
		$Fit.EXPDECAY3firstDecay	t1
		$Fit.EXPDECAY3secondDecay 	t2
		$Fit.EXPDECAY3thirdDecay	t3
		$Fit.EXPDECAY3initial	x0
		$Fit.EXPDECAY3inittime	pv2:2
		$Fit.EXPDECAY3YOffset	y0
		$Fit.EXPDECAY3YOffsetVar	pv1:2
		$Fit.EXPDECAY3Verify;
	pv5=1;pv6=1;			/* turn on A2 and t2 variables */
	pv7=1;pv8=1;			/* turn on A3 and t3 variables */

	
[FitGuess]
/* a rough fit to get init guess */ 
/// HYYU check the type for fitting
	if( run.section(,CheckData) )
		return 1;
/// HYYU end check data type

	NoFitCurve = -1;		/* do not generate fit curve */
	nlsf.cleanupfitdata();
	nlsf.fitdata$=%C;
	if(nlsf.iterate(1)==-1)
		return 1;
	nlsf.iterate(2);
	nlsf.iterate(5);
	//------------ CPY 7/28/97 v4.9996 b2840 DOUBLE_FIT_CURVE_FOR_EXPDECAY2
	//nlsf.end(8);			/* terminate fit */
	nlsf.end(13);// 8+4+1, 8 = no paste parameter to notes, 4= no para to graph, 1 = no fit curve
	//------------ DOUBLE_FIT_CURVE_FOR_EXPDECAY2
	return	0;


[KineticInit]
/* CPY v3.53 changed to add %1 argument */	

	limit %C;
					/* find max/min in both X and Y for the data */

	run.section(,SetXYoffset,%1);
		/* set y0 and x0 based on limit.###
		 * will set y0 or x0 to zero if
		 * they are close to zero
		 */
		 
	/* next we need to find the time constant(t1) and amplitude (A1) */
	del dummy;/* incase it was not deleted from other parts */

	copy -s 20 %C dummy;
		/* we interpolate the data with 20 points and put into
		 * a temporary data set called dummy
		 */
	
//	set dummy -f 0;			/* this remove any possible offset in x */
	dummy-y0;			/* also remove y offset */
	dummy = ln(dummy);
	/*LR -B dummy;
		linear regression on the beginning
		changed to simple LR, CPY v3.493 */
	LR -N dummy;
	#! copy dummy test_B;LR.B=;LR.A=;

	del dummy;			/* we are interested only in the parameters */
	
	t1=-1/LR.B;t1=$(t1,*3);
	A1=exp(LR.A);A1=$(A1,*3);	/* limit them to 3 sig digits */
	if(y0==0) 
		pv1=0;			/* hold y0 if it is zero */
	A2=0;A3=0;			/* to disable the other two exponentials */
	nlsf.msgprompt=2;		/* No_dependency_msg Cao 5/5/94*/

	return	0;

///Kyle 12/14/2009 QA80-14832 GRAPH_ANALYSIS_QUICK_FIT_DYNA_MENU
[QFitExecPoly]
//	%1: Order
//	%2: use panel tool

	int		nOrder = %1;
	int		nUsePanelTool = %2;
	if(nUsePanelTool)
	{
		addtool_quickfit func:="" order:=nOrder;
	}
	else
	{
		quickfit func:="" order:=nOrder;
	}

[QFitExecNLF]
//	%1: function
//	%2: use panel tool

	string	strFunction = %1;
	int		nUsePanelTool = %2;
	if(nUsePanelTool)
	{
		addtool_quickfit func:=strFunction$ order:=0;
	}
	else
	{
		quickfit func:=strFunction$ order:=0;
	}

[QFitEdit]
	Run.LoadOC(Originlab\QuickFit.c, 16);
	run -OC OpenQuickFitEditDlg;

[QFitPrefer]
	Run.LoadOC(Originlab\QuickFit.c, 16);
	run -OC OpenQuickFitOutputPreferDlg;	

[QFitFindXY]
	Run.LoadOC(Originlab\QuickFit.c, 16);
	run -OC OpenQuickFitFindXYDlg;	
///End GRAPH_ANALYSIS_QUICK_FIT_DYNA_MENU

/// Iris 1/22/2010 COMMENT_OUT_UNUSEFUL_CODES
/*
///------ Folger 01/14/09 QA81-14832 SUPPORT_QUICK_FIT_THEME_WITH_PREFERENCE_SETTINGS
[QExecTheme]
	Run.LoadOC(Originlab\QuickFit.c, 16);
	run -OC ExecuteQuickFitTheme(%1, %2);
///------ End SUPPORT_QUICK_FIT_THEME_WITH_PREFERENCE_SETTINGS
*/
///End COMMENT_OUT_UNUSEFUL_CODES