/*------------------------------------------------------------------------------*
 * File Name:Stats_Operations 													*
 * Creation: CPY Feb 21, 2004													*
 * Purpose: Autoupdate Operation support for stats related functions			*
 * Copyright (c) Originlab Corp.	2004, 2005									*
 * All Rights Reserved															*
 * 																				*
 * Modification Log:															*
 *	ML 3/3/2004 RANGE_BASED_REGRESSIONS											*
 *	ML 5/24/2004 QA70-6376 REPORT_TABLE_MULTIHEADERS_MORE_WORK					*
 *	CPY 6/9/04 TABLE_HEADER_CLEANUP_FOR_SINGLE_OR_MULTIPLE_SETS					*
 *	ML 8/17/2004 QA70-6825 RLOG_QUERY											*
 *	CPY 11/26/04 OUTPUT_FIT_CURVES_TO_SOURCE_SHEET								*
 *  Iris 4/12/05 MOVE_CURVE_OPTION_TO_EACH_GRAPH								*
 *  Iris 4/21/05 UPDATE_RESIDUAL_CALCULATION_METHOD								*
 *	ML 6/6/2005 STYLE_LINKS_WITH_OFFSETS										*
 *	ML 6/9/2005 REPEATITIVE_STYLES_IN_GRID_THEMES								*
 *	ML 7/20/2005 FITTING_FUNCTION_FORMULA_IN_REPORT								*
 *	ML 10/13/2005 QA70-8157 SPECIAL_NAMES_STYLES_IN_FLAT_SHEETS					*
 *  Iris 11/15/05 QA70-8297 NOT_SHOW_RESIDUAL_DATA_IF_GRAPH_CHECKBOX_IS_UNCHECK *
 *	YuI 11/09/05 QA70-8279 REPORT_TREE_AND_REPORT_DATA_XVARIABLES				*
 *  Jim 2/22/06 ADD_RESIDUAL_LAG_PLOT_TO_RESIDUALS_PLOTS_BRANCH					*
 *	ML 4/28/2006 FRIENDLY_CUSTOM_TABLE_THEME_GENERATION							*
 *  Thomas 05/30/2006 CALL_SETREPORTWORKSHEETDESIGNATION_INSTEAD				*
 *  Thomas 06/08/06 MOVE_ANOVA_CHECK_BOX_TO_QUANTITIES_BRANCH					*
 *  Alex 06/19/06 SET_COVARIANCE_AND_CORRELATION_TABLE_OPEN                     *
 *  Alex 06/19/06 SET_COVARIANCE_AND_CORRELATION_TABLE_ON_OPTIONS_OF_USER       *
 *	Cheney 2006-8-31 ADD_AVERAGE_DATA_TABLE										*
 *	Cheney 2006-9-1 AVE_REPLICA_DATA_IF_PLOTTYPE_EXIST_AND_NOT_RAW_DATA 		*
 *	Cheney 2006-9-1 GET_MULTICURVE_DATA_FOR_AVE_REPLICA							*
 *  Joseph 9/18/06 CHANGE_FINDX_FROMY_STEP										*
 *	ML 9/18/2006 DATARANGE_EXTRACTION_APPARENT_FIT								*
 *	ML 9/20/2006 RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT					*
 *  Iris 9/27/06 KEEP_RESULT_DATA_EVEN_THOUGH_NOT_PLOT							*
 *	Cheney 2006-10-10 CONCATENATE_IS_ONE_METHOD_OF_AVERAGE						*
 *	Arvin 10/23/06 FITTING_RESIDUALS_HISTOGRAM_PLOT_CENTRALIZED					*
 *	Cheney 2006-10-25 ADD_A_NEW_TORLERANCE										*
 *	Cheney 2006-11-1 CHANGE_sReg_FROM_REF_TO_POINTER							*
 *  Arvin 11/02/06 ALL_LEGEND_SAME_NAME_FOR_FIT_GRAPH							*
 *	Cheney 2006-11-13 SET_PARAMS_VALUE_WITH_SIGNIFICENT_DIGITS					*
 *	CPY 11/13/06 SHOULD_NEVER_ROUND_PARAM_VALUES_INTERNALLY						*
 *	ML 11/13/2006 THEME_DIGITS_PARAMETERS_TBL									*
 *	Cheney 2006-11-15 FIT_SHOULD_BY_RAW_DATA_AND_PLOT_TYPE_ONLY_WORK_FOR_GRAPH_DISPLAY
 *	Iris 11/30/2006 ADDITIONAL_LABEL_ROWS_IN_CURVE_SHEETS						*
 *	Cheney 2006-12-1 CLEAN_CODE													*	
 *  Iris 12/29/2006 v8.0534 PARAM_NAME_AS_TAGNAME_FOR_CELL_LINKING				*
 *	Arvin 01/18/06 CALC_RESIDUAL_WITH_REPLICA									*
 *  Iris 01/31/2007 SHOW_PARAMS_IN_SUMMARY_TABLE_ON_PARAMS_QUANTITIES			*
 *	Arvin 02/13/07 ADD_X_DATA_TO_RESIDUAL_DATA_TABLE							*
 *	Cheney 2007-3-24 SHOULD_NOT_PASS_DERIVED_PARAMS_WHEN_FIND_X_FROM_Y			*
 *	ML 4/4/2007 FOR_FIT_MODE_FIGURING_OUT_MUST_NOT_USE_COMBINED_SINCE_COMBINED_GetNumData_ALWAYS_1
 *	Cheney 2007-4-12 SET_FIXED_VALUE_AS_STRING_INSTEAD_OF_INT					*
 *	Cheney 2007-4-13 CORRECT_RESIDUAL_COMPUTING_WHEN_MULTI_INDEP_AND_DEP		*
 *	Cheney 2007-4-13 FIX_BUG_OF_CUSTOM_TABLE_DISAPPEAR_WHEN_CONCATENATE			*
 *	Cheney 2007-4-24 SHOULD_SET_ONLY_ONCE_EVENT_HANDLER_IN_ONE_TREENODE			*
 *	Cheney 2007-5-17 LINEAR_FIT_SHOULD_CONSISTENT_WITH_FIT_NL					*
 *	Cheney 2007-5-21 NEED_UPDATE_ERROR_CHECKING_OF_REPORT_TABLE_FOR_OPERATION_BASED_TOOLS
 *	Cheney 2007-5-28 IF_EMPTY_DATA_SET_SHOULD_SET_MISSING_AS_RESULT				*
 *	Cheney 2007-6-15 IF_CHANGE_PARAM_SHOULD_ALSO_UPDATE_TBL_THEME				*
 *	Arvin 06/20/07 v8.0645 WRONG_CONF_PRED_BAND_FOR_MULTI_PEAKS_FIT				*
 *	Cheney 2007-6-19 ALWAYS_FIND_XY_FROM_CUMULATIVE_FIT_CURVE_IF_PEAK_FIT		*
 *  Iris 06/27/2007 v8.0650 ACCESS_NODE_BY_DATAID_TO_AVOLID_RUNTIME_ERR			*
 *	Nicole 07/05/2007 v8.0655 REMOVE_SPACE_FOR_LOCATION_STRING					*
 *  Iris 07/30/2007 FIX_GRAPH_NUM_OF_COLS_CHANGED_IN_CHANGE_PARAM				*
 *	Arvin 08/02/07 CHECK_WEIGHT_DATA_HAS_MISSING_AND_NEGATIVE_VALUES			*
 *	Arvin 08/03/07 WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA				*
 *	Arvin 08/10/07 QA70-10197 ADD_NONE_OPTION_FOR_ERROR_AS_WEIGHT_IN_LR_PR_AND_MR
 *	Arvin 08/13/07 v8.0680 FIND_PRED_AND_CONF_BAND_AND_ELLIPSE_PLOT_INDEX		*
 *	Echo 8/17/07	MOVE_TO_PAGE_UTILS											*
 *	Arvin 08/29/07 QA70-10073-P7 WRONG_AVE_ERR_NODE_ORDER						*
 *	Cheney 2007-8-31 QA70-10330 CLEAN_UP_PLOT_SETTING_BRANCH_IN_OUTPUT_RESULT_NODE
 *	Arvin 09/06/07 SHOULD_CHECK_REPORT_SHEET_AVAILABLE							*
 *	Cheney 2007-9-7 SHOULD_JUST_SET_SHOW_AS_FALSE_IF_NOT_CHECK_PLOT_FIT_CURVE	*
 *	Cheney 2007-9-18 IF_FROM_THEME_SHOULD_NOT_UPDATE_CUSTOM_RANGE				*
 *	TD 10-04-2007 QA80-10478 LOCALISED_REPORTTREE_ISSUE							*
 *  CPY 10/12/07 10522-P3 CLEANUP_IF_LOOSE_DATASET_SHOULD_NOT_PUT_REPORT_SHEET_TO_SOURCE
 *	Arvin 10/22/07 ADD_CHECKBOX_USE_SOURCE_GRAPH_COLOR_TO_SET_FITCURVES_COLOR	*
 *	Arvin 10/23/07 QA70-10559-P3 SHOULD_NOT_CREATE_EMPTY_SHEET_WHEN_UNCHECK_ALL_RESIDUALS_CHECK_BOX
 *	Arvin 10/23/07 QA70-10559-P3 SHOULD_NOT_CREATE_EMPTY_SHEET_WHEN_UNCHECK_FITTED_CURVES_PLOT
 *	RVD 10/30/2007 v8.0737 qa7-10609 REPORT_FOOTNOTE_STYLE_THEME				*
 *	ML 10/31/2007 QA70-10630 LOCALIZING_KEYWORDS_FOR_XF_AND_THEMES				*
 *	Jasmine 11/05/07 SUBTRACT_BASELINE_BEFORE_PFM_FIT							*
 *	Jasmine 11/08/07 ADD_SHARED_TO_PARAMETER_REPORT_TABLE						*
 *	Folger 11/08/07 CATEGORY_NEEDED_WHEN_LOCALIZE								*
 *	Arvin 11/15/07 QA70-10619 KEEP_AVE_DATA_NODE_FOR_NULL_DATASET				*
 *	Arvin 11/28/07 WRONG_INPUT_X_Y_DATA_FOR_APPARENT_FIT						*
 *	Folger 12/04/07 LOCALIZE_PARAMETER_TABLE									*
 *	Arvin 12/24/07 QA70-10442 XDATATYPE_SHOULD_NOT_SAVE_DATATYPE_ATTRIB_INTO_THEME
 *	Arvin 01/03/08 ADD_STAR_MARK_FOR_SHARED_PARAMS as cp said					*
 *	ML 1/25/2008 MISMATCHED_BODY_WITH_DECLARATION_PREVENTS_COMPILATION			*
 *	Arvin 01/28/08 QA70-10923 CALC_CONFIDENCE_AND_PREDICTION_BANDS				*
 *	Arvin 02/15/08 QA70-11097 KEEP_ESCAPED_STRINGS								*
 *	Folger 03/12/08 FIXED_RUNTIME_ERROR_WHEN_TRTBL_IS_TREE_BRANCH				*
 *	Folger 03/19/08 QA80-10598 NEW_GETN_LOCALIZAED_CHECK_MACRO					*
 *	Arvin 03/25/08 MOVE_REPLICA_BARANCH_OUT_OF_FIT_CONTROL_BRANCH as CP said	*
 *	Folger 04/01/08 QA80-11304 SHOW_SHARED_SIGN_IN_REPORT_SHEET_FOR_REPLICA_FITTING
 *  Iris 4/16/2008 REMOVE_PARAM_TABLE_IF_IT_IS_EMPTY							*
 *	Iris 4/23/2008 NOT_GENERAGE_TABLE_IF_NOT_REPORT_TO_IMPROVE_NLSF_SPEED		*
 *	Folger 04/23/08 SUPPORT_GROUP_SHARED_IN_NANOSIZER							*
 *	Hong 13/05/08 QA80-11541 ADD_FOOTNODE_IF_UNCHECK_USE_REDUCED_CHISQR			*
 *	Folger 05/20/08 USE_ENGLISH_LABEL_TO_GENERATE_REPORT_TREENODE_TAGNAME		*
 *	Jasmine 06/11/08 QA80-11678 TO_HIDE_STATS_TABLE_SHOULD_CHECK_QUANTIT_STATS	*
 *	Folger 06/17/08 QA80-11723 REMOVE_UNWANTED_GRAPH1_NODE_FOR_NLFIT_WITH_CHANGED_AXIS
 *	Jasmine 08/19/08 QA80-12046 OFFSET_PARAM_SHOULD_HAVE_SAME_SUFFIX_FORMAT_AS_OTHERS
 *	Hong 09/03/08 QA80-12130 NLFIT_SESSION_SUPPORT_SEPARATE_FIT					*
 *	Kyle 10/20/08 PEAK_NUMBER_OFFSET_IS_ALWAYS_ONE								*
 *	Sophy 10/28/2008 SHOULD_REARRANGE_LAYERS_WHEN_SWITCH_BETWEEN_SINGLE_INDEP_N_DEP_AND_MULTI_IDEP_N_DEP
 *	Folger 11/06/08 QA80-12538 v0.966 CENTRALIZE_CODE_ABOUT_GETTING_GUI_REPLICA_NODE
 *  Iris 11/20/2008 v8.0975d QA80-12591-S1 SET_TO_USE_SOURCE_GRAPH_SCALE_TYPE_IF_NOT_LINEAR_SCALE_TYPE*
 *	Sophy 11/24/2008 v8.978c CHECK_SET_XDATATYPE_VALUE_ON_APPLY_THEME			*
 *	Sophy 11/28/2008 v8.0980d QA80-12591-P5 ADD_AUTO_SUPPORT_FOR_LR_AND_PR_FITCURVE_XDATATYPE
 *	Folger 12/01/08 v8.0981 MORE_ON_USE_UNCONVERTED_DATA_LABEL_FOR_REGSTATS_TABLE_COLUMNS
 *	Hong 12/03/08 QA80-12499 v8.0982 FIX_DUPLICATE_ID_CAUSE_SOME_DATA_DISAPPEAR_IN_REPORT_SHEET
 *	Sophy 12/11/2008 v8.984d NLFIT_XDATATYPE_SHOULD_BE_SOURCE_GRAPH_SCALE_TYPE_AS_LR_WHEN_DATA_FROM_GRAPH
 *	Folger 12/11/08 QA80-12766 v8.0985 SIGNIFICANT_DIGITS_FAILS_TO_APPLY_TO_NLSF_FITTING_REPORT
 *	Jack 12/19/2008 QA80-12329 MULTI_INDEP_DEPS_BAND_CALCULATION				*
 *	Folger 12/22/08 QA80-12766-P2 v8.0990 SIGNIFICANT_DIGITS_NOT_WORKING_FOR_MULTIPLE_DATASETS_REPORT
 *	Hong 12/23/08 v8.0990 PA_AVOID_NESTED_LOOP_BY_CACHE_LAST_RESULT				*
 *	Jack 12/25/2008 QA80-12329 CENTRALIZE_MULTI_INDEP_DEPS_BAND_CALCULATION		*
 *	Sophy 1/15/2009 v8.0957 QA80-12918 FITCURVE_X_COLULMN_FORMAT_MUST_BE_CONSISTENT_WITH_SOURCE_DATA
 *	Folger 02/25/09 SHARED_SYMBOL_FAILS_TO_SHOW_IN_PA_FITTING_REPORT			*
 *  Iris 3/16/2009 QA80-13285-P1 FIX_DUPLICATE_RESIDUAL_DATA_REPORT_FOR_DIFF_RESIDUAL_REPORT_AND_PLOT
 *	Kyle 03/18/2009 QA80-13305 FIX_APPARENT_LINEAR_FIT_OUTPUT_WRONG_X_VALUES_FOR_RESIDUAL
 *	Folger 03/23/09 PA_FAILS_TO_MAKE_CORRECT_RESIDUAL_PLOT_WHEN_HAS_ONLY_ONE_PEAK
 *	Folger 03/24/09 QA80-13331-P1 CUSTOMIZED_OUTPUT_COLUMN_LONGNAME_FORMAT_SUPPORT
 *  Iris 3/26/2009 QA80-13353 NEED_SURPLUS_RESULT_CURVE_TABLE_WHEN_CHANGE_PARAM_OR_RECALCULATE
 *	Folger 03/28/09 QA80-12786 SUPPORT_DATA_TIME_FORMAT_DISPLAY_FOR_GENERAL_FITTING_TOOLS_CUSTOM_XDATATYPE
 *	Kyle 03/31/2009 QA80-3224 NEW_OPTION_TO_SUPPORT_LINEAR_FIT_WITH_ERROR_BAR	*
 *	Sophy 4/3/2009 QA80-13352 SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
 *	Kyle 04/09/2009 QA80-3224-P1 SHOW_WEIGHTING_MODE							*
 *  Iris 4/29/2009 QA80-12017 NEED_ADD_NEW_REPORT_ITEM_WHEN_RECALCULATE_ON_OLD_OPJ
 *  Iris 5/19/2009 QA80-13596 ADD_APPERENT_FIT_MSG_IN_PARAM_TABLE_FOOTNOTE		*
 *  Iris 5/25/2009 QA80-13596 INCLUDE_APPEART_FIT_FOOTNOTE_IN_SR6				*
 *	Hong 05/27/09 QA80-13670 FIX_FIX_STATUS_NOT_KEPT_WHEN_RECALCULATE_OLD_OPERATION
 *	Sim 06-17-2009 QA80-13786-P2-P4 SPEEP_UP_LINEAR_FIT_WITHOUT_REPORT_TABLE	*
 *	Folger 07/07/09 NANOSIZER_PARAMETER_SHARE_INFO_NOT_SHOW_CORRECTLY_IN_REPORT	*
 *	Sophy 7/8/2009 v8.1060 CLEAN_CODE_SUPPORT_UPDATE_Y_DATATYPE_BRANCH			*
 *	Sophy 7/22/2009 v8.1073 NANOSIZER_NEED_TO_GET_ORIGINAL_INPUTDATA			*
 *	Kyle 08/10/2009 QA80-14077 ADD_PARAMETER_UNIT_TO_FITTING_REPORT				*
 *  Iris 9/10/2009 QA80-11710-P2 IMPROVE_REPORT_GRAPH_WHEN_PLOT_IN_ONE_GRAPH_WITH_GROUPING_DATA
 *  Iris 9/25/2009 FIX_LR_STILL_REPORT_EMPTY_ANOVA_TABLE_IF_NOT_CHECKED_ON_GUI	*
 *  Iris 10/10/2009 QA80-14440 FOND_DUPLICATE_PARAM_NAME_AS_REPORT_TREENODE_NAME*
 *  Iris 11/24/2009 QA81-3224-P2 FIX_WEIGHT_NOT_CORRECT_IN_NOTES_TABLE			*
 *	Hong 12/24/09 QA80-14832 NLFIT_OPEN_BY_HOTKEY_SOPPORT_APPLY_SETTING_FROM_QUICKFIT_WITHOUT_ANY_THEME
 *  Iris 11/24/2009 QA81-3224-P5 FIX_ERRBARWEIGHT_IS_ENABLE_WHEN_CHANGE_PARAM_MORE
 *	Folger 03/19/10 QA81-15218 ADD_LINEAR_FIT_AND_POLYNOMIAL_FIT_TO_QUICKFIT_CONTEXT_MENU
 *	Folger 03/24/10 QA81-15218-P3 BRING_UP_POLYNOMIAL_FIT_FROM_QUICK_FIT_SHOULD_APPLY_CURRECT_ORDER
 *	Folger 03/24/10 QA81-15218-P2 SHOULD_TAKE_CARE_OF_ERROR_WHEN_SWITCH_TO_LINEAR_FIT
 *	Jasmine 05/24/10 SRVC-12 ALLOW_SAME_AS_INPUT_FOR_ALL_SURFACE_FIT			*
 *  Iris 6/17/2010 ORG-301 FIX_MR_WHEN_INPUTDATA_LONGNAME_IS_NUMERIC_BUG		*
 *	Folger 08/25/10 ORG-897-P4 FITTER_OPERATION_OUTPUT_FIT_CURVE_AND_RESIDUAL_X_SHOULD_FOLLOW_SOURCE
 *	Sophy 9/13/2010 ORG-1037-S1 NO_APPARENT_FIT_FOOTNOTE_WHEN_BOTH_XY_AXES_LINEAR_ON_SRC_GRAPH
 *------------------------------------------------------------------------------*/
     
#include <Origin.h>
#include <report_utils.h>
#include "nlsf_utils.h" /// Iris 7/08/2008 CLEAN_DUP_CALC_AVE_DATA_CODE_IN_NLSF_PREVIEW_AND_OP

#include "FitCommon.h"

///Cheney 2006-8-24 ADD
#ifndef _FDF_TREE_H 
#include <FDFTree.h> 
#endif 

#ifndef __ONLSF_H__ 
#include <ONLSF.h> 
#endif
///end ADD 

//------ Folger 11/08/07 CATEGORY_NEEDED_WHEN_LOCALIZE
#define STR_CAT_STATS "Statistics"
//------ End CATEGORY_NEEDED_WHEN_LOCALIZE

#include <event_utils.h>///Cheney 2007-8-23 QA70-10290 FITCURVE_AND_REPORT_SHOULD_BE_SAME_BOOK_IF_SRC_DATA_FROM_DIFF_BOOK

////////////////////////////////////////////////////////////////////////////////
// Begin basic support functions
////////////////////////////////////////////////////////////////////////////////
// CPY 2/20/04, general function for ANOVA table, can be shared
/// ML 3/3/2004 RANGE_BASED_REGRESSIONS
//static void stats_tree_add_ANOVA_table(TreeNode trCal, const RegANOVA& sANOVA)

/// ML 3/3/2004 RANGE_BASED_REGRESSIONS


/// ML 5/24/2004 QA70-6376 REPORT_TABLE_MULTIHEADERS_MORE_WORK
//void	add_factor_values(TreeNode &trParent, vector<string> &vstrFactors, int nStartIndex)
//{
//	string		strTag, strLabel;
//	int			nNumFactors = vstrFactors.GetSize();
//	for (int ifct = nStartIndex; ifct < nNumFactors; ifct++)
//	{
//		strTag.Format("Factor%d", ifct + 1);
//		TreeNode		trFctValue = trParent.AddNode(strTag);
//		trFctValue.strVal = vstrFactors[ifct];
//		strLabel.Format("Factor %d", ifct + 1);
//		trFctValue.SetAttribute(STR_LABEL_ATTRIB, strLabel);
//		
//		trFctValue.SetAttribute(STR_LABEL_ATTRIB, strLabel);
//	}
//}


/// end REPORT_TABLE_MULTIHEADERS_MORE_WORK

/// end RANGE_BASED_REGRESSIONS

///Echo 8/17/07	MOVE_TO_PAGE_UTILS
///Arvin 08/13/07 v8.0680 FIND_PRED_AND_CONF_BAND_AND_ELLIPSE_PLOT_INDEX
/*
static bool string_range_has_key(const string& strPlotRange, LPCSTR lpcszKey, bool bCaseSensitive)
{
	bool bFind = false;
	string strKey(lpcszKey);
	bFind = strPlotRange.Find(strKey) >= 0;
	if(!bCaseSensitive)
	{
		strKey.MakeLower();
		bFind |= strPlotRange.Find(strKey) >= 0;
		strKey.MakeUpper();
		bFind |= strPlotRange.Find(strKey) >= 0;
	}
	return bFind;
}

int find_plot_index_by_key(const GraphLayer& gl, LPCSTR lpcszKey1, LPCSTR lpcszKey2, int nPlotFrom, bool bCaseSensitive, DWORD dwCntrl)
{
	if(lpcszKey1 == NULL)
		return -1;
	
	int index = 0;
	bool bFind = false;
	foreach(DataPlot dp in gl.DataPlots)
	{
		if(nPlotFrom >=0 && nPlotFrom > index)
		{
			//do nothing
		}
		else
		{
			string strPlotRange;
			BOOL bRet = dp.GetRangeString(strPlotRange, dwCntrl);
			if(lpcszKey1)
			{
				bFind = string_range_has_key(strPlotRange, lpcszKey1, bCaseSensitive);
				if(bFind && lpcszKey2)
					bFind = string_range_has_key(strPlotRange, lpcszKey2, bCaseSensitive);
			}
			if(bFind)
				return index;
		}
		
		index++;
	}
	
	return -1;
}
///end FIND_PRED_AND_CONF_BAND_AND_ELLIPSE_PLOT_INDEX
*/
///END MOVE_TO_PAGE_UTILS

///Arvin 11/28/07 WRONG_INPUT_X_Y_DATA_FOR_APPARENT_FIT
static void _covert_vector_apparent(vector &v, GraphLayer &grLayAppar, int nAxis, BOOL bForward = FALSE)
{
	if (grLayAppar)
	{
		vector		vTransf(v.GetSize());
		if ( grLayAppar.ConvertByAxis(v, v.GetSize(), nAxis, bForward, vTransf) )
			v = vTransf;
	}
}
///end WRONG_INPUT_X_Y_DATA_FOR_APPARENT_FIT

#define		DATA_LABEL_NODE_NAME			"Data"
static	void	add_report_data_label_node(TreeNode& trNode, const string &strDataLabel)
{
	if ( !strDataLabel.IsEmpty() )
	{
		TreeNode		trLabel = trNode.AddTextNode(strDataLabel, DATA_LABEL_NODE_NAME);
	}
} 

//----------- CPY 8/12/04 ANOVA_IN_SEPARATE_TABLES
 
#ifndef ANOVA_IN_SEPARATE_TABLES
//static	TreeNode	stats_tree_set_one_ANOVA_set(TreeNode &trANOVA, LPCSTR lpcszName, const string &strDataLabel, int index, int nID, const RegANOVA& sANOVA, int indInStruct, vector<string> &vstrFactors) /// Iris 10/06/04 
///Arvin 05/25/07 ADD_CORRECTED_TOTAL_ROW_FOR_ANOVA_TABLE_FOR_FITNL
//TreeNode	stats_tree_set_one_ANOVA_set(TreeNode &trANOVA, LPCSTR lpcszName,  LPCSTR lpcszDataLabel, int index, int nID, const RegANOVA& sANOVA, int indInStruct)
TreeNode	stats_tree_set_one_ANOVA_set(TreeNode &trANOVA, LPCSTR lpcszName, LPCSTR lpcszDataLabel, int index, int nID, const RegANOVA& sANOVA, int indInStruct, LPCSTR lpcszLabel)
///end ADD_CORRECTED_TOTAL_ROW_FOR_ANOVA_TABLE_FOR_FITNL
{
	string			strTag;
	strTag.Format("%s%d", lpcszName, index + 1);	
	TreeNode		tr = tree_check_get_node(trANOVA, strTag, nID);
	
	int				nLabelIndex = -1;
	string			strDataLabel(lpcszDataLabel);
	if ( !strDataLabel.IsEmpty() )
		tree_add_one_label(tr, strDataLabel, nLabelIndex++);
	///Arvin 05/25/07 ADD_CORRECTED_TOTAL_ROW_FOR_ANOVA_TABLE_FOR_FITNL
	//tree_add_one_label(tr, lpcszName, 0);
	if(lpcszLabel)
		tree_add_one_label(tr, lpcszLabel, nLabelIndex++);
	/// Iris 05/29/2007 v8.0629 DUPLICATE_LABEL_IN_ANOVA_ONE_WAY
	//else
	//	tree_add_one_label(tr, lpcszName, 0);
	///end DUPLICATE_LABEL_IN_ANOVA_ONE_WAY
	///end ADD_CORRECTED_TOTAL_ROW_FOR_ANOVA_TABLE_FOR_FITNL
	RegANOVARow		stTemp;
	stTemp = sANOVA.AnovaTable[indInStruct];
	tr = stTemp;
	
	if(nID)
		tr.ID = nID; 
	
	if(tr.DOF)
		///Cheney 2007-10-27 CLEAN_UP_LOCALIZATION_THINGS
		//tr.DOF.SetAttribute(STR_LABEL_ATTRIB, "DF");
	///Sophy 3/30/2009 QA80-13352 SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
		//tr.DOF.SetAttribute(STR_LABEL_ATTRIB, _L("DF") );
	{
		tr.DOF.SetAttribute(STR_LABEL_ATTRIB, _L("DF") );
		tr.DOF.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
	}
	///end SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
		///end CLEAN_UP_LOCALIZATION_THINGS
	
	/// Iris 11/08/05 change some row label for ANOVA table
	if(tr.SSq)
		///Cheney 2007-10-27 CLEAN_UP_LOCALIZATION_THINGS
		//tr.SSq.SetAttribute(STR_LABEL_ATTRIB, "Sum of Squares");
	///Sophy 3/30/2009 QA80-13352 SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
		//tr.SSq.SetAttribute(STR_LABEL_ATTRIB, _L("Sum of Squares") );
	{
		tr.SSq.SetAttribute(STR_LABEL_ATTRIB, _L("Sum of Squares") );
		tr.SSq.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
	}
	///end SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
		///end CLEAN_UP_LOCALIZATION_THINGS
		
	if(tr.MeanSq)
		///Cheney 2007-10-27 CLEAN_UP_LOCALIZATION_THINGS
		//tr.MeanSq.SetAttribute(STR_LABEL_ATTRIB, "Mean Square");
	///Sophy 3/30/2009 QA80-13352 SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
		//tr.MeanSq.SetAttribute(STR_LABEL_ATTRIB, _L("Mean Square") );
	{
		tr.MeanSq.SetAttribute(STR_LABEL_ATTRIB, _L("Mean Square") );
		tr.MeanSq.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);		
	}
	///end SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
		///end CLEAN_UP_LOCALIZATION_THINGS
	
	///Iris 10/27/04 ADD_F_P_VALUE_TO_ANOVA_TABLE
	///Cheney 2007-10-27 CLEAN_UP_LOCALIZATION_THINGS
	//tree_check_get_node(tr, "FValue", IDE_ANOVA_FVALUE, STR_LABEL_ATTRIB, "F Value");
	//tree_check_get_node(tr, "PValue", IDE_ANOVA_PVALUE, STR_LABEL_ATTRIB, "Prob>F");
	tree_check_get_node(tr, "FValue", IDE_ANOVA_FVALUE, STR_LABEL_ATTRIB, _L("F Value") );
	tree_check_get_node(tr, "PValue", IDE_ANOVA_PVALUE, STR_LABEL_ATTRIB, _L("Prob>F") );
	///end CLEAN_UP_LOCALIZATION_THINGS
	if(ANOVA_MODEL == indInStruct)
	{
		tr.FValue.dVal = sANOVA.Fvalue;
		tr.PValue.dVal = sANOVA.Pvalue;
	}	
	///End ADD_F_P_VALUE_TO_ANOVA_TABLE
	///Sophy 3/30/2009 QA80-13352 SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
	tr.FValue.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
	tr.PValue.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
	///end SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES

	/// Iris 11/08/05 MeanSq of Total is always shown as missing value, so remove it
	if(ANOVA_TOTAL == indInStruct && tr.MeanSq)
		tr.MeanSq.Remove();
		
	return tr;
}

bool		stats_tree_add_ANOVA_table(TreeNode &trOp, const string &strDataLabel, int index,  int nTotalNumData, const RegANOVA& sANOVA, vector<string> &vstrFactors)
{
	///Iris 6/06/05 CENTRALIZE_GUI_STRUCTURE
	//bool bShowANOVA = trOp.GUI.Output.Report.Create.ANOVAtable.nVal;
	TreeNode trGUIANOVA = trOp.GUI.Quantities.ANOVAtable;
	if(!trGUIANOVA)
		return false;
	
	bool bShowANOVA = trGUIANOVA.nVal;	
	
	TreeNode		trANOVA = trOp.Calculation.ANOVAs;
	if(!trANOVA)
		return error_report("Operation tree has no ANOVAs branch!!");

	tree_check_set_hidden(trANOVA, bShowANOVA?false:true);
	
	if( bShowANOVA ) ///Iris 5/19/2008 NOT_GENERAGE_TABLE_IF_NOT_REPORT_TO_IMPROVE_NLSF_SPEED_MORE
	{
		/// Iris 05/29/2007 v8.0629 DUPLICATE_LABEL_IN_ANOVA_ONE_WAY
		//stats_tree_set_one_ANOVA_set(trANOVA, "Model", strDataLabel, index, index + IDST_ANOVA_Model, sANOVA, ANOVA_MODEL);
		//stats_tree_set_one_ANOVA_set(trANOVA, "Error", strDataLabel, index, index + IDST_ANOVA_Error, sANOVA, ANOVA_ERR);
		//stats_tree_set_one_ANOVA_set(trANOVA, "Total", strDataLabel, index, index + IDST_ANOVA_Total, sANOVA, ANOVA_TOTAL);
		stats_tree_set_one_ANOVA_set(trANOVA, "Model", strDataLabel, index, index + IDST_ANOVA_Model, sANOVA, ANOVA_MODEL, _L("Model"));
		stats_tree_set_one_ANOVA_set(trANOVA, "Error", strDataLabel, index, index + IDST_ANOVA_Error, sANOVA, ANOVA_ERR, _L("Error"));
		stats_tree_set_one_ANOVA_set(trANOVA, "Total", strDataLabel, index, index + IDST_ANOVA_Total, sANOVA, ANOVA_TOTAL, _L("Total"));
		///end DUPLICATE_LABEL_IN_ANOVA_ONE_WAY
	}
	
	return true;
}
///Arvin 05/25/07 ADD_CORRECTED_TOTAL_ROW_FOR_ANOVA_TABLE_FOR_FITNL
//Echo said ANOVA table row label should different between NLSF and regression,so we need a new version function to add ANOVA table
TreeNode	stats_tree_add_corrected_total_set_to_anova_table(TreeNode &trANOVA, LPCSTR lpcszName, LPCSTR lpcszLabel, LPCSTR lpcszDataLabel, int index, int nID, const RegANOVARow& stCorrTotal)
{
	string			strTag;
	strTag.Format("%s%d", lpcszName, index + 1);	
	TreeNode		tr = tree_check_get_node(trANOVA, strTag, nID);
	
	string			strDataLabel(lpcszDataLabel);
	if ( !strDataLabel.IsEmpty() )
		tree_add_one_label(tr, strDataLabel);
	tree_add_one_label(tr, lpcszLabel, 0);

	RegANOVARow		stTemp;
	stTemp = stCorrTotal;
	tr = stTemp;
	
	if(nID)
		tr.ID = nID; 
	
	if(tr.DOF)
		///Cheney 2007-10-27 CLEAN_UP_LOCALIZATION_THINGS
		//tr.DOF.SetAttribute(STR_LABEL_ATTRIB, "DF");
	///Sophy 3/30/2009 QA80-13352 SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
		//tr.DOF.SetAttribute(STR_LABEL_ATTRIB, _L("DF") );
	{
		tr.DOF.SetAttribute(STR_LABEL_ATTRIB, _L("DF") );
		tr.DOF.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
	}
	///end SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
		///end CLEAN_UP_LOCALIZATION_THINGS
	
	/// Iris 11/08/05 change some row label for ANOVA table
	if(tr.SSq)
		///Cheney 2007-10-27 CLEAN_UP_LOCALIZATION_THINGS
		//tr.SSq.SetAttribute(STR_LABEL_ATTRIB, "Sum of Squares");
	///Sophy 3/30/2009 QA80-13352 SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
		//tr.SSq.SetAttribute(STR_LABEL_ATTRIB, _L("Sum of Squares") );
	{
		tr.SSq.SetAttribute(STR_LABEL_ATTRIB, _L("Sum of Squares") );
		tr.SSq.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
	}
	///end SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
		///end CLEAN_UP_LOCALIZATION_THINGS
	if(tr.MeanSq)
		///Cheney 2007-10-27 CLEAN_UP_LOCALIZATION_THINGS
		//tr.MeanSq.SetAttribute(STR_LABEL_ATTRIB, "Mean Square");
	///Sophy 3/30/2009 QA80-13352 SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
		//tr.MeanSq.SetAttribute(STR_LABEL_ATTRIB, _L("Mean Square") );
	{
		tr.MeanSq.SetAttribute(STR_LABEL_ATTRIB, _L("Mean Square") );
		tr.MeanSq.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
	}
	///end SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
		///end CLEAN_UP_LOCALIZATION_THINGS
	
	///Iris 10/27/04 ADD_F_P_VALUE_TO_ANOVA_TABLE
	///Cheney 2007-10-27 CLEAN_UP_LOCALIZATION_THINGS
	//tree_check_get_node(tr, "FValue", IDE_ANOVA_FVALUE, STR_LABEL_ATTRIB, "F Value");
	//tree_check_get_node(tr, "PValue", IDE_ANOVA_PVALUE, STR_LABEL_ATTRIB, "Prob>F");
	tree_check_get_node(tr, "FValue", IDE_ANOVA_FVALUE, STR_LABEL_ATTRIB, _L("F Value") );
	tree_check_get_node(tr, "PValue", IDE_ANOVA_PVALUE, STR_LABEL_ATTRIB, _L("Prob>F") );	
	///end CLEAN_UP_LOCALIZATION_THINGS
	///Sophy 3/30/2009 QA80-13352 SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
	tr.FValue.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
	tr.PValue.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
	///end SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
	/// Iris 11/08/05 MeanSq of Total is always shown as missing value, so remove it
	if(tr.MeanSq)
		tr.MeanSq.Remove();
		
	return tr;
}

bool stats_tree_add_ANOVA_table(TreeNode &trOp, const string &strDataLabel, int index,  int nTotalNumData, const RegANOVA& sANOVA, vector<string> &vstrFactors, RegANOVARow& stCorrTotal)
{
	///Iris 6/06/05 CENTRALIZE_GUI_STRUCTURE
	//bool bShowANOVA = trOp.GUI.Output.Report.Create.ANOVAtable.nVal;
	TreeNode trGUIANOVA = trOp.GUI.Quantities.ANOVAtable;
	if(!trGUIANOVA)
		return false;
	
	bool bShowANOVA = trGUIANOVA.nVal;	
	
	TreeNode		trANOVA = trOp.Calculation.ANOVAs;
	if(!trANOVA)
		return error_report("Operation tree has no ANOVAs branch!!");

	tree_check_set_hidden(trANOVA, bShowANOVA?false:true);
	
	if( bShowANOVA )///Iris 5/19/2008 NOT_GENERAGE_TABLE_IF_NOT_REPORT_TO_IMPROVE_NLSF_SPEED_MORE
	{
		/// Iris 05/29/2007 v8.0629 DUPLICATE_LABEL_IN_ANOVA_ONE_WAY
		//stats_tree_set_one_ANOVA_set(trANOVA, "Regression", strDataLabel, index, index + IDST_ANOVA_Model, sANOVA, ANOVA_MODEL);
		//stats_tree_set_one_ANOVA_set(trANOVA, "Residual", strDataLabel, index, index + IDST_ANOVA_Error, sANOVA, ANOVA_ERR);
		stats_tree_set_one_ANOVA_set(trANOVA, "Regression", strDataLabel, index, index + IDST_ANOVA_Model, sANOVA, ANOVA_MODEL, _L("Regression"));
		stats_tree_set_one_ANOVA_set(trANOVA, "Residual", strDataLabel, index, index + IDST_ANOVA_Error, sANOVA, ANOVA_ERR, _L("Residual"));
		///end DUPLICATE_LABEL_IN_ANOVA_ONE_WAY
		stats_tree_set_one_ANOVA_set(trANOVA, "UCTotal", strDataLabel, index, index + IDST_ANOVA_Total, sANOVA, ANOVA_TOTAL, _L("Uncorrected Total"));
		stats_tree_add_corrected_total_set_to_anova_table(trANOVA, "CTotal", STR_ANOAVA_GUI_LABEL_CTOTAL, strDataLabel, index, index + IDST_ANOVA_CTotal, stCorrTotal);
	}
	
	return true;
}
///end ADD_CORRECTED_TOTAL_ROW_FOR_ANOVA_TABLE_FOR_FITNL
#else //ANOVA_IN_SEPARATE_TABLES
//static	TreeNode	stats_tree_set_one_ANOVA_set(TreeNode &trANOVA, LPCSTR lpcszName, LPCSTR lpcszLabel, int nID, const RegANOVA& sANOVA, int nANOVARow)  /// Iris 10/06/04
TreeNode	stats_tree_set_one_ANOVA_set(TreeNode &trANOVA, LPCSTR lpcszName, LPCSTR lpcszLabel, int nID, const RegANOVA& sANOVA, int nANOVARow)
{
	TreeNode		tr = tree_check_get_node(trANOVA, lpcszName, nID);
	if( 0 != lstrlen(lpcszLabel) )
		tree_add_one_label(tr, lpcszLabel);

	RegANOVARow		stTemp;
	stTemp = sANOVA.AnovaTable[nANOVARow];
	tr = stTemp;
	
	if(nID)
		tr.ID = nID;
	
	if(tr.DOF)
		///Cheney 2007-10-27 CLEAN_UP_LOCALIZATION_THINGS
		//tr.DOF.SetAttribute(STR_LABEL_ATTRIB, "DOF");
	///Sophy 3/30/2009 QA80-13352 SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
		//tr.DOF.SetAttribute(STR_LABEL_ATTRIB, _L("DOF") );
	{
		tr.DOF.SetAttribute(STR_LABEL_ATTRIB, _L("DOF") );
		tr.DOF.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
	}
	///end SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
		///end CLEAN_UP_LOCALIZATION_THINGS
	/// Iris 11/08/05 change some row label for ANOVA table
	if(tr.SSq)
		///Cheney 2007-10-27 CLEAN_UP_LOCALIZATION_THINGS
		//tr.SSq.SetAttribute(STR_LABEL_ATTRIB, "Sum of Squares");
	///Sophy 3/30/2009 QA80-13352 SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
		//tr.SSq.SetAttribute(STR_LABEL_ATTRIB, _L("Sum of Squares") );
	{
		tr.SSq.SetAttribute(STR_LABEL_ATTRIB, _L("Sum of Squares") );
		tr.SSq.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
	}
	///end SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
		///end CLEAN_UP_LOCALIZATION_THINGS
	if(tr.MeanSq)
		///Cheney 2007-10-27 CLEAN_UP_LOCALIZATION_THINGS
		//tr.MeanSq.SetAttribute(STR_LABEL_ATTRIB, "Mean Square");
	///Sophy 3/30/2009 QA80-13352 SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
		//tr.MeanSq.SetAttribute(STR_LABEL_ATTRIB, _L("Mean Square") );
	{
		tr.MeanSq.SetAttribute(STR_LABEL_ATTRIB, _L("Mean Square") );
		tr.MeanSq.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
	}
	///end SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
		///end CLEAN_UP_LOCALIZATION_THINGS

	///Iris 10/27/04 ADD_F_P_VALUE_TO_ANOVA_TABLE
	///Cheney 2007-10-27 CLEAN_UP_LOCALIZATION_THINGS
	//tree_check_get_node(tr, "FValue", IDE_ANOVA_FVALUE, STR_LABEL_ATTRIB, "F Value");
	//tree_check_get_node(tr, "PValue", IDE_ANOVA_PVALUE, STR_LABEL_ATTRIB, "Prob>F");
	tree_check_get_node(tr, "FValue", IDE_ANOVA_FVALUE, STR_LABEL_ATTRIB, _L("F Value") );
	tree_check_get_node(tr, "PValue", IDE_ANOVA_PVALUE, STR_LABEL_ATTRIB, _L("Prob>F") );
	///end CLEAN_UP_LOCALIZATION_THINGS
	if(ANOVA_MODEL == nANOVARow)
	{
		tr.FValue.dVal = sANOVA.Fvalue;
		tr.PValue.dVal = sANOVA.Pvalue;
	}	
	///End ADD_F_P_VALUE_TO_ANOVA_TABLE
	///Sophy 3/30/2009 QA80-13352 SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
	tr.FValue.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
	tr.PValue.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
	///end SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
	
	/// Iris 11/08/05 MeanSq of Total is always shown as missing value, so remove it
	if(ANOVA_TOTAL == nANOVARow && tr.MeanSq)
		tr.MeanSq.Remove();
	
	return tr;
}
bool stats_tree_add_ANOVA_table(TreeNode &trOp, const string &strDataLabel, int index, int nTotalNumData, const RegANOVA& sANOVA, const vector<string> &vstrFactors)
{
	///Iris 6/06/05 CENTRALIZE_GUI_STRUCTURE
	//bool bShowANOVA = trOp.GUI.Output.Report.Create.ANOVAtable.nVal;
	
	/// Thomas 06/08/06 MOVE_ANOVA_CHECK_BOX_TO_QUANTITIES_BRANCH
	//bool bShowANOVA = op_get_optional_tables(trOp.GUI).ANOVAtable.nVal;
	/// Iris 7/28/06 CLEANUP_THOMAS_CODES
	//bool bShowANOVA = trOp.GUI.quantities.ANOVAtable.nVal;
	TreeNode trGUIANOVA = trOp.GUI.Quantities.ANOVAtable;
	if(!trGUIANOVA)
		return error_report("Operation GUI tree has no ANOVAtable branch!!");
	bool bShowANOVA = trGUIANOVA.nVal;
	///end CLEANUP_THOMAS_CODES	
	/// End MOVE_ANOVA_CHECK_BOX_TO_QUANTITIES_BRANCH
	
	TreeNode		trANOVA = trOp.Calculation.ANOVAs;
	if(!trANOVA)
		return error_report("Operation tree has no ANOVAs branch!!");
	///Arvin  11/15/06 ANOVA_TABLE_CHAOS_AFTER_CHANGE_PARAMETER
	//trANOVA shouldn't has subnode, before the first time adding ANOVA table.
	else
	{
		if(index == 0)
		{
			trANOVA.RemoveChildrenWithPrefix();
		}
	}
	///end ANOVA_TABLE_CHAOS_AFTER_CHANGE_PARAMETER
	tree_check_set_hidden(trANOVA, bShowANOVA?false:true);
	
	bool		bHaveSubLevel = 1 < nTotalNumData;
		
	///// ML 8/17/2004 QA70-6825 RLOG_QUERY
	////TreeNode trOneSet = check_add_enumerated_node(trANOVA, "ANOVA", index + 1, index + IDST_ANOVAS, STR_LABEL_ATTRIB, strDataLabel);
	//TreeNode trOneSet = check_add_enumerated_node(trANOVA, "ANOVA", index + 1, make_one_set_ID(IDST_ANOVAS, index), STR_LABEL_ATTRIB, strDataLabel);
	///// end RLOG_QUERY
	int				nIDTable = make_one_set_ID(IDST_ANOVAS, index);
	TreeNode	trOneSet;
	if ( bHaveSubLevel )
		trOneSet = check_add_enumerated_node(trANOVA, "ANOVA", index + 1, nIDTable, STR_LABEL_ATTRIB, strDataLabel);
	else
	{
		trOneSet = trANOVA;
		trOneSet.ID = nIDTable;
	}
	 
	stats_tree_set_one_ANOVA_set(trOneSet, "Model", _L(""), IDST_ANOVA_Model, sANOVA, ANOVA_MODEL);
	stats_tree_set_one_ANOVA_set(trOneSet, "Error", _L(""), IDST_ANOVA_Error, sANOVA, ANOVA_ERR);
	stats_tree_set_one_ANOVA_set(trOneSet, "Total", _L(""), IDST_ANOVA_Total, sANOVA, ANOVA_TOTAL);
	
	return true;
}
#endif //ANOVA_IN_SEPARATE_TABLES
//-------- end ANOVA_IN_SEPARATE_TABLES

///Sophy 10/9/2008 QA80-10536-P12 REMOVE_FITTEDVALUE_FROM_RESIDUAL_AND_FINDXY_IF_NO_FITTED_CURVES_PLOT
int fitlinear_fitted_curves_option_changed( TreeNode& trGUI )
{
	OutputGUIManagerBase*	pOutManager = get_output_GUI_manager_pointer( trGUI );
	if( pOutManager )
		pOutManager->CheckUpdateFitOutputBookSheetGUI( trGUI, trGUI.InputData, NLFIT_GENERAL_XY_FITTING );
	return 0;
}
///end REMOVE_FITTEDVALUE_FROM_RESIDUAL_AND_FINDXY_IF_NO_FITTED_CURVES_PLOT

///Sophy 11/28/2008 v8.0980d QA80-12591-P5 ADD_AUTO_SUPPORT_FOR_LR_AND_PR_FITCURVE_XDATATYPE
bool stats_update_xdatatype_min_max_by_auto(const TreeNode& trInputData, TreeNode& trXDataType)
{
	if( !trInputData || !trXDataType || FIT_CURVE_CUSTOM != trXDataType.Range.nVal )
		return false;
	
	XYRange	drInput;
	drInput.Create(trInputData, false);
	
	vector vX, vY;
	drInput.GetData(vY, vX);
	
	double	dXMin, dXMax;
	int		nMinAuto, nMaxAuto;
	TreeNode trXMin = trXDataType.Min;
	TreeNode trXMax = trXDataType.Max;
	
	if( trXMin )
		nMinAuto = octree_get_auto_support(&trXMin);
	if( trXMax )
		nMaxAuto = octree_get_auto_support(&trXMax);
	
	vX.GetMinMax(dXMin, dXMax);
	
	if( 1 == nMinAuto )
		trXDataType.Min.dVal = dXMin;
	if( 1 == nMaxAuto )
		trXDataType.Max.dVal = dXMax;
	
	///------ Folger 03/28/09 QA80-12786 SUPPORT_DATA_TIME_FORMAT_DISPLAY_FOR_GENERAL_FITTING_TOOLS_CUSTOM_XDATATYPE
	update_dataformat_start_end_interval(trInputData, trXDataType, "Min", "Max");
	///------ End SUPPORT_DATA_TIME_FORMAT_DISPLAY_FOR_GENERAL_FITTING_TOOLS_CUSTOM_XDATATYPE
	
	return true;
}
///end ADD_AUTO_SUPPORT_FOR_LR_AND_PR_FITCURVE_XDATATYPE

//---- CPY 6/9/04 TABLE_HEADER_CLEANUP_FOR_SINGLE_OR_MULTIPLE_SETS
#define STR_PARAMS	_LE("Parameters")
// added bDataLabelAsTableMainHeader
//

//------ Folger 12/11/08 QA80-12766 v8.0985 SIGNIFICANT_DIGITS_FAILS_TO_APPLY_TO_NLSF_FITTING_REPORT
#define		STR_SIGNIFICANT_DIGITS_FOR_PRARMETER_TABLE	"SignificantDigitsForReport"

static	void	_set_sinificant_digits_to_params(TreeNode& trParam, int& nSignDigitsPrev, const vector<int>& vnSignDigits, int nIndex, bool bIsDerived)
{
	if ( bIsDerived )
	{
		trParam.SetAttribute(STR_SIGNIFICANT_DIGITS_FOR_PRARMETER_TABLE, nSignDigitsPrev);
	}
	else
	{
		if ( nIndex >= vnSignDigits.GetSize() )
			return;
		
		trParam.SetAttribute(STR_SIGNIFICANT_DIGITS_FOR_PRARMETER_TABLE, vnSignDigits[nIndex]);
		nSignDigitsPrev = vnSignDigits[nIndex];
	}
}
//------ End SIGNIFICANT_DIGITS_FAILS_TO_APPLY_TO_NLSF_FITTING_REPORT

/// Iris 4/29/2009 QA80-12017 NEED_ADD_NEW_REPORT_ITEM_WHEN_RECALCULATE_ON_OLD_OPJ
//virtual
void		FitterOperation::GUIOnUpdateTreeBeforeRunning(const MultipleVersion& mvOld, TreeNode &trGUINew, TreeNode &trGUIOriginal, TreeNode& trOperation)
{
	StatsOpBase::GUIOnUpdateTreeBeforeRunning(mvOld, trGUINew, trGUIOriginal, trOperation);
		
	if ( is_integer_part_less_then(mvOld.GetVersion(STR_OP_NAME_FITTER_OP), m_mvCur.GetVersion(STR_OP_NAME_FITTER_OP)) )
	{
		#ifdef INSERT_NEW_REPORT_ENTRY_IN_OLD_OPJ_WHEN_RECALCULATE
		TreeNode& trNotesTable = trOperation.Calculation.Notes;
		if( trNotesTable )
		{
			TreeNode trEquation = trNotesTable.Equation;
			ASSERT(trEquation);
			if(trEquation)
			{
				if( !trNotesTable.NumFuncParams )	
				{
					trNotesTable.InsertNode(trEquation, "NumFuncParams", IDE_NOTES_NUM_PARAMS);
				}
				if( !trNotesTable.NumDerivParams )	
				{
					trNotesTable.InsertNode(trEquation, "NumDerivParams", IDE_NOTES_NUM_DERIVED_PARAMS);
				}				
				if( !trNotesTable.NumDataSets )	
				{
					trNotesTable.InsertNode(trEquation, "NumDataSets", IDE_NOTES_NUM_DATASET);
				}	
			}			
		}
		#endif //INSERT_NEW_REPORT_ENTRY_IN_OLD_OPJ_WHEN_RECALCULATE
		
		/// Hong 05/27/09 QA80-13670 FIX_FIX_STATUS_NOT_KEPT_WHEN_RECALCULATE_OLD_OPERATION
		// Hong, VC level have assumption of check size of SignDigites when SetParamSettings, and old operation have bug of wrong tagName which is SignDigites,
		// see FitterOperation::makeParamsTblTheme which is aready fixed by Folger.
		TreeNode		trFitWorkArea = trOperation.FitWorkArea;
		if ( trFitWorkArea )
		{
			TreeNode trTypoSignDigit = trFitWorkArea.Parameters.SignDigites;
			if ( trTypoSignDigit )
			{
				TreeNode		trSignDigit = tree_check_get_node(trFitWorkArea.Parameters, "SignificantDigit");
				// Hong, to do, Replace fail to work in case of vector values, so use nVals directly for temp,
				// can remove temp code once #13679 is fixed.
				//trSignDigit.Replace(trTypoSignDigit, TRUE, TRUE);
				trSignDigit.nVals = trTypoSignDigit.nVals;
				trTypoSignDigit.Remove();
			}
		}
		/// end FIX_FIX_STATUS_NOT_KEPT_WHEN_RECALCULATE_OLD_OPERATION
	}	
}
///end NEED_ADD_NEW_REPORT_ITEM_WHEN_RECALCULATE_ON_OLD_OPJ

///Kyle 08/10/2009 QA80-14077 ADD_PARAMETER_UNIT_TO_FITTING_REPORT
static void _param_row_insert_unit(TreeNode& trRow, LPCSTR lpcszUnit)
{
	if(trRow && trRow.Value)
	{
		// add node Unit before Value
		TreeNode trUnit = trRow.InsertNode(trRow.Value, "Unit");

		trUnit.DataID = IDE_PARAM_UNIT;
		trUnit.strVal = lpcszUnit;
	}
}
///End ADD_PARAMETER_UNIT_TO_FITTING_REPORT

static string _get_param_valid_cname(vector<string>& vsParamNames, int index)
{
	vector<string> vsParamNamesTemp(index+1);
	for(int nn = 0; nn <= index; nn++)
	{		
		string 	strName = vsParamNames[nn];
		strName.TrimLeft();
		strName.TrimRight();
		strName.MakeValidCName();
		/// Iris 6/17/2010 ORG-301 FIX_MR_WHEN_INPUTDATA_LONGNAME_IS_NUMERIC_BUG
		if( strName.IsEmpty() )
			strName = "Param" + (string)(index+1);
		///End FIX_MR_WHEN_INPUTDATA_LONGNAME_IS_NUMERIC_BUG
		vsParamNamesTemp[nn] = strName;
	}
	
	vector<int> 	vnMapIndices;
	vector<uint> 	vnR1s, vnOccurences;
	vsParamNamesTemp.FindDuplicates(vnMapIndices, vnR1s, true, vnOccurences);
	if( vnMapIndices[index] == -1 ) // not duplicate
		return vsParamNamesTemp[index];
	else
	{
		int nFirstOccur = vsParamNamesTemp.Find(vsParamNamesTemp[index]);
		if( nFirstOccur >=0 && nFirstOccur < vsParamNamesTemp.GetSize() )
		{
			vector<string> vsR1s;
			convert_uint_vector_to_string_vector(vnR1s, vsR1s);
			int nPlace = vsR1s.Find((string)nFirstOccur);
			if( nPlace >= 0 && nPlace < vnOccurences.GetSize() )
			{
				int nCount = vnOccurences[nPlace];
				return (string)(vsParamNamesTemp[index] + nCount);
			}
			else
			{
				ASSERT(false);
			}
		}		
		else
		{
			ASSERT(false);
		}
	}
	return vsParamNamesTemp[index];
}	
		
// This function add Parameters branch to tree
// pFitParams = pointer to array of structs
// vnIDs = vector of IDs for each parameter, if no IDs are needed, still need to fill vnIDs with zeros
TreeNode	FitterOperation::stats_tree_add_Parameters(const string &strDataLabel, bool bDataLabelAsTableMainHeader, TreeNode &trOp, 
///Kyle 08/10/2009 QA80-14077 ADD_PARAMETER_UNIT_TO_FITTING_REPORT
		//int index, const FitParameter* pFitParams, vector<string> &vstrParamNames, vector<string>& vstrParamNamesPostfix, 
		int index, const FitParameter* pFitParams, const FITPARAMSINFO& stParamInfo, 
///End ADD_PARAMETER_UNIT_TO_FITTING_REPORT
		///Arvin 08/03/07 WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
		//vector<string> &vstrFactors, const FitDerivedParameter* pstDerivedParams, int nNumDerivedParams, vector<bool> &vbIsDerived)
		///Arvin 01/03/08 ADD_STAR_MARK_FOR_SHARED_PARAMS as cp said
		//vector<string> &vstrFactors, const FitDerivedParameter* pstDerivedParams, int nNumDerivedParams, vector<bool> &vbIsDerived, int nMultiplicity, int nNumParamInFunc, int nDupUnit)
		vector<string> &vstrFactors, const FitDerivedParameter* pstDerivedParams, int nNumDerivedParams, vector<bool> &vbIsDerived, int nMultiplicity, int nNumParamInFunc, int nDupUnit, vector<bool> &vbIsShared)
		///end ADD_STAR_MARK_FOR_SHARED_PARAMS
		///end WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
{
	///Kyle 08/10/2009 QA80-14077 ADD_PARAMETER_UNIT_TO_FITTING_REPORT
	vector<string> &vstrParamNames = *stParamInfo.pvsParamNames;
	vector<string> &vstrParamNamesPostfix = *stParamInfo.pvsParamNamesPostfix;
	vector<string> &vstrParamUnits = *stParamInfo.pvsParamUnits;
	///End ADD_PARAMETER_UNIT_TO_FITTING_REPORT
	FitParameter			param;
	FitDerivedParameter		stDerivedParam;
	/// Iris 11/30/06 v8.0517 TRM_0_FROM_DERIVED_PARAMS_ERR_TVAL_ETC
	int				nParams = vstrParamNames.GetSize();
	TreeNode		trCal = trOp.Calculation;	///Jasmine 11/14/07 FIT_BASELINE_AS_WELL_AS_OTHER_PEAKS
	TreeNode		trParams = tree_check_get_node(trCal, STR_PARAMS, IDST_FIT_PARAMETER, STR_LABEL_ATTRIB, GetLocalized(STR_PARAMS));

	int				nNodeIndexStart = index * nParams;
	int				nParamNameHeaderIndex = -1; // as main header

	if(bDataLabelAsTableMainHeader && strDataLabel.IsEmpty())
	{
		error_report("empty str lable and trying to add as table main header");
		bDataLabelAsTableMainHeader = false;
	}
	if(bDataLabelAsTableMainHeader)
		nParamNameHeaderIndex = 0; // as subheader
//--- CPY 11/13/06 SHOULD_NEVER_ROUND_PARAM_VALUES_INTERNALLY
/*
	///Cheney 2006-11-13 SET_PARAMS_VALUE_WITH_SIGNIFICENT_DIGITS
	bool bUseSignDigtes = false;
	vector<int> vnSignDigits;
	TreeNode trFitWorkArea = trCal.Parent().FitWorkArea;
	if(trFitWorkArea)
	{
		TreeNode trSignDigtes = trFitWorkArea.Parameters.SignDigites;
		vnSignDigits = trSignDigtes.nVals;
		bUseSignDigtes = true;
	}
	///end SET_PARAMS_VALUE_WITH_SIGNIFICENT_DIGITS
*/	
	TreeNode		trRow;
	string			strTag;
	int				nID;
	int				nNumNonDerivedParams = nParams - nNumDerivedParams;/// Iris 11/30/06 v8.0517 TRM_0_FROM_DERIVED_PARAMS_ERR_TVAL_ETC
	int				nParam = 0, nDerivedParam = 0;
	///Arvin 08/03/07 WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
	int nPeakOrder = 1; 
	string strTableLabel = strDataLabel;
	///end WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
	///Jasmine 11/08/07 ADD_SHARED_TO_PARAMETER_REPORT_TABLE
	vector<int> vnShared;
	///------ Folger 07/07/09 NANOSIZER_PARAMETER_SHARE_INFO_NOT_SHOW_CORRECTLY_IN_REPORT
	//if(IsMulFuncsFit())
	if ( IsFitPeak() )
	///------ End NANOSIZER_PARAMETER_SHARE_INFO_NOT_SHOW_CORRECTLY_IN_REPORT
	///------ Folger 02/25/09 SHARED_SYMBOL_FAILS_TO_SHOW_IN_PA_FITTING_REPORT
		//ParameterGetShared(vnShared);
	{
		ParameterGetShared(vnShared);
		if ( NULL != vbIsShared && NULL != vbIsDerived )
		{
			ASSERT(vbIsShared.GetSize() == vbIsDerived.GetSize());
			int		nn = 0;
			for ( int ii=0; ii<vbIsShared.GetSize(); ++ii )
			{
				if ( vbIsDerived[ii] )
					continue;
				
				vbIsShared[ii] = vnShared[nn++];
			}
		}
	}
	///------ End SHARED_SYMBOL_FAILS_TO_SHOW_IN_PA_FITTING_REPORT
	///End ADD_SHARED_TO_PARAMETER_REPORT_TABLE	
	///Jasmine 11/14/07 FIT_BASELINE_AS_WELL_AS_OTHER_PEAKS
	bool bHasBaselinePeak = false;
	///Arvin 12/05/07 XOP_NEED_SUPPORT_PFW
	//As jasmine said, tag name of PFW tree node should be PFWTree
	//if(trOp.PFMTree)
	//	bHasBaselinePeak = HasBaselinePeak(trOp.PFMTree);
	///Jasmine 06/15/09 NO_NEED_PFM_TREE
	//if(trOp.PFWTree)
		bHasBaselinePeak = HasBaselinePeak();//trOp.PFWTree	
	///End NO_NEED_PFM_TREE
	///end XOP_NEED_SUPPORT_PFW
	
	//------ Folger 12/11/08 QA80-12766 v8.0985 SIGNIFICANT_DIGITS_FAILS_TO_APPLY_TO_NLSF_FITTING_REPORT
	vector<int>		vnSignDigits;
	///------ Folger 12/22/08 QA80-12766-P2 v8.0990 SIGNIFICANT_DIGITS_NOT_WORKING_FOR_MULTIPLE_DATASETS_REPORT
	//GetSignDigitsArray(vnSignDigits);
	GetSignDigitsArray(vnSignDigits, index);
	///------ End SIGNIFICANT_DIGITS_NOT_WORKING_FOR_MULTIPLE_DATASETS_REPORT
	int				nSignDigitsPrev = 0;
	//------ End SIGNIFICANT_DIGITS_FAILS_TO_APPLY_TO_NLSF_FITTING_REPORT
	
	///End FIT_BASELINE_AS_WELL_AS_OTHER_PEAKS
	/// Hong 12/23/08 v8.0990 PA_AVOID_NESTED_LOOP_BY_CACHE_LAST_RESULT
	int				nLastPeakNoWithoutOffset = -1, nLastPeaksNum = -1;
	/// end PA_AVOID_NESTED_LOOP_BY_CACHE_LAST_RESULT
	for(int ii = 0; ii < nParams; ii++)
	{
		/// Iris 11/30/06 v8.0517 TRM_0_FROM_DERIVED_PARAMS_ERR_TVAL_ETC
		//param = pFitParams[ii];
		//---- Iris 12/30/2006 v8.0534 CORRECT_DERIVED_PARAMS_ORDER_FOR_REPLICA_CASE
		//if(ii < nNumNonDerivedParams)
		//---- 
		if( vbIsDerived && vbIsDerived[ii] && 0 != nNumDerivedParams)
		{
			stDerivedParam.Value = pstDerivedParams[nDerivedParam].Value;
			nDerivedParam++;
		}
		else
		{
			param = pFitParams[nParam];
			//nParam++;//later
		}
		///end TRM_0_FROM_DERIVED_PARAMS_ERR_TVAL_ETC
		
		///Arvin 08/03/07 WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
		if(nMultiplicity > 1)
		{
			int nSepParamInd = nNumParamInFunc + nNumDerivedParams + (nPeakOrder-1)*(nDupUnit+nNumDerivedParams);
			if(ii >= nSepParamInd)
				nPeakOrder++;
			
			strTableLabel = _L("Peak") + ftoa(nPeakOrder) + "(" + strDataLabel +")";
			if(ii == nSepParamInd && nPeakOrder > 1)
			{
				///Jasmine 08/19/08 QA80-12046 OFFSET_PARAM_SHOULD_HAVE_SAME_SUFFIX_FORMAT_AS_OTHERS
				string strSuffix = vstrParamNamesPostfix[ii];
				strSuffix.TrimLeft( vstrParamNames[ii] );
				if(strSuffix.IsEmpty() || 0 == strSuffix.CompareNoCase(vstrParamNamesPostfix[ii]) )
					strSuffix = ftoa(nPeakOrder);
				///End OFFSET_PARAM_SHOULD_HAVE_SAME_SUFFIX_FORMAT_AS_OTHERS
				
				//Copy unduplicated params value from peak1
				for(int jj = 0; jj < nNumParamInFunc-nDupUnit; jj++)
				{
					FitParameter	paramCopy;
					paramCopy = pFitParams[jj];
					string 	strRowName = vstrParamNamesPostfix[jj];
					strRowName.TrimLeft();
					strRowName.TrimRight();
					strRowName += strSuffix;
					strRowName.MakeValidCName();
					trRow = tree_check_get_node(trParams, strRowName);
					if( !trRow )
					{
						error_report("Fail to construct one new row by parameter name as tagname");
						return trParams;
					}
					
					//------ Folger 12/11/08 QA80-12766 v8.0985 SIGNIFICANT_DIGITS_FAILS_TO_APPLY_TO_NLSF_FITTING_REPORT
					_set_sinificant_digits_to_params(trRow, nSignDigitsPrev, vnSignDigits, jj, vbIsDerived ? vbIsDerived[ii] : false);
					//------
					
					if ( bDataLabelAsTableMainHeader )
						tree_add_one_label(trRow, strTableLabel);
					//------ Folger 12/04/07 LOCALIZE_PARAMETER_TABLE
					//tree_add_one_label(trRow, vstrParamNames[jj], nParamNameHeaderIndex);
					tree_add_one_label(trRow, GetLocalized(vstrParamNames[jj]), nParamNameHeaderIndex);
					//------
					trRow += paramCopy;
					int nID  = make_one_set_ID(IDST_FIT_PARAMETER_ONE_SET + ii, index); 
					trRow.ID = make_one_set_ID(nID, jj+1); 
		
					if(trRow.Fix)
						trRow.Fix.strVal = trRow.Fix.nVal? "Y" : "N";
					
					//------ Folger 04/23/08 SUPPORT_GROUP_SHARED_IN_NANOSIZER
					TreeNode trShared = trRow.InsertNode(trRow.Fix, "Shared");

					if(trShared)
					{
						trShared.DataID = IDE_PARAM_SHARED;
						trShared.nVal = jj < vnShared.GetSize()? vnShared[jj] : 0;
					}
					//------
					///Kyle 08/10/2009 QA80-14077 ADD_PARAMETER_UNIT_TO_FITTING_REPORT
					if(jj<vstrParamUnits.GetSize())
						_param_row_insert_unit(trRow, vstrParamUnits[jj]);
					///End ADD_PARAMETER_UNIT_TO_FITTING_REPORT
				}
			}
			//------ Folger 04/01/08 QA80-11304 SHOW_SHARED_SIGN_IN_REPORT_SHEET_FOR_REPLICA_FITTING
			if ( vbIsShared != NULL && nPeakOrder == 1 )
			{
				if ( vbIsShared[ii] != 0 )
				{			
					for ( int jj=0; jj<nMultiplicity-1; ++jj )
						//nNumParamInFunc - nDupUnit means replica offset
						vbIsShared[nSepParamInd + (nDupUnit+nNumDerivedParams) * jj + ii - nNumParamInFunc + nDupUnit] = 1;
				}
			}
			//------
		}
		///end WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
		///Jasmine 11/07/07 ADD_PEAK_NUMBER_TO_PFM_PARAMETERS		
		else if(IsMulFuncsFit())
		{
			bool bFuncFirstParam = false;
			string strFunction;
			///Jasmine 11/14/07 FIT_BASELINE_AS_WELL_AS_OTHER_PEAKS
			///Kyle 10/20/08 PEAK_NUMBER_OFFSET_IS_ALWAYS_ONE
			//nPeakOrder = bHasBaselinePeak ? 0 : 1;//offset
			nPeakOrder = 1;
			///End PEAK_NUMBER_OFFSET_IS_ALWAYS_ONE
			/// Hong 12/23/08 v8.0990 PA_AVOID_NESTED_LOOP_BY_CACHE_LAST_RESULT
			//GetPeakNumber(ii, nPeakOrder, bFuncFirstParam);
			bool bFuncRet = GetPeakNumber(ii, nPeakOrder, bFuncFirstParam, &nLastPeakNoWithoutOffset, &nLastPeaksNum);
			ASSERT(bFuncRet);
			/// end PA_AVOID_NESTED_LOOP_BY_CACHE_LAST_RESULT
			if(trOp.PFWTree)
			{
				TreeNode trPeak = tree_get_node_by_tagname(trOp.PFWTree, "Peak"+(string)nPeakOrder, true);
				if(trPeak)
					strFunction = trPeak.Function.FuncName.strVal;
			}
			///Kyle 10/20/08 PEAK_NUMBER_OFFSET_IS_ALWAYS_ONE
			//strTableLabel = 0 == nPeakOrder? _L("Baseline") : _L("Peak") + ftoa(nPeakOrder);// + "(" + strDataLabel +")";
			strTableLabel = bHasBaselinePeak && 1 == nPeakOrder? _L("Baseline") : _L("Peak") + ftoa(bHasBaselinePeak? nPeakOrder-1:nPeakOrder);// + "(" + strDataLabel +")";
			///End PEAK_NUMBER_OFFSET_IS_ALWAYS_ONE
			
			strTableLabel += "("+strFunction+")";
			///End FIT_BASELINE_AS_WELL_AS_OTHER_PEAKS
			if(bFuncFirstParam && 0 < ii && !bHasBaselinePeak)//add y0 to other peak group
			{
				int jj = 0;//now only y0 i.e. the first parameter need copy
				FitParameter	paramCopy;
				paramCopy = pFitParams[jj];
				string 	strRowName = vstrParamNamesPostfix[jj];
				strRowName.TrimLeft();
				strRowName.TrimRight();
				///Jasmine 08/13/08 QA80-12009 PARAM_HAS_SAME_NOTATION_AS_75_FOR_MULTI_DS_AND_REPLICA_AND_PEAK
				string strPrefix;
				int	nIndex = string_to_prefix_end_number(strPrefix.GetBuffer(MAXLINE), strRowName);
				strPrefix.ReleaseBuffer();
				//strRowName += ftoa(nPeakOrder-1);
				strRowName = strPrefix + ftoa(nPeakOrder);
				///End PARAM_HAS_SAME_NOTATION_AS_75_FOR_MULTI_DS_AND_REPLICA_AND_PEAK
				strRowName.MakeValidCName();
				trRow = tree_check_get_node(trParams, strRowName);
				if( !trRow )
				{
					error_report("Fail to construct one new row by parameter name as tagname");
					return trParams;
				}
				
				//------ Folger 12/11/08 QA80-12766 v8.0985 SIGNIFICANT_DIGITS_FAILS_TO_APPLY_TO_NLSF_FITTING_REPORT
				_set_sinificant_digits_to_params(trRow, nSignDigitsPrev, vnSignDigits, jj, vbIsDerived ? vbIsDerived[ii] : false);
				//------
				
				if ( bDataLabelAsTableMainHeader )
					tree_add_one_label(trRow, strTableLabel);
				//------ Folger 12/04/07 LOCALIZE_PARAMETER_TABLE
				//tree_add_one_label(trRow, vstrParamNames[jj], nParamNameHeaderIndex);
				tree_add_one_label(trRow, GetLocalized(vstrParamNames[jj]), nParamNameHeaderIndex);
				//------
				trRow += paramCopy;
				///Jasmine 11/08/07 ADD_SHARED_TO_PARAMETER_REPORT_TABLE
				if(trRow.Fix)
				{
					TreeNode trFix = trRow.Fix;
					TreeNode trShared = trRow.InsertNode(trFix, "Shared");

					if(trShared)
					{
						trShared.DataID = IDE_PARAM_SHARED;
						trShared.nVal = jj < vnShared.GetSize()? vnShared[jj] : 0;
					}
				}
				//End ADD_SHARED_TO_PARAMETER_REPORT_TABLE
				///Kyle 08/10/2009 QA80-14077 ADD_PARAMETER_UNIT_TO_FITTING_REPORT
				if(jj<vstrParamUnits.GetSize())
					_param_row_insert_unit(trRow, vstrParamUnits[jj]);
				///End ADD_PARAMETER_UNIT_TO_FITTING_REPORT

				int nID  = make_one_set_ID(IDST_FIT_PARAMETER_ONE_SET + ii, index); 
				trRow.ID = make_one_set_ID(nID, jj+1); 
				if(trRow.Fix)
					trRow.Fix.strVal = trRow.Fix.nVal? "Y" : "N";
			}
			
		}
		///End ADD_PEAK_NUMBER_TO_PFM_PARAMETERS
		
		/// Iris 12/29/2006 v8.0534 PARAM_NAME_AS_TAGNAME_FOR_CELL_LINKING 
		//trRow = check_add_enumerated_node(trParams, CALCULATION_PARAMETER_PREFIX, nNodeIndexStart + ii + 1);
		/// Iris 10/10/2009 QA80-14440 FOND_DUPLICATE_PARAM_NAME_AS_REPORT_TREENODE_NAME
		// after trim left, trim right and make valid c name, have duplicate treenode names exist, so the next same name treenode will overwrite the previous one.
		/*
		string 	strRowName = vstrParamNamesPostfix[ii];
		strRowName.TrimLeft();
		strRowName.TrimRight();
		strRowName.MakeValidCName();
		*/
		string	strRowName = _get_param_valid_cname(vstrParamNamesPostfix, ii);
		///end FOND_DUPLICATE_PARAM_NAME_AS_REPORT_TREENODE_NAME
		trRow = tree_check_get_node(trParams, strRowName);
		if( !trRow )
		{
			error_report("Fail to construct one new row by parameter name as tagname");
			return trParams;
		}
		///end PARAM_NAME_AS_TAGNAME_FOR_CELL_LINKING
		
		//------ Folger 12/11/08 QA80-12766 v8.0985 SIGNIFICANT_DIGITS_FAILS_TO_APPLY_TO_NLSF_FITTING_REPORT
		_set_sinificant_digits_to_params(trRow, nSignDigitsPrev, vnSignDigits, nParam, vbIsDerived ? vbIsDerived[ii] : false);
		//------
		
		if ( bDataLabelAsTableMainHeader )
			///Arvin 08/03/07 WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
			//tree_add_one_label(trRow, strDataLabel);
			tree_add_one_label(trRow, strTableLabel);
			///end WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
		
		/// TD 10-04-2007 QA80-10478 LOCALISED_REPORTTREE_ISSUE
		//tree_add_one_label(trRow, vstrParamNames[ii], nParamNameHeaderIndex);
		///Arvin 11/02/07 CLEAN_UP_LOCALIZATION_STRINGS
		//string	strTranslated = getTranslatedParamStr(vstrParamNames[ii]);
		//string	strTranslated = _L(vstrParamNames[ii]);
		//------ Folger 12/04/07 LOCALIZE_PARAMETER_TABLE
		//string	strTranslated = vstrParamNames[ii]; /// Hong 11/07/07 v.8.0742 FIX_ERROR_LOCALIZED
		string	strTranslated = GetLocalized(vstrParamNames[ii]);
		//------
		///end CLEAN_UP_LOCALIZATION_STRINGS
		
		///Arvin 01/03/08 ADD_STAR_MARK_FOR_SHARED_PARAMS as cp said
		if(vbIsShared && ii < vbIsShared.GetSize() && vbIsShared[ii])
			strTranslated = strTranslated + "*";
		///end ADD_STAR_MARK_FOR_SHARED_PARAMS
		tree_add_one_label(trRow, strTranslated, nParamNameHeaderIndex);
		/// end LOCALISED_REPORTTREE_ISSUE
		//--- CPY 11/13/06 SHOULD_NEVER_ROUND_PARAM_VALUES_INTERNALLY
		/*
		///Cheney 2006-11-13 SET_PARAMS_VALUE_WITH_SIGNIFICENT_DIGITS
		if(bUseSignDigtes)
			_set_param_value_by_significant_digit(param, vnSignDigits[ii + nParams*index]);
		///end SET_PARAMS_VALUE_WITH_SIGNIFICENT_DIGITS
		*/
		/// Iris 11/30/06 v8.0517 TRM_0_FROM_DERIVED_PARAMS_ERR_TVAL_ETC
		//trRow += param;
		//---- Iris 12/30/2006 v8.0534 CORRECT_DERIVED_PARAMS_ORDER_FOR_REPLICA_CASE
		//if(ii < nNumNonDerivedParams)
		//----
		if( vbIsDerived && vbIsDerived[ii] && 0 != nNumDerivedParams)
		{
			trRow += stDerivedParam;
			///Cheney 2007-3-24 SHOULD_NOT_PASS_DERIVED_PARAMS_WHEN_FIND_X_FROM_Y
			trRow.SetAttribute(STR_ATTRIB_DERIVED_PARAM, true);
			///end SHOULD_NOT_PASS_DERIVED_PARAMS_WHEN_FIND_X_FROM_Y
		}
		else
		{
			trRow += param;
			///Jasmine 11/08/07 ADD_SHARED_TO_PARAMETER_REPORT_TABLE
			if(trRow.Fix)
			{
				TreeNode trFix = trRow.Fix;
				TreeNode trShared = trRow.InsertNode(trFix, "Shared");

				if(trShared)
				{
					trShared.DataID = IDE_PARAM_SHARED;
					trShared.nVal = nParam < vnShared.GetSize()? vnShared[nParam] : 0;
				}
			}
			///End ADD_SHARED_TO_PARAMETER_REPORT_TABLE
			nParam++;
		}
		///end TRM_0_FROM_DERIVED_PARAMS_ERR_TVAL_ETC
		
		///Kyle 08/10/2009 QA80-14077 ADD_PARAMETER_UNIT_TO_FITTING_REPORT
		if(ii<vstrParamUnits.GetSize())
			_param_row_insert_unit(trRow, vstrParamUnits[ii]);
		///End ADD_PARAMETER_UNIT_TO_FITTING_REPORT
		
		/// ML 8/17/2004 QA70-6825 RLOG_QUERY
		//trRow.ID = IDST_FIT_PARAMETER_ON_SET + nNodeIndexStart + ii + 1; 
		trRow.ID = make_one_set_ID(IDST_FIT_PARAMETER_ONE_SET + ii, index); 
		/// end RLOG_QUERY
		///Sophy 3/30/2009 QA80-13352 SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
		tree_set_attribute_to_all_nodes(trRow, STR_COL_DESIGNATION_ATTRIB, (string)OKDATAOBJ_DESIGNATION_Y);
		if ( trRow.Error )
			trRow.Error.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_ERROR);
		///end SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
		///Cheney 2007-4-12 SET_FIXED_VALUE_AS_STRING_INSTEAD_OF_INT
		if(trRow.Fix)
			trRow.Fix.strVal = trRow.Fix.nVal? "Y" : "N";
		///end SET_FIXED_VALUE_AS_STRING_INSTEAD_OF_INT
	}
	/*
	string strBranchLabel = _L("Parameters");
	if(!strDataLabel.IsEmpty() && !bDataLabelAsTableMainHeader)
		strBranchLabel += ": " +  strDataLabel;
	
	trParams.SetAttribute(STR_LABEL_ATTRIB, strBranchLabel);
	*/	
	return trParams;
}

int stats_tree_get_Parameters(const TreeNode &trCal, int index, FitParameter* pFitParams, vector<string> &vstrParamNames)
{
	int				nParams = vstrParamNames.GetSize();
	TreeNode		trParams = trCal.GetNode(STR_PARAMS);
	if(!trParams)
		return -1;
	
	TreeNode		trRow;
	string			strTag;
	int				nID;
	for(int ii = 0; ii < nParams; ii++)
	{
		trRow = tree_get_node_by_id(trParams, make_one_set_ID(IDST_FIT_PARAMETER_ONE_SET + ii, index));
		pFitParams[ii] = trRow;
	}
	return nParams;
}
//---- 
///Arvin 06/12/07 OUTPUT_COV_AND_COR_MATRIX_FOR_GLOBAL_FIT
void FitterOperation::RemoveUnusedParams(vector<string> &vstrParamNames, vector<bool> &vbUnused)
{
	vector<string> vstrParamsTemp;
	vstrParamsTemp = vstrParamNames;
	int nHasRemove = 0;
	
	for(int ii = 0; ii < vbUnused.GetSize(); ii++)
	{
		if(vbUnused[ii] && ii < vstrParamsTemp.GetSize())
		{
			vstrParamNames.RemoveAt(ii-nHasRemove);
			nHasRemove++;
		}
	}
}
///end OUTPUT_COV_AND_COR_MATRIX_FOR_GLOBAL_FIT

///Arvin 11/09/07 SUPPORT_FIX_SLOPE_IN_FITLINEAR
bool  FitterOperation::RemoveFixedInterceptAndSlope(TreeNode& trGUI, vector<string>& vStrParams)
{
	if(!trGUI || vStrParams.GetSize() <= 0)
		return false;
	
	TreeNode trIntercept = trGUI.Fit.FixIntercept;
	if(trIntercept)
	{
		bool bFixIntercept = trIntercept.nVal;
		if(bFixIntercept && vStrParams.GetSize() > 0)
			vStrParams.RemoveAt(0);//Remove the parameter called "Intercept"
	}
	
	return true;
}
///end SUPPORT_FIX_SLOPE_IN_FITLINEAR

///Arvin 11/24/06 MULTI_DATA_NEED_MULTI_COVARIANCE_AND_CORRELATION_TABLE
///Arvin 05/23/07 v8.0624 COV_AND_CORR_TABLE_CHAOS_WHILE_CHANGE_PARAMETER
//bool stats_tree_add_cov_or_corr_table(TreeNode &trOp, const string& strTagName, const string& strDataLabel, int index, int nTotalNumData, int nID, const matrix& mCovOrCorr, const vector<string> &vstrParamNames)
///Arvin 05/29/07 v8.0629 COV_AND_CORR_MATRIX_SHOULD_REMOVE_DERIVED_PARAMS
//bool FitterOperation::AddCovOrCorrMatrixToReportTree(TreeNode &trOp, const string& strDataLabel, int index, int nTotalNumData, int nID, const matrix& mCovOrCorr, const vector<string> &vstrParamNames)
bool FitterOperation::AddCovOrCorrMatrixToReportTree(TreeNode &trOp, const string& strDataLabel, int index, int nTotalNumData, int nID, const matrix& mCovOrCorr, const vector<string> &vstrParamNames, vector<bool> &vbIsDerived)
///END COV_AND_CORR_MATRIX_SHOULD_REMOVE_DERIVED_PARAMS
///end COV_AND_CORR_TABLE_CHAOS_WHILE_CHANGE_PARAMETER
{
	///Arvin 05/23/07 v8.0624 COV_AND_CORR_TABLE_CHAOS_WHILE_CHANGE_PARAMETER
	//TreeNode trOutputMatrix; 
	//if(nID == IDST_REG_COV_TABLE)
		//trOutputMatrix = trOp.GUI.Quantities.mCov;
		//
	//else if(nID == IDST_REG_CORR_TABLE)
		//trOutputMatrix = trOp.GUI.Quantities.mCor;
	TreeNode trOutputMatrix; 
	string strTagName;
	/// ML 10/31/2007 QA70-10630 LOCALIZING_KEYWORDS_FOR_XF_AND_THEMES
	string		strNodeLabel;
	/// end LOCALIZING_KEYWORDS_FOR_XF_AND_THEMES
	if(nID == IDST_REG_COV_TABLE)
	{
		trOutputMatrix = trOp.GUI.Quantities.mCov;
		/// ML 10/31/2007 QA70-10630 LOCALIZING_KEYWORDS_FOR_XF_AND_THEMES
		//strTagName = _L("Covariance");
		strTagName = "Covariance";
		strNodeLabel = _L("Covariance");
		/// end LOCALIZING_KEYWORDS_FOR_XF_AND_THEMES
	}
	else if(nID == IDST_REG_CORR_TABLE)
	{
		trOutputMatrix = trOp.GUI.Quantities.mCor;
		/// ML 10/31/2007 QA70-10630 LOCALIZING_KEYWORDS_FOR_XF_AND_THEMES
		//strTagName = _L("Correlation");
		strTagName = "Correlation";
		strNodeLabel = _L("Correlation");
		/// end LOCALIZING_KEYWORDS_FOR_XF_AND_THEMES
	}
	///end COV_AND_CORR_TABLE_CHAOS_WHILE_CHANGE_PARAMETER
	if(!trOutputMatrix)
		return error_report("Operation GUI tree has no " + strTagName +" branch!!");
	
	bool 	bShow = trOutputMatrix.nVal;
	tree_check_set_hidden(trOp.Calculation.GetNode(strTagName), bShow ? false : true); /// Iris 6/06/2008 v8.0879 FIX_SHOW_TABLE_NAME_EVEN_TABLE_IS_EMPTY_IN_RESULT_LOG
	/// Iris 5/19/2008 NOT_GENERAGE_TABLE_IF_NOT_REPORT_TO_IMPROVE_NLSF_SPEED_MORE
	if( !bShow )
		return true;
	///end NOT_GENERAGE_TABLE_IF_NOT_REPORT_TO_IMPROVE_NLSF_SPEED_MORE
	TreeNode trCal = trOp.Calculation;
	/// ML 10/31/2007 QA70-10630 LOCALIZING_KEYWORDS_FOR_XF_AND_THEMES
	//TreeNode trTable = tree_check_get_node(trCal, strTagName, nID, STR_LABEL_ATTRIB, strTagName);
	TreeNode	trTable = tree_check_get_node(trCal, strTagName, nID, STR_LABEL_ATTRIB, strNodeLabel);
	/// end LOCALIZING_KEYWORDS_FOR_XF_AND_THEMES
	if(!trTable)
		return error_report("Operation tree has no " + strTagName + " branch!!");
	else
	{
		if(index == 0)
		{
			trTable.RemoveChildrenWithPrefix();
		}
	}
	///Arvin 08/07/07 CAN_NOT_SHOW_COV_AND_CORR_MATRIX_CHANGE_PARAMETER
	//tree_check_set_hidden(trTable, bShow?false:true);
	trTable.Show = bShow;
	///end CAN_NOT_SHOW_COV_AND_CORR_MATRIX_CHANGE_PARAMETER
	///Arvin 05/23/07 v8.0624 COV_AND_CORR_TABLE_CHAOS_WHILE_CHANGE_PARAMETER
	//bool		bHaveSubLevel = 1 < nTotalNumData;	
	//int			nIDTable = make_one_set_ID(nID, index);
	//TreeNode	trOneTable;
	//if ( bHaveSubLevel )
		//trOneTable = check_add_enumerated_node(trTable, strTagName, index + 1, nIDTable, STR_LABEL_ATTRIB, strDataLabel);
	//else
	//{
		//trOneTable = trTable;
		//trOneTable.ID = nIDTable;
	//}
	int			nIDTable = make_one_set_ID(nID, index);
	TreeNode	trOneTable;
	trOneTable = check_add_enumerated_node(trTable, strTagName, index + 1, nIDTable, STR_LABEL_ATTRIB, strDataLabel);
	///end COV_AND_CORR_TABLE_CHAOS_WHILE_CHANGE_PARAMETER
	///Arvin 02/14/07 GET_PAREMETERS_SHOULD_NOT_CONSIDER_FIX_INTERCEPT
	//tree_result_table_add_matrix(trOneTable, mCovOrCorr, vstrParamNames, vstrParamNames, true);
	vector<string> vStrParams;
	vStrParams = vstrParamNames;
	///Arvin 06/12/07 OUTPUT_COV_AND_COR_MATRIX_FOR_GLOBAL_FIT
	if(vbIsDerived)
		RemoveUnusedParams(vStrParams, vbIsDerived);
	///end OUTPUT_COV_AND_COR_MATRIX_FOR_GLOBAL_FIT
	
	///Arvin 11/09/07 SUPPORT_FIX_SLOPE_IN_FITLINEAR
	//TreeNode trIntercept = trOp.GUI.Fit.FixIntercept;
	//if(trIntercept)
	//{
	//	bool bFixIntercept = trIntercept.nVal;
	//	if(bFixIntercept && vStrParams.GetSize() > 0)
	//		vStrParams.RemoveAt(0);//Remove the parameter called "Intercept"
	//}
	///Arvin 01/25/08 QA70-10923 CALC_CONFIDENCE_AND_PREDICTION_BANDS
	//We should keep covariance and correlation matrix consistent with NLSF
	//If parameter is fixed, we should set corresponding row and col as missing values 
	//RemoveFixedInterceptAndSlope(trOp.GUI, vStrParams);
	///end CALC_CONFIDENCE_AND_PREDICTION_BANDS
	
	///END SUPPORT_FIX_SLOPE_IN_FITLINEAR
	
	///Arvin 05/23/07 v8.0624 COV_AND_CORR_TABLE_CHAOS_WHILE_CHANGE_PARAMETER
	//tree_result_table_add_matrix(trOneTable, mCovOrCorr, vStrParams, vStrParams, true);
	tree_result_table_add_matrix(trOneTable, mCovOrCorr, vStrParams, vStrParams, true);
	if(trOneTable)
		trOneTable.SetAttribute(TREE_Table, GetTableStringMain());
	///end COV_AND_CORR_TABLE_CHAOS_WHILE_CHANGE_PARAMETER
	///end GET_PAREMETERS_SHOULD_NOT_CONSIDER_FIX_INTERCEPT
	return true;
}
///END MULTI_DATA_NEED_MULTI_COVARIANCE_AND_CORRELATION_TABLE
////////////////////////////////////////////////////////////////////////////////
// End basic support functions
////////////////////////////////////////////////////////////////////////////////



///////////////////////////////////////////////////////////////////////////////
//--------- CPY 11/26/04 OUTPUT_FIT_CURVES_TO_SOURCE_SHEET

//virtual 
//bool FitterOperation::UpdateInsertedColumns(TreeNode& trOp, const DataRange& rngInput, int nDataIndex, int nTotalNumData, DataRange& rngOutput)
bool FitterOperation::UpdateInsertedColumns(TreeNode& trOp, const DataRange& rngInput, int nDataIndex, int nTotalNumData, DataRange& rngOutput, int nOutOption)
{
	/// Iris 10/13/06 v8.0495 OUTPUT_FITCURVE_RESIDUAL_TO_SOURCE_NOT_WORK
	//TreeNode	trFit = GetOneResultCurvesTable(trOp, nDataIndex, nTotalNumData, GRAPH_FIT_CURVE);//getFitCuvesTable(trOp, nDataIndex, nTotalNumData);
	//if(!trFit)
		//return error_report("FitterOperation::UpdateInsertedColumns found fit curves table missing");
	TreeNode trCurves = GetResultCurvesBranch(trOp, nDataIndex, nTotalNumData, nOutOption);
	if(!trCurves)
		return error_report("FitterOperation::UpdateInsertedColumns found result curves table missing");
	///end OUTPUT_FITCURVE_RESIDUAL_TO_SOURCE_NOT_WORK
	
	int r1, c1, r2, c2;
	Worksheet wksInput;
	///Arvin 11/17/06 FITTED_CURVE_POSITION_WRONG_FOR_CONCATENATE
	//if(!find_input_range_bounding_box(rngInput, r1, c1, r2, c2, wksInput, nDataIndex))
	//	return error_report("UpdateInsertedColumns failed find_input_range_bounding_box");
	/// Iris 02/27/2007 v8.0570 RENAME_DATA_MODE_TO_AVOID_CONFUSE
	//int nDataMode = DATA_MODE_INDEP_CONSOLID;
	int nDataMode = DATA_MODE_GLOBAL;
	///end RENAME_DATA_MODE_TO_AVOID_CONFUSE
	TreeNode trInputData = trOp.GUI.InputData;
	if(!trInputData)
		return false;
		
	trInputData.GetAttribute(STR_USE_ATTRIB, nDataMode);
	if(nDataMode == DATA_MODE_CONCATENATE)
	{
		int numSubRanges;
		int nNumData = GetNumData(trOp, rngInput, NULL, NULL, NULL, &numSubRanges);
		if(!find_input_range_bounding_box(rngInput, r1, c1, r2, c2, wksInput, numSubRanges-1))
			return error_report("UpdateInsertedColumns failed find_input_range_bounding_box");
	}
	else
	{
		if(!find_input_range_bounding_box(rngInput, r1, c1, r2, c2, wksInput, nDataIndex))
			return error_report("UpdateInsertedColumns failed find_input_range_bounding_box");
	}
	///end FITTED_CURVE_POSITION_WRONG_FOR_CONCATENATE
	
	/// Iris 9/17/05 QA70-8015-P15 OUTPUT_RESULT_CURVE_TO_WKS
	//return InsertReportToSourceWks(trOp, trFit, wksInput, c2 + 1, rngOutput);
	return InsertReportToWks(trOp, trCurves, wksInput, c2 + 1, rngOutput);
	///End OUTPUT_RESULT_CURVE_TO_WKS
}


/// ML 9/20/2006 RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT
/*
bool FitterOperation::CalcReportConfPredBandsTable(TreeNode &trOp, TreeNode &trFC, vector &vFitX, vector &vFitY, FitParameter* psFitParameter, RegStats &stRegStats, RegCalcInternal &stReg)
{
	FitResultCurveOptions	fitOptions;
	TreeNode trFittedCurve = GetGUIGraphNodes(trOp);
	fitOptions = trFittedCurve;
	
	double 		dof = stRegStats.DOF;
	// t(1-alpha/2,dof) ------- alpha: significance level
	double		tvalue = tTable(1 - (1.0 - fitOptions.Confidence/100.0) / 2, dof);
	
	string strConfidenceLevel = fitOptions.Confidence;
	strConfidenceLevel += "%";
	
	bool 	bRet = false; ///Iris 4/18/05 FIX_NLSF_CONF_PREDI_BAND_NOT_WORK
	int nConf = fitOptions.ConfBands;
	if(nConf)
	{
		/// Iris 11/08/05 REMOVE_EMPTY_COLUMNS_FOR_RESULT_CURVE_BOOK
		TreeNode	trLCB = tree_check_get_node(trFC, "LCB", IDST_FIT_LCB, STR_LABEL_ATTRIB, "Lower " + strConfidenceLevel + " Confidence Limit");
		trLCB.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
		TreeNode	trUCB = tree_check_get_node(trFC, "UCB", IDST_FIT_UCB, STR_LABEL_ATTRIB, "Upper " + strConfidenceLevel + " Confidence Limit");
		trUCB.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
		///End REMOVE_EMPTY_COLUMNS_FOR_RESULT_CURVE_BOOK
		
		vector 		vConf, vSerr;
		bRet = MakeFitErrConf(trOp, vFitX, vSerr, psFitParameter, stRegStats, stReg);
		if(bRet)  ///Iris 4/18/05 FIX_NLSF_CONF_PREDI_BAND_NOT_WORK
		{
			vConf = vFitY - tvalue * vSerr;
			trLCB.dVals = vConf;
			vConf = vFitY + tvalue * vSerr;
			trUCB.dVals = vConf;
		}
	}
	
	if(0 == nConf || !bRet)
	{
		TreeNode	trLCB = trFC.GetNode("LCB");
		TreeNode	trUCB = trFC.GetNode("UCB");
		if(trLCB)
			trLCB.Remove();
		if(trUCB)
			trUCB.Remove();
	}

	// Prediction bands
	int nPred = fitOptions.PredBands;
	if(nPred)
	{
		/// Iris 11/08/05 REMOVE_EMPTY_COLUMNS_FOR_RESULT_CURVE_BOOK
		TreeNode	trLPB = tree_check_get_node(trFC, "LPB", IDST_FIT_LPB, STR_LABEL_ATTRIB, "Lower " + strConfidenceLevel + " Predictioin Limit");
		trLPB.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
		TreeNode	trUPB = tree_check_get_node(trFC, "UPB", IDST_FIT_UPB, STR_LABEL_ATTRIB, "Upper " + strConfidenceLevel + " Predictioin Limit");
		trUPB.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
		///End REMOVE_EMPTY_COLUMNS_FOR_RESULT_CURVE_BOOK
	
		vector 		vPre, vSerr;
		bRet = MakeFitErrPred(trOp, vFitX, vSerr, psFitParameter, stRegStats, stReg);
		if(bRet)  ///Iris 4/18/05 FIX_NLSF_CONF_PREDI_BAND_NOT_WORK
		{
			vPre = vFitY - tvalue * vSerr;
			trLPB.dVals = vPre;
			vPre = vFitY + tvalue * vSerr;	
			trUPB.dVals = vPre;
		}
	}
	
	if(0 == nPred || !bRet)
	{
		TreeNode	trLPB = trFC.GetNode("LPB");
		TreeNode	trUPB = trFC.GetNode("UPB");
		if(trLPB)
			trLPB.Remove();
		if(trUPB)
			trUPB.Remove();		
	}
	
	return true;
}
*/
///Cheney 2006-11-1 CHANGE_sReg_FROM_REF_TO_POINTER
//bool FitterOperation::makeConfOrPredTbl(BOOL bDo, bool bConf, GraphLayer &grLayAppar, TreeNode &trOp, TreeNode &trFC, vector &vFitX, vector &vFitY, FitParameter* psFitParameter, RegStats &stRegStats, RegCalcInternal &stReg, double tvalue, LPCSTR lpcszConfLevel)
///Arvin 12/04/06 ADD_CONF_PRED_BANDS_FOR_MR
//bool FitterOperation::makeConfOrPredTbl(BOOL bDo, bool bConf, GraphLayer &grLayAppar, TreeNode &trOp, TreeNode &trFC, vector &vFitX, vector &vFitY, FitParameter* psFitParameter, RegStats &stRegStats, RegCalcInternal* pstReg, double tvalue, LPCSTR lpcszConfLevel)
///Arvin 06/11/07 CENTRALIZE_FITTING_RESULT_LABELS as max's suggestion
//bool FitterOperation::makeConfOrPredTbl(BOOL bDo, bool bConf, GraphLayer &grLayAppar, TreeNode &trOp, TreeNode &trFC, vector &vFitX, vector &vFitY, FitParameter* psFitParameter, RegStats &stRegStats, RegCalcInternal* pstReg, double tvalue, LPCSTR lpcszConfLevel, vector& vSE)
///Arvin 01/11/08 QA70-10923 CALC_CONFIDENCE_AND_PREDICTION_BANDS
//bool FitterOperation::makeConfOrPredTbl(BOOL bDo, bool bConf, GraphLayer &grLayAppar, TreeNode &trOp, TreeNode &trFC, vector &vFitX, vector &vFitY, FitParameter* psFitParameter, RegStats &stRegStats, RegCalcInternal* pstReg, double tvalue, LPCSTR lpcszConfLevel, vector& vSE, LPCSTR lpcszDataLabel)
/////end CENTRALIZE_FITTING_RESULT_LABELS
/////------
/////end CHANGE_sReg_FROM_REF_TO_POINTER
//{
	//string		strTagL, strTagU;
	//int			nIdL, nIdU;
	//string		strType;
	///// Iris 11/30/06 USE_SHORTR_LONG_NAME
	///*	
	//string		strLabelL = _L("Lower "), strLabelU = _L("Upper ");
	//strLabelL += lpcszConfLevel;
	//strLabelU += lpcszConfLevel;
	//*/
	//string		strLabelL = lpcszConfLevel;
	//string		strLabelU = lpcszConfLevel;	
	/////end USE_SHORTR_LONG_NAME
	//if (bConf)
	//{
		//nIdL = IDST_FIT_LCB;
		//nIdU = IDST_FIT_UCB;
		//strTagL = "LCL";
		//strTagU = "UCL";
		///// Nicole 07/05/2007 v8.0655 REMOVE_SPACE_FOR_LOCATION_STRING
		////strType = _L(" Confidence Limit");
		//strType = " " + _L("Confidence Limit");
		///// END REMOVE_SPACE_FOR_LOCATION_STRING
	//}
	//else
	//{
		//nIdL = IDST_FIT_LPB;
		//nIdU = IDST_FIT_UPB;
		//strTagL = "LPL";
		//strTagU = "UPL";
		///// Nicole 07/05/2007 v8.0655 REMOVE_SPACE_FOR_LOCATION_STRING
		////strType = _L(" Prediction Limit");
		//strType =" " +  _L("Prediction Limit");
		///// END REMOVE_SPACE_FOR_LOCATION_STRING
	//}
	///// Iris 11/30/06 USE_SHORTR_LONG_NAME
	////strLabelL += strType;
	////strLabelU += strType;
	//strLabelL += " " + strTagL;
	//strLabelU += " " + strTagU;
	/////end USE_SHORTR_LONG_NAME
	/////Arvin 06/11/07 CENTRALIZE_FITTING_RESULT_LABELS as max's suggestion
	//string	strConvertedDataLabel(lpcszDataLabel);
	//ConvertEscapedString(strConvertedDataLabel);
	//strLabelL = strLabelL + " " + _L("of") + " " + strConvertedDataLabel;
	//strLabelU = strLabelU + " " + _L("of") + " " +strConvertedDataLabel;
	/////end CENTRALIZE_FITTING_RESULT_LABELS
	//bool			bDone = FALSE;
//
	//if (bDo)
	//{	
		//vector 		vConf, vSerr;
		/////Arvin 12/04/06 ADD_CONF_PRED_BANDS_FOR_MR
		///*
		/////Cheney 2006-11-1 CHANGE_sReg_FROM_REF_TO_POINTER
		////bDone = bConf ? MakeFitErrConf(trOp, vFitX, vSerr, psFitParameter, stRegStats, stReg) : MakeFitErrPred(trOp, vFitX, vSerr, psFitParameter, stRegStats, stReg);
		//bDone = bConf ? MakeFitErrConf(trOp, vFitX, vSerr, psFitParameter, stRegStats, pstReg) : MakeFitErrPred(trOp, vFitX, vSerr, psFitParameter, stRegStats, pstReg);
		/////end CHANGE_sReg_FROM_REF_TO_POINTER
		//*/
		//if(vSE && vSE.GetSize() > 0)//In this condition, vSerr has been calculated by CallLLOC as MR doing 
		//{
			//vSerr = vSE;
			//bDone = TRUE;
		//}
		//else
			//bDone = bConf ? MakeFitErrConf(trOp, vFitX, vSerr, psFitParameter, stRegStats, pstReg) : MakeFitErrPred(trOp, vFitX, vSerr, psFitParameter, stRegStats, pstReg);
		/////end 	ADD_CONF_PRED_BANDS_FOR_MR
		//if(bDone)
		//{
			//TreeNode	trL = tree_check_get_node(trFC, strTagL, nIdL, STR_LABEL_ATTRIB, strLabelL);
			//trL.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
			//
			//TreeNode	trU = tree_check_get_node(trFC, strTagU, nIdU, STR_LABEL_ATTRIB, strLabelU);
			//trU.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
			//
			///// Iris 11/30/2006 ADDITIONAL_LABEL_ROWS_IN_CURVE_SHEETS
			//tree_add_one_label(trL, strType, 0);
			//tree_add_one_label(trU, strType, 0);
			///// end ADDITIONAL_LABEL_ROWS_IN_CURVE_SHEETS
			//
			//vConf = vFitY - tvalue * vSerr;
			//if (grLayAppar)
				//grLayAppar.ConvertByAxis(vConf, vConf.GetSize(), OKAXISTYPE_Y, FALSE);
			//trL.dVals = vConf;
			//vConf = vFitY + tvalue * vSerr;
			//if (grLayAppar)
				//grLayAppar.ConvertByAxis(vConf, vConf.GetSize(), OKAXISTYPE_Y, FALSE);
			//trU.dVals = vConf;
		//}
	//}
	//
	//if (!bDone)
	//{
		//TreeNode	trL = trFC.GetNode(strTagL);
		//TreeNode	trU = trFC.GetNode(strTagU);
		//if(trL)
			//trL.Remove();
		//if(trU)
			//trU.Remove();		
	//}
	//
	//return bDone;
//}

/// Jack 12/25/2008 QA80-12329 CENTRALIZE_MULTI_INDEP_DEPS_BAND_CALCULATION
//void FitterOperation::GetConfOrPredTblLabelAndID(bool bConf, string& strTagL, string& strTagU, string& strLabelL, string& strLabelU, string& strType, int* pnIdL, int* pnIdU, LPCSTR lpcszLevel, LPCSTR lpcszDataLabel = NULL)
void FitterOperation::GetConfOrPredTblLabelAndID(bool bConf, string& strTagL, string& strTagU, string& strLabelL, string& strLabelU, string& strType, int* pnIdL, int* pnIdU, LPCSTR lpcszLevel, LPCSTR lpcszDataLabel = NULL, bool bMultiIndepDepCase = false, int iDep=0)
///End CENTRALIZE_MULTI_INDEP_DEPS_BAND_CALCULATION
{	
	int			nIdL, nIdU;
	strLabelL = lpcszLevel;
	strLabelU = lpcszLevel;	
	if (bConf)
	{
		nIdL = IDST_FIT_LCB;
		nIdU = IDST_FIT_UCB;
		strTagL = "LCL";
		strTagU = "UCL";
		strType = " " + _L("Confidence Limit");
	}
	else
	{
		nIdL = IDST_FIT_LPB;
		nIdU = IDST_FIT_UPB;
		strTagL = "LPL";
		strTagU = "UPL";
		strType =" " +  _L("Prediction Limit");
	}
	
	strLabelL += " " + strTagL;
	strLabelU += " " + strTagU;
	strLabelL = strLabelL;
	strLabelU = strLabelU;
	string	strConvertedDataLabel(lpcszDataLabel);
	if(!strConvertedDataLabel.IsEmpty())
	{
		///------ Folger 03/24/09 QA80-13331-P1 CUSTOMIZED_OUTPUT_COLUMN_LONGNAME_FORMAT_SUPPORT
		//ConvertEscapedString(strConvertedDataLabel);
		MakeFullRangeEscapeString(strConvertedDataLabel);
		///------ End CUSTOMIZED_OUTPUT_COLUMN_LONGNAME_FORMAT_SUPPORT
		/// Iris 3/23/2009 QA80-13331-P1 CENTRILIZE_REPORT_COL_LABEL_CODES
		//strLabelL = strLabelL + " " + _L("of") + " " + strConvertedDataLabel;
		//strLabelU = strLabelU + " " + _L("of") + " " +strConvertedDataLabel;
		strLabelL = ConstructReportDataColLabel(strLabelL, strConvertedDataLabel);
		strLabelU = ConstructReportDataColLabel(strLabelU, strConvertedDataLabel);
		///end CENTRILIZE_REPORT_COL_LABEL_CODES
	}

/// Jack 12/25/2008 QA80-12329 CENTRALIZE_MULTI_INDEP_DEPS_BAND_CALCULATION
	//if(pnIdL)
		//*pnIdL = nIdL;
	//if(pnIdU)
		//*pnIdU = nIdU;
	if(bMultiIndepDepCase)
	{
		int nIDLIdep = make_one_set_ID(nIdL, iDep);	
		int nIDUIdep = make_one_set_ID(nIdU, iDep);
	
		string str = (iDep+1);
		strTagL = strTagL + str;
		strTagU = strTagU + str;
		
		if(pnIdL)
		*pnIdL = nIDLIdep;
		if(pnIdU)
			*pnIdU = nIDUIdep;
	}
	else
	{
		if(pnIdL)
			*pnIdL = nIdL;
		if(pnIdU)
			*pnIdU = nIdU;
	}
///End CENTRALIZE_MULTI_INDEP_DEPS_BAND_CALCULATION	
}

/// ML 1/25/2008 MISMATCHED_BODY_WITH_DECLARATION_PREVENTS_COMPILATION
//bool FitterOperation::CalcConfOrPredBounds(TreeNode &trOp, bool bConf, double dBoundLevel, vector& vLower, vector& vUpper, vector& vIndep1, vector &vFitY, GraphLayer& grLayAppar, FitParameter* psFitParameter, RegStats &stRegStats, RegCalcInternal* pstReg, vector& vSE, vector& vIndep2, int index)
///Arvin 01/28/08 QA70-10923 CALC_CONFIDENCE_AND_PREDICTION_BANDS
//We need the index argument to calculate confidence and prediction bands of Polynomial Fit
//bool FitterOperation::CalcConfOrPredBounds(TreeNode &trOp, bool bConf, double dBoundLevel, vector& vLower, vector& vUpper, vector& vIndep1, vector &vFitY, GraphLayer& grLayAppar, FitParameter* psFitParameter, RegStats &stRegStats, RegCalcInternal* pstReg, vector& vSE, vector& vIndep2)
bool FitterOperation::CalcConfOrPredBounds(TreeNode &trOp, bool bConf, double dBoundLevel, vector& vLower, vector& vUpper, vector& vIndep1, vector &vFitY, GraphLayer& grLayAppar, FitParameter* psFitParameter, RegStats &stRegStats, RegCalcInternal* pstReg, vector& vSE, vector& vIndep2, int index)
///end CALC_CONFIDENCE_AND_PREDICTION_BANDS
/// end MISMATCHED_BODY_WITH_DECLARATION_PREVENTS_COMPILATION
{
	double 		dof = stRegStats.DOF;
	double		tvalue = tTable(1 - (1.0 - dBoundLevel/100.0) / 2, dof);
	vector 		vConf, vSerr;
	bool		bDone = false;
	if(vSE && vSE.GetSize() > 0)//In this condition, vSerr has been calculated by CallLLOC as MR doing 
	{
		vSerr = vSE;
		bDone = true;
	}
	else
		bDone = bConf ? MakeFitErrConf(trOp, vIndep1, vSerr, psFitParameter, stRegStats, pstReg) : MakeFitErrPred(trOp, vIndep1, vSerr, psFitParameter, stRegStats, pstReg);
		
	if(bDone)
	{	
		vLower = vFitY - tvalue * vSerr;
		if (grLayAppar)
			grLayAppar.ConvertByAxis(vLower, vLower.GetSize(), OKAXISTYPE_Y, FALSE);
		
		vUpper = vFitY + tvalue * vSerr;
		if (grLayAppar)
			grLayAppar.ConvertByAxis(vUpper, vUpper.GetSize(), OKAXISTYPE_Y, FALSE);
		
		return true;
	}
	
	return false;
}

/// Jack 12/19/2008 QA80-12329 MULTI_INDEP_DEPS_BAND_CALCULATION
/// Jack 12/25/2008 QA80-12329 CENTRALIZE_MULTI_INDEP_DEPS_BAND_CALCULATION
//void FitterOperation::GetConfOrPredTblLabelAndIDMultiDep(bool bConf, string& strTagL, string& strTagU, string& strLabelL, string& strLabelU, string& strType, int* pnIdL, int* pnIdU, LPCSTR lpcszLevel, LPCSTR lpcszDataLabel, int iDep)
//{	
	//int			nIdL, nIdU;
	//strLabelL = lpcszLevel;
	//strLabelU = lpcszLevel;	
	//if (bConf)
	//{
		//nIdL = IDST_FIT_LCB;
		//nIdU = IDST_FIT_UCB;
		//strTagL = "LCL";
		//strTagU = "UCL";
		//strType = " " + _L("Confidence Limit");
	//}
	//else
	//{
		//nIdL = IDST_FIT_LPB;
		//nIdU = IDST_FIT_UPB;
		//strTagL = "LPL";
		//strTagU = "UPL";
		//strType =" " +  _L("Prediction Limit");
	//}
	//
	//strLabelL += " " + strTagL;
	//strLabelU += " " + strTagU;
	//strLabelL = strLabelL;
	//strLabelU = strLabelU;
	//string	strConvertedDataLabel(lpcszDataLabel);
	//if(!strConvertedDataLabel.IsEmpty())
	//{
		//ConvertEscapedString(strConvertedDataLabel);
		//strLabelL = strLabelL + " " + _L("of") + " " + strConvertedDataLabel;
		//strLabelU = strLabelU + " " + _L("of") + " " +strConvertedDataLabel;
	//}
	//
	//
	//int nIDLIdep = make_one_set_ID(nIdL, iDep);	
	//int nIDUIdep = make_one_set_ID(nIdU, iDep);
	//
	//string str = (iDep+1);
	//strTagL = strTagL + str;
	//strTagU = strTagU + str;
	//
	//
	//
	//if(pnIdL)
		//*pnIdL = nIDLIdep;
	//if(pnIdU)
		//*pnIdU = nIDUIdep;
//}
///End CENTRALIZE_MULTI_INDEP_DEPS_BAND_CALCULATION

bool FitterOperation::CalcConfOrPredBounds(TreeNode &trOp, bool bConf, double dBoundLevel, vector& vLower, vector& vUpper, matrix &mIndeps, vector &vFitY, GraphLayer& grLayAppar, FitParameter* psFitParameter, RegStats &stRegStats, RegCalcInternal* pstReg, vector& vSE, int index, int iDep)
{
	return false;
}

bool FitterOperation::MakeConfOrPredTbl(TreeNode &trOp, TreeNode& trFC, bool bConf, GraphLayer &grLayAppar, matrix &mIndeps, vector &vFitY, FitParameter* psFitParameter, RegStats &stRegStats, RegCalcInternal* pstReg, int nGraphIndex, vector& vSE, LPCSTR lpcszDataLabel, int index, int numDeps)
{
	FitResultCurveOptions	fitOptions;
	TreeNode trFittedCurve = GetGUIGraphNodes(trOp, nGraphIndex);
	fitOptions = trFittedCurve;
	
	bool	bConfBand = fitOptions.ConfBands;
	bool 	bPredBand = fitOptions.PredBands;
	if((!bConfBand && bConf) || (!bPredBand && !bConf))
		return false;
	
	double dLevel = fitOptions.Confidence;
	string strLevel = dLevel;
	strLevel += "%";
	
	
	int nSize = mIndeps.GetNumRows();
	
	for(int idep=0; idep<numDeps; idep++)
	{
		int nIdL, nIdU;
		string strTagL, strTagU, strLabelL, strLabelU, strType; 
/// Jack 12/25/2008 QA80-12329 CENTRALIZE_MULTI_INDEP_DEPS_BAND_CALCULATION
//		GetConfOrPredTblLabelAndIDMultiDep(bConf, strTagL, strTagU, strLabelL, strLabelU, strType, &nIdL, &nIdU, strLevel, lpcszDataLabel, idep);
		GetConfOrPredTblLabelAndID(bConf, strTagL, strTagU, strLabelL, strLabelU, strType, &nIdL, &nIdU, strLevel, lpcszDataLabel, true, idep);
///End	CENTRALIZE_MULTI_INDEP_DEPS_BAND_CALCULATION	
	
		
		vector vLower(nSize), vUpper(nSize);
		/// ML 1/25/2008 MISMATCHED_BODY_WITH_DECLARATION_PREVENTS_COMPILATION
		//if(!CalcConfOrPredBounds(trOp, bConf, dLevel, vLower, vUpper, vIndep1, vFitY, grLayAppar, psFitParameter, stRegStats, pstReg, vSE, vIndep2, index))
		///Arvin 01/28/08 QA70-10923 CALC_CONFIDENCE_AND_PREDICTION_BANDS
		//if(!CalcConfOrPredBounds(trOp, bConf, dLevel, vLower, vUpper, vIndep1, vFitY, grLayAppar, psFitParameter, stRegStats, pstReg, vSE, vIndep2))
		if(!CalcConfOrPredBounds(trOp, bConf, dLevel, vLower, vUpper, mIndeps, vFitY, grLayAppar, psFitParameter, stRegStats, pstReg, vSE, index, idep))
		///end CALC_CONFIDENCE_AND_PREDICTION_BANDS
		/// end MISMATCHED_BODY_WITH_DECLARATION_PREVENTS_COMPILATION
		{
			TreeNode	trL = trFC.GetNode(strTagL);
			TreeNode	trU = trFC.GetNode(strTagU);
			if(trL)
				trL.Remove();
			if(trU)
				trU.Remove();	
			return false;
		}
		
		TreeNode	trL = tree_check_get_node(trFC, strTagL, nIdL, STR_LABEL_ATTRIB, strLabelL);
		if(trL)
		{
			trL.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
			tree_add_one_label(trL, strType, 0);
			trL.dVals = vLower;
		}
				
		TreeNode	trU = tree_check_get_node(trFC, strTagU, nIdU, STR_LABEL_ATTRIB, strLabelU);
		if(trU)
		{
			trU.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
			tree_add_one_label(trU, strType, 0);
			trU.dVals = vUpper;
		}
	}
	
	
	return false;
}

bool FitterOperation::CalcReportConfPredBandsTableMultiIndepDep(TreeNode &trOp, TreeNode &trFC, matrix &mIndeps, vector &vFitY, FitParameter* psFitParameter, RegStats &stRegStats, RegCalcInternal* pstReg, GraphLayer &grLayAppar , int nGraphIndex , vector& vSerr, LPCSTR lpcszDataLabel, int index, int numDeps)
{
	//calculate and add confidence bands 
	MakeConfOrPredTbl(trOp, trFC, true, grLayAppar, mIndeps, vFitY, psFitParameter, stRegStats, pstReg, nGraphIndex, vSerr, lpcszDataLabel, index, numDeps);
	//calculate and add prediction bands 
	MakeConfOrPredTbl(trOp, trFC, false, grLayAppar, mIndeps, vFitY, psFitParameter, stRegStats, pstReg, nGraphIndex, vSerr, lpcszDataLabel, index, numDeps);
	return true; 
}
/// End MULTI_INDEP_DEPS_BAND_CALCULATION


/// ML 1/25/2008 MISMATCHED_BODY_WITH_DECLARATION_PREVENTS_COMPILATION
//bool FitterOperation::MakeConfOrPredTbl(TreeNode &trOp, TreeNode& trFC, bool bConf, GraphLayer &grLayAppar, vector &vIndep1, vector &vFitY, FitParameter* psFitParameter, RegStats &stRegStats, RegCalcInternal* pstReg, int nGraphIndex, vector& vSE, LPCSTR lpcszDataLabel, vector& vIndep2, int index)
///Arvin 01/28/08 QA70-10923 CALC_CONFIDENCE_AND_PREDICTION_BANDS
//We need the index argument to calculate confidence and prediction bands of Polynomial Fit
//bool FitterOperation::MakeConfOrPredTbl(TreeNode &trOp, TreeNode& trFC, bool bConf, GraphLayer &grLayAppar, vector &vIndep1, vector &vFitY, FitParameter* psFitParameter, RegStats &stRegStats, RegCalcInternal* pstReg, int nGraphIndex, vector& vSE, LPCSTR lpcszDataLabel, vector& vIndep2)
bool FitterOperation::MakeConfOrPredTbl(TreeNode &trOp, TreeNode& trFC, bool bConf, GraphLayer &grLayAppar, vector &vIndep1, vector &vFitY, FitParameter* psFitParameter, RegStats &stRegStats, RegCalcInternal* pstReg, int nGraphIndex, vector& vSE, LPCSTR lpcszDataLabel, vector& vIndep2, int index)
///end CALC_CONFIDENCE_AND_PREDICTION_BANDS
/// end MISMATCHED_BODY_WITH_DECLARATION_PREVENTS_COMPILATION
{
	FitResultCurveOptions	fitOptions;
	TreeNode trFittedCurve = GetGUIGraphNodes(trOp, nGraphIndex);
	fitOptions = trFittedCurve;
	
	bool	bConfBand = fitOptions.ConfBands;
	bool 	bPredBand = fitOptions.PredBands;
	if((!bConfBand && bConf) || (!bPredBand && !bConf))
		return false;
	
	double dLevel = fitOptions.Confidence;
	string strLevel = dLevel;
	strLevel += "%";
	
	int nIdL, nIdU;
	string strTagL, strTagU, strLabelL, strLabelU, strType; 
	GetConfOrPredTblLabelAndID(bConf, strTagL, strTagU, strLabelL, strLabelU, strType, &nIdL, &nIdU, strLevel, lpcszDataLabel);
	
	int nSize = vIndep1.GetSize();
	vector vLower(nSize), vUpper(nSize);
	/// ML 1/25/2008 MISMATCHED_BODY_WITH_DECLARATION_PREVENTS_COMPILATION
	//if(!CalcConfOrPredBounds(trOp, bConf, dLevel, vLower, vUpper, vIndep1, vFitY, grLayAppar, psFitParameter, stRegStats, pstReg, vSE, vIndep2, index))
	///Arvin 01/28/08 QA70-10923 CALC_CONFIDENCE_AND_PREDICTION_BANDS
	//if(!CalcConfOrPredBounds(trOp, bConf, dLevel, vLower, vUpper, vIndep1, vFitY, grLayAppar, psFitParameter, stRegStats, pstReg, vSE, vIndep2))
	if(!CalcConfOrPredBounds(trOp, bConf, dLevel, vLower, vUpper, vIndep1, vFitY, grLayAppar, psFitParameter, stRegStats, pstReg, vSE, vIndep2, index))
	///end CALC_CONFIDENCE_AND_PREDICTION_BANDS
	/// end MISMATCHED_BODY_WITH_DECLARATION_PREVENTS_COMPILATION
	{
		TreeNode	trL = trFC.GetNode(strTagL);
		TreeNode	trU = trFC.GetNode(strTagU);
		if(trL)
			trL.Remove();
		if(trU)
			trU.Remove();	
		return false;
	}
	
	TreeNode	trL = tree_check_get_node(trFC, strTagL, nIdL, STR_LABEL_ATTRIB, strLabelL);
	if(trL)
	{
		trL.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
		tree_add_one_label(trL, strType, 0);
		trL.dVals = vLower;
	}
			
	TreeNode	trU = tree_check_get_node(trFC, strTagU, nIdU, STR_LABEL_ATTRIB, strLabelU);
	if(trU)
	{
		trU.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
		tree_add_one_label(trU, strType, 0);
		trU.dVals = vUpper;
	}
	
	return false;
}
///end CALC_CONFIDENCE_AND_PREDICTION_BANDS

///Cheney 2006-11-1 CHANGE_sReg_FROM_REF_TO_POINTER
//bool FitterOperation::CalcReportConfPredBandsTable(TreeNode &trOp, TreeNode &trFC, vector &vFitX, vector &vFitY, FitParameter* psFitParameter, RegStats &stRegStats, RegCalcInternal &stReg, GraphLayer &grLayAppar)
///Arvin 12/04/06 ADD_CONF_PRED_BANDS_FOR_MR
//bool FitterOperation::CalcReportConfPredBandsTable(TreeNode &trOp, TreeNode &trFC, vector &vFitX, vector &vFitY, FitParameter* psFitParameter, RegStats &stRegStats, RegCalcInternal* pstReg, GraphLayer &grLayAppar, int nGraphIndex)///Arvin 12/02/06  MR_NEED_CLAC_CONF_OR_PRED_FOR_PARTIAL_REGRESSION
///Arvin 06/11/07 CENTRALIZE_FITTING_RESULT_LABELS as max's suggestion
//bool FitterOperation::CalcReportConfPredBandsTable(TreeNode &trOp, TreeNode &trFC, vector &vFitX, vector &vFitY, FitParameter* psFitParameter, RegStats &stRegStats, RegCalcInternal* pstReg, GraphLayer &grLayAppar, int nGraphIndex, vector& vSerr)///Arvin 12/02/06  MR_NEED_CLAC_CONF_OR_PRED_FOR_PARTIAL_REGRESSION
///Arvin 01/11/08 QA70-10923 CALC_CONFIDENCE_AND_PREDICTION_BANDS
/*
bool FitterOperation::CalcReportConfPredBandsTable(TreeNode &trOp, TreeNode &trFC, vector &vFitX, vector &vFitY, FitParameter* psFitParameter, RegStats &stRegStats, RegCalcInternal* pstReg, GraphLayer &grLayAppar, int nGraphIndex, vector& vSerr, LPCSTR lpcszDataLabel)///Arvin 12/02/06  MR_NEED_CLAC_CONF_OR_PRED_FOR_PARTIAL_REGRESSION
///end CENTRALIZE_FITTING_RESULT_LABELS
///end ADD_CONF_PRED_BANDS_FOR_MR
///end CHANGE_sReg_FROM_REF_TO_POINTER
{
	FitResultCurveOptions	fitOptions;
	///Arvin 12/02/06 MR_NEED_CLAC_CONF_OR_PRED_FOR_PARTIAL_REGRESSION
	//TreeNode trFittedCurve = GetGUIGraphNodes(trOp);
	TreeNode trFittedCurve = GetGUIGraphNodes(trOp, nGraphIndex);
	///END MR_NEED_CLAC_CONF_OR_PRED_FOR_PARTIAL_REGRESSION
	fitOptions = trFittedCurve;
	
	double 		dof = stRegStats.DOF;
	// t(1-alpha/2,dof) ------- alpha: significance level
	double		tvalue = tTable(1 - (1.0 - fitOptions.Confidence/100.0) / 2, dof);
	
	string strConfidenceLevel = fitOptions.Confidence;
	strConfidenceLevel += "%";
	
	int			nConf = fitOptions.ConfBands;
	
	///Cheney 2006-11-1 CHANGE_sReg_FROM_REF_TO_POINTER
	//makeConfOrPredTbl(nConf, true, grLayAppar, trOp, trFC, vFitX, vFitY, psFitParameter, stRegStats, stReg, tvalue, strConfidenceLevel);
	///Arvin 12/04/06 ADD_CONF_PRED_BANDS_FOR_MR
	//makeConfOrPredTbl(nConf, true, grLayAppar, trOp, trFC, vFitX, vFitY, psFitParameter, stRegStats, pstReg, tvalue, strConfidenceLevel);
	///Arvin 06/11/07 CENTRALIZE_FITTING_RESULT_LABELS as max's suggestion
	//makeConfOrPredTbl(nConf, true, grLayAppar, trOp, trFC, vFitX, vFitY, psFitParameter, stRegStats, pstReg, tvalue, strConfidenceLevel, vSerr);
	makeConfOrPredTbl(nConf, true, grLayAppar, trOp, trFC, vFitX, vFitY, psFitParameter, stRegStats, pstReg, tvalue, strConfidenceLevel, vSerr, lpcszDataLabel);
	///end CENTRALIZE_FITTING_RESULT_LABELS
	///end ADD_CONF_PRED_BANDS_FOR_MR
	///end CHANGE_sReg_FROM_REF_TO_POINTER
	
	int			nPred = fitOptions.PredBands;
	///Cheney 2006-11-1 CHANGE_sReg_FROM_REF_TO_POINTER
	//makeConfOrPredTbl(nPred, false, grLayAppar, trOp, trFC, vFitX, vFitY, psFitParameter, stRegStats, stReg, tvalue, strConfidenceLevel);
	///Arvin 12/04/06 ADD_CONF_PRED_BANDS_FOR_MR
	//makeConfOrPredTbl(nPred, false, grLayAppar, trOp, trFC, vFitX, vFitY, psFitParameter, stRegStats, pstReg, tvalue, strConfidenceLevel);
	///Arvin 06/11/07 CENTRALIZE_FITTING_RESULT_LABELS as max's suggestion
	//makeConfOrPredTbl(nPred, false, grLayAppar, trOp, trFC, vFitX, vFitY, psFitParameter, stRegStats, pstReg, tvalue, strConfidenceLevel, vSerr);
	makeConfOrPredTbl(nPred, false, grLayAppar, trOp, trFC, vFitX, vFitY, psFitParameter, stRegStats, pstReg, tvalue, strConfidenceLevel, vSerr, lpcszDataLabel);
	///end CENTRALIZE_FITTING_RESULT_LABELS
	///end ADD_CONF_PRED_BANDS_FOR_MR
	///end CHANGE_sReg_FROM_REF_TO_POINTER
	
	return true;
}
*/

/// ML 1/25/2008 MISMATCHED_BODY_WITH_DECLARATION_PREVENTS_COMPILATION
//bool FitterOperation::CalcReportConfPredBandsTable(TreeNode &trOp, TreeNode &trFC, vector &vIndep1, vector &vFitY, FitParameter* psFitParameter, RegStats &stRegStats, RegCalcInternal* pstReg, GraphLayer &grLayAppar, int nGraphIndex, vector& vSerr, LPCSTR lpcszDataLabel, vector &vIndep2, int index)
//{
//	//calculate and add confidence bands 
//	MakeConfOrPredTbl(trOp, trFC, true, grLayAppar, vIndep1, vFitY, psFitParameter, stRegStats, pstReg, nGraphIndex, vSerr, lpcszDataLabel, vIndep2, index);
//	//calculate and add prediction bands 
//	MakeConfOrPredTbl(trOp, trFC, false, grLayAppar, vIndep1, vFitY, psFitParameter, stRegStats, pstReg, nGraphIndex, vSerr, lpcszDataLabel, vIndep2, index);
//	return true; 
//}
///Arvin 01/28/08 QA70-10923 CALC_CONFIDENCE_AND_PREDICTION_BANDS
//We need the index argument to calculate confidence and prediction bands of Polynomial Fit
//bool FitterOperation::CalcReportConfPredBandsTable(TreeNode &trOp, TreeNode &trFC, vector &vIndep1, vector &vFitY, FitParameter* psFitParameter, RegStats &stRegStats, RegCalcInternal* pstReg, GraphLayer &grLayAppar, int nGraphIndex, vector& vSerr, LPCSTR lpcszDataLabel, vector &vIndep2)
//{
	////calculate and add confidence bands 
	//MakeConfOrPredTbl(trOp, trFC, true, grLayAppar, vIndep1, vFitY, psFitParameter, stRegStats, pstReg, nGraphIndex, vSerr, lpcszDataLabel, vIndep2);
	////calculate and add prediction bands 
	//MakeConfOrPredTbl(trOp, trFC, false, grLayAppar, vIndep1, vFitY, psFitParameter, stRegStats, pstReg, nGraphIndex, vSerr, lpcszDataLabel, vIndep2);
	//return true; 
//}
bool FitterOperation::CalcReportConfPredBandsTable(TreeNode &trOp, TreeNode &trFC, vector &vIndep1, vector &vFitY, FitParameter* psFitParameter, RegStats &stRegStats, RegCalcInternal* pstReg, GraphLayer &grLayAppar, int nGraphIndex, vector& vSerr, LPCSTR lpcszDataLabel, vector &vIndep2, int index)
{
	//calculate and add confidence bands 
	MakeConfOrPredTbl(trOp, trFC, true, grLayAppar, vIndep1, vFitY, psFitParameter, stRegStats, pstReg, nGraphIndex, vSerr, lpcszDataLabel, vIndep2, index);
	//calculate and add prediction bands 
	MakeConfOrPredTbl(trOp, trFC, false, grLayAppar, vIndep1, vFitY, psFitParameter, stRegStats, pstReg, nGraphIndex, vSerr, lpcszDataLabel, vIndep2, index);
	return true; 
}
///end CALC_CONFIDENCE_AND_PREDICTION_BANDS
/// end MISMATCHED_BODY_WITH_DECLARATION_PREVENTS_COMPILATION
///end CALC_CONFIDENCE_AND_PREDICTION_BANDS

/// end RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT



/// ML 9/18/2006 DATARANGE_EXTRACTION_APPARENT_FIT
bool	FitterOperation::IsApparentFit(TreeNode &trOp)
{
	/// Iris 1/22/2010 FIX_APPARENT_FIT_INFO_APPEAR_IN_MR_PARAM_TABLE_FOOTNOTE
	//if ( trOp.GUI.Fit.ApparentFit && trOp.GUI.Fit.ApparentFit.nVal )
	if ( trOp.GUI.Fit.ApparentFit && trOp.GUI.Fit.ApparentFit.nVal && trOp.GUI.Fit.ApparentFit.Show )
	///End FIX_APPARENT_FIT_INFO_APPEAR_IN_MR_PARAM_TABLE_FOOTNOTE
		return true;
	
	return false;
}
/// end DATARANGE_EXTRACTION_APPARENT_FIT

/// Iris 04/03/2007 RESET_DATA_MODE_AFTER_APPLIED_THEME_AND_CHOOSE_DATA
//virtual
/// Hong 12/24/09 QA80-14832 NLFIT_OPEN_BY_HOTKEY_SOPPORT_APPLY_SETTING_FROM_QUICKFIT_WITHOUT_ANY_THEME
//BOOL	FitterOperation::OperationtoGUI(TreeNode& trOperation, bool bInit, string* pstrSelectedTheme, bool bSetDefaultInputOnInit) // = NULL, = true
///Sophy 1/11/2010 SUPPORT_OPEN_NLFIT_FROM_QUICKFIT_CONTEXT_MENU
//BOOL	FitterOperation::OperationtoGUI(TreeNode& trOperation, bool bInit, string* pstrSelectedTheme, bool bSetDefaultInputOnInit, bool bFromHotkey/* = false*/) // = NULL, = true
BOOL	FitterOperation::OperationtoGUI(TreeNode& trOperation, bool bInit, string* pstrSelectedTheme, bool bSetDefaultInputOnInit, DWORD dwExeCtrl/* = 0*/, DWORD dwParam/* = 0*/) // = NULL, = true
///end SUPPORT_OPEN_NLFIT_FROM_QUICKFIT_CONTEXT_MENU
/// end NLFIT_OPEN_BY_HOTKEY_SOPPORT_APPLY_SETTING_FROM_QUICKFIT_WITHOUT_ANY_THEME
{
	/// Hong 12/24/09 QA80-14832 NLFIT_OPEN_BY_HOTKEY_SOPPORT_APPLY_SETTING_FROM_QUICKFIT_WITHOUT_ANY_THEME
	//if( !WksReportOperation::OperationtoGUI(trOperation, bInit, pstrSelectedTheme, bSetDefaultInputOnInit) )
	///Sophy 1/11/2010 SUPPORT_OPEN_NLFIT_FROM_QUICKFIT_CONTEXT_MENU
	//if( !WksReportOperation::OperationtoGUI(trOperation, bInit, pstrSelectedTheme, bSetDefaultInputOnInit, bFromHotkey) )
	if( !WksReportOperation::OperationtoGUI(trOperation, bInit, pstrSelectedTheme, bSetDefaultInputOnInit, dwExeCtrl, dwParam) )
	///end SUPPORT_OPEN_NLFIT_FROM_QUICKFIT_CONTEXT_MENU
	/// end NLFIT_OPEN_BY_HOTKEY_SOPPORT_APPLY_SETTING_FROM_QUICKFIT_WITHOUT_ANY_THEME
		return false;
	
	//check data mode after applied theme and if not consistent with the number of datasets then need to reset it, from CP
	CheckResetFitMode(trOperation);
	
	return true;
}

void	FitterOperation::CheckResetFitMode(TreeNode& trOperation)
{
	TreeNode	trInputData = trOperation.GUI.InputData;
	string		strCombo;
	if( trInputData && trInputData.GetAttribute(STR_ATTRIB_BRANCH_COMBO, strCombo) ) 
	{
		DataRange dr;
		dr.Create();
		dr.SetTree(trInputData);
		if(dr)
		{
			/// ML 4/4/2007 FOR_FIT_MODE_FIGURING_OUT_MUST_NOT_USE_COMBINED_SINCE_COMBINED_GetNumData_ALWAYS_1
			//int		nTotalNumData = dr.GetNumData(GetDataRules(trOperation));
			//_check_reset_fit_mode(trInputData, nTotalNumData);
			int		numSubData = 0;
			int		nTotalNumData = dr.GetNumData(GetDataRules(trOperation), NULL, NULL, NULL, &numSubData);
			///Sophy 10/28/2008 SHOULD_REARRANGE_LAYERS_WHEN_SWITCH_BETWEEN_SINGLE_INDEP_N_DEP_AND_MULTI_IDEP_N_DEP
			//_check_reset_fit_mode(trInputData, nTotalNumData, numSubData);
			stats_check_reset_fit_mode(trInputData, nTotalNumData, numSubData);
			///end SHOULD_REARRANGE_LAYERS_WHEN_SWITCH_BETWEEN_SINGLE_INDEP_N_DEP_AND_MULTI_IDEP_N_DEP
			/// ML 4/4/2007 FOR_FIT_MODE_FIGURING_OUT_MUST_NOT_USE_COMBINED_SINCE_COMBINED_GetNumData_ALWAYS_1
		}
	}

}
///end RESET_DATA_MODE_AFTER_APPLIED_THEME_AND_CHOOSE_DATA

/// ML 9/20/2006 RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT
// Used when the original vector must be preserved.
static	void	set_vector_apparent(vector &v, GraphLayer &grLayAppar, TreeNode &trNode, int nAxis, BOOL bForward = FALSE)
{
	if (grLayAppar)
	{
		vector		vTransf(v.GetSize());
		vector		*pv;
		if ( grLayAppar.ConvertByAxis(v, v.GetSize(), nAxis, bForward, vTransf) )
			pv = &vTransf;
		else
			pv = &v;
		
		trNode.dVals = *pv;
	}
	///Cheney 2007-5-28 IF_EMPTY_DATA_SET_SHOULD_SET_MISSING_AS_RESULT	
	//else
		//trNode.dVals = v;
	else if(v.GetSize() > 0)
		trNode.dVals = v;
	else
		trNode.dVals = NANUM;
	///end IF_EMPTY_DATA_SET_SHOULD_SET_MISSING_AS_RESULT
}

/// end RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT

///Iris 9/21/06 MULTI_INDEP_PLOTS_NEED_OUT_MATRIX_GRAPH	
/////Iris 4/01/05 FIT_REGRESSION_PLOTS
////bool	FitterOperation::ConstructCurvesAndGraphs(TreeNode &trOp, int index, int nTotalNumData, const string &strDataLabel, vector &vX, vector & vY, FitParameter *psFitParameter, RegStats *psRegStats, RegCalcInternal *psReg, DWORD dwPlotObjUID)
//bool	FitterOperation::ConstructCurvesAndGraphs(TreeNode &trOp, int index, int nTotalNumData, const string &strDataLabel, vector &vX, vector & vY, matrix &mXs, FitParameter *psFitParameter, RegStats *psRegStats, RegCalcInternal *psReg, DWORD dwPlotObjUID, int nMultiplicity)
///Arvin 12/04/06 ADD_CONF_PRED_BANDS_FOR_MR
//bool	FitterOperation::ConstructCurvesAndGraphs(TreeNode &trOp, int index, int nTotalNumData, LPCSTR strDataLabel, vector &vX, vector & vY, matrix &mXs, FitParameter *psFitParameter, RegStats *psRegStats, RegCalcInternal *psReg, DWORD dwPlotObjUID, int nMultiplicity, matrix& mYs)
///Arvin 12/12/06 ADD_RESIDUAL_ANALYSIS_FOR_FITTING
//bool	FitterOperation::ConstructCurvesAndGraphs(TreeNode &trOp, int index, int nTotalNumData, LPCSTR strDataLabel, vector &vX, vector & vY, matrix &mXs, FitParameter *psFitParameter, RegStats *psRegStats, RegCalcInternal *psReg, DWORD dwPlotObjUID, int nMultiplicity, matrix& mYs, vector& vSerr)
///Arvin 06/07/07 CENTRALIZE_FITTING_RESULT_LABELS as max's suggestion
//bool	FitterOperation::ConstructCurvesAndGraphs(TreeNode &trOp, int index, int nTotalNumData, LPCSTR strDataLabel, vector &vX, vector & vY, matrix &mXs, FitParameter *psFitParameter, RegStats *psRegStats, RegCalcInternal *psReg, DWORD dwPlotObjUID, int nMultiplicity, matrix& mYs, vector& vSerr, vector& vWeights)
bool	FitterOperation::ConstructCurvesAndGraphs(TreeNode &trOp, int index, int nTotalNumData, LPCSTR strDataLabel, vector &vX, vector & vY, matrix &mXs, FitParameter *psFitParameter, RegStats *psRegStats, RegCalcInternal *psReg, DWORD dwPlotObjUID, int nMultiplicity, matrix& mYs, vector& vSerr, vector& vWeights, LPCSTR lpcsDataLabelCurves)
///end CENTRALIZE_FITTING_RESULT_LABELS
///end ADD_RESIDUAL_ANALYSIS_FOR_FITTING
///end ADD_CONF_PRED_BANDS_FOR_MR
{
	/// ML 9/18/2006 DATARANGE_EXTRACTION_APPARENT_FIT
	GraphLayer	grLayAppar;
	if ( dwPlotObjUID && IsApparentFit(trOp) )
	{
		DataPlot		dpl;
		dpl = Project.GetObject(dwPlotObjUID);
		if (dpl.IsValid())
			dpl.GetParent(grLayAppar);
	}
	/// end DATARANGE_EXTRACTION_APPARENT_FIT
	//////////////////////////////
	//////////////////////////////
	// 1. Curves
	TreeNode trFittedCurve = GetGUIGraphNodes(trOp);
	int nNumX = GetNumX(trOp);
	///Cheney 2007-4-13 CORRECT_RESIDUAL_COMPUTING_WHEN_MULTI_INDEP_AND_DEP
	int nNumY = GetNumY(trOp);
	///end CORRECT_RESIDUAL_COMPUTING_WHEN_MULTI_INDEP_AND_DEP
	///Arvin 06/07/07 CENTRALIZE_FITTING_RESULT_LABELS as max's suggestion
	string strDataLabelCurves(strDataLabel);
	if(lpcsDataLabelCurves)
		strDataLabelCurves = lpcsDataLabelCurves;
	///end CENTRALIZE_FITTING_RESULT_LABELS
	/// Iris 01/17/2007 JUST_OUTPUT_FIT_DATA_ONLY_ASK_FIT_PLOT
	////--- Iris 9/27/06 KEEP_RESULT_DATA_EVEN_THOUGH_NOT_PLOT
	////if(trFittedCurve && trFittedCurve.Use)
	//if( trFittedCurve )
	////---
	///Cheney 2007-9-7 SHOULD_JUST_SET_SHOW_AS_FALSE_IF_NOT_CHECK_PLOT_FIT_CURVE
	//if(trFittedCurve && trFittedCurve.Use)
	if(trFittedCurve)
	///end SHOULD_JUST_SET_SHOW_AS_FALSE_IF_NOT_CHECK_PLOT_FIT_CURVE
	///end JUST_OUTPUT_FIT_DATA_ONLY_ASK_FIT_PLOT
	{
		vector		vFitX, vFitY;
		FitResultCurveOptions	fitOptions;
		fitOptions = trFittedCurve;
		
		FitResultCurveDataOptions fitDataOptions;
		/// Iris 11/02/2009 QA81-14546 OP_DLG_NEW_STRUCTURE
		/*
		fitDataOptions = trFittedCurve.XDataType;
		fitDataOptions.DataType = trFittedCurve.XDataType.Use;  //DataType treenode is branch, cannot be assigned data to struct auto
		*/
		fitDataOptions = OP_GUI_FIT_X_DATA_BRANCH(trOp.GUI);
		fitDataOptions.DataType = OP_GUI_FIT_X_DATA_BRANCH(trOp.GUI).Use;
		///end OP_DLG_TOTALLY_NEW_STRUCTURE
		//---- CPY 9/22/05 QA70-8015-P15 USE_SET_REPORT_TREE_TO_INTERNALLY_PUT_TREE_INTO_FLAT_SHEET
		string strTableLabel, strPlotLabel, strDataLabelTemp(strDataLabel);
		//GetCustomGraphTypeName(strTableLabel, GRAPH_FIT_CURVE);
		///------ Folger 03/24/09 QA80-13331-P1 CUSTOMIZED_OUTPUT_COLUMN_LONGNAME_FORMAT_SUPPORT
		//ConvertEscapedString(strDataLabelTemp);
		MakeFullRangeEscapeString(strDataLabelTemp);
		///------ End CUSTOMIZED_OUTPUT_COLUMN_LONGNAME_FORMAT_SUPPORT
		
		/// Iris 3/23/2009 QA80-13331-P1 CENTRILIZE_REPORT_COL_LABEL_CODES
		//strPlotLabel = GetAnalysisName() + " " + _L("of") + " " + strDataLabelTemp;
		strPlotLabel = ConstructReportDataColLabel(GetAnalysisName(), strDataLabelTemp);
		///end CENTRILIZE_REPORT_COL_LABEL_CODES
		
		///Arvin 06/07/07 CENTRALIZE_FITTING_RESULT_LABELS as max's suggestion
		//strTableLabel = "Fit Curves";
		//TreeNode	trFC = CheckCreateOneResultCurvesTable(trOp, index, nTotalNumData, GRAPH_FIT_CURVE, STR_FIT_CURVES_TABLE, IDST_FIT_CURVES, strTableLabel, strDataLabel);
		//--- Iris 3/16/2009 QA80-13285-P2 CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
		/*
		if(IsSeparateSheetForDataset(trOp))
			strTableLabel = _L("Fit Curve"); //Corresponding to columns' comment
		else
			strTableLabel = _L("Fitted Values"); //Corresponding to columns' parameters
		TreeNode	trFC = CheckCreateOneResultCurvesTable(trOp, index, nTotalNumData, GRAPH_FIT_CURVE, STR_FIT_CURVES_TABLE, IDST_FIT_CURVES, strTableLabel, strDataLabelCurves);
		*/
		TreeNode	trFC = CheckCreateOneFitCurvesTable(trOp, index, nTotalNumData);
		//---CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
		
		///end CENTRALIZE_FITTING_RESULT_LABELS
		//----
		///Cheney 2006-9-1 AVE_REPLICA_DATA_IF_PLOTTYPE_EXIST_AND_NOT_RAW_DATA 
		//if(!AddAveData(trOp, index, trFC, vX, vY))
		///Arvin 08/29/07 QA70-10073-P7 WRONG_AVE_ERR_NODE_ORDER
		if(trFC)
			trFC.Reset(true);
		///end WRONG_AVE_ERR_NODE_ORDER
		if(isPlotAverageData())
		///Arvin 11/28/07 WRONG_INPUT_X_Y_DATA_FOR_APPARENT_FIT
		//AddAveData(trOp, index, trFC, vX, vY);
		{
			vector vTempX, vTempY;
			vTempX = vX; vTempY = vY;
			if( IsApparentFit(trOp))
			{
				_covert_vector_apparent(vTempX, grLayAppar, OKAXISTYPE_X);
				_covert_vector_apparent(vTempY, grLayAppar, OKAXISTYPE_Y);
			}
			AddAveData(trOp, index, trFC, vTempX, vTempY);
		}
		///end WRONG_INPUT_X_Y_DATA_FOR_APPARENT_FIT
			//error_report("Falied to get average data");
		///end AVE_REPLICA_DATA_IF_PLOTTYPE_EXIST_AND_NOT_RAW_DATA	
		///Cheney 2006-11-21 SHOULD_CLEAN_UP_AVE_DATA_IF_NOT_PLOT_AVE_DATA
		//when change parameter, if change data mode, should update ave data node accordingnally
		///Arvin 08/29/07 QA70-10073-P7 WRONG_AVE_ERR_NODE_ORDER 
		//else if(trFC)
		//	trFC.Reset(true);
		///END WRONG_AVE_ERR_NODE_ORDER
		///end SHOULD_CLEAN_UP_AVE_DATA_IF_NOT_PLOT_AVE_DATA
		
		///Iris 9/21/06 MULTI_INDEP_PLOTS_NEED_OUT_MATRIX_GRAPH
		/*
		MakeFitX(index, strDataLabel, vX, vFitX, trOp, fitDataOptions); 
		MakeFitY(index, trOp, vFitX, vFitY, psFitParameter);
		
		TreeNode	trFitX = tree_check_get_node(trFC, "FitX", IDST_FIT_X);
		trFitX.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_X);
		/// ML 9/20/2006 RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT
		//trFitX.dVals = vFitX;
		set_vector_apparent(vFitX, grLayAppar, trFitX, OKAXISTYPE_X);
		/// end RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT
		
		TreeNode	trFitY = tree_check_get_node(trFC, "FitY", IDST_FIT_Y, STR_LABEL_ATTRIB, strPlotLabel);	
		trFitY.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
		/// ML 9/20/2006 RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT
		//trFitY.dVals = vFitY;
		set_vector_apparent(vFitY, grLayAppar, trFitY, OKAXISTYPE_Y);
		/// end RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT
		*/
		matrix mFitXs, mFitYs;
		///Cheney 2007-4-13 CORRECT_RESIDUAL_COMPUTING_WHEN_MULTI_INDEP_AND_DEP
		//if( nNumX > 1 )
		if(nNumX > 1 || nNumY > 1)
		///end CORRECT_RESIDUAL_COMPUTING_WHEN_MULTI_INDEP_AND_DEP
		{
			calcAddFitCurvesIntoTable(trOp, trFC, index, strPlotLabel, mXs, mFitXs, mFitYs, fitDataOptions, grLayAppar);
			/// Jack 12/19/2008 QA80-12329 MULTI_INDEP_DEPS_BAND_CALCULATION
			CalcReportConfPredBandsTableMultiIndepDep(trOp, trFC, mFitXs, vFitY, psFitParameter, *psRegStats, psReg, grLayAppar, GRAPH_FIT_CURVE, vSerr, strDataLabel, index, nNumY);
			/// End MULTI_INDEP_DEPS_BAND_CALCULATION
		}
		else
		{
			/// Iris 2/15/06 QA70-8461 v8.0365 INCLUDE_RPLICA_FOR_FITTING
			/// Iris 3/31/2009 QA80-13361 FIT_CURVE_PLOT_IS_BLACK_AFTER_CHANGE_PARAM
			//if(nMultiplicity > 1)
			if(nMultiplicity > 1 || IsMulFuncsFit() )
			///end FIT_CURVE_PLOT_IS_BLACK_AFTER_CHANGE_PARAM
			{		
				calcAddMultiPeaksFitCurveTable(trOp, trFC, index, vX, vFitX, vFitY, fitDataOptions, psFitParameter, nMultiplicity); 
			}
			///End INCLUDE_RPLICA_FOR_FITTING
			else
			{
				calcAddFitCurvesIntoTable(trOp, trFC, index, strPlotLabel, vX, vFitX, vFitY, fitDataOptions, psFitParameter, grLayAppar);
			}
		}			
		///end MULTI_INDEP_PLOTS_NEED_OUT_MATRIX_GRAPH
		updateFitCurvesXColumnFormat(trFC, nNumX, index);		///Sophy 1/15/2009 v8.0957 QA80-12918 FITCURVE_X_COLULMN_FORMAT_MUST_BE_CONSISTENT_WITH_SOURCE_DATA
		///Cheney 2006-11-1 CHANGE_sReg_FROM_REF_TO_POINTER
		///// ML 9/20/2006 RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT
		////CalcReportConfPredBandsTable(trOp, trFC, vFitX, vFitY, psFitParameter, *psRegStats, *psReg);
		//CalcReportConfPredBandsTable(trOp, trFC, vFitX, vFitY, psFitParameter, *psRegStats, *psReg, grLayAppar);
		///// end RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT
		///Arvin 12/04/06 ADD_CONF_PRED_BANDS_FOR_MR
		//CalcReportConfPredBandsTable(trOp, trFC, vFitX, vFitY, psFitParameter, *psRegStats, psReg, grLayAppar);
		///Arvin 06/11/07 CENTRALIZE_FITTING_RESULT_LABELS as max's suggestion
		//CalcReportConfPredBandsTable(trOp, trFC, vFitX, vFitY, psFitParameter, *psRegStats, psReg, grLayAppar, GRAPH_FIT_CURVE, vSerr);
		///Arvin 01/25/08 QA70-10923 CALC_CONFIDENCE_AND_PREDICTION_BANDS
		//CalcReportConfPredBandsTable(trOp, trFC, vFitX, vFitY, psFitParameter, *psRegStats, psReg, grLayAppar, GRAPH_FIT_CURVE, vSerr, strDataLabel);
		/// ML 1/25/2008 MISMATCHED_BODY_WITH_DECLARATION_PREVENTS_COMPILATION
		//CalcReportConfPredBandsTable(trOp, trFC, vFitX, vFitY, psFitParameter, *psRegStats, psReg, grLayAppar, GRAPH_FIT_CURVE, vSerr, strDataLabel, NULL, index);
		///Arvin 01/28/08 QA70-10923 CALC_CONFIDENCE_AND_PREDICTION_BANDS
		//We need the index argument to calculate confidence and prediction bands of Polynomial Fit
		//CalcReportConfPredBandsTable(trOp, trFC, vFitX, vFitY, psFitParameter, *psRegStats, psReg, grLayAppar, GRAPH_FIT_CURVE, vSerr, strDataLabel, NULL);
		/// Jack 12/19/2008 QA80-12329 MULTI_INDEP_DEPS_BAND_CALCULATION
		if((nNumX == 1 || nNumY == 1))
		/// End MULTI_INDEP_DEPS_BAND_CALCULATION
		CalcReportConfPredBandsTable(trOp, trFC, vFitX, vFitY, psFitParameter, *psRegStats, psReg, grLayAppar, GRAPH_FIT_CURVE, vSerr, strDataLabel, NULL, index);
		///end CALC_CONFIDENCE_AND_PREDICTION_BANDS
		/// end MISMATCHED_BODY_WITH_DECLARATION_PREVENTS_COMPILATION
		///end CALC_CONFIDENCE_AND_PREDICTION_BANDS
		///end CENTRALIZE_FITTING_RESULT_LABELS
		///end ADD_CONF_PRED_BANDS_FOR_MR
		///end CHANGE_sReg_FROM_REF_TO_POINTER
		
		///Cheney 2007-5-28 IF_EMPTY_DATA_SET_SHOULD_SET_MISSING_AS_RESULT
		//for supportting empty data set, should not hide it if empty
		//tree_hide_empty_nodes(trFC); 
		///end IF_EMPTY_DATA_SET_SHOULD_SET_MISSING_AS_RESULT
		
		/// Iris 9/04/06 SET_COL_DESIG_SEPARATELY
		///// Thomas 05/30/2006 CALL_SETREPORTWORKSHEETDESIGNATION_INSTEAD
		///*
		/////Iris 9/17/05 SET_COL_TYPE_IN_RESULT_TABLE_NODE
		//int 		nColIndex = 0;
		//vector<int> vecDesignation;
		//GetColumnDesignation(trOp, trFC.Children.Count(), vecDesignation);
		//foreach(TreeNode trSub in trFC.Children)
		//{
			//trSub.SetAttribute(STR_COL_DESIGNATION_ATTRIB, vecDesignation[nColIndex]);
			//nColIndex++;
		//}
		/////End SET_COL_TYPE_IN_RESULT_TABLE_NODE
		//*/
		//SetReportWorksheetDesignation(trOp, trFC);
		///// End CALL_SETREPORTWORKSHEETDESIGNATION_INSTEAD
		///end SET_COL_DESIG_SEPARATELY
		///Cheney 2007-9-7 SHOULD_JUST_SET_SHOW_AS_FALSE_IF_NOT_CHECK_PLOT_FIT_CURVE
		int nReportFitCurve = 0;
		trFittedCurve.GetAttribute( STR_USE_ATTRIB, nReportFitCurve);
		if(!nReportFitCurve)
			trFC.Show = false;
		///Arvin 10/23/07 QA70-10559-P3 SHOULD_NOT_CREATE_EMPTY_SHEET_WHEN_UNCHECK_FITTED_CURVES_PLOT
		else
			trFC.Show = true;
		///end SHOULD_NOT_CREATE_EMPTY_SHEET_WHEN_UNCHECK_FITTED_CURVES_PLOT
		///end SHOULD_JUST_SET_SHOW_AS_FALSE_IF_NOT_CHECK_PLOT_FIT_CURVE
	}
	
	/// ML 9/20/2006 RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT
	/*
	AddResidualsDataTable(trOp, index, nTotalNumData, strDataLabel, psFitParameter, vX, vY, mXs);
	AddResidualHistogramTable(trOp, index, nTotalNumData, strDataLabel, psFitParameter, vX, vY, mXs);	
	AddResidualFitTable(trOp, index, nTotalNumData, strDataLabel, psFitParameter, vX, vY, mXs);	
	AddResidualOrderTable(trOp, index, nTotalNumData, strDataLabel, psFitParameter, vX, vY, mXs);	
	AddResidualLagTable(trOp, index, nTotalNumData, strDataLabel, psFitParameter, vX, vY, mXs); ///Jim 2/22/06 v8.0368 ADD_RESIDUAL_LAG_PLOT_TO_RESIDUALS_PLOTS_BRANCH
	*/
	// This call may change vX if apparent!
	///Cheney 2007-4-13 CORRECT_RESIDUAL_COMPUTING_WHEN_MULTI_INDEP_AND_DEP
	//if( nNumX > 1 )
	if(nNumX > 1 || nNumY > 1)
	///end CORRECT_RESIDUAL_COMPUTING_WHEN_MULTI_INDEP_AND_DEP
	{	
		///Arvin 06/07/07 CENTRALIZE_FITTING_RESULT_LABELS as max's suggestion
		//AddResidualTables(true, trOp, index, nTotalNumData, strDataLabel, psFitParameter, mXs, mYs);
		AddResidualTables(true, trOp, index, nTotalNumData, strDataLabel, psFitParameter, mXs, mYs, strDataLabelCurves);
		///end CENTRALIZE_FITTING_RESULT_LABELS
	}
	else
	{
		///Arvin 12/12/06 ADD_RESIDUAL_ANALYSIS_FOR_FITTING
		//AddResidualTables(true, trOp, index, nTotalNumData, strDataLabel, psFitParameter, vX, vY, mXs, grLayAppar);
		///Arvin 01/17/06 CALC_RESIDUAL_WITH_REPLICA
		//AddResidualTables(true, trOp, index, nTotalNumData, strDataLabel, psFitParameter, vX, vY, mXs, grLayAppar, vWeights);
		///Arvin 06/07/07 CENTRALIZE_FITTING_RESULT_LABELS as max's suggestion
		//AddResidualTables(true, trOp, index, nTotalNumData, strDataLabel, psFitParameter, vX, vY, mXs, grLayAppar, vWeights, nMultiplicity);
		AddResidualTables(true, trOp, index, nTotalNumData, strDataLabel, psFitParameter, vX, vY, mXs, grLayAppar, vWeights, nMultiplicity, strDataLabelCurves);
		///end CENTRALIZE_FITTING_RESULT_LABELS
		///end CALC_RESIDUAL_WITH_REPLICA
		///end ADD_RESIDUAL_ANALYSIS_FOR_FITTING
	}
	
	/// end RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT

	
	//////////////////////////////
	// 2. Graphs:
	
	/// YuI 12/07/04 v7.5172 PICTURE_IN_REPORT_IMPROVEMENT
	/*
	ReportCreateGraphHelper crtGraph(CREATE_GRAPH_PREPARE_TREE, trOp, index, 0, strDataLabel);
	return crtGraph.AddGraphToTreeNode();
	*/	 	

	//-------- CPY 12/31/04 PICTURE_IN_REPORT_IN_BASE_CLASS
	//TreeNode trImage = CheckCreateImageNode(trOp, 0, index, strDataLabel);
 	//UpdateImageNodePlottingInfo(trImage, index);
 	/// Iris 01/08/2007 v8.0538 REPORT_GRAPHS_ARRANGEMENT
 	//PrepareGraphNodes(trOp, GetNumGraphs(), index, strDataLabel); 
 	///end REPORT_GRAPHS_ARRANGEMENT
 	//-------- 	
 	
 	return true;
	/// end PICTURE_IN_REPORT_IMPROVEMENT
}


/// Iris 01/17/2007 v8.0543 CORRECT_THE_WAY_TO_GET_DATA_LABEL
/*
/// Arvin 11/03/06 ALL_LEGEND_SAME_NAME_FOR_FIT_GRAPH
virtual void FitterOperation::GetOneInputColString(int index, int nCol, string& strCol)
{
	DataRange rngInput;
	GetInput(rngInput);
	if(!rngInput)
		error_report("Get input data rang failed!");
	
	int r1, r2, c1, c2;
	Worksheet sourceWks;
	string strRange;
	int colNum;
	TreeNode trOp;
	GetTree(trOp);
	int numX = GetNumX(trOp);
	int numY = GetNumY(trOp);
	
	if(numX > 1 || numY > 1)
	{
		rngInput.GetRange(numX+nCol, r1, c1, r2, c2, sourceWks, &strRange);
		colNum = c1;
	}			
	else
	{	
		DataRange dr;
		DWORD dwRules = DRR_GET_DEPENDENT;
		rngInput.GetNLFitSubRange(dr, DRR_NLFIT, index, 0, 0);
		int numRange = dr.GetNumRanges();
		for( int ii = 0; ii < numRange; ii++)
		{
			dr.GetRange(ii, r1, c1, r2, c2, sourceWks, &strRange);
			bool bY = strRange.Compare("Y") == 0 ? true : false;
			if(bY)
			{
				colNum = c1;
				break;
			}
		}
	}
	
	Column col(sourceWks, colNum);
	if(col) //---- Iris 11/07/06 GET_RUNTIME_ERR_WHEN_COL_IS_INVALID
	{
		col.GetRangeString(strCol);
		strCol.Replace("Col(", "");
		strCol.Replace(")", "");
		strCol = GetAnalysisName()+ " of " + strCol;
	}
}
///END ALL_LEGEND_SAME_NAME_FOR_FIT_GRAPH
*/
////end CORRECT_THE_WAY_TO_GET_DATA_LABEL

bool FitterOperation::addOneFitDataIntoTable(TreeNode& trFC, matrix& mFitData, GraphLayer& grLayAppar, bool bIsX, int index, LPCSTR lpcszDataLabel)
{	
	int 	nNumFitData = mFitData.GetNumCols();
	for(int ncol=0; ncol<nNumFitData; ncol++)
	{
		vector 	vFit;
		///Arvin 05/23/07 v8.0624 EMPTY_DATA_SET_RUNTIME_ERROR
		//mFitData.GetColumn(vFit, ncol);
		if(mFitData.GetNumRows() > 0)
			mFitData.GetColumn(vFit, ncol);
		///end EMPTY_DATA_SET_RUNTIME_ERROR
		
		string 		strName = bIsX? "FitX" : "FitY";
		if(nNumFitData > 1)
			strName += (ncol+1);
		
		int			nID = bIsX? IDST_FIT_X : IDST_FIT_Y;		
		nID = make_one_set_ID(nID, ncol+1);
		
		/// Arvin 11/03/06 ALL_LEGEND_SAME_NAME_FOR_FIT_GRAPH
		//TreeNode	trFit = tree_check_get_node(trFC, strName, nID);
		/// Iris 01/17/2007 v8.0543 CORRECT_THE_WAY_TO_GET_DATA_LABEL
		/*
		string strLabel;
		if(!bIsX)
			GetOneInputColString(index, ncol, strLabel);
		else
			strLabel = "Independent Variable";
		*/
		string 	strLabel(lpcszDataLabel);
		if(bIsX)
			strLabel = STR_REPORT_X_COL_LONG_NAME;
		///end CORRECT_THE_WAY_TO_GET_DATA_LABEL
		
		TreeNode	trFit = tree_check_get_node(trFC, strName, nID, STR_LABEL_ATTRIB, strLabel);
		///end ALL_LEGEND_SAME_NAME_FOR_FIT_GRAPH
		
		trFit.SetAttribute(STR_COL_DESIGNATION_ATTRIB, bIsX? OKDATAOBJ_DESIGNATION_X : OKDATAOBJ_DESIGNATION_Y);
		/// ML 11/27/2006 ADDITIONAL_LABEL_ROWS_IN_CURVE_SHEETS
		///Arvin 06/07/07 CENTRALIZE_FITTING_RESULT_LABELS as max's suggestion
		//tree_add_one_label(trFit, _L("Fit Curves"), 0);
		/// Iris 3/19/2009 QA80-13285-P2 FIT_RESULT_CURVE_COL_LABEL_NEW_DESIGN
		//tree_add_one_label(trFit, _L("Fitted Values"), 0);
		string strTableSubLabel = _L("Fitted Values");
		GetCustomGraphTypeName(strTableSubLabel, GRAPH_FIT_CURVE);
		tree_add_one_label(trFit, strTableSubLabel, 0);	
		///END FIT_RESULT_CURVE_COL_LABEL_NEW_DESIGN
		
		///end CENTRALIZE_FITTING_RESULT_LABELS
		/// end ADDITIONAL_LABEL_ROWS_IN_CURVE_SHEETS
		/// ML 9/20/2006 RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT
		//trFitX.dVals = vFitX;
		set_vector_apparent(vFit, grLayAppar, trFit, bIsX? OKAXISTYPE_X : OKAXISTYPE_Y);
		/// end RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT
	}	
	
	return true;
}

bool FitterOperation::calcAddFitCurvesIntoTable(TreeNode& trOp, TreeNode& trFC, int index, LPCSTR lpcszDataLabel, vector& vX, vector& vFitX, vector& vFitY, const FitResultCurveDataOptions& fitDataOptions, FitParameter *psFitParameter, GraphLayer&	grLayAppar)
{
	MakeFitX(index, lpcszDataLabel, vX, vFitX, trOp, fitDataOptions); 

	MakeFitY(index, trOp, vFitX, vFitY, psFitParameter);
	
	matrix mFitX(vFitX.GetSize(), 1);
	matrix mFitY(vFitY.GetSize(), 1);
	///Arvin 05/23/07 v8.0624 EMPTY_DATA_SET_RUNTIME_ERROR
	//mFitX.SetColumn(vFitX, 0);
	//mFitY.SetColumn(vFitY, 0);
	if(mFitX.GetNumCols() > 0 && mFitX.GetNumRows() > 0)
		mFitX.SetColumn(vFitX, 0);
	if(mFitY.GetNumCols() > 0 && mFitY.GetNumRows() > 0)
		mFitY.SetColumn(vFitY, 0);
	///end EMPTY_DATA_SET_RUNTIME_ERROR
	/// Arvin 11/03/06 ALL_LEGEND_SAME_NAME_FOR_FIT_GRAPH
	//addOneFitDataIntoTable(trFC, mFitX, grLayAppar, true);
	//addOneFitDataIntoTable(trFC, mFitY, grLayAppar, false);
	addOneFitDataIntoTable(trFC, mFitX, grLayAppar, true, index, lpcszDataLabel);
	addOneFitDataIntoTable(trFC, mFitY, grLayAppar, false, index, lpcszDataLabel);
	///end ALL_LEGEND_SAME_NAME_FOR_FIT_GRAPH
	return true;
}

bool FitterOperation::calcAddFitCurvesIntoTable(TreeNode& trOp, TreeNode& trFC, int index, LPCSTR lpcszDataLabel, matrix& mXs, matrix& mFitXs, matrix& mFitYs, const FitResultCurveDataOptions& fitDataOptions, GraphLayer& grLayAppar)
{
	MakeFitX(index, lpcszDataLabel, mXs, mFitXs, trOp, fitDataOptions); 
	MakeFitY(trOp, mFitXs, mFitYs, index); 
	/// Arvin 11/03/06 ALL_LEGEND_SAME_NAME_FOR_FIT_GRAPH
	//addOneFitDataIntoTable(trFC, mFitXs, grLayAppar, true);
	//addOneFitDataIntoTable(trFC, mFitYs, grLayAppar, false);
	addOneFitDataIntoTable(trFC, mFitXs, grLayAppar, true, index, lpcszDataLabel);
	addOneFitDataIntoTable(trFC, mFitYs, grLayAppar, false, index, lpcszDataLabel);
	///end ALL_LEGEND_SAME_NAME_FOR_FIT_GRAPH
	
	return true;
}

///Sophy 1/15/2009 v8.0957 QA80-12918 FITCURVE_X_COLULMN_FORMAT_MUST_BE_CONSISTENT_WITH_SOURCE_DATA
bool FitterOperation::updateFitCurvesXColumnFormat(TreeNode& trFC, int nNumX, int nDatasetIndex)
{
	if ( !trFC || nNumX < 1 )
		return false;
	
	string strFitX = "FitX";
	TreeNode trFitX;
	Column colX;
	if ( nNumX > 1 ) //multi indeps
	{
		for( int index = 0; index < nNumX; index++) 
		{
			trFitX = trFC.GetNode(strFitX + (index + 1));//label start from FitX1
			UpdateOneXColumnFormat(trFitX, index + nDatasetIndex * nNumX);
		}
	}
	else
	{
		trFitX = trFC.GetNode(strFitX);
		UpdateOneXColumnFormat(trFitX, nDatasetIndex * nNumX);
	}
	return true;
}

bool FitterOperation::UpdateOneXColumnFormat(TreeNode& trCol, int nIndex)
{
	XYRange xyRange;
	GetInput(xyRange);
	if ( !trCol || !xyRange )
		return false;
	
	Column colX;
	if ( xyRange.GetXColumn(colX, nIndex) )
		///------ Folger 08/25/10 ORG-897-P4 FITTER_OPERATION_OUTPUT_FIT_CURVE_AND_RESIDUAL_X_SHOULD_FOLLOW_SOURCE
		//return trCol.SetAttribute(STR_COL_FORMAT_ATTRIB, colX.GetFormat());
	{
		int		nUID = colX.GetUID(TRUE);
		DWORD	dwCntrl = SRC_COL_PROPERTY_FORMAT;
		return okutil_source_column_property(&trCol, &nUID, &dwCntrl, FALSE);
	}
		///------ End FITTER_OPERATION_OUTPUT_FIT_CURVE_AND_RESIDUAL_X_SHOULD_FOLLOW_SOURCE
	
	return false;
}
///end FITCURVE_X_COLULMN_FORMAT_MUST_BE_CONSISTENT_WITH_SOURCE_DATA

/// Iris 2/15/06 QA70-8461 v8.0365 INCLUDE_RPLICA_FOR_FITTING
void FitterOperation::calcAddMultiPeaksFitCurveTable(TreeNode& trOp, TreeNode& trFC, int index, vector& vX, vector& vFitX, vector& vFitY, const tagFitResultCurveDataOptions& fitOptions, FitParameter *psFitParameter, int nMultiplicity)
{
	///Arvin 03/25/08 MOVE_REPLICA_BARANCH_OUT_OF_FIT_CONTROL_BRANCH as CP said
	//TreeNode trPlotEachPeak = trOp.GUI.Fit.Replica.PeakCurve;
	//------ Folger 11/06/08 QA80-12538 v0.966 CENTRALIZE_CODE_ABOUT_GETTING_GUI_REPLICA_NODE
	//TreeNode trPlotEachPeak = trOp.GUI.Replica.PeakCurve;
	TreeNode trPlotEachPeak = get_gui_replica_node(trOp.GUI).PeakCurve;
	//------ End CENTRALIZE_CODE_ABOUT_GETTING_GUI_REPLICA_NODE
	///end MOVE_REPLICA_BARANCH_OUT_OF_FIT_CONTROL_BRANCH
	if(!trPlotEachPeak || !trPlotEachPeak.Enable)
		return;
	
	string strDataLabel;
	MakeFitX(index, strDataLabel, vX, vFitX, trOp, fitOptions); 
	TreeNode	trFitX = tree_check_get_node(trFC, "FitX", IDST_FIT_X);
	///Cheney 2007-5-28 IF_EMPTY_DATA_SET_SHOULD_SET_MISSING_AS_RESULT	
	//trFitX.dVals = vFitX;
	if(vFitX.GetSize() > 0)
		trFitX.dVals = vFitX;
	else
		trFitX.dVals = NANUM;
	///end IF_EMPTY_DATA_SET_SHOULD_SET_MISSING_AS_RESULT
	trFitX.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_X);
	///Jasmine 11/14/07 FIT_BASELINE_AS_WELL_AS_OTHER_PEAKS
	bool bHasBaselinePeak = false;
	///Arvin 12/05/07 XOP_NEED_SUPPORT_PFW
	//As jasmine said, tag name of PFW tree node should be PFWTree
	//if(trOp.PFMTree)
	//	bHasBaselinePeak = HasBaselinePeak(trOp.PFMTree);
	///Jasmine 06/15/09 NO_NEED_PFM_TREE
	//if(trOp.PFWTree)
		bHasBaselinePeak = HasBaselinePeak();//trOp.PFWTree	
	///End NO_NEED_PFM_TREE
	///end XOP_NEED_SUPPORT_PFW

	int nPeakOffset = bHasBaselinePeak? 0 : 1;
	///End FIT_BASELINE_AS_WELL_AS_OTHER_PEAKS
	vector	vCumulate;	
	for(int ii=0; ii<nMultiplicity; ii++)
	{
		MakeFitY(index, trOp, vFitX, vFitY, psFitParameter, NULL, ii);
		if(vCumulate.GetSize() == 0)
			vCumulate.SetSize(vFitY.GetSize());
		vCumulate += vFitY;
		
		if(trPlotEachPeak.nVal)
		{
			///Cheney 2007-10-27 CLEAN_UP_LOCALIZATION_THINGS
			//string 		strLabel = "Fit Peak " + (ii+1); /// Iris 2/27/06 SUPPORT_PFM_IN_NLFIT_DLG
			string 		strLabel;
			if(bHasBaselinePeak && 0 == ii)
				strLabel = STR_LABEL_BASELINE_FIT_CURVE;
			else
				strLabel.Format("%s %d", STR_LABEL_PEAK_FIT_CURVE, ii+nPeakOffset); /// Iris 2/27/06 SUPPORT_PFM_IN_NLFIT_DLG	///Jasmine 11/14/07 FIT_BASELINE_AS_WELL_AS_OTHER_PEAKS
			///end CLEAN_UP_LOCALIZATION_THINGS
			/// Hong 12/03/08 QA80-12499 v8.0982 FIX_DUPLICATE_ID_CAUSE_SOME_DATA_DISAPPEAR_IN_REPORT_SHEET
			//TreeNode	trFitY = check_add_enumerated_node(trFC, "FitY", ii+1, IDST_FIT_Y+ii+1, STR_LABEL_ATTRIB, strLabel);			
			TreeNode	trFitY = check_add_enumerated_node(trFC, "FitY", ii+1, make_one_set_ID(IDST_FIT_Y, index+ii+1), STR_LABEL_ATTRIB, strLabel);
			/// end FIX_DUPLICATE_ID_CAUSE_SOME_DATA_DISAPPEAR_IN_REPORT_SHEET
			///Cheney 2007-5-28 IF_EMPTY_DATA_SET_SHOULD_SET_MISSING_AS_RESULT	
			//trFitY.dVals = vFitY;
			if(vFitY.GetSize() > 0)
				trFitY.dVals = vFitY;
			else
				trFitY.dVals = NANUM;
			///end IF_EMPTY_DATA_SET_SHOULD_SET_MISSING_AS_RESULT
			trFitY.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
		}
		///Arvin 01/11/06 CUMULATIVE_FITTED_CURVE
		/*
		else if(ii == nMultiplicity -1) //if last peak
		{
			double 	dY0 = psFitParameter[0].Value; //Iris 07/06/06 always to get the first parameter's value as Y0 since for now the functions all are Peak fitting function when nMultiplicity > 1
			vCumulate -= dY0 * (nMultiplicity - 1);
			
			TreeNode	trFitY = tree_check_get_node(trFC, "FitY", IDST_FIT_Y);
			trFitY.dVals = vCumulate;
			trFitY.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
		}
		*/
		//-----
	}
	///Jasmine 11/05/07 SUBTRACT_BASELINE_BEFORE_PFM_FIT, write codes into a function
	/*
	///Arvin 06/20/07 v8.0645 WRONG_CONF_PRED_BAND_FOR_MULTI_PEAKS_FIT
	//Always get vCumulate as vFitY to calculate confidence and predict band 
	/// Iris 07/2007/07 FIX_GET_INVAID_Y0_IN_PFM
	//double 	dY0 = psFitParameter[0].Value; //Iris 07/06/06 always to get the first parameter's value as Y0 since for now the functions all are Peak fitting function when nMultiplicity > 1
	double	dY0 = GetBaseLineY0(psFitParameter);
	///end FIX_GET_INVAID_Y0_IN_PFM
	vCumulate -= dY0 * (nMultiplicity - 1);
	*/
	CumulativeSubtractBaseline(vFitX, vCumulate, nMultiplicity - 1, GetBaseLineY0(psFitParameter));
	///End SUBTRACT_BASELINE_BEFORE_PFM_FIT
	if(vCumulate.GetSize() > 0)
		vFitY = vCumulate;
	///end WRONG_CONF_PRED_BAND_FOR_MULTI_PEAKS_FIT
	///Arvin 01/11/06 CUMULATIVE_FITTED_CURVE
	///Arvin 03/25/08 MOVE_REPLICA_BARANCH_OUT_OF_FIT_CONTROL_BRANCH as CP said
	//TreeNode trPlotCumPeak = trOp.GUI.Fit.Replica.CumulativeCurve; 
	//------ Folger 11/06/08 QA80-12538 v0.966 CENTRALIZE_CODE_ABOUT_GETTING_GUI_REPLICA_NODE
	//TreeNode trPlotCumPeak = trOp.GUI.Replica.CumulativeCurve; 
	TreeNode trPlotCumPeak = get_gui_replica_node(trOp.GUI).CumulativeCurve; 
	//------ End CENTRALIZE_CODE_ABOUT_GETTING_GUI_REPLICA_NODE
	///end MOVE_REPLICA_BARANCH_OUT_OF_FIT_CONTROL_BRANCH
	if(!trPlotCumPeak)
		return;
	
	if(trPlotCumPeak.nVal) //if last peak
	{
		///Arvin 06/20/07 v8.0645 WRONG_CONF_PRED_BAND_FOR_MULTI_PEAKS_FIT
		//double 	dY0 = psFitParameter[0].Value; //Iris 07/06/06 always to get the first parameter's value as Y0 since for now the functions all are Peak fitting function when nMultiplicity > 1
		//vCumulate -= dY0 * (nMultiplicity - 1);
		///end WRONG_CONF_PRED_BAND_FOR_MULTI_PEAKS_FIT
		///Cheney 2007-6-19 ALWAYS_FIND_XY_FROM_CUMULATIVE_FIT_CURVE_IF_PEAK_FIT
		//string 		strLabel = "Cumulative Fit Peak";
		string 		strLabel = STR_LABEL_CUMULATIVE_FIT_CURVE;
		///end ALWAYS_FIND_XY_FROM_CUMULATIVE_FIT_CURVE_IF_PEAK_FIT
		int nID;
		if(trPlotEachPeak.nVal)
			/// Hong 12/03/08 QA80-12499 v8.0982 FIX_DUPLICATE_ID_CAUSE_SOME_DATA_DISAPPEAR_IN_REPORT_SHEET
			//nID = IDST_FIT_Y+nMultiplicity+1;
			nID = make_one_set_ID(IDST_FIT_Y, index+nMultiplicity+1);
			/// end FIX_DUPLICATE_ID_CAUSE_SOME_DATA_DISAPPEAR_IN_REPORT_SHEET
		else
			nID = IDST_FIT_Y;
		
		TreeNode	trFitY = tree_check_get_node(trFC, "FitY", nID, STR_LABEL_ATTRIB, strLabel);
		///Cheney 2007-5-28 IF_EMPTY_DATA_SET_SHOULD_SET_MISSING_AS_RESULT	
		//trFitY.dVals = vCumulate;
		if(vCumulate.GetSize() > 0)
			trFitY.dVals = vCumulate;
		else
			trFitY.dVals = NANUM;
		///end IF_EMPTY_DATA_SET_SHOULD_SET_MISSING_AS_RESULT
		trFitY.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
	}
	///end CUMULATIVE_FITTED_CURVE
}
///End INCLUDE_RPLICA_FOR_FITTING

/// Hong 09/03/08 QA80-12130 NLFIT_SESSION_SUPPORT_SEPARATE_FIT
//bool FitterOperation::AddRegStatsToReportTree(TreeNode& trOp, int index, const string &strDataLabel, int nTotalNumData, const vector<string> &vstrFactors, const RegStats &sRegStats)
bool FitterOperation::AddRegStatsToReportTree(TreeNode& trOp, int index, const string &strDataLabel, int nTotalNumData, const vector<string> &vstrFactors, const RegStats &sRegStats, int* pnSetIndex/* = NULL*/)
/// end NLFIT_SESSION_SUPPORT_SEPARATE_FIT
{
	TreeNode		trCal = trOp.Calculation;
	TreeNode		trTable = tree_check_get_node(trCal, "RegStats", IDST_REG_STATS_RESULTS);
	//------ Folger 03/19/08 QA80-10598 NEW_GETN_LOCALIZAED_CHECK_MACRO
	trTable.SetAttribute(STR_LABEL_ATTRIB, _L(TABLE_DESC_STATS));
	//------
	TreeNode		trRow = check_add_enumerated_node(trTable, CALCULATION_REPORT_TABLE_COL_PREFIX, index + 1, IDST_TEMP_ONE_SET, STR_LABEL_ATTRIB, strDataLabel);
	tree_add_more_labels(trRow, vstrFactors);		// multiple sets values:
	trRow = sRegStats;

	//--- Iris 03/09/2007 SET_COL_TYPE_FOR_COPY_TABLE_FOR_NEW_SHEET_TRANSPOSE
	///Sophy 3/30/2009 QA80-13352 SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
	//foreach(TreeNode trN in trRow.Children)
	//{
		//trN.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
	//}
	tree_set_attribute_to_all_nodes(trRow, STR_COL_DESIGNATION_ATTRIB, (string)OKDATAOBJ_DESIGNATION_Y, true);
	///end SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
	if(trRow.RMSESD)
		trRow.RMSESD.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_ERROR);
	//---

	//---- CPY 2/21/06 ADD_FOOT_NOTE_TO_TABLE
	// temp example code, should be remove once Echo/Iris knows how to add this in other more relavant places
//	TreeNode trFooter = tree_check_get_node(trTable, "Footer", IDE_FOOTNOTE_BEGIN, TREE_Footnote, "1"); // just need the TREE_Footnote attribute, value does not matter, so 1 is good
//	trFooter.strVal = "Footnote line1\nFootNote line 2";
	//----- end ADD_FOOT_NOTE_TO_TABLE
	
	///Iris 3/23/05 HIDDEN_CORRELATION_IN_PR_MR
	FilterStatsReport(trOp);
	
	trRow.ID = make_one_set_ID(IDST_REG_STATS_ONE_SET, index);
	
	if(nTotalNumData > 1 && 0 == index)
		trTable.SetAttribute(TREE_Table, GetTableStringMain());
	else if(1 == nTotalNumData)
		trTable.SetAttribute(TREE_Table, GetTableStringSupport(true,false,true,GETNBRANCH_OPEN));

	
	return true;
}

///Arvin 12/29/06 ADD_INDEX_FOR_DERIVED_PARAMETERS
bool FitterOperation::ParamsNamesAddPostfix(vector<string>& vsParamNames, int index, int nFunc)
{	
	if(index > 0)
	{
		for(int ii = 0; ii < vsParamNames.GetSize(); ii++)
			vsParamNames[ii] = vsParamNames[ii] + "_" + (string)(index+1);
	}	
	return true;
}
///end ADD_INDEX_FOR_DERIVED_PARAMETERS


/// Iris 12/30/2006 v8.0534 CORRECT_DERIVED_PARAMS_ORDER_FOR_REPLICA_CASE
//virtual 
bool FitterOperation::AddParamterTableToReportTree(TreeNode &trOp, int index, const string &strDataLabel, int nTotalNumData, const vector<string> &vstrFactors,
///Arvin 08/03/07 WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA		
//const FitParameter* pFitParams, vector<string>& vstrParamNames, vector<string>& vstrParamNamesPostfix, const FitDerivedParameter* pstDerivedParams, int nNumDerivedParams, vector<bool> &vbIsDerived)
///Arvin 01/03/08 ADD_STAR_MARK_FOR_SHARED_PARAMS as cp said
//const FitParameter* pFitParams, vector<string>& vstrParamNames, vector<string>& vstrParamNamesPostfix, const FitDerivedParameter* pstDerivedParams, int nNumDerivedParams, vector<bool> &vbIsDerived, int nMultiplicity, int nNumParamInFunc, int nDupUnit)
///Kyle 08/10/2009 QA80-14077 ADD_PARAMETER_UNIT_TO_FITTING_REPORT
//const FitParameter* pFitParams, vector<string>& vstrParamNames, vector<string>& vstrParamNamesPostfix, const FitDerivedParameter* pstDerivedParams, int nNumDerivedParams, vector<bool> &vbIsDerived, int nMultiplicity, int nNumParamInFunc, int nDupUnit, vector<bool> &vbIsShared)
const FitParameter* pFitParams, const FITPARAMSINFO& stParamInfo, const FitDerivedParameter* pstDerivedParams, int nNumDerivedParams, vector<bool> &vbIsDerived, int nMultiplicity, int nNumParamInFunc, int nDupUnit, vector<bool> &vbIsShared)
///End ADD_PARAMETER_UNIT_TO_FITTING_REPORT
///end ADD_STAR_MARK_FOR_SHARED_PARAMS
///end WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
{
	/// Iris 4/23/2008 NOT_GENERAGE_TABLE_IF_NOT_REPORT_TO_IMPROVE_NLSF_SPEED
	TreeNode 	trGUIParams = trOp.GUI.Quantities.Parameters;
	// if not choose any one parameter result to report, then no need to go on in this function
	/// Iris 6/06/2008 v8.0879 FIX_SHOW_TABLE_NAME_EVEN_TABLE_IS_EMPTY_IN_RESULT_LOG
	//if( tree_GUI_are_all_uncheck(trGUIParams) )
		//return true;
	bool		bShowParams = !tree_GUI_are_all_uncheck(trGUIParams);
	tree_check_set_hidden(trOp.Calculation.Parameters, bShowParams ? false : true);
	if( !bShowParams )
		return true;
	///end FIX_SHOW_TABLE_NAME_EVEN_TABLE_IS_EMPTY_IN_RESULT_LOG
	///end NOT_GENERAGE_TABLE_IF_NOT_REPORT_TO_IMPROVE_NLSF_SPEED

	///Kyle 08/10/2009 QA80-14077 ADD_PARAMETER_UNIT_TO_FITTING_REPORT
	//int			nParams = vstrParamNames.GetSize();
	int			nParams = stParamInfo.pvsParamNames->GetSize();
	///End ADD_PARAMETER_UNIT_TO_FITTING_REPORT
	// Fit Parameters
	///Arvin 05/24/07 v8.0624 PARAMETER_LABELS_MISSING_WHILE_CHANGE_PARAMETE
	//bool 		bHaveSubLevel = nTotalNumData>1? true:false;
	//TreeNode 	trParams = stats_tree_add_Parameters(strDataLabel, bHaveSubLevel, trOp.Calculation, index, pFitParams, vstrParamNames, vstrParamNamesPostfix, vstrFactors, pstDerivedParams, nNumDerivedParams, vbIsDerived);
	///Arvin 01/03/08 ADD_STAR_MARK_FOR_SHARED_PARAMS as cp said
	//TreeNode 	trParams = stats_tree_add_Parameters(strDataLabel, true, trOp, index, pFitParams, vstrParamNames, vstrParamNamesPostfix, vstrFactors, pstDerivedParams, nNumDerivedParams, vbIsDerived, nMultiplicity, nNumParamInFunc, nDupUnit);
	///Kyle 08/10/2009 QA80-14077 ADD_PARAMETER_UNIT_TO_FITTING_REPORT
	//TreeNode 	trParams = stats_tree_add_Parameters(strDataLabel, true, trOp, index, pFitParams, vstrParamNames, vstrParamNamesPostfix, vstrFactors, pstDerivedParams, nNumDerivedParams, vbIsDerived, nMultiplicity, nNumParamInFunc, nDupUnit, vbIsShared);
	TreeNode 	trParams = stats_tree_add_Parameters(strDataLabel, true, trOp, index, pFitParams, stParamInfo, vstrFactors, pstDerivedParams, nNumDerivedParams, vbIsDerived, nMultiplicity, nNumParamInFunc, nDupUnit, vbIsShared);
	///End ADD_PARAMETER_UNIT_TO_FITTING_REPORT
	///end ADD_STAR_MARK_FOR_SHARED_PARAMS
	///END PARAMETER_LABELS_MISSING_WHILE_CHANGE_PARAMETE
	if(trParams)
	{
		trParams.SetAttribute(TREE_Table, GetTableStringMain(false));
		FilterParameterQuantities(trParams);
		/// ML 6/9/2005 REPEATITIVE_STYLES_IN_GRID_THEMES
		if (1 == index)			// set periodicity only if there is more than one data (and only once suffices)
			SetTablePeriodicity(trParams, 0, nParams);
		/// end REPEATITIVE_STYLES_IN_GRID_THEMES
		return true;
	}	
	
	return false;
}
///end CORRECT_DERIVED_PARAMS_ORDER_FOR_REPLICA_CASE

///Arvin 08/03/07 WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
/// Iris 10/10/2009 QA80-14440 FOND_DUPLICATE_PARAM_NAME_AS_REPORT_TREENODE_NAME
//static void _add_one_params_table(const TreeNode& trSummaryGUI, const FitDerivedParameter* pstDerivedParams, const string& strParamName, TreeNode& trCol, TreeNode& trParams, int& nRows, int nNumValuesForOneParam, int nPeakOrder, bool bIsDerivedParams = false, int nDerivedParamIndex = 0)
static void _add_one_params_table(const TreeNode& trSummaryGUI, const FitDerivedParameter* pstDerivedParams, const vector<string>& vsParamNames, int nParam, TreeNode& trCol, TreeNode& trParams, int& nRows, int nNumValuesForOneParam, int nPeakOrder, bool bIsDerivedParams = false, int nDerivedParamIndex = 0)
///end FOND_DUPLICATE_PARAM_NAME_AS_REPORT_TREENODE_NAME
{
	
	for(int nValIndex = 0; nValIndex < nNumValuesForOneParam; nValIndex++)
	{
		/// Iris 10/10/2009 QA80-14440 FOND_DUPLICATE_PARAM_NAME_AS_REPORT_TREENODE_NAME
		//string		strTagName = strParamName;
		ASSERT( nParam < vsParamNames.GetSize() );
		string		strParamName = vsParamNames[nParam];
		string		strTagName = _get_param_valid_cname(vsParamNames, nParam);
		///end FOND_DUPLICATE_PARAM_NAME_AS_REPORT_TREENODE_NAME
		
		///Arvin 08/03/07 WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
		//if(nPeakOrder > 1)
		//	strTagName += ftoa(nPeakOrder-1);
		///end WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
			
		/// Iris 01/31/2007 SHOW_PARAMS_IN_SUMMARY_TABLE_ON_PARAMS_QUANTITIES
		//string		strValName = 0 == nValIndex? "Value" : "Error";
		TreeNode	trOneParamOut;	
		///Cheney 2007-10-27 CLEAN_UP_LOCALIZATION_THINGS
		//string		strLabel = "Value";
		///Arvin 11/02/07 CLEAN_UP_LOCALIZATION_STRINGS
		//string		strLabel = _L("Value");
		string		strTag = "Value";
		///end CLEAN_UP_LOCALIZATION_STRINGS
		///end CLEAN_UP_LOCALIZATION_THINGS
		if( !bIsDerivedParams )
		{
			trOneParamOut = trParams.Children.Item(nValIndex);
			if(!trOneParamOut.Show)
				 continue;
			///Arvin 11/02/07 CLEAN_UP_LOCALIZATION_STRINGS
			//if(!trOneParamOut.GetAttribute(STR_LABEL_ATTRIB, strLabel)) 	 
			//	strLabel = trOneParamOut.tagName;
			strTag = trOneParamOut.tagName;
			
				 	
		}
		///end SHOW_PARAMS_IN_SUMMARY_TABLE_ON_PARAMS_QUANTITIES
		if( !bIsDerivedParams )
		{
			///Arvin 11/02/07 CLEAN_UP_LOCALIZATION_STRINGS
			//strTagName += "_" + strLabel;
			strTagName += "_" + strTag;
			///end CLEAN_UP_LOCALIZATION_STRINGS
		}
		strTagName.MakeValidCName();
			
		//TreeNode 	trRow = tree_check_get_node(trCol, strTagName, IDST_TEMP_ONE_SET, STR_LABEL_ATTRIB, _L(strParamName));
		TreeNode 	trRow = tree_check_get_node(trCol, strTagName, IDST_TEMP_ONE_SET, STR_LABEL_ATTRIB, GetLocalized(strParamName)); /// Hong 11/07/07 v.8.0742 FIX_ERROR_LOCALIZED
		///Arvin 11/02/07 CLEAN_UP_LOCALIZATION_STRINGS
		TreeNode trTemp = trSummaryGUI.GetNode(strTag);
		string strLabel = strTag;
		if(trTemp)
		{
			//------ Folger 03/19/08 QA80-10598 NEW_GETN_LOCALIZAED_CHECK_MACRO
			double dRLS = 0;
			LT_get_var("@RLS", &dRLS);
			if ( dRLS == 0 )
				trTemp.GetAttribute(STR_LABEL_ATTRIB, strLabel);
			else
			//------
				trTemp.GetAttribute(STR_LABEL_E_ATTRIB, strLabel);	
		}
		///end CLEAN_UP_LOCALIZATION_STRINGS
		tree_add_one_label(trRow, strLabel, 0);
		
		trRow.ID = make_one_set_ID(IDST_FIT_PARAMETER_ONE_SET, nRows++);
			
		if( !bIsDerivedParams )
		{
			/// Iris 01/31/2007 SHOW_PARAMS_IN_SUMMARY_TABLE_ON_PARAMS_QUANTITIES
			//trRow.dVal = 0 == nValIndex? pFitParams[nBuildInParamIndex].Value : pFitParams[nBuildInParamIndex].Error;
			trRow.dVal = trOneParamOut.dVal;				
			///end SHOW_PARAMS_IN_SUMMARY_TABLE_ON_PARAMS_QUANTITIES
		}
		else
		{
			if(NULL != pstDerivedParams)
			{
				trRow.dVal = pstDerivedParams[nDerivedParamIndex].Value;
			}
		}
	}
		
}
///end WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA

/// Iris 01/09/2007 v8.0539 ADD_PARAMTERS_SUMMARY_TABLE
///Arvin 08/03/07 WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
//bool FitterOperation::AddParamtersSummaryTableToReportTree(TreeNode& trOp, int index, LPCSTR lpcszDataLabel, int nTotalNumData, const FitParameter* pFitParams, const vector<string>& vstrParamNames, const FitDerivedParameter* pstDerivedParams, int nNumDerivedParams, const RegStats &sRegStats)
bool FitterOperation::AddParamtersSummaryTableToReportTree(TreeNode& trOp, int index, LPCSTR lpcszDataLabel, int nTotalNumData, const FitParameter* pFitParams, const vector<string>& vstrParamNames, const FitDerivedParameter* pstDerivedParams, int nNumDerivedParams, const RegStats &sRegStats, vector<bool> &vbIsDerived, int nMultiplicity, int nNumParamInFunc, int nDupUnit)
///end WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
{
	/// Iris 4/23/2008 NOT_GENERAGE_TABLE_IF_NOT_REPORT_TO_IMPROVE_NLSF_SPEED
	// if not Summary on GUI or unchecked, should not go on in this funciton
	TreeNode	trSummaryGUI = trOp.GUI.Quantities.SummaryTable;
	/// Iris 6/06/2008 v8.0879 FIX_SHOW_TABLE_NAME_EVEN_TABLE_IS_EMPTY_IN_RESULT_LOG
	//if( !trSummaryGUI || 0 == trSummaryGUI.Use)
		//return true;
	bool		bShowSummary = trSummaryGUI && 0 != trSummaryGUI.Use;
	tree_check_set_hidden(trOp.Calculation.Summary, bShowSummary ? false : true);
	if( !bShowSummary )
		return true;
	///end FIX_SHOW_TABLE_NAME_EVEN_TABLE_IS_EMPTY_IN_RESULT_LOG
	///end NOT_GENERAGE_TABLE_IF_NOT_REPORT_TO_IMPROVE_NLSF_SPEED
	
	int 			ii;
	int				nTotalParams = vstrParamNames.GetSize();

	/// Iris 01/31/2007 SHOW_PARAMS_IN_SUMMARY_TABLE_ON_PARAMS_QUANTITIES
	//TreeNode				trParamQuantities = trOp.GUI.Quantities.Parameters;
	FitDerivedParameter		stDerivedParam;
	//end SHOW_PARAMS_IN_SUMMARY_TABLE_ON_PARAMS_QUANTITIES
	
	string 		strSummaryLabel = _L("Summary");
	TreeNode	trSummary = tree_check_get_node(trOp.Calculation, "Summary", IDST_FIT_PARAMETERS_SUMMARY, STR_LABEL_ATTRIB, strSummaryLabel);
	trSummary.SetAttribute(TREE_Table, GetTableStringMain(false));	
	trSummary.Show = true;
	
	/// Iris 03/02/2007 v8.0573 NOT_CHECK_USE_VAL_BY_GETATTRIB, just in order to check if GUI struct changed, old OGW & OTW still can do AU.
	/*
	/// Iris 02/28/2007 v8.0572 ADD_OPTIONS_TO_CONTRL_CONTENTS_IN_SUMMARY_TABLE
	//trSummary.Show = trOp.GUI.Quantities.SummaryTable.nVal;
	int		nCheck;
	/// Iris 03/01/2007 v8.0573 FIX_OLD_OGW_FILE_FAIL_TO_AU
	//if( !trOp.GUI.Quantities.Summary.GetAttribute(STR_USE_ATTRIB, nCheck) || 0 == nCheck )
	TreeNode	trSummaryGUI = trOp.GUI.Quantities.SummaryTable;
	if( trSummaryGUI && !trSummaryGUI.GetAttribute(STR_USE_ATTRIB, nCheck) || 0 == nCheck )
	///end FIX_OLD_OGW_FILE_FAIL_TO_AU
	*/
	
	/// Iris 4/23/2008 NOT_GENERAGE_TABLE_IF_NOT_REPORT_TO_IMPROVE_NLSF_SPEED
	/*
	TreeNode	trSummaryGUI = trOp.GUI.Quantities.SummaryTable;
	if( !trSummaryGUI || 0 == trSummaryGUI.Use)
	/// end NOT_CHECK_USE_VAL_BY_GETATTRIB
	{
		trSummary.Show = false;
		return true;
	}
	///end ADD_OPTIONS_TO_CONTRL_CONTENTS_IN_SUMMARY_TABLE
	*/
	///end NOT_GENERAGE_TABLE_IF_NOT_REPORT_TO_IMPROVE_NLSF_SPEED
	
	///Arvin 08/03/07 WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
	int nPeakOrder = 1; 
	string strTableLabel(lpcszDataLabel);
	string strTemp = strTableLabel;
	if(nMultiplicity > 1 || IsMulFuncsFit())
		strTableLabel = _L("Peak") + ftoa(nPeakOrder) + _L("(") + strTemp + _L(")");
	///end WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
	int			nColID = make_one_set_ID(IDST_FIT_PARAMETERS_SUMMARY, index + 1);
	///Arvin 08/03/07 WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
	//TreeNode	trCol = check_add_enumerated_node(trSummary, CALCULATION_REPORT_TABLE_ROW_PREFIX, index + 1, nColID, STR_LABEL_ATTRIB, lpcszDataLabel);
	TreeNode	trCol = check_add_enumerated_node(trSummary, CALCULATION_REPORT_TABLE_ROW_PREFIX, index + 1, nColID, STR_LABEL_ATTRIB, strTableLabel);
	///end WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
	int			nRows = 0;
	
	// Add Parameter info
	int			nBuildInParamIndex = 0;
	int			nDerivedParamIndex = 0;
	
	/// Hong 12/23/08 v8.0990 PA_AVOID_NESTED_LOOP_BY_CACHE_LAST_RESULT
	int				nLastPeakNoWithoutOffset = -1, nLastPeaksNum = -1;
	/// end PA_AVOID_NESTED_LOOP_BY_CACHE_LAST_RESULT
	for( ii = 0; ii < nTotalParams; ii++)
	{
		///Arvin 08/03/07 WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
		bool	bIsDerivedParams = ii >= (nTotalParams - nNumDerivedParams);//check the current row is Derive Parameter 
		if(vbIsDerived)
			bIsDerivedParams = vbIsDerived[ii];
		///end WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
		/// Iris 01/31/2007 SHOW_PARAMS_IN_SUMMARY_TABLE_ON_PARAMS_QUANTITIES
		/*
		int		nNumValuesForOneParam = bIsDerivedParams? 1 : 2;
		*/
		int		nNumValuesForOneParam = 1;
		Tree 	trParams;
		if( !bIsDerivedParams )
		{
			trParams += (FitParameter)pFitParams[nBuildInParamIndex];
			/// Iris 02/28/2007 v8.0572 ADD_OPTIONS_TO_CONTRL_CONTENTS_IN_SUMMARY_TABLE
			//tree_copy_values_to_attributes(trParamQuantities, trParams, STR_LABEL_ATTRIB);
			//octree_delete_nodes_by_attribute(&trParams, STR_SHOW_ATTRIB, false);
			foreach(TreeNode trN in trParams.Children)
			{
				TreeNode trOption = trOp.GUI.Quantities.SummaryTable.GetNode(trN.tagName);
				if(trOption)
					trN.Show = trOption.nVal;
				else
					trN.Show = 0;
			}
			///end ADD_OPTIONS_TO_CONTRL_CONTENTS_IN_SUMMARY_TABLE
			///Sophy 3/30/2009 QA80-13352 SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
			tree_set_attribute_to_all_nodes(trParams, STR_COL_DESIGNATION_ATTRIB, (string)OKDATAOBJ_DESIGNATION_Y, true);
			if ( trParams.Error )
				trParams.Error.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_ERROR);
			///end SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
			nNumValuesForOneParam = trParams.Children.Count();
		}			
		///end SHOW_PARAMS_IN_SUMMARY_TABLE_ON_PARAMS_QUANTITIES
		
		///Arvin 08/03/07 WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
		if(nMultiplicity > 1)
		{
			int nSepParamInd = nNumParamInFunc + nNumDerivedParams + (nPeakOrder-1)*(nDupUnit+nNumDerivedParams);
			if(ii >= nSepParamInd)
				nPeakOrder++;
			
			strTableLabel = _L("Peak") + ftoa(nPeakOrder) + _L("(") + strTemp +_L(")");
			if(ii == nSepParamInd && nPeakOrder > 1)
			{
				//int		nColID = make_one_set_ID(IDST_FIT_PARAMETERS_SUMMARY, index + 1);
				nRows = 0;
				int nColID = make_one_set_ID(IDST_FIT_PARAMETERS_SUMMARY, index + nPeakOrder);
				trCol = check_add_enumerated_node(trSummary, CALCULATION_REPORT_TABLE_ROW_PREFIX, index + nPeakOrder, nColID, STR_LABEL_ATTRIB, strTableLabel);
				//Copy unduplicated params value from peak1
				for(int jj = 0; jj < nNumParamInFunc-nDupUnit; jj++)
				{
					Tree trParamsTemp;
					trParamsTemp += (FitParameter)pFitParams[jj];
		
					foreach(TreeNode trN in trParamsTemp.Children)
					{
						TreeNode trOption = trOp.GUI.Quantities.SummaryTable.GetNode(trN.tagName);
						if(trOption)
							trN.Show = trOption.nVal;
						else
							trN.Show = 0;
					}
		
					nNumValuesForOneParam = trParamsTemp.Children.Count();
					/// Iris 10/10/2009 QA80-14440 FOND_DUPLICATE_PARAM_NAME_AS_REPORT_TREENODE_NAME
					//_add_one_params_table(trSummaryGUI, pstDerivedParams, vstrParamNames[jj], trCol, trParamsTemp, nRows, nNumValuesForOneParam, nPeakOrder)
					_add_one_params_table(trSummaryGUI, pstDerivedParams, vstrParamNames, jj, trCol, trParamsTemp, nRows, nNumValuesForOneParam, nPeakOrder);
					///end FOND_DUPLICATE_PARAM_NAME_AS_REPORT_TREENODE_NAME
				}
			}
		}
		///end WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
		///Jasmine 11/07/07 ADD_PEAK_NUMBER_TO_PFM_PARAMETERS		
		else if(IsMulFuncsFit())
		{
			bool bFuncFirstParam = false;			
			/// Hong 12/23/08 v8.0990 PA_AVOID_NESTED_LOOP_BY_CACHE_LAST_RESULT
			//GetPeakNumber(ii, nPeakOrder, bFuncFirstParam);
			bool bFuncRet = GetPeakNumber(ii, nPeakOrder, bFuncFirstParam, &nLastPeakNoWithoutOffset, &nLastPeaksNum);
			ASSERT(bFuncRet);
			/// end PA_AVOID_NESTED_LOOP_BY_CACHE_LAST_RESULT
			strTableLabel = _L("Peak") + ftoa(nPeakOrder) + _L("(") + strTemp +_L(")");
			if(bFuncFirstParam && 0 < ii)
			{
				nRows = 0;
				int nColID = make_one_set_ID(IDST_FIT_PARAMETERS_SUMMARY, index + nPeakOrder);
				trCol = check_add_enumerated_node(trSummary, CALCULATION_REPORT_TABLE_ROW_PREFIX, index + nPeakOrder, nColID, STR_LABEL_ATTRIB, strTableLabel);
				//Copy unduplicated params value from peak1
				int jj = 0; //add y0 to other peak group
				Tree trParamsTemp;
				trParamsTemp += (FitParameter)pFitParams[jj];		
				foreach(TreeNode trN in trParamsTemp.Children)
				{
					TreeNode trOption = trOp.GUI.Quantities.SummaryTable.GetNode(trN.tagName);
					if(trOption)
						trN.Show = trOption.nVal;
					else
						trN.Show = 0;
				}
				nNumValuesForOneParam = trParamsTemp.Children.Count();
				/// Iris 10/10/2009 QA80-14440 FOND_DUPLICATE_PARAM_NAME_AS_REPORT_TREENODE_NAME
				//_add_one_params_table(trSummaryGUI, pstDerivedParams, vstrParamNames[jj], trCol, trParamsTemp, nRows, nNumValuesForOneParam, nPeakOrder)
				_add_one_params_table(trSummaryGUI, pstDerivedParams, vstrParamNames, jj, trCol, trParamsTemp, nRows, nNumValuesForOneParam, nPeakOrder);
				///end FOND_DUPLICATE_PARAM_NAME_AS_REPORT_TREENODE_NAME
			}
		}
		///End ADD_PEAK_NUMBER_TO_PFM_PARAMETERS
		///Arvin 08/03/07 WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
		/*
		for(int nValIndex = 0; nValIndex < nNumValuesForOneParam; nValIndex++)
		{
			string		strTagName = vstrParamNames[ii];
			///Arvin 08/03/07 WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
			if(nParamOrder > 1)
				strTagName += ftoa(nParamOrder-1);
			///end WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
			
			/// Iris 01/31/2007 SHOW_PARAMS_IN_SUMMARY_TABLE_ON_PARAMS_QUANTITIES
			//string		strValName = 0 == nValIndex? "Value" : "Error";
			TreeNode	trOneParamOut;
			string		strLabel = "Value";
			if( !bIsDerivedParams )
			{
				 trOneParamOut = trParams.Children.Item(nValIndex);
				 if(!trOneParamOut.Show)
				 	continue;
				 
				 if(!trOneParamOut.GetAttribute(STR_LABEL_ATTRIB, strLabel))
				 	strLabel = trOneParamOut.tagName;
				 	
			}
			///end SHOW_PARAMS_IN_SUMMARY_TABLE_ON_PARAMS_QUANTITIES
			if( !bIsDerivedParams )
			{
				strTagName += "_" + strLabel;
			}
			strTagName.MakeValidCName();
			
			TreeNode 	trRow = tree_check_get_node(trCol, strTagName, IDST_TEMP_ONE_SET, STR_LABEL_ATTRIB, vstrParamNames[ii]);
			tree_add_one_label(trRow, strLabel, 0);
			trRow.ID = make_one_set_ID(IDST_FIT_PARAMETER_ONE_SET, nRows++);
			
			if( !bIsDerivedParams )
			{
				/// Iris 01/31/2007 SHOW_PARAMS_IN_SUMMARY_TABLE_ON_PARAMS_QUANTITIES
				//trRow.dVal = 0 == nValIndex? pFitParams[nBuildInParamIndex].Value : pFitParams[nBuildInParamIndex].Error;
				trRow.dVal = trOneParamOut.dVal;				
				///end SHOW_PARAMS_IN_SUMMARY_TABLE_ON_PARAMS_QUANTITIES
			}
			else
			{
				if(NULL != pstDerivedParams)
				{
					trRow.dVal = pstDerivedParams[nDerivedParamIndex].Value;
				}
			}
		}
		*/
		/// Iris 10/10/2009 QA80-14440 FOND_DUPLICATE_PARAM_NAME_AS_REPORT_TREENODE_NAME
		//_add_one_params_table(trSummaryGUI, pstDerivedParams, vstrParamNames[ii], trCol, trParams, nRows, nNumValuesForOneParam, nPeakOrder, bIsDerivedParams, nDerivedParamIndex);
		_add_one_params_table(trSummaryGUI, pstDerivedParams, vstrParamNames, ii, trCol, trParams, nRows, nNumValuesForOneParam, nPeakOrder, bIsDerivedParams, nDerivedParamIndex);
		///end FOND_DUPLICATE_PARAM_NAME_AS_REPORT_TREENODE_NAME		
		///end WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
		if(bIsDerivedParams)
			nDerivedParamIndex++;
		else
			nBuildInParamIndex++;
		
	}

	/// Iris 02/28/2007 v8.0572 ADD_OPTIONS_TO_CONTRL_CONTENTS_IN_SUMMARY_TABLE
	//Add Statistics info.
	///Arvin 08/03/07 WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
	//As max said, we only need add follow cells for first peak, the cells of rest peaks are empty 
	string			strTag;
	strTag.Format("%s%d", CALCULATION_REPORT_TABLE_ROW_PREFIX, index +  1);
	trCol = tree_check_get_node(trSummary, strTag);
	if(!trCol)
	    return false;
	///end  WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA   
	if(NULL != sRegStats)
	{
		Tree	trTemp;
		trTemp += sRegStats;
		
		foreach(TreeNode trN in trTemp.Children)
		{
			TreeNode 	trOption = trSummaryGUI.GetNode(trN.tagName);
			if(trOption && trOption.nVal)
			{			
				string		strLabel;
				
				//------ Folger 03/19/08 QA80-10598 NEW_GETN_LOCALIZAED_CHECK_MACRO
				//if( !trOption.GetAttribute(STR_LABEL_ATTRIB, strLabel) )
					//strLabel = trOption.tagName;
				double dRLS = 0;
				LT_get_var("@RLS", &dRLS);
				if ( dRLS == 0 )
					trOption.GetAttribute(STR_LABEL_ATTRIB, strLabel);
				else
					trOption.GetAttribute(STR_LABEL_E_ATTRIB, strLabel);
				if ( strLabel.IsEmpty() )
					strLabel = trOption.tagName;
				//------
				
				//------ Folger 05/20/08 USE_ENGLISH_LABEL_TO_GENERATE_REPORT_TREENODE_TAGNAME
				//string		strTagName = "Stats_" + trOption.tagName;
				string		strLabelE;
				trOption.GetAttribute(STR_LABEL_E_ATTRIB, strLabelE);
				string		strTagName = "Stats_" + strLabelE;
				//------
								
				strTagName.MakeValidCName();
				
				TreeNode 	trRow = tree_check_get_node(trCol, strTagName, IDST_TEMP_ONE_SET, STR_LABEL_ATTRIB, _L("Statistics"));
				tree_add_one_label(trRow, strLabel, 0);
				trRow.ID = make_one_set_ID(IDST_FIT_PARAMETER_ONE_SET, nRows++);
				
				trRow.dVal = trN.dVal;
			}
		}
		///Sophy 3/30/2009 QA80-13352 SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
		tree_set_attribute_to_all_nodes(trTemp, STR_COL_DESIGNATION_ATTRIB, (string)OKDATAOBJ_DESIGNATION_Y, true);
		///end SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES

	}
	///end ADD_OPTIONS_TO_CONTRL_CONTENTS_IN_SUMMARY_TABLE
	///Sophy 3/30/2009 QA80-13352 SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
	tree_set_attribute_to_all_nodes(trCol, STR_COL_DESIGNATION_ATTRIB, (string)OKDATAOBJ_DESIGNATION_Y, true);
	///Sophy 4/3/2009 QA80-13352 SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
	//if ( trCol.y0_Error )
		//trCol.y0_Error.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_ERROR);
	//if ( trCol.xc_Error )
		//trCol.xc_Error.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_ERROR);
	//if ( trCol.w_Error )
		//trCol.w_Error.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_ERROR);
	//if ( trCol.A_Error )
		//trCol.A_Error.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_ERROR);
	//if ( trCol.Intercept_Error )
		//trCol.Intercept_Error.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_ERROR);
	//if ( trCol.Slope_Error )
		//trCol.Slope_Error.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_ERROR);
	foreach ( TreeNode trNode in trCol.Children )
	{
		string strTagName = trNode.tagName;
		if ( strTagName.Match("*_Error", true) ) //match case sensitively
			trNode.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_ERROR);
	}
	///end SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES
	///end SUPPORT_SPECIFY_COLUMN_DESIGNATIONS_IN_REPORT_TABLES

	OnAfterAddParamtersSummaryTable(trOp, index);/// Iris 5/19/2008 RENAME_OLD_FUNCTION_AND_MOVE_TO_SUIT_PLACE

	return true;
}

/// end ADD_PARAMTERS_SUMMARY_TABLE

/// Iris 12/30/2006 v8.0534 CORRECT_DERIVED_PARAMS_ORDER_FOR_REPLICA_CASE
/*
///Iris 4/02/05 ADD_VY_VX_AS_ARGUMENT
//bool FitterOperation::AddOneDataStatsResultsToReportTree(TreeNode &trOp, int index, const string &strDataLabel, int nTotalNumData, const vector<string> &vstrFactors, const FitParameter* pFitParams, 
//const RegANOVA& sANOVA, const RegStats &sRegStats, matrix& mCov, matrix& mCorr, const vector<string>& vsDerivedParamNames, const vector<double>& vdDerivedParamValues)// = NULL = NULL = NULL = NULL
bool FitterOperation::AddOneDataStatsResultsToReportTree(TreeNode &trOp, int index, const string &strDataLabel, int nTotalNumData, const vector<string> &vstrFactors, vector &vY, vector &vX, matrix & mMultiIndep, const FitParameter* pFitParams, 
const RegANOVA& sANOVA, const RegStats &sRegStats, matrix& mCov, matrix& mCorr, const vector<string>& vsDerivedParamNames, const vector<double>& vdDerivedParamValues)// = NULL = NULL = NULL = NULL
*/
bool FitterOperation::AddOneDataStatsResultsToReportTree(TreeNode &trOp, int index, const string &strDataLabel, int nTotalNumData, const vector<string> &vstrFactors, vector &vY, vector &vX, matrix & mMultiIndep, const FitParameter* pFitParams, 
///Arvin 05/25/07 ADD_CORRECTED_TOTAL_ROW_FOR_ANOVA_TABLE_FOR_FITNL
//vector<string>& vstrParamNames, vector<string>& vstrParamNamesPostfix, const RegANOVA& sANOVA, const RegStats &sRegStats, matrix& mCov, matrix& mCorr, const FitDerivedParameter* pstDerivedParams, int nNumDerivedParams, vector<bool> &vbIsDerived, bool bReportStats, bool bReportANOVA)// = NULL, = NULL, = NULL, =0, =NULL, =true, =true
///Arvin 08/03/07 WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
//vector<string>& vstrParamNames, vector<string>& vstrParamNamesPostfix, const RegANOVA& sANOVA, const RegStats &sRegStats, matrix& mCov, matrix& mCorr, const FitDerivedParameter* pstDerivedParams, int nNumDerivedParams, vector<bool> &vbIsDerived, bool bReportStats, bool bReportANOVA, RegANOVARow& stCorrTotal)// = NULL, = NULL, = NULL, =0, =NULL, =true, =true
///Arvin 01/03/08 ADD_STAR_MARK_FOR_SHARED_PARAMS as cp said
//vector<string>& vstrParamNames, vector<string>& vstrParamNamesPostfix, const RegANOVA& sANOVA, const RegStats &sRegStats, matrix& mCov, matrix& mCorr, const FitDerivedParameter* pstDerivedParams, int nNumDerivedParams, vector<bool> &vbIsDerived, bool bReportStats, bool bReportANOVA, RegANOVARow& stCorrTotal, int nMultiplicity, int nNumParamInFunc, int nDupUnit)// = NULL, = NULL, = NULL, =0, =NULL, =true, =true
//------ Folger 12/01/08 v8.0981 MORE_ON_USE_UNCONVERTED_DATA_LABEL_FOR_REGSTATS_TABLE_COLUMNS
//vector<string>& vstrParamNames, vector<string>& vstrParamNamesPostfix, const RegANOVA& sANOVA, const RegStats &sRegStats, matrix& mCov, matrix& mCorr, const FitDerivedParameter* pstDerivedParams, int nNumDerivedParams, vector<bool> &vbIsDerived, bool bReportStats, bool bReportANOVA, RegANOVARow& stCorrTotal, int nMultiplicity, int nNumParamInFunc, int nDupUnit, vector<bool> &vbIsShared)// = NULL, = NULL, = NULL, =0, =NULL, =true, =true
///Kyle 08/10/2009 QA80-14077 ADD_PARAMETER_UNIT_TO_FITTING_REPORT
//vector<string>& vstrParamNames, vector<string>& vstrParamNamesPostfix, const RegANOVA& sANOVA, const RegStats &sRegStats, matrix& mCov, matrix& mCorr, const FitDerivedParameter* pstDerivedParams, int nNumDerivedParams, vector<bool> &vbIsDerived, bool bReportStats, bool bReportANOVA, RegANOVARow& stCorrTotal, int nMultiplicity, int nNumParamInFunc, int nDupUnit, vector<bool> &vbIsShared, const string* pstrDataLabelUnconverted/* = NULL*/)// = NULL, = NULL, = NULL, =0, =NULL, =true, =true
const FITPARAMSINFO& stParamInfo, const RegANOVA& sANOVA, const RegStats &sRegStats, matrix& mCov, matrix& mCorr, const FitDerivedParameter* pstDerivedParams, int nNumDerivedParams, vector<bool> &vbIsDerived, bool bReportStats, bool bReportANOVA, RegANOVARow& stCorrTotal, int nMultiplicity, int nNumParamInFunc, int nDupUnit, vector<bool> &vbIsShared, const string* pstrDataLabelUnconverted/* = NULL*/)// = NULL, = NULL, = NULL, =0, =NULL, =true, =true
///End ADD_PARAMETER_UNIT_TO_FITTING_REPORT
//------
///end ADD_STAR_MARK_FOR_SHARED_PARAMS
///end WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
///end ADD_CORRECTED_TOTAL_ROW_FOR_ANOVA_TABLE_FOR_FITNL
{

	/// Iris 12/30/2006 v8.0534 CORRECT_DERIVED_PARAMS_ORDER_FOR_REPLICA_CASE
	//The old order of parameters is y0,xc,w,A, xc2, w2, A2, sigma, FWHM, sigma2, FWHM2, but should be y0,xc,w,A, sigma, FWHM, xc2, w2, A2, sigma2, FWHM2
	//so AddParamterTableToReportTree must be overload in FitNL
	///Arvin 08/03/07 WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
	//if( !AddParamterTableToReportTree(trOp, index, strDataLabel, nTotalNumData, vstrFactors, pFitParams, vstrParamNames, vstrParamNamesPostfix, pstDerivedParams, nNumDerivedParams, vbIsDerived) )
	string strCovertedDataLabel = strDataLabel;
	///Arvin 02/15/08 QA70-11097 KEEP_ESCAPED_STRINGS
	//ConvertEscapedString(strCovertedDataLabel);
	///END KEEP_ESCAPED_STRINGS
	///Arvin 01/03/08 ADD_STAR_MARK_FOR_SHARED_PARAMS as cp said
	//if( !AddParamterTableToReportTree(trOp, index, strCovertedDataLabel, nTotalNumData, vstrFactors, pFitParams, vstrParamNames, vstrParamNamesPostfix, pstDerivedParams, nNumDerivedParams, vbIsDerived, nMultiplicity, nNumParamInFunc, nDupUnit) )	
	///Kyle 08/10/2009 QA80-14077 ADD_PARAMETER_UNIT_TO_FITTING_REPORT
	//if( !AddParamterTableToReportTree(trOp, index, strCovertedDataLabel, nTotalNumData, vstrFactors, pFitParams, vstrParamNames, vstrParamNamesPostfix, pstDerivedParams, nNumDerivedParams, vbIsDerived, nMultiplicity, nNumParamInFunc, nDupUnit, vbIsShared) )	
	if( !AddParamterTableToReportTree(trOp, index, strCovertedDataLabel, nTotalNumData, vstrFactors, pFitParams, stParamInfo, pstDerivedParams, nNumDerivedParams, vbIsDerived, nMultiplicity, nNumParamInFunc, nDupUnit, vbIsShared) )	
	///End ADD_PARAMETER_UNIT_TO_FITTING_REPORT
	///end ADD_STAR_MARK_FOR_SHARED_PARAMS
	///end 	WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
	{
		trOp.Calculation.Parameters.Remove();/// Iris 4/23/2008 v8.0848 FIX_GET_RUNTIME_ERR_WHEN_NOT_REPORT_PARAMS_TABLE
		error_report("error adding parameter table");
	}
	///end PARAM_NAME_AS_TAGNAME_FOR_CELL_LINKING
	
	/// Iris 01/09/2007 v8.0539 ADD_PARAMTERS_SUMMARY_TABLE
	///Arvin 08/03/07 WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
	//if( !AddParamtersSummaryTableToReportTree(trOp, index, strDataLabel, nTotalNumData, pFitParams, vstrParamNames, pstDerivedParams, nNumDerivedParams, sRegStats) )
	vector<string>& vstrParamNames = *stParamInfo.pvsParamNames;					///Kyle 08/10/2009 QA80-14077 ADD_PARAMETER_UNIT_TO_FITTING_REPORT
	if( !AddParamtersSummaryTableToReportTree(trOp, index, strCovertedDataLabel, nTotalNumData, pFitParams, vstrParamNames, pstDerivedParams, nNumDerivedParams, sRegStats, vbIsDerived, nMultiplicity, nNumParamInFunc, nDupUnit) )
	///end WRONG_PARAMETER_SUMARY_TABLE_WHILE_FIT_REPLICA
	{
		trOp.Calculation.Summary.Remove();/// Iris 4/23/2008 v8.0848 FIX_GET_RUNTIME_ERR_WHEN_NOT_REPORT_PARAMS_TABLE
		error_report("error adding parameters summary table");
	}
	/// end ADD_PARAMTERS_SUMMARY_TABLE
	
	//////////////////////////////////////////////////////
	// ANOVA table (optional)
	if( bReportANOVA && sANOVA )
	{
		///Arvin 05/25/07 ADD_CORRECTED_TOTAL_ROW_FOR_ANOVA_TABLE_FOR_FITNL
		//if(!stats_tree_add_ANOVA_table(trOp, strDataLabel, index, nTotalNumData, sANOVA, vstrFactors))
			//error_report("error adding ANOVA table");

		//------ Folger 12/01/08 v8.0981 MORE_ON_USE_UNCONVERTED_DATA_LABEL_FOR_REGSTATS_TABLE_COLUMNS
		string strLabel = pstrDataLabelUnconverted ? *pstrDataLabelUnconverted : strDataLabel;
		//------
			
		if(stCorrTotal)
		{
			//------ Folger 12/01/08 v8.0981 MORE_ON_USE_UNCONVERTED_DATA_LABEL_FOR_REGSTATS_TABLE_COLUMNS
			//if(!stats_tree_add_ANOVA_table(trOp, strDataLabel, index, nTotalNumData, sANOVA, vstrFactors, stCorrTotal))
			if(!stats_tree_add_ANOVA_table(trOp, strLabel, index, nTotalNumData, sANOVA, vstrFactors, stCorrTotal))
			//------
				error_report("error adding ANOVA table");
		}
		else
		{
			//------ Folger 12/01/08 v8.0981 MORE_ON_USE_UNCONVERTED_DATA_LABEL_FOR_REGSTATS_TABLE_COLUMNS
			//if(!stats_tree_add_ANOVA_table(trOp, strDataLabel, index, nTotalNumData, sANOVA, vstrFactors))
			if(!stats_tree_add_ANOVA_table(trOp, strLabel, index, nTotalNumData, sANOVA, vstrFactors))
			//------
				error_report("error adding ANOVA table");
		}
		///end ADD_CORRECTED_TOTAL_ROW_FOR_ANOVA_TABLE_FOR_FITNL
	}	
	/// Iris 9/25/2009 FIX_LR_STILL_REPORT_EMPTY_ANOVA_TABLE_IF_NOT_CHECKED_ON_GUI
	tree_check_set_hidden(trOp.Calculation.ANOVAs, bReportANOVA ? false : true);	
	///end FIX_LR_STILL_REPORT_EMPTY_ANOVA_TABLE_IF_NOT_CHECKED_ON_GUI
		
	//////////////////////////////////////////////////////
	// Stat:
	if(sRegStats && bReportStats)
	{
		AddRegStatsToReportTree(trOp, index, strDataLabel, nTotalNumData, vstrFactors, sRegStats);
	}
	///Jasmine 06/11/08 QA80-11678 TO_HIDE_STATS_TABLE_SHOULD_CHECK_QUANTIT_STATS
	bool bShowReportStats = true;
	if( tree_GUI_are_all_uncheck(trOp.GUI.Quantities.Statistics) )
		bShowReportStats = false;
	else if(trOp.Calculation.RegStats.IsEmpty() || trOp.Calculation.RegStats.FirstNode.IsEmpty() )
		bShowReportStats = false;	
	//tree_check_set_hidden(trOp.Calculation.RegStats, bReportStats ? false : true); /// Iris 6/06/2008 v8.0879 FIX_SHOW_TABLE_NAME_EVEN_TABLE_IS_EMPTY_IN_RESULT_LOG
	tree_check_set_hidden(trOp.Calculation.RegStats, bShowReportStats ? false : true); /// Iris 6/06/2008 v8.0879 FIX_SHOW_TABLE_NAME_EVEN_TABLE_IS_EMPTY_IN_RESULT_LOG
	///End TO_HIDE_STATS_TABLE_SHOULD_CHECK_QUANTIT_STATS
	
	//////////////////////////////////////////////////////
	///Arvin 11/24/06 MULTI_DATA_NEED_MULTI_COVARIANCE_AND_CORRELATION_TABLE
	/*
	/// Iris 9/27/04 ADD_COV_AND_CORR_REPORT
	// Cov:
	TreeNode	trTable;
	string strPrefix = nTotalNumData > 1? "Mat" : "";
	//int nSingleTable = GetTableStringSupport(false, false, true, false);///Alex 06/19/06 SET_COVARIANCE_AND_CORRELATION_TABLE_OPEN
	int nSingleTable = atof(GetTableStringMain(false));
	if(isMatValid(mCov))
	{
		string	strTagName = "Covariance";
		trTable = tree_check_get_node(trCal, strTagName, IDST_REG_COV_TABLE, STR_LABEL_ATTRIB, strTagName);
		///Alex 06/19/06 SET_COVARIANCE_AND_CORRELATION_TABLE_ON_OPTIONS_OF_USER
		bool bShowmCov = trOp.GUI.Quantities.mCov.nVal;
		tree_check_set_hidden(trTable, bShowmCov?false:true);
		///End SET_COVARIANCE_AND_CORRELATION_TABLE_ON_OPTIONS_OF_USER
		
		/// Iris 8/16/06 NEED_SPECIAL_ROW_COL_HEADER_FOR_MATRIX_TABLE
		//TreeNode	trMat = GetSubReportNode(trTable, index, IDST_REG_COVS, strDataLabel, strPrefix, nSingleTable);
		//trMat.mat.ID = IDE_COR_MATIRX;
		//trMat.mat.dVals2 = mCov;
		tree_result_table_add_matrix(trTable, mCov, vstrParamNames, vstrParamNames, true);
		trTable.SetAttribute(TREE_Table, nSingleTable);
		///end NEED_SPECIAL_ROW_COL_HEADER_FOR_MATRIX_TABLE
	}
	else
		trCal.RemoveChild(IDST_REG_COV_TABLE);
	
	// Corr:	
	if(isMatValid(mCorr))
	{
		string	strTagName = "Correlation";
		trTable = tree_check_get_node(trCal, strTagName, IDST_REG_CORR_TABLE, STR_LABEL_ATTRIB, strTagName);
		///Alex 06/19/06 SET_COVARIANCE_AND_CORRELATION_TABLE_ON_OPTIONS_OF_USER
		bool bShowmCorr = trOp.GUI.Quantities.mCor.nVal;
		tree_check_set_hidden(trTable, bShowmCorr?false:true);
		///End SET_COVARIANCE_AND_CORRELATION_TABLE_ON_OPTIONS_OF_USER
		/// Iris 8/16/06 NEED_SPECIAL_ROW_COL_HEADER_FOR_MATRIX_TABLE
		//TreeNode	trMat = GetSubReportNode(trTable, index, IDST_REG_CORRS, strDataLabel, strPrefix, nSingleTable);
		//trMat.mat.ID = IDE_CORR_MATRIX;
		//trMat.mat.dVals2 = mCorr;
		tree_result_table_add_matrix(trTable, mCorr, vstrParamNames, vstrParamNames, true);
		trTable.SetAttribute(TREE_Table, nSingleTable);
		///end NEED_SPECIAL_ROW_COL_HEADER_FOR_MATRIX_TABLE		
	}
	else
		trCal.RemoveChild(IDST_REG_CORR_TABLE);	
	*/
	TreeNode		trCal = trOp.Calculation;
	/// Iris 4/23/2008 NOT_GENERAGE_TABLE_IF_NOT_REPORT_TO_IMPROVE_NLSF_SPEED
	//if(isMatValid(mCov) )
	TreeNode		trGUICov = trOp.GUI.Quantities.mCov;
	///Iris 5/19/2008 NOT_GENERAGE_TABLE_IF_NOT_REPORT_TO_IMPROVE_NLSF_SPEED_MORE, the old logic is not good, should not remove table if not choose in change param, should hide table
	//if( isMatValid(mCov) && trGUICov && trGUICov.nVal)
	if( isMatValid(mCov) && trGUICov )
	///end NOT_GENERAGE_TABLE_IF_NOT_REPORT_TO_IMPROVE_NLSF_SPEED
	{
		///Arvin 05/23/07 v8.0624 COV_AND_CORR_TABLE_CHAOS_WHILE_CHANGE_PARAMETER
		//string	strTagName = "Covariance";
		//if(!stats_tree_add_cov_or_corr_table(trOp, strTagName, strDataLabel, index, nTotalNumData, IDST_REG_COV_TABLE, mCov, vstrParamNames))
		//------ Folger 12/01/08 v8.0981 MORE_ON_USE_UNCONVERTED_DATA_LABEL_FOR_REGSTATS_TABLE_COLUMNS
		//if(!AddCovOrCorrMatrixToReportTree(trOp, strDataLabel, index, nTotalNumData, IDST_REG_COV_TABLE, mCov, vstrParamNames, vbIsDerived))
		if(!AddCovOrCorrMatrixToReportTree(trOp, pstrDataLabelUnconverted ? *pstrDataLabelUnconverted : strDataLabel, index, nTotalNumData, IDST_REG_COV_TABLE, mCov, vstrParamNames, vbIsDerived))
		//------
		///end 	COV_AND_CORR_TABLE_CHAOS_WHILE_CHANGE_PARAMETER
			error_report("error adding Covariance table");
	}
	/// Iris 9/25/2009 FIX_LR_STILL_REPORT_EMPTY_ANOVA_TABLE_IF_NOT_CHECKED_ON_GUI
	bool bReportCov = (trGUICov && trGUICov.Show && trGUICov.nVal);
	tree_check_set_hidden(trOp.Calculation.Covariance, bReportCov ? false : true);
	///end FIX_LR_STILL_REPORT_EMPTY_ANOVA_TABLE_IF_NOT_CHECKED_ON_GUI
	
	///Iris 5/19/2008 NOT_GENERAGE_TABLE_IF_NOT_REPORT_TO_IMPROVE_NLSF_SPEED_MORE
	//else
	//	trCal.RemoveChild(IDST_REG_COV_TABLE);
	///end NOT_GENERAGE_TABLE_IF_NOT_REPORT_TO_IMPROVE_NLSF_SPEED_MORE
	
	
	/// Iris 4/23/2008 NOT_GENERAGE_TABLE_IF_NOT_REPORT_TO_IMPROVE_NLSF_SPEED
	//if(isMatValid(mCorr) )
	TreeNode		trGUICorr = trOp.GUI.Quantities.mCor;
	///Iris 5/19/2008 NOT_GENERAGE_TABLE_IF_NOT_REPORT_TO_IMPROVE_NLSF_SPEED_MORE, the old logic is not good, should not remove table if not choose in change param, should hide table
	//if( isMatValid(mCorr) && trGUICorr && trGUICorr.nVal)
	if( isMatValid(mCorr) && trGUICorr )
	///end NOT_GENERAGE_TABLE_IF_NOT_REPORT_TO_IMPROVE_NLSF_SPEED_MORE
	///end NOT_GENERAGE_TABLE_IF_NOT_REPORT_TO_IMPROVE_NLSF_SPEED
	{
		///Arvin 05/23/07 v8.0624 COV_AND_CORR_TABLE_CHAOS_WHILE_CHANGE_PARAMETER
		//string	strTagName = "Correlation";
		//if(!stats_tree_add_cov_or_corr_table(trOp, strTagName, strDataLabel, index, nTotalNumData, IDST_REG_CORR_TABLE, mCorr, vstrParamNames))
		//------ Folger 12/01/08 v8.0981 MORE_ON_USE_UNCONVERTED_DATA_LABEL_FOR_REGSTATS_TABLE_COLUMNS
		//if(!AddCovOrCorrMatrixToReportTree(trOp, strDataLabel, index, nTotalNumData, IDST_REG_CORR_TABLE, mCorr, vstrParamNames, vbIsDerived))
		if(!AddCovOrCorrMatrixToReportTree(trOp, pstrDataLabelUnconverted ? *pstrDataLabelUnconverted : strDataLabel, index, nTotalNumData, IDST_REG_CORR_TABLE, mCorr, vstrParamNames, vbIsDerived))
		//------
		///end 	COV_AND_CORR_TABLE_CHAOS_WHILE_CHANGE_PARAMETER
			error_report("error adding Correlation table");
	}
	/// Iris 9/25/2009 FIX_LR_STILL_REPORT_EMPTY_ANOVA_TABLE_IF_NOT_CHECKED_ON_GUI
	bool bReportCorr = (trGUICorr && trGUICorr.Show && trGUICorr.nVal);
	tree_check_set_hidden(trOp.Calculation.Correlation, bReportCorr ? false : true);
	///end FIX_LR_STILL_REPORT_EMPTY_ANOVA_TABLE_IF_NOT_CHECKED_ON_GUI
	///Iris 5/19/2008 NOT_GENERAGE_TABLE_IF_NOT_REPORT_TO_IMPROVE_NLSF_SPEED_MORE
	//else
		//trCal.RemoveChild(IDST_REG_CORR_TABLE);	
	///end NOT_GENERAGE_TABLE_IF_NOT_REPORT_TO_IMPROVE_NLSF_SPEED_MORE
	///END MULTI_DATA_NEED_MULTI_COVARIANCE_AND_CORRELATION_TABLE
	
	/// Iris 5/19/2008 RENAME_OLD_FUNCTION_AND_MOVE_TO_SUIT_PLACE
	//OnAfterAddOneDataStatsResultsToReportTree(trOp, index);
	///end RENAME_OLD_FUNCTION_AND_MOVE_TO_SUIT_PLACE
	
	return true;
}

/// Iris 5/19/2008 RENAME_OLD_FUNCTION_AND_MOVE_TO_SUIT_PLACE
//void FitterOperation::OnAfterAddOneDataStatsResultsToReportTree(TreeNode &trOp, int index)
void FitterOperation::OnAfterAddParamtersSummaryTable(TreeNode &trOp, int index)
///end RENAME_OLD_FUNCTION_AND_MOVE_TO_SUIT_PLACE
{
	//empty
}

///Cheney 2006-8-25 USE_CALLBACK_TO_DO_GET_X_FROM_Y
bool FitterOperation::GetXFromY(matrix& mXs, const vector& vy, int nOuputIndex, TreeNode& trOp)
{
	///Joseph 09/27/06 FINDXY_TO_SEPERATE_SHEET
	/// Iris 10/29/2009 QA81-14546 OP_DLG_NEW_STRUCTURE
	//TreeNode trCol = trOp.GUI.Calibration.Custom2.Cols;
	TreeNode trCol = OP_GUI_CALIBRATION_BRANCH(trOp.GUI).Custom2.Cols;
	///end OP_DLG_NEW_STRUCTURE
	if(!trCol.IsValid())
		return false;
	mXs.SetSize(trCol.nVal, vy.GetSize());
	//mXs.SetSize(1, vy.GetSize());
	///End FINDXY_TO_SEPERATE_SHEET
	mXs = NANUM;
	
	vector 		vFitX, vFitY;
	///Joseph 09/27/06 FINDXY_TO_SEPERATE_SHEET
	//if( !GetFitCurve(vFitX, vFitY, nOuputIndex) )
	///Cheney 2007-6-19 ALWAYS_FIND_XY_FROM_CUMULATIVE_FIT_CURVE_IF_PEAK_FIT
	//if( !GetFitCurve(trOp, vFitX, vFitY, nOuputIndex))
	int nPeaks = 0;
	if( !GetFitCurve(trOp, vFitX, vFitY, nPeaks, nOuputIndex) )
	///end ALWAYS_FIND_XY_FROM_CUMULATIVE_FIT_CURVE_IF_PEAK_FIT
		return false;
	///End FINDXY_TO_SEPERATE_SHEET
	
	vector vParams;
	///Cheney 2007-6-19 ALWAYS_FIND_XY_FROM_CUMULATIVE_FIT_CURVE_IF_PEAK_FIT
	//GetFitParams(vParams, nOuputIndex, trOp);
	//int nParamsSize = vParams.GetSize();
	///end ALWAYS_FIND_XY_FROM_CUMULATIVE_FIT_CURVE_IF_PEAK_FIT
	
	TreeNode trFuncList = trOp.GUI.FunctionSelection.FunctionList;
	string	strFuncFileName = trFuncList ? trFuncList.strVal : "POLY"; //if NLfit get func name, else should be polynomial 
	
	int 		nSize = vFitX.GetSize();
	///Joseph 9/18/06 CHANGE_FINDX_FROMY_STEP
	double dXMax,dXMin;
	vFitX.GetMinMax(dXMin, dXMax);
	int nMaxSize = (dXMax - dXMin)/ 0.1 ;
	if(nMaxSize > 10*nSize)
	{
		nSize = 10*nSize;
	}
	else if(nMaxSize > nSize)
	{
		nSize = nMaxSize;
	}
	vFitX.SetSize(nSize);
	double dStep = (dXMax - dXMin ) / ( double )(nSize - 1);
	vFitX.Data(dXMin, dXMax, dStep);
	Tree tr;
	vector vcTemp;
	vFitY = vcTemp;
	///Cheney 2007-6-19 ALWAYS_FIND_XY_FROM_CUMULATIVE_FIT_CURVE_IF_PEAK_FIT
	//GetYFromX(vFitX,vFitY, nOuputIndex, trOp);
	GetYFromX(vFitX,vFitY, nOuputIndex, trOp, NULL, nPeaks, vParams);	
	int nParamsSize = vParams.GetSize();
	///end ALWAYS_FIND_XY_FROM_CUMULATIVE_FIT_CURVE_IF_PEAK_FIT
	///End CHANGE_FINDX_FROMY_STEP
	for(int nn = 0; nn < vy.GetSize(); nn++)
	{			
		double 		dY = vy[nn];
		vector		vx(nSize);
		vector<int>	vnXi(nSize);
		vx = NANUM;
		
		PFN_STR_INT_DOUBLE_DOUBLE_DOUBLEP pFunc = Project.FindFunction("compute_y_by_x", "OriginLab\\nlsf_utils.c");
		///Cheney 2006-10-25 ADD_A_NEW_TORLERANCE, in worksheet, precesion is 10^-5, so need to add a new tol to check if out of bound
		//if( OE_NOERROR == ocmath_find_xs(dY, nSize, vFitX, vFitY, nSize, vx, strFuncFileName, nParamsSize, vParams, pFunc, vnXi) )	
		if( OE_NOERROR == ocmath_find_xs(dY, nSize, vFitX, vFitY, nSize, vx, strFuncFileName, nParamsSize, vParams, pFunc, vnXi, 1E-5) )
		///end ADD_A_NEW_TORLERANCE
		{
			// remove the unwanted the data from vx to get real size				
			//vnXi.Replace(-nSize, MATREPL_TEST_EQUAL, NANUM);  //vectorbase::Replace not work
			//vnXi.TrimRight();
			int nXi = vnXi.GetSize() -1; 
			while( nXi >= 0)
			{
				if( vnXi[nXi] != -nSize )
					break;
				
				vnXi.RemoveAt(nXi);				
				nXi = vnXi.GetSize() -1;					
			}
			
			vx.SetSize(vnXi.GetSize());
			
			if( 0 != vx.GetSize() )
			{
				if( mXs.GetNumRows() < vx.GetSize() )
					mXs.SetSize( vx.GetSize(), vy.GetSize() );
				mXs.SetColumn(vx, nn);
			}
		}
	}
	
	return true;
}
///end USE_CALLBACK_TO_DO_GET_X_FROM_Y 
//////////////////////////////////////////////////
//////////////////////////////////////////////////

static	void	add_link_offsets(string &str, int *pnFirst, int *pnSecond, BOOL bPrefix)
{
	string		strOffsets;
	
	if ( pnFirst )
	{
		if ( pnSecond )
			strOffsets.Format("[%d:%d]", *pnFirst, *pnSecond);
		else
			strOffsets.Format("[%d]", *pnFirst);
	}
	else if ( pnSecond )
	{
		strOffsets.Format("[:%d]", *pnSecond);
	}
	
	if ( bPrefix )
		str += STR_LINK_CELL_VALUE_PREFIX;

	str += strOffsets;
}


static	void	table_theme_set_vector(TreeNode &tr, int index, const vector<string> &vstrData)
{
	TreeNode		trVectors = tree_check_get_node(tr, "Vectors");
	string			strNodeName;
	strNodeName.Format("Vector%d", index + 1);
	TreeNode		trVector = tree_check_get_node(trVectors, strNodeName);
	trVector.Data.strVals = vstrData;
}


static	void	make_cell_link_to_2D_table(string &str, int nIDTable, int nIDFirst, int nSecond, int *pnFirst = NULL, int *pnSecond = NULL)
{
	int			arrnIDs[3];
	arrnIDs[0] = nIDTable;
	arrnIDs[1] = nIDFirst;
	arrnIDs[2] = nSecond;
	build_report_nodes_link_string(str, arrnIDs, 3);
	
	add_link_offsets(str, pnFirst, pnSecond, FALSE);
	
	return;
}

/// ML 6/6/2005 STYLE_LINKS_WITH_OFFSETS
static	void	make_cell_link_to_whole_table(string &str, int nIDTable)
{
	int			nAll = -1;
	make_cell_link_to_2D_table(str, nIDTable, IDL_LABELS_AND_DATA, IDL_LABELS_AND_DATA, &nAll, &nAll);
}
/// end STYLE_LINKS_WITH_OFFSETS




// bckColor = -1 means don't set it. Otherwise it is OCOLOR.
// nPeriodXXXwise = 0 means not to set period in that direction
static	TreeNode	table_theme_add_link_style(TreeNode &tr, int index, LPCSTR lpcszName, bool *pbBold = NULL, int bckColor = -1,
				DWORD dwBorders = 0, int nPeriodRowwise = 0, int nPeriodColwise = 0, int nBorderColor = 0, int nMerging = -1)
{
	string			strNodeName;
	strNodeName.Format("LinkStyle%d", index + 1);
	TreeNode		trLinkStyles = tree_check_get_node(tr, "LinkStyles");
	TreeNode		trLinkStyle = tree_check_get_node(trLinkStyles, strNodeName);
	
	trLinkStyle.Name.strVal = lpcszName;
	/// ML 10/13/2005 QA70-8157 SPECIAL_NAMES_STYLES_IN_FLAT_SHEETS
	/*
	if ( pbBold )
		trLinkStyle.Style.Font.Bold.nVal = *pbBold ? 1 : 0;
	
	if ( bckColor != -1 )
		trLinkStyle.Style.Fill.FillColor.nVal = bckColor;
	
	if (dwBorders)
	{
		TreeNode	trBorders = trLinkStyle.AddNode("Borders");
		table_theme_add_border(trBorders, "Left", (dwBorders & BORSTY_LEFT) != 0, nBorderColor);
		table_theme_add_border(trBorders, "Right", (dwBorders & BORSTY_RIGHT) != 0, nBorderColor);
		table_theme_add_border(trBorders, "Top", (dwBorders & BORSTY_TOP) != 0, nBorderColor);
		table_theme_add_border(trBorders, "Bottom", (dwBorders & BORSTY_BOTTOM) != 0, nBorderColor);
		table_theme_add_border(trBorders, "InsideVertical", (dwBorders & BORSTY_INSIDE_VERT) != 0, nBorderColor);
		table_theme_add_border(trBorders, "InsideHorizontal", (dwBorders & BORSTY_INSIDE_HORIZ) != 0, nBorderColor);
	}
	
	if (nPeriodRowwise || nPeriodColwise)
	{
		TreeNode	trRepeatInfos = tree_check_get_node(trLinkStyle, "RepeatInfos");
		if (nPeriodColwise)
		{
			TreeNode	trRepeatInfo = tree_check_get_node(trRepeatInfos, "Horizontal");
			table_style_set_repeat_dir(trRepeatInfo, nPeriodColwise);
		}
		if (nPeriodRowwise)
		{
			TreeNode	trRepeatInfo = tree_check_get_node(trRepeatInfos, "Vertical");
			table_style_set_repeat_dir(trRepeatInfo, nPeriodRowwise);
		}
	}
	
	if ( 0 <= nMerging )
	{
		trLinkStyle.Style.Merge.nVal = nMerging;
	}
	*/	
	
	table_theme_setup_style(trLinkStyle, pbBold, bckColor, dwBorders, nPeriodRowwise, nPeriodColwise, nBorderColor, nMerging);
	/// end SPECIAL_NAMES_STYLES_IN_FLAT_SHEETS
	
	return trLinkStyle;
}


//#define			REPEATED_BORDERS_COLOR		0x0100ff00
#define			REPEATED_BORDERS_COLOR		0
static	bool		custom_table_theme_set_repeated_borders(TreeNode &trParent, int &nStyleIndex, LPCSTR lpcszLink, bool bRowwise)
{
	string			strTblStyle = lpcszLink;
	int				nRowLnkStyleRef = bRowwise ? LNKSTLREF_DATA_ONLY : LNKSTLREF_LABEL_AND_DATA;
	int				nColLnkStyleRef = bRowwise ? LNKSTLREF_LABEL_AND_DATA : LNKSTLREF_DATA_ONLY;
	okutil_make_linkedstyle_offset_string(true, &strTblStyle, nRowLnkStyleRef, 0, -1, nColLnkStyleRef, 0, -1);

	int				nPeriodRowwise = bRowwise ? -1 : 0;
	int				nPeriodColwise = bRowwise ? 0 : -1;
	DWORD			dwBorders = bRowwise ? BORSTY_BOTTOM : BORSTY_RIGHT;
	table_theme_add_link_style(trParent, nStyleIndex++, strTblStyle, NULL, -1, dwBorders, nPeriodRowwise, nPeriodColwise, REPEATED_BORDERS_COLOR);

	return true;
}


static	bool		custom_table_theme_add_header_styles(TreeNode &trParent, int &nStyleIndex, LPCSTR lpcszLink, bool bRowHeader, int nHeadersColor = -1, bool bBold = true)
{
	bool			*pbBold = NULL;
	if (bBold)
		pbBold = &bBold;
	string			strTblStyle = lpcszLink;
	// Header labels of the linked table:
	int				nRowLnkStyleRef = bRowHeader ? LNKSTLREF_DATA_ONLY : LNKSTLREF_LABEL_ONLY;
	int				nColLnkStyleRef = bRowHeader ? LNKSTLREF_LABEL_ONLY : LNKSTLREF_DATA_ONLY;
	okutil_make_linkedstyle_offset_string(true, &strTblStyle, nRowLnkStyleRef, 0, -1, nColLnkStyleRef, 0, -1);
	int				nMerging = bRowHeader ? GMC_VERT : GMC_HORZ;
	table_theme_add_link_style(trParent, nStyleIndex++, strTblStyle, pbBold, nHeadersColor, 0, 0, 0, 0, nMerging);
	
	strTblStyle = lpcszLink;
	// We need additional style just for borders under or to the right of headers (they should extend through the entire length/width of the linked table):
	nRowLnkStyleRef = bRowHeader ? LNKSTLREF_LABEL_AND_DATA : LNKSTLREF_LABEL_ONLY;
	nColLnkStyleRef = bRowHeader ? LNKSTLREF_LABEL_ONLY : LNKSTLREF_LABEL_AND_DATA;
	okutil_make_linkedstyle_offset_string(true, &strTblStyle, nRowLnkStyleRef, 0, -1, nColLnkStyleRef, 0, -1);
	DWORD			dwBorders = bRowHeader ? BORSTY_RIGHT : BORSTY_BOTTOM;
	table_theme_add_link_style(trParent, nStyleIndex++, strTblStyle, NULL, -1, dwBorders);
	
	return true;
}

static	void		custom_table_theme_set_whole_table_link_styles(TreeNode &trParent, int &nStyleIndex, LPCSTR lpcszLink, int nHeadersColor = -1, bool bBoldHeaders = true, bool bRowwisePeriodic = false, bool bColwisePeriodic = false)
{
	custom_table_theme_add_header_styles(trParent, nStyleIndex, lpcszLink, true, nHeadersColor, bBoldHeaders);	
	custom_table_theme_add_header_styles(trParent, nStyleIndex, lpcszLink, false, nHeadersColor, bBoldHeaders);

	if (bRowwisePeriodic)
		custom_table_theme_set_repeated_borders(trParent, nStyleIndex, lpcszLink, true);
	if (bColwisePeriodic)
		custom_table_theme_set_repeated_borders(trParent, nStyleIndex, lpcszLink, false);
}


/// ML 4/28/2006 FRIENDLY_CUSTOM_TABLE_THEME_GENERATION
// virtual
int		FitterOperation::GetTableIdForGraph(string *pstr, TreeNode& trOp)
{
	bool			bEnabled = false;
	TreeNode		tr = GetOrCreateCustomTable(trOp, 0, &bEnabled);
	if( !tr.IsValid() || !bEnabled )
		return 0;

	int				nID = tr.ID;
	/// 
	if ( pstr )
	{
		*pstr = "RegrTable";
	}
	return nID;
}
/// end FRIENDLY_CUSTOM_TABLE_THEME_GENERATION


// virtual
// Returns the total count.
int		FitterOperation::GetStatisticsTablePropertiesForCustomTable(vector<int> &vn)
{
	int			nCount = 2;
	vn.SetSize(nCount);
	
	vn[0] = IDE_FIT_REDUCED_CHI_SQUARE;
	vn[1] = IDE_FIT_RSQUARE_COD;
	
	return nCount;
}


/// ML 7/20/2005 FITTING_FUNCTION_FORMULA_IN_REPORT
static	bool	make_one_whole_row_style(TreeNode &trRoot, LPCSTR lpcszLink, int &nLinkStyleIndex, bool *pbBold, int nHeadersColor)
{
	string			strLink = lpcszLink;
	// This makes a style string that will ensure two things:
	// The row labels part of the link should be bold accordign to pbBold and background colored with nHeadersColor.
	// Since it is row label, rowwise (i.e. down the rows) we want the style rectangle to occupy the data only area
	// (so that column labels, if any, are not affected), whereas columnwise we want labels only (since row labels
	// are in columns):
	okutil_make_linkedstyle_offset_string(true, &strLink, LNKSTLREF_DATA_ONLY, 0, -1, LNKSTLREF_LABEL_ONLY, 0, -1);
	
	// Add the style link to the tree (the border should be to the right):
	table_theme_add_link_style(trRoot, nLinkStyleIndex++, strLink, pbBold, nHeadersColor, BORSTY_RIGHT);
	
	return true;
}
/// end FITTING_FUNCTION_FORMULA_IN_REPORT



/**
		It creates a theme for the custom table for regressions.
	Parameters:
		treeTh=the tree to receive the theme.
		vnStatisticsTableProps=[optional] the IDs of the properties from the Statistics table to be added
								between the Input Data linked table and the Parameters linked table.
		nHeadersColor=the color (as OCOLOR) for the linked table headers background, or -1 for no color
		bBoldHeaders=whether the headers should be bold or not
	Returns:
		TRUE if OK.
*/
BOOL	make_regressions_custom_table_theme(TreeNode &treeTh, vector<int> &vnStatisticsTableProps, int nHeadersColor, bool bBoldHeaders)
{
	// Add the node "Root" as required by the table theme:
	TreeNode		trRoot = treeTh.AddNode("Root");
	
	bool			*pbBold = NULL;
	if (bBoldHeaders)
		pbBold = &bBoldHeaders;
	int				nAll = -1;
	
	// No grid lines:
	trRoot.Dimensions.Horizontal.GridLines.nVal = 0;
	trRoot.Dimensions.Vertical.GridLines.nVal = 0;
	
	// To allow merging globally in the table (this does not mean that
	// there will be merging; it still needs to be set separately for
	// a desired linkes style):
	trRoot.MergeCells.nVal = GMC_BOTH;

	///////////////////////////////////////////////////////////////////////////
	// All the cell values for a theme must be in string vector. We'll put all
	// the link values into one vector:
	/// ML 7/20/2005 FITTING_FUNCTION_FORMULA_IN_REPORT
	// int				nTotalRowsCount = 3;		// by default: Input Data Table, one empty row, Parameters Table
	int				nTotalRowsCount = 5;		// by default: Input Data Table, one empty row, equation, one empty row, Parameters Table
	/// end FITTING_FUNCTION_FORMULA_IN_REPORT
	int				nIndexInData = 0;			// this is to keep track where we are with the data
	
	vector<string>	vstrValues;
	vstrValues.SetSize(nTotalRowsCount);
	
	// Input Data table:
	string			strInputDataTbl;
	// Make a link string for the entire "Input Data" table:
	make_cell_link_to_whole_table(strInputDataTbl, IDST_REPORT_INPUT_TABLE);
	// Add to the vector of values:
	vstrValues[nIndexInData++] = strInputDataTbl;
	
	++nIndexInData;		// one empty row  (for aesthetic reasons) before the next stuff
	
	/// ML 7/20/2005 FITTING_FUNCTION_FORMULA_IN_REPORT
	string			strEquation;
	// Even though IDST_REPORT_NOTES is a 1D table, I can use make_cell_link_to_2D_table() to make a link
	// to one whole row of that table: 
	make_cell_link_to_2D_table(strEquation, IDST_REPORT_NOTES, IDE_NOTES_EQUATION, IDL_LABELS_AND_DATA, NULL, &nAll);
	vstrValues[nIndexInData++] = strEquation;
	++nIndexInData;		// one empty row  (for aesthetic reasons) before the next stuff
	/// end FITTING_FUNCTION_FORMULA_IN_REPORT
	
	int				nFromStatisticsTable = vnStatisticsTableProps ? vnStatisticsTableProps.GetSize() : 0;
	vector<string>	vstrFromStatsTable;	// here cache the links since we'll need them below for styles
	if (0 < nFromStatisticsTable)
	{
		vstrFromStatsTable.SetSize(nFromStatisticsTable);			// we need to cache the value links for later
		nTotalRowsCount += nFromStatisticsTable + 1;		// +1 is for another empty row after the Statistics props
		// Need to increase the vector for values since we are adding some rows from the Statistics table
		vstrValues.SetSize(nTotalRowsCount);
		for (int ii = 0; ii < nFromStatisticsTable; ii++)
		{
			string		strStatsLink;
			//string		strValue;
			int			nIDValue = vnStatisticsTableProps[ii];
			// Make a link to one whole row of the "Statistics" table (both row labels and data):
			make_cell_link_to_2D_table(strStatsLink, IDST_REG_STATS_RESULTS, IDL_LABELS_AND_DATA, nIDValue, NULL, &nAll);
			// Add the values:
			vstrValues[nIndexInData++] = strStatsLink;
			vstrFromStatsTable[ii] = strStatsLink;
		}
	
		++nIndexInData;		// one empty row before the next stuff
	}
	
	// Paramaters table:
	string			strParamsTbl;
	make_cell_link_to_whole_table(strParamsTbl, IDST_FIT_PARAMETER);
	// Add the value for the link for the entire Parameters table:	
	vstrValues[nIndexInData++] = strParamsTbl;

	// Now that the vector of values is ready, set it inot the theme:
	table_theme_set_vector(trRoot, 0, vstrValues);

	//////////////////////////////////
	// Now we need to set link styles.
	int				nLinkStyleIndex = 0;		// this keeps track pf the link styles index:
	// Make standard styles for the linked Input Data table and add to the tree:
	custom_table_theme_set_whole_table_link_styles(trRoot, nLinkStyleIndex, strInputDataTbl, nHeadersColor, bBoldHeaders);
	
	/// ML 7/20/2005 FITTING_FUNCTION_FORMULA_IN_REPORT
	// The styles for the Equation row from "Notes" table:
	//okutil_make_linkedstyle_offset_string(true, &strEquation, LNKSTLREF_DATA_ONLY, 0, -1, LNKSTLREF_LABEL_ONLY, 0, -1);
	//table_theme_add_named_style(trRoot, nLinkStyleIndex++, strEquation, pbBold, nHeadersColor, BORSTY_RIGHT);
	make_one_whole_row_style(trRoot, strEquation, nLinkStyleIndex, pbBold, nHeadersColor);
	/// end FITTING_FUNCTION_FORMULA_IN_REPORT

	
	// Styles for the Statistics parts:
	for (int ii = 0; ii < nFromStatisticsTable; ii++)
	{
		string			strLink = vstrFromStatsTable[ii];
		make_one_whole_row_style(trRoot, strLink, nLinkStyleIndex, pbBold, nHeadersColor);
	}
	
	// Finally, add te styles for the Params table (with the rowwise periodicity of borders to separate paramater values for
	// individual datasets):
	custom_table_theme_set_whole_table_link_styles(trRoot, nLinkStyleIndex, strParamsTbl, nHeadersColor, bBoldHeaders, true);
	
	return TRUE;
}



/// ML 6/1/2005 STYLE_LINKS_WITH_OFFSETS
// Set this to -1 if you don't want the color:
#define			TABLE_HEADERS_COLOR				0x01ffe0e0

// virtual
BOOL	FitterOperation::GetCustomTableDefaultTheme(TreeNode &treeTh)
{
	vector<int>		vnStatisticsTableProps;
	int				nNumStatsTblProps = GetStatisticsTablePropertiesForCustomTable(vnStatisticsTableProps);
	return make_regressions_custom_table_theme(treeTh, vnStatisticsTableProps, TABLE_HEADERS_COLOR);
	//return make_regressions_custom_table_theme(treeTh, NULL, TABLE_HEADERS_COLOR, false);
	/*
	TreeNode		trRoot = treeTh.AddNode("Root");
	
	bool			bBold = true;
	int				nAll = -1;
	
	// No grid lines:
	trRoot.Dimensions.Horizontal.GridLines.nVal = 0;
	trRoot.Dimensions.Vertical.GridLines.nVal = 0;
	
	// To allow merging globally in the table (this doers not mean that
	// there will be merging; it still needs to be set separately for
	// a desired linkes style):
	trRoot.MergeCells.nVal = GMC_BOTH;

	int				nTotalRowsCount = 3;		// by default: Input Data Table, one empty row, Parameters Table
	int				nIndexInData = 0;
	
	vector<string>	vstrFirstColumn;
	vstrFirstColumn.SetSize(nTotalRowsCount);
	
	// Input Data table:
	string			strInputDataTbl;
	make_cell_link_to_whole_table(strInputDataTbl, IDST_REPORT_INPUT_TABLE);
	vstrFirstColumn[nIndexInData++] = strInputDataTbl;
	
	++nIndexInData;		// one empty row before the next stuff
	
	vector<int>		vn;
	int				nFromStatisticsTable = GetStatisticsTablePropertiesForCustomTable(vn);
	vector<string>	vstrFromStatsTable;
	if (0 < nFromStatisticsTable)
	{
		vstrFromStatsTable.SetSize(nFromStatisticsTable);			// we need to cache the value links for later
		nTotalRowsCount += nFromStatisticsTable + 1;		// +1 is for another empty row after the Statistics props
		vstrFirstColumn.SetSize(nTotalRowsCount);
		for (int ii = 0; ii < nFromStatisticsTable; ii++)
		{
			string		strStatsLink;
			//string		strValue;
			int			nIDValue = vn[ii];
			make_cell_link_to_2D_table(strStatsLink, IDST_REG_STATS_RESULTS, IDL_LABELS_AND_DATA, nIDValue, NULL, &nAll);
			vstrFirstColumn[nIndexInData++] = strStatsLink;
			vstrFromStatsTable[ii] = strStatsLink;
		}
	
		++nIndexInData;		// one empty row before the next stuff
	}
	
	// Paramaters table:
	string			strParamsTbl;
	make_cell_link_to_whole_table(strParamsTbl, IDST_FIT_PARAMETER);
	
	vstrFirstColumn[nIndexInData++] = strParamsTbl;
	
	// Set the data vectors:
	table_theme_set_vector(trRoot, 0, vstrFirstColumn);

	int				nLinkStyleIndex = 0;
	// The styles for the Input Data table:
	custom_table_theme_set_whole_table_link_styles(trRoot, nLinkStyleIndex, strInputDataTbl);
	
	// Styles for the Satistics parts:
	for (int ii = 0; ii < nFromStatisticsTable; ii++)
	{
		string			strLink = vstrFromStatsTable[ii];
		okutil_make_linkedstyle_offset_string(true, &strLink, LNKSTLREF_DATA_ONLY, 0, -1, LNKSTLREF_LABEL_ONLY, 0, -1);
		table_theme_add_named_style(trRoot, nLinkStyleIndex++, strLink, &bBold, TABLE_HEADERS_COLOR, BORSTY_RIGHT);
	}
	
	// The styles for the Params table (with thw rowwise periodicity of borders to separate paramater values for
	// individual datasets):
	custom_table_theme_set_whole_table_link_styles(trRoot, nLinkStyleIndex, strParamsTbl, true);
	
	return TRUE;
	*/
}

/// end STYLE_LINKS_WITH_OFFSETS


/*
// virtual
BOOL	FitterOperation::GetCustomTableDefaultTheme(TreeNode &treeTh)
{
	/// ML 6/1/2005 STYLE_LINKS_WITH_OFFSETS
	return GetCustomTableDefaultTheme2(treeTh);
	/// end STYLE_LINKS_WITH_OFFSETS
	
	
	TreeNode	trRoot = treeTh.AddNode("Root");
	
	// No grid lines:
	trRoot.Dimensions.Horizontal.GridLines.nVal = 0;
	trRoot.Dimensions.Vertical.GridLines.nVal = 0;
	int			nLinkStyleIndex = 0;
	bool		bBold = true;
	
	int			nTotalRowsCount = 4;		// by default, for input data labels, and values, one empty row for aesthetics, and params
	int			nAll = -1;
	
	string		strLabelYSource;
	make_cell_link_to_2D_table(strLabelYSource, IDST_REPORT_INPUT_TABLE, IDL_BEGIN, IDE_INPUT_Y);
	
	string		strLabelXSource;
	make_cell_link_to_2D_table(strLabelXSource, IDST_REPORT_INPUT_TABLE, IDL_BEGIN, IDE_INPUT_X);

	int			nInputDataOneSet = make_one_set_ID(IDST_REPORT_INPUT_ONE_SET, 0);
	string		strYSources;
	make_cell_link_to_2D_table(strYSources, IDST_REPORT_INPUT_TABLE, nInputDataOneSet, IDE_INPUT_Y, &nAll);
	
	string		strXSources;
	make_cell_link_to_2D_table(strXSources, IDST_REPORT_INPUT_TABLE, nInputDataOneSet, IDE_INPUT_X, &nAll);
	
	int			nIndexInData = 0;
	vector<string>	vstrFirstColumn, vstrSecondColumn;
	vstrFirstColumn.SetSize(nTotalRowsCount);
	vstrSecondColumn.SetSize(nTotalRowsCount);
	vstrFirstColumn[nIndexInData] = strLabelYSource;
	vstrSecondColumn[nIndexInData] = strLabelXSource;
	++nIndexInData;
	vstrFirstColumn[nIndexInData] = strYSources;
	vstrSecondColumn[nIndexInData] = strXSources;
	// Leave index [2] empty for aesthetics
	nIndexInData += 2;
	
	vector<int>	vn;
	int			nFromStatisticsTable = GetStatisticsTablePropertiesForCustomTable(vn);
	vector<int>	vnStatsLabelsIndices;
	if (0 < nFromStatisticsTable)
	{
		vnStatsLabelsIndices.SetSize(nFromStatisticsTable);
		
		nTotalRowsCount += nFromStatisticsTable + 1;		// +1 for additional empty row after the props from statistics table
		vstrFirstColumn.SetSize(nTotalRowsCount);
		vstrSecondColumn.SetSize(nTotalRowsCount);
		for (int ii = 0; ii < nFromStatisticsTable; ii++)
		{
			string		strLabel;
			string		strValue;
			int			nIDValue = vn[ii];
			make_cell_link_to_2D_table(strLabel, IDST_REG_STATS_RESULTS, IDL_BEGIN, nIDValue);
			make_cell_link_to_2D_table(strValue, IDST_REG_STATS_RESULTS, make_one_set_ID(IDST_REG_STATS_ONE_SET, 0), nIDValue);
			
			vstrFirstColumn[nIndexInData] = strLabel;
			vstrSecondColumn[nIndexInData] = strValue;
			vnStatsLabelsIndices[ii] = nIndexInData;
			++nIndexInData;
			
			// Make the label bold:
		}
		
		++nIndexInData;		// an empty row
	}
	
	// Parameters:
	ASSERT(nIndexInData == nTotalRowsCount - 1);
	string		strParametersLabels;
	int			nIDParamsOneSet = make_one_set_ID(IDST_FIT_PARAMETER_ONE_SET, 0);
	make_cell_link_to_2D_table(strParametersLabels, IDST_FIT_PARAMETER, nIDParamsOneSet, IDL_BEGIN, &nAll, &nAll);
	
	string		strParamValues;
	make_cell_link_to_2D_table(strParamValues, IDST_FIT_PARAMETER, nIDParamsOneSet, IDE_PARAM_VALUE, &nAll);
	
	vstrFirstColumn[nIndexInData] = strParametersLabels;
	vstrSecondColumn[nIndexInData] = strParamValues;
	
	vector<string>	vstrThirdCol;
	vstrThirdCol.SetSize(nTotalRowsCount);
	// In the third column only error values:
	string		strErrorValues;
	make_cell_link_to_2D_table(strErrorValues, IDST_FIT_PARAMETER, nIDParamsOneSet, IDE_PARAM_ERROR, &nAll);
	vstrThirdCol[nIndexInData] = strErrorValues;
	
	// Finally set all the vectors:
	table_theme_set_vector(trRoot, 0, vstrFirstColumn);
	table_theme_set_vector(trRoot, 1, vstrSecondColumn);
	table_theme_set_vector(trRoot, 2, vstrThirdCol);
	
	// Set all the styles:
	table_theme_add_named_style(trRoot, nLinkStyleIndex++, strLabelYSource, &bBold);
	table_theme_add_named_style(trRoot, nLinkStyleIndex++, strLabelXSource, &bBold);
	for (int jj = 0; jj < nFromStatisticsTable; jj++)
	{
		int			ind = vnStatsLabelsIndices[jj];
		table_theme_add_named_style(trRoot, nLinkStyleIndex++, vstrFirstColumn[ind], &bBold);
	}
	table_theme_add_named_style(trRoot, nLinkStyleIndex++, strParametersLabels, &bBold);

	return TRUE;
}
*/

//--- CPY 9/22/05 QA70-8015-P15 USE_SET_REPORT_TREE_TO_INTERNALLY_PUT_TREE_INTO_FLAT_SHEET
/*
TreeNode FitterOperation::getFitCuvesTable(const TreeNode& trOp, int nDataIndex, int nTotalNumData)
{
	//////////////////
	TreeNode	trFit;
	TreeNode	trFitCuvesTable = FIT_CURVES_BRANCH(trOp);
	
	/// YuI 12/07/04 v7.5172 PICTURE_IN_REPORT_IMPROVEMENT
	if( nTotalNumData < 0 )
		nTotalNumData = GetTotalNumData(trOp);
	if( nTotalNumData <= 0 )
	{
		error_report("getFitCuvesTable failed");
		return trFit;
	}
	/// end PICTURE_IN_REPORT_IMPROVEMENT
	
	bool bHaveSubLevel = (1 < nTotalNumData);
	if (bHaveSubLevel)
	{
		string	strCuvTable = CALCULATION_FIT_CURVES_PREFIX;
		strCuvTable += (nDataIndex + 1);
		if(trFitCuvesTable)
			trFit = tree_check_get_node(trFitCuvesTable, strCuvTable);
	}
	else
	{
		ASSERT(0 == nDataIndex);
		trFit = trFitCuvesTable;
	}

	if(!trFit)
		error_report("getFitCuvesTable failed");
	
	return trFit;
}*/

///Cheney 2006-9-1 ADD_AVERAGE_DATA
bool FitterOperation::AddAveData(TreeNode& trOp, int nIndex, TreeNode& trFC, vector& vX, vector& vY)
{
	TreeNode trGraph = GetGUIGraphNodes(trOp, GRAPH_FIT_CURVE);
	if(!trGraph)
		return false;
	
	///Cheney/Iris 2006-9-4 AVE_REPLICA_DATA_IF_PLOTTYPE_EXIST_AND_NOT_RAW_DATA
	//if(!trGraph.PlotType)
		//return true;
	//
	//if(trGraph.PlotType.nVal == PLOT_TYPE_ROW_DATA)
		//return true;
	//if( !isPlotAverageData() )
		//return true;
	///end AVE_REPLICA_DATA_IF_PLOTTYPE_EXIST_AND_NOT_RAW_DATA
	
	vector vAveX, vAveY, vAveErr;
	///Cheney 2006-10-10 CONCATENATE_IS_ONE_METHOD_OF_AVERAGE
	if(trGraph.PlotType.nVal == PLOT_TYPE_RAW_DATA)
	{
		vAveX = vX;
		vAveY = vY;
	}
	else
	{
	///end CONCATENATE_IS_ONE_METHOD_OF_AVERAGE
		int nAveSize = vX.GetSize();	
		int nErrType = (trGraph.PlotType.nVal == PLOT_TYPE_MEAN_SE) ? AVMC_SE : AVMC_SD;
		
		///Cheney 2006-12-1 CLEAN_CODE	
		//if(!calReplicaData(vX, vY, nAveSize, vAveX, vAveY, vAveErr, nErrType))
		///Arvin 11/15/07 QA70-10619 KEEP_AVE_DATA_NODE_FOR_NULL_DATASET
		if(nAveSize != 0)			
		{
			///end 	KEEP_AVE_DATA_NODE_FOR_NULL_DATASET
			/// Iris 7/08/2008 CLEAN_DUP_CALC_AVE_DATA_CODE_IN_NLSF_PREVIEW_AND_OP			
			//if(!calReplicaData(vX, vY, nAveSize, vAveX, vAveY, &vAveErr, nErrType))
			if(!nlsf_calc_ave_data(vX, vY, nAveSize, vAveX, vAveY, vAveErr, nErrType))
			///end CLEAN_CODE
				return false;
			
			if(nAveSize == 0)
				return true;
		}///Arvin 11/15/07 QA70-10619 KEEP_AVE_DATA_NODE_FOR_NULL_DATASET
		
		///Cheney 2006-11-15 FIT_SHOULD_BY_RAW_DATA_AND_PLOT_TYPE_ONLY_WORK_FOR_GRAPH_DISPLAY
		////should set src data to ave data.
		//vX = vAveX;
		//vY = vAveY;
		///end FIT_SHOULD_BY_RAW_DATA_AND_PLOT_TYPE_ONLY_WORK_FOR_GRAPH_DISPLAY
	}
	
	///Arvin 11/15/07 QA70-10619 KEEP_AVE_DATA_NODE_FOR_NULL_DATASET
	//Avoid report sheet chaos
	if(vX.GetSize() == 0)
	{
		vAveX.Add(NANUM); 
		vAveY.Add(NANUM);
		vAveErr.Add(NANUM);
	}
	///end KEEP_AVE_DATA_NODE_FOR_NULL_DATASET
	TreeNode	trAveX = tree_check_get_node(trFC, "AveX", IDST_FIT_AVEX);
	trAveX.dVals = vAveX;
	trAveX.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_X);
	
	///Cheney 2007-10-27 CLEAN_UP_LOCALIZATION_THINGS
	//string strAveYLabel = "Concatenate data";
	//if(trGraph.PlotType.nVal == PLOT_TYPE_MEAN_SE)
		//strAveYLabel = "Mean, SE";
	//else if(trGraph.PlotType.nVal == PLOT_TYPE_MEAN_SD)
		//strAveYLabel = "Mean, SD";
	string strAveYLabel = _L("Concatenate data");
	if(trGraph.PlotType.nVal == PLOT_TYPE_MEAN_SE)
		strAveYLabel = _L("Mean, SE");
	else if(trGraph.PlotType.nVal == PLOT_TYPE_MEAN_SD)
		strAveYLabel = _L("Mean, SD");
	///end CLEAN_UP_LOCALIZATION_THINGS
	TreeNode	trAveY = tree_check_get_node(trFC, "AveY", IDST_FIT_AVEY, STR_LABEL_ATTRIB, strAveYLabel);	
	trAveY.dVals = vAveY;
	trAveY.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
	///Arvin 05/29/07 CONCATENATE_HAS_NOT_YERR_WHEN_PLOT_TYPE_IS_RAW_DATA
	if(trGraph.PlotType.nVal == PLOT_TYPE_RAW_DATA)
		return true;
	///end CONCATENATE_HAS_NOT_YERR_WHEN_PLOT_TYPE_IS_RAW_DATA
	TreeNode	trAveErr = tree_check_get_node(trFC, "AveErr", IDST_FIT_AVEERR);	
	trAveErr.dVals = vAveErr;
	trAveErr.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_ERROR);
	
	return true;
}
///end ADD_AVERAGE_DATA

/// Iris 7/08/2008 CLEAN_DUP_CALC_AVE_DATA_CODE_IN_NLSF_PREVIEW_AND_OP
/*
///Cheney 2006-12-1 CLEAN_CODE	
///Cheney 2006-8-31 ADD_AVERAGE_DATA_TABLE
//bool FitterOperation::calReplicaData(vector& vX, vector& vY, int nAveSize, vector& vAveX, vector& vAveY, vector& vAveErr, int nErrType)
bool FitterOperation::calReplicaData(vector& vX, vector& vY, int nAveSize, vector& vAveX, vector& vAveY, vector* pvAveErr, int nErrType)
///end CLEAN_CODE
{
	vAveX.SetSize(nAveSize);
	vAveY.SetSize(nAveSize);
	vector vAveErr; ///Cheney 2006-12-1 CLEAN_CODE	
	vAveErr.SetSize(nAveSize);
	
	OneCurveData *multiCruveData = (OneCurveData*)malloc(sizeof(OneCurveData));
	if (NULL == multiCruveData)
		return false;
	
	if(!_get_multi_curves_data(vX, vY, multiCruveData))
		return false;
	
	int nNumCurve = 1;
	int nRet = ocmath_ave_replica_data_for_multiple_curves(nNumCurve, multiCruveData, &nAveSize, vAveX, vAveY, vAveErr, nErrType);
	
	free(multiCruveData[0].pX);
	free(multiCruveData[0].pY);
	free(multiCruveData);
	
	if(nRet != OE_NOERROR)
		return false;

	vAveX.SetSize(nAveSize);
	vAveY.SetSize(nAveSize);
	///Cheney 2006-12-1 CLEAN_CODE	
	if(pvAveErr != NULL)
	{
		*pvAveErr = vAveErr;
		pvAveErr->SetSize(nAveSize);
	}
	//vAveErr.SetSize(nAveSize);	
	///end CLEAN_CODE
	
	return true;
}
///end ADD_AVERAGE_DATA_TABLE
*/
///end CLEAN_DUP_CALC_AVE_DATA_CODE_IN_NLSF_PREVIEW_AND_OP


///Cheney 2006-9-1 GET_MULTICURVE_DATA_FOR_AVE_REPLICA
static bool _get_multi_curves_data(vector& vX, vector& vY, OneCurveData *multiCruveData)
{
	int	nDataSize = vY.GetSize();
	if (vX.GetSize() < nDataSize)
		nDataSize = vX.GetSize();
	
	double *px = (double*)malloc(sizeof(double) * nDataSize);
	double *py = (double*)malloc(sizeof(double) * nDataSize);
	if (NULL == px || NULL == py)
		return false;
	
	memcpy(px, vX, sizeof(double)*nDataSize);
	memcpy(py, vY, sizeof(double)*nDataSize);
	
	multiCruveData[0].nSize = nDataSize;
	multiCruveData[0].pX = px;
	multiCruveData[0].pY = py;
	
	return true;
}
///end GET_MULTICURVE_DATA_FOR_AVE_REPLICA


/// ML 9/20/2006 RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT
/*
bool FitterOperation::AddResidualsDataTable(TreeNode &trOp, int index, int nTotalNumData, const string &strDataLabel, FitParameter *psFitParameter, vector &vX, vector &vY, matrix &mMultiIndep)
{
	TreeNode trResidual = GetGUIGraphNodes(trOp, GRAPH_RESIDUALS_SCATTER);
	if(trResidual && 0 != trResidual.nVal)
	{
		vector vRe, vFitY;
		if( !getResidualData(trOp, index, psFitParameter, vX, vY, vFitY, vRe, mMultiIndep))
			return false;	
		
		AddGraphDataOneTable(trOp, index, nTotalNumData, strDataLabel, "ResidualData", 
				"Residuals vs. Independent Variable - Data", IDST_FIT_RESIDUALS_SCATTER, IDST_REPORT_RESIDUAL_SCATTER_ONE_SET, vX, "X", vRe, "Residuals", GRAPH_RESIDUALS_SCATTER, false);
	}
	return true;	
}


bool FitterOperation::AddResidualHistogramTable(TreeNode &trOp, int index, int nTotalNumData, const string &strDataLabel, FitParameter *psFitParameter, vector &vX, vector &vY, matrix &mXs)
{	
	TreeNode trResidual = GetGUIGraphNodes(trOp, GRAPH_RESIDUALS_HISTOGRAM);
	if(trResidual && 0 != trResidual.nVal)
	{
		vector 	vRe, vFitY;
		if( !getResidualData(trOp, index, psFitParameter, vX, vY, vFitY, vRe, mXs))
			return false;		
	
		vector 	vRowNum;
		vRowNum.Data(1, vRe.GetSize(), 1);
		
		AddGraphDataOneTable(trOp, index, nTotalNumData, strDataLabel, STR_RESIDUALS_HISTOGRAM_TABLE, 
				"Histogram of the Residuals", IDST_FIT_RESIDUALS_DATA, IDST_REPORT_RESIDUAL_HISTOGRAM_ONE_SET, vRowNum, "Frequency", vRe, "Residual", GRAPH_RESIDUALS_HISTOGRAM, false);
	}
	return true;		
	
}
*/
/// end RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT

/// ML 9/20/2006 RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT
//bool FitterOperation::getResidualData(TreeNode &trOp, int index, FitParameter *psFitParameter, const vector &vX, const vector &vY, vector& vFitY, vector &vResidual, const matrix &mXs)
// vFitY may be returned transformed back to real space if apparent.
///Arvin 01/17/06 CALC_RESIDUAL_WITH_REPLICA
//bool FitterOperation::getResidualData(TreeNode &trOp, int index, FitParameter *psFitParameter, const vector &vX, const vector &vY, vector& vFitY, vector &vResidual, const matrix &mXs, GraphLayer &grLayAppar)
bool FitterOperation::getResidualData(TreeNode &trOp, int index, FitParameter *psFitParameter, const vector &vX, const vector &vY, vector& vFitY, vector &vResidual, const matrix &mXs, GraphLayer &grLayAppar, int nPeak)
///------
/// end RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT
{
	//TreeNode	trFitY;
	///Arvin 01/17/06 CALC_RESIDUAL_WITH_REPLICA
	//if( !MakeFitY(index, trOp, vX, vFitY, psFitParameter, mXs))
	if( !MakeFitY(index, trOp, vX, vFitY, psFitParameter, mXs, nPeak))
	///end CALC_RESIDUAL_WITH_REPLICA
		return error_report("getResidualData, fail to Make FitY");
	
	if(vY.GetSize() != vFitY.GetSize())
		return error_report("getResidualData, the size of vY is not same as the size of vFitY");
	
	vResidual.SetSize(vFitY.GetSize());
	/// ML 9/20/2006 RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT
	//vResidual = vY - vFitY;
	if (grLayAppar)
	{
		vector		vYTransf(vY.GetSize());
		//vYTransf = vY;
		vector		*pvY;
		if ( grLayAppar.ConvertByAxis(vY, vY.GetSize(), OKAXISTYPE_Y, FALSE, vYTransf) )
			pvY = &vYTransf;
		else
			pvY = &vY;
		
		grLayAppar.ConvertByAxis(vFitY, vFitY.GetSize(), OKAXISTYPE_Y, FALSE);
		vResidual = *pvY - vFitY;
	}
	else
		vResidual = vY - vFitY;
	/// end RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT
	
	return true;
	
}

bool FitterOperation::getResidualData(TreeNode &trOp, int index, FitParameter *psFitParameter, matrix &mXs, matrix &mYs, matrix &mFitYs, matrix &mResiduals)
{
	if( !MakeFitY(trOp, mXs, mFitYs, index) )
		return error_report("getResidualData, fail to Make FitY");
	
	if(mYs.GetNumCols() != mFitYs.GetNumCols() || mYs.GetNumRows() != mFitYs.GetNumRows())
		return error_report("getResidualData, the size of mYs is not same as the size of mFitYs");
	
	mResiduals.SetSize(mYs.GetNumRows(), mYs.GetNumCols());
	
	///Cheney 2007-5-28 IF_EMPTY_DATA_SET_SHOULD_SET_MISSING_AS_RESULT	
	if(mYs.GetNumRows() > 0 && mYs.GetNumCols() > 0)
		mResiduals = mYs - mFitYs;
	else
		mResiduals.SetSize(mYs.GetNumRows(), mYs.GetNumCols());
	///end IF_EMPTY_DATA_SET_SHOULD_SET_MISSING_AS_RESULT
	
	return true;
}

/// ML 9/20/2006 RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT
/*
bool FitterOperation::AddResidualFitTable(TreeNode &trOp, int index, int nTotalNumData, const string &strDataLabel, FitParameter *psFitParameter, vector &vX, vector &vY, matrix &mXs)
{
	TreeNode trResidual = GetGUIGraphNodes(trOp, GRAPH_RESIDUALS_VERSUS_FITS_PLOT);
	if(trResidual && 0 != trResidual.nVal)
	{
		vector vRe, vFitY;
		if( !getResidualData(trOp, index, psFitParameter, vX, vY, vFitY, vRe, mXs))
			return false;
		
		AddGraphDataOneTable(trOp, index, nTotalNumData, strDataLabel, STR_RESIDUALS_FIT_GRAPH_TABLE, "Residuals vs. Predicted Values", IDST_FIT_RESIDUALS_VERSUS_FITS_DATA,
			IDST_REPORT_RESIDUAL_FIT_ONE_SET, vFitY, "Fit", vRe, "Residual", GRAPH_RESIDUALS_VERSUS_FITS_PLOT, false);
	}
	return true;		
}	

bool FitterOperation::AddResidualOrderTable(TreeNode &trOp, int index, int nTotalNumData, const string &strDataLabel, FitParameter *psFitParameter, vector &vX, vector &vY, matrix &mXs)
{
	TreeNode trResidual = GetGUIGraphNodes(trOp, GRAPH_RESIDUALS_VERSUS_ORDER_PLOT);
	if(trResidual && 0 != trResidual.nVal)
	{
		vector vRe, vFitY;
		if( !getResidualData(trOp, index, psFitParameter, vX, vY, vFitY, vRe, mXs))
			return false;
		
		vector 	vOrder;
		vOrder.Data(1, vRe.GetSize(), 1);
		
		AddGraphDataOneTable(trOp, index, nTotalNumData, strDataLabel, STR_RESIDUALS_ORDER_GRAPH_TABLE, "Residuals vs. the Order of the Data", IDST_FIT_RESIDUALS_VERSUS_ORDER_DATA,
			IDST_REPORT_RESIDUAL_ORDER_ONE_SET, vOrder, "Order", vRe, "Residual", GRAPH_RESIDUALS_VERSUS_ORDER_PLOT, false);
	}	
	return true;
}	

///Jim 2/22/06 v8.0368 ADD_RESIDUAL_LAG_PLOT_TO_RESIDUALS_PLOTS_BRANCH
bool FitterOperation::AddResidualLagTable(TreeNode &trOp, int index, int nTotalNumData, const string &strDataLabel, FitParameter *psFitParameter, vector &vX, vector &vY, matrix &mXs)
{
	TreeNode trResidual = GetGUIGraphNodes(trOp, GRAPH_RESIDUALS_LAG_PLOT);
	if(trResidual && 0 != trResidual.nVal)
	{
		vector vRe, vFitY;
		if( !getResidualData(trOp, index, psFitParameter, vX, vY, vFitY, vRe, mXs))
			return false;
		
		vector 	vReX;
		vReX = vRe;
		vReX.RemoveAt(vReX.GetSize()-1);
		vRe.RemoveAt(0);
			
		AddGraphDataOneTable(trOp, index, nTotalNumData, strDataLabel, STR_RESIDUALS_LAG_GRAPH_TABLE, "Residuals Lag Plot", IDST_FIT_RESIDUALS_LAG_DATA,
			IDST_REPORT_RESIDUAL_LAG_ONE_SET, vReX, "Residual(I-1)", vRe, "Residual", GRAPH_RESIDUALS_LAG_PLOT, false);
	}
	return true;
}
//END ADD_RESIDUAL_LAG_PLOT_TO_RESIDUALS_PLOTS_BRANCH
*/
/// end RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT

/// ML 9/20/2006 RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT
bool	FitterOperation::GUIHasResidualTable(TreeNode &trOp, int nGraphIndex)
{
	TreeNode	trTbl = GetGUIGraphNodes(trOp, nGraphIndex);
	//------ Folger 03/12/08 FIXED_RUNTIME_ERROR_WHEN_TRTBL_IS_TREE_BRANCH
	//if (trTbl && 0 != trTbl.nVal)
		//return true;
	if ( trTbl && trTbl.Show != 0 )		//if attribute "Show" not exist, then get -1 default to show
	{
		if ( trTbl.FirstNode && trTbl.Use != 0 || !trTbl.FirstNode && trTbl.nVal != 0 )
			return true;
	}
	//------
	
	return false;
}
///Arvin 12/11/06 ADD_RESIDUAL_ANALYSIS_FOR_FITTING
bool FitterOperation::GetAllTypeResidualData(const TreeNode &trOp, const vector& vX, const vector& vRegularRes, vector& vStand, vector& vStud, vector& vStudDel, int index, int nPeak, vector &vY, vector &vWeights, matrix &mXs)
{
	///Arvin 01/17/06 CALC_RESIDUAL_WITH_REPLICA
	/*
	if(GetOneTypeResidualData(trOp, vX, vRegularRes, vStand, index, nPeak, STANDARDIZED_RESIDUAL, vY, vWeights, mXs)&&
		GetOneTypeResidualData(trOp, vX, vRegularRes, vStud, index, nPeak, STUDENTIZED_RESIDUAL, vY, vWeights, mXs)&&
		GetOneTypeResidualData(trOp, vX, vRegularRes, vStudDel, index, nPeak, STUDENTIZED_DELETED_RESIDUAL, vY, vWeights, mXs))
		return true;
	*/
	///end CALC_RESIDUAL_WITH_REPLICA
	return false;
}

///Arvin 01/17/06 CALC_RESIDUAL_WITH_REPLICA
bool FitterOperation::GetCumRegularResidualData(const TreeNode &trOp, const vector& vX, const vector &vY, FitParameter *psFitParameter, vector& vCumRegular, vector& vFitY, int index, int nMultiplicity, vector &vWeights, matrix &mXs, GraphLayer &grLayAppar, matrix& mResiduals)
{
	double 	dY0 = psFitParameter[0].Value; 
	for(int ii=0; ii<nMultiplicity; ii++)
	{
		vector vRe, vTempFitY;
		if(!getResidualData(trOp, index, psFitParameter, vX, vY, vTempFitY, vRe, mXs, grLayAppar, ii))
			return false;
		
		if(vFitY.GetSize() == 0)
			vFitY.SetSize(vFitY.GetSize());
		vFitY += vTempFitY;
		
		if(vCumRegular.GetSize() == 0)
			vCumRegular.SetSize(vFitY.GetSize());
		vCumRegular += vRe;
		
		if(mResiduals.GetNumRows() == 0)
			mResiduals.SetSize(vFitY.GetSize(), nMultiplicity);
		if(vRe.GetSize() > 0)///Cheney 2007-5-28 IF_EMPTY_DATA_SET_SHOULD_SET_MISSING_AS_RESULT	
			mResiduals.SetColumn(vRe, ii);
	}
	
	///------ Folger 03/23/09 PA_FAILS_TO_MAKE_CORRECT_RESIDUAL_PLOT_WHEN_HAS_ONLY_ONE_PEAK
	if ( nMultiplicity > 1 )
	{
	///------ End PA_FAILS_TO_MAKE_CORRECT_RESIDUAL_PLOT_WHEN_HAS_ONLY_ONE_PEAK
		vFitY -= dY0*(nMultiplicity-1);
		vector vy(vY.GetSize()), vTemp(vY.GetSize());
		vy = dY0*(nMultiplicity-1);
		vTemp = vY;
		vTemp *= (nMultiplicity-1);
		vy -= vTemp;
		if(vCumRegular.GetSize() > 0)///Cheney 2007-5-28 IF_EMPTY_DATA_SET_SHOULD_SET_MISSING_AS_RESULT
			vCumRegular += vy;
	}		///------ Folger 03/23/09 PA_FAILS_TO_MAKE_CORRECT_RESIDUAL_PLOT_WHEN_HAS_ONLY_ONE_PEAK
	
	return true;
}

bool FitterOperation::GetDiffCumResidualData(const TreeNode &trOp, const vector& vX, const vector &vY, const matrix& mRegular, FitParameter *psFitParameter, vector& vStand, vector& vStud, vector& vStudDel, int index, int nMultiplicity, vector &vWeights, matrix &mXs)
{
	double 	dY0 = psFitParameter[0].Value; 
	for(int ii=0; ii<nMultiplicity; ii++)
	{
		vector vRe;
		mRegular.GetColumn(vRe, ii);
		if(vStand.GetSize() == 0)
		{
			vStand.SetSize(vRe.GetSize());
			vStand = NANUM;
		}
		if(vStud.GetSize() == 0)
		{
			vStud.SetSize(vRe.GetSize());
			vStud = NANUM;
		}
		if(vStudDel.GetSize() == 0)
		{
			vStudDel.SetSize(vRe.GetSize());
			vStudDel = NANUM;
		}
		vector vTempStand, vTempStud, vTempStudDel;
		if(GetAllTypeResidualData(trOp, vX, vRe, vTempStand, vTempStud, vTempStudDel, index, ii, vY, vWeights, mXs))
		{
			vStand += vTempStand;
			vStud += vTempStud;
			vStudDel += vTempStudDel;
		}
		else
			return false;
	}
	
	vector vy(vY.GetSize()), vTemp(vY.GetSize());
	vy = dY0*(nMultiplicity-1);
	vTemp = vY;
	vTemp *= (nMultiplicity-1);
	vy -= vTemp;
	vStand += vy;
	vStud += vy;
	vStudDel += vy;	
	
	return true;		
}
///end CALC_RESIDUAL_WITH_REPLICA

bool	FitterOperation::GUIHasWhatTypeResidualTables(TreeNode &trOp, int nResType)
{
	/// Iris 10/29/2009 QA81-14546 OP_DLG_NEW_STRUCTURE
	//TreeNode trResAnalysis = trOp.GUI.ResAnalysis;
	TreeNode trResAnalysis = OP_GUI_RESIDUAL_ANALYSIS_BRANCH(trOp.GUI);
	///end OP_DLG_NEW_STRUCTURE
	//--- Iris 3/16/2009 QA80-13285-P1 FIX_DUPLICATE_RESIDUAL_DATA_REPORT_FOR_DIFF_RESIDUAL_REPORT_AND_PLOT
	//if(!trResAnalysis)
	if(!trResAnalysis || !trResAnalysis.Show)
	//---
		return false;
	
	///Arvin 01/18/06 CALC_RESIDUAL_WITH_REPLICA
	//We can not do residual analysis for muti-peak fitting, so disable it temporarily
	/*
	switch(nResType)
	{
	case REGULAR_RESIDUAL:
		if(0 != trResAnalysis.Regular.nVal)
			return true;
		break;
	case STANDARDIZED_RESIDUAL:
		if(0 != trResAnalysis.Stad.nVal)
			return true;
		break;
	case STUDENTIZED_RESIDUAL:
		if(0 != trResAnalysis.Stud.nVal)
			return true;
		break;
	case STUDENTIZED_DELETED_RESIDUAL:
		if(0 != trResAnalysis.StudDel.nVal)
			return true;
		break;
	}
	*/
	TreeNode trRegular = trResAnalysis.Regular;
	TreeNode trStad = trResAnalysis.Stad;
	TreeNode trStud = trResAnalysis.Stud;
	TreeNode trStudDel = trResAnalysis.StudDel; 
	///Arvin 10/23/07 QA70-10559-P3 SHOULD_NOT_CREATE_EMPTY_SHEET_WHEN_UNCHECK_ALL_RESIDUALS_CHECK_BOX
	bool bRegular, bStad, bStud, bStudDel;
	bRegular	= trRegular.Enable && trRegular.nVal;
	bStad		= trStad.Enable && trStad.nVal;
	bStud		= trStud.Enable && trStud.nVal;
	bStudDel	= trStudDel.Enable && trStudDel.nVal;
	///end SHOULD_NOT_CREATE_EMPTY_SHEET_WHEN_UNCHECK_ALL_RESIDUALS_CHECK_BOX
	switch(nResType)
	{
	case REGULAR_RESIDUAL:
		///Arvin 10/23/07 QA70-10559-P3 SHOULD_NOT_CREATE_EMPTY_SHEET_WHEN_UNCHECK_ALL_RESIDUALS_CHECK_BOX
		//if(trRegular.Enable && trRegular.nVal)
		//	return true;
		//break;
		return bRegular;
		///end SHOULD_NOT_CREATE_EMPTY_SHEET_WHEN_UNCHECK_ALL_RESIDUALS_CHECK_BOX
	case STANDARDIZED_RESIDUAL:
		///Arvin 10/23/07 QA70-10559-P3 SHOULD_NOT_CREATE_EMPTY_SHEET_WHEN_UNCHECK_ALL_RESIDUALS_CHECK_BOX
		//if(trStad.Enable && trStad.nVal)
		//	return true;
		//break;
		return bStad;
		///end SHOULD_NOT_CREATE_EMPTY_SHEET_WHEN_UNCHECK_ALL_RESIDUALS_CHECK_BOX
	case STUDENTIZED_RESIDUAL:
		///Arvin 10/23/07 QA70-10559-P3 SHOULD_NOT_CREATE_EMPTY_SHEET_WHEN_UNCHECK_ALL_RESIDUALS_CHECK_BOX
		//if(trStud.Enable && trStud.nVal)
		//	return true;
		//break;
		return bStud;
		///end SHOULD_NOT_CREATE_EMPTY_SHEET_WHEN_UNCHECK_ALL_RESIDUALS_CHECK_BOX
	case STUDENTIZED_DELETED_RESIDUAL:
		///Arvin 10/23/07 QA70-10559-P3 SHOULD_NOT_CREATE_EMPTY_SHEET_WHEN_UNCHECK_ALL_RESIDUALS_CHECK_BOX
		//if(trStudDel.Enable && trStudDel.nVal)
		//	return true;
		//break;
		return bStudDel;
		///end SHOULD_NOT_CREATE_EMPTY_SHEET_WHEN_UNCHECK_ALL_RESIDUALS_CHECK_BOX
	///Arvin 10/23/07 QA70-10559-P3 SHOULD_NOT_CREATE_EMPTY_SHEET_WHEN_UNCHECK_ALL_RESIDUALS_CHECK_BOX
	case ANY_TYPE_RESIDUAL:
		return (bRegular || bStad || bStud || bStudDel)
	default:
		return false;
	///end 	SHOULD_NOT_CREATE_EMPTY_SHEET_WHEN_UNCHECK_ALL_RESIDUALS_CHECK_BOX
	}
	///end CALC_RESIDUAL_WITH_REPLICA
	
	return false;
}
///Arvin 02/13/07 ADD_X_DATA_TO_RESIDUAL_DATA_TABLE by max's suggestion
bool FitterOperation::AddXDataTable(TreeNode &trTable, vector& vX)
{
	int nSubTableID = make_one_set_ID(IDST_FIT_RESIDUAL_ANALYSIS, 0);
	LPCSTR lpcszDataLabel = STR_REPORT_X_COL_LONG_NAME;
	string strTagRow = "X";
	
	TreeNode trCol = tree_check_get_node(trTable, strTagRow, nSubTableID, STR_LABEL_ATTRIB, lpcszDataLabel);
	if(vX.GetSize() > 0)
		trCol.dVals = vX;
	else
		trCol.dVals = NANUM;
	
	trCol.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_X);
	//--- Iris 3/16/2009 QA80-13285-P2 CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
	// subHeader attribute will be put into Column Parameters label when do report, not good, so remove
	//tree_add_one_label(trCol, lpcszLabel, 0);
	//---end CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
	
	return true;	
}
///end ADD_X_DATA_TO_RESIDUAL_DATA_TABLE

//--- Iris 3/16/2009 QA80-13285-P2 CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
//bool FitterOperation::AddDiffTypeResidualDataTable(TreeNode &trTable, vector& vRe, int nResType)
bool FitterOperation::AddDiffTypeResidualDataTable(TreeNode &trTable, LPCSTR lpcszDataLabel, vector& vRe, int nResType)
//---
{
	int nSubTableID = make_one_set_ID(IDST_FIT_RESIDUAL_ANALYSIS, nResType+1);
	///Cheney 2007-10-27 CLEAN_UP_LOCALIZATION_THINGS
	//LPCSTR lpcszLabel = "Different Type Residual Data"; 
	//LPCSTR lpcszLabel = _L("Different Type Residual Data");  //--- Iris 3/16/2009 QA80-13285-P2 CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
	///end CLEAN_UP_LOCALIZATION_THINGS
	//LPCSTR lpcszDataLabel;//--- Iris 3/16/2009 QA80-13285-P2 CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS, centralize code
	/*
	switch(nResType)
	{
	case REGULAR_RESIDUAL:
		strTagRow = "ResRegular";
		break;
	case STANDARDIZED_RESIDUAL:
		strTagRow = "ResStand";
		break;
	case STUDENTIZED_RESIDUAL:
		strTagRow = "ResStud";
		break;
	case STUDENTIZED_DELETED_RESIDUAL:
		strTagRow = "ResSudDel";
		break;
	}	
	*/
	string strTagRow = GetDiffResidualDataTableTagName(nResType);
	string strDataLabel = GetResidualDataTableYDataLabel(nResType, lpcszDataLabel);
	
	//addOneColToResultCurveTable(trTable, vRe, lpcszTableSubLabel, lpcszYLabel, nSubTableID, 1, OKDATAOBJ_DESIGNATION_Y);
	
	TreeNode trCol = tree_check_get_node(trTable, strTagRow, nSubTableID, STR_LABEL_ATTRIB, strDataLabel);
	if(vRe.GetSize() > 0)
		trCol.dVals = vRe;
	else
		///Cheney 2007-5-28 IF_EMPTY_DATA_SET_SHOULD_SET_MISSING_AS_RESULT	
		//return false;
		trCol.dVals = NANUM;
		///end IF_EMPTY_DATA_SET_SHOULD_SET_MISSING_AS_RESULT
	
	trCol.SetAttribute(STR_COL_DESIGNATION_ATTRIB, OKDATAOBJ_DESIGNATION_Y);
	//--- Iris 3/16/2009 QA80-13285-P2 CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
	// subHeader attribute will be put into Column Parameters label when do report, not good, so remove
	//tree_add_one_label(trCol, lpcszLabel, 0);
	//---end CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
	
	return true;	
}
///Arvin 01/18/06 CALC_RESIDUAL_WITH_REPLICA
//We can not do residual analysis for muti-peak fitting, so disable it temporarily
/*	
bool FitterOperation::GetOneTypeResidualData(const TreeNode &trOp, const vector& vX, const vector &vY, FitParameter *psFitParameter, vector& vResidual, int nResType, int index, int nMultiplicity, vector &vWeights, matrix &mXs, GraphLayer &grLayAppar)
{
	vector vRe, vFitY, vStand, vStud, vStudDel;
	if(nMultiplicity > 1)
	{
		matrix mRegular;
		if(!GetCumRegularResidualData(trOp, vX, vY, psFitParameter, vRe, vFitY, index, nMultiplicity, vWeights, mXs, grLayAppar, mRegular))
			return false;
		
		if(nResType == REGULAR_RESIDUAL)
		{
			vResidual = vRe;
			return true;
		}
		
		if(!GetDiffCumResidualData(trOp, vX, vY, mRegular, psFitParameter, vStand, vStud, vStudDel, index, nMultiplicity, vWeights, mXs))
			return false;
	
	}
	else
	{
		if(!getResidualData(trOp, index, psFitParameter, vX, vY, vFitY, vRe, mXs, grLayAppar))
			return false;
		
		if(nResType == REGULAR_RESIDUAL)
		{
			vResidual = vRe;
			return true;
		}
		
		if(!GetAllTypeResidualData(trOp, vX, vRe, vStand, vStud, vStudDel, index, 0, vY, vWeights, mXs))
			return false;
	}
	
	switch(nResType)
	{
	case STANDARDIZED_RESIDUAL:
		vResidual = vStand;
		break;
	case STUDENTIZED_RESIDUAL:
		vResidual = vStud;
		break;
	case STUDENTIZED_DELETED_RESIDUAL:
		vResidual = vStudDel;
		break;
	}
		
	return true;
}
*/
bool FitterOperation::GetOneTypeResidualData(const TreeNode &trOp, const vector& vX, const vector& vRegularRes, vector& vResidual, int index, int nPeak, int nResType, vector &vY, vector &vWeights, matrix &mXs)
{
	if(nResType == REGULAR_RESIDUAL)
	{
		vResidual = vRegularRes;
		return true;
	}
	vector vStand, vStud, vStudDel;
	if(GetAllTypeResidualData(trOp, vX, vRegularRes, vStand, vStud, vStudDel, index, nPeak, vY, vWeights, mXs))
	{
		switch(nResType)
		{
		case STANDARDIZED_RESIDUAL:
			vResidual = vStand;
			break;
		case STUDENTIZED_RESIDUAL:
			vResidual = vStud;
			break;
		case STUDENTIZED_DELETED_RESIDUAL:
			vResidual = vStudDel;
			break;
		}
		
		return true;
	}
	
	return false;
}
///end CALC_RESIDUAL_WITH_REPLICA	
int	FitterOperation::GUIHasWhatTypeResidualGraph(TreeNode &trOp)
{
	///Arvin 01/18/06 CALC_RESIDUAL_WITH_REPLICA
	/*
	TreeNode trResidual = trOp.GUI.Residuals;
	if(trResidual)
		return trResidual.ResType.nVal;
	*/
	/// Iris 11/02/2009 QA81-14546 OP_DLG_NEW_STRUCTURE
	//TreeNode trResType = trOp.GUI.Residuals.ResType;
	TreeNode trResType = OP_GUI_BRANCH_OF_RESIDUAL_PLOTS_CHECKBOX(trOp.GUI).ResType;
	///end OP_DLG_NEW_STRUCTURE
	if(trResType)
	{
		if(trResType.Enable)
			return trResType.nVal;
		else
			return 0;
	}
	///end CALC_RESIDUAL_WITH_REPLICA
	return -1;
}
///end ADD_RESIDUAL_ANALYSIS_FOR_FITTING

//--- Iris 3/16/2009 QA80-13285-P1 FIX_DUPLICATE_RESIDUAL_DATA_REPORT_FOR_DIFF_RESIDUAL_REPORT_AND_PLOT
bool FitterOperation::UseResidualAnalysisDataReportForPlotting(TreeNode &trOp, int* pnYIndex)
{
	int			nGraphResidualType = GUIHasWhatTypeResidualGraph(trOp);
	bool		bRes = GUIHasWhatTypeResidualTables(trOp, nGraphResidualType);
	if( bRes )
	{
		// if pnYIndex is not NULL, then to check and return Y column index of relative residual type in residual data table 
		if(pnYIndex)
		{
			*pnYIndex = -1;
			for(int iType = REGULAR_RESIDUAL; iType <= nGraphResidualType; iType++)
			{
				if( GUIHasWhatTypeResidualTables(trOp, iType) )
					(*pnYIndex)++;				
			}
		}
		return true;		
	}
	return false;
}
//---FIX_DUPLICATE_RESIDUAL_DATA_REPORT_FOR_DIFF_RESIDUAL_REPORT_AND_PLOT
string FitterOperation::GetDiffResidualDataTableTagName(int nResType)
{
	string strTagRow;
	switch(nResType)
	{
	case REGULAR_RESIDUAL:
		strTagRow = "ResRegular";
		break;
	case STANDARDIZED_RESIDUAL:
		strTagRow = "ResStand";
		break;
	case STUDENTIZED_RESIDUAL:
		strTagRow = "ResStud";
		break;
	case STUDENTIZED_DELETED_RESIDUAL:
		strTagRow = "ResSudDel";
		break;
	}	
	return strTagRow;
}
string FitterOperation::GetResidualDataTableYDataLabel(int nResType, LPCSTR lpcszDataLabel)
{
	string str;
	switch(nResType)
	{
	case REGULAR_RESIDUAL:
		str = _LC("Regular Residual", STR_CAT_STATS);
		break;
	case STANDARDIZED_RESIDUAL:
		str = _L("Standardized Residual");
		break;
	case STUDENTIZED_RESIDUAL:
		str = _L("Studentized Residual");
		break;
	case STUDENTIZED_DELETED_RESIDUAL:
		str = _L("Studentized Deleted Residual");
		break;
	}
	if( NULL == lpcszDataLabel ) // if lpcszDataLabel is NULL will result without data postfix.
		return str;
	
	/// Iris 3/23/2009 QA80-13331-P1 CENTRILIZE_REPORT_COL_LABEL_CODES
	//string strLabel = str + " " + _L("of") + " " + lpcszDataLabel;
	string strLabel = ConstructReportDataColLabel(str, lpcszDataLabel);
	///end CENTRILIZE_REPORT_COL_LABEL_CODES
	return strLabel;
}

///Arvin 12/11/06 ADD_RESIDUAL_ANALYSIS_FOR_FITTING
//virtual bool FitterOperation::AddResidualTables(bool bDataTbl, TreeNode &trOp, int index, int nTotalNumData, const string &strDataLabel, FitParameter *psFitParameter, vector &vX, vector &vY, matrix &mXs, GraphLayer &grLayAppar)
///Arvin 01/17/06 CALC_RESIDUAL_WITH_REPLICA
//virtual bool FitterOperation::AddResidualTables(bool bDataTbl, TreeNode &trOp, int index, int nTotalNumData, const string &strDataLabel, FitParameter *psFitParameter, vector &vX, vector &vY, matrix &mXs, GraphLayer &grLayAppar, vector& vWeights)
///Arvin 06/07/07 CENTRALIZE_FITTING_RESULT_LABELS as max's suggestion
//virtual bool FitterOperation::AddResidualTables(bool bDataTbl, TreeNode &trOp, int index, int nTotalNumData, const string &strDataLabel, FitParameter *psFitParameter, vector &vX, vector &vY, matrix &mXs, GraphLayer &grLayAppar, vector& vWeights, int nMultiplicity)
virtual bool FitterOperation::AddResidualTables(bool bDataTbl, TreeNode &trOp, int index, int nTotalNumData, const string &strDataLabel, FitParameter *psFitParameter, vector &vX, vector &vY, matrix &mXs, GraphLayer &grLayAppar, vector& vWeights, int nMultiplicity, LPCSTR lpcsDataLabelCurves)
///end CENTRALIZE_FITTING_RESULT_LABELS
///------
///end ADD_RESIDUAL_ANALYSIS_FOR_FITTING
{
	/// Iris 02/06/2007 JUST_OUTPUT_FIT_DATA_ONLY_ASK_FIT_PLOT
	/*
	//--- Iris 9/27/06 KEEP_RESULT_DATA_EVEN_THOUGH_NOT_PLOT
	//bool		bResDataTbl = bDataTbl && GUIHasResidualTable(trOp, GRAPH_RESIDUALS_SCATTER);
	bool		bResDataTbl = bDataTbl;
	//--- 
	*/
	bool		bResDataTbl = bDataTbl && GUIHasResidualTable(trOp, GRAPH_RESIDUALS_SCATTER);
	///end JUST_OUTPUT_FIT_DATA_ONLY_ASK_FIT_PLOT
	///Arvin 06/07/07 CENTRALIZE_FITTING_RESULT_LABELS as max's suggestion
	string 		strDataLabelCurve = strDataLabel;
	if(lpcsDataLabelCurves)
		strDataLabelCurve = lpcsDataLabelCurves;
	///end CENTRALIZE_FITTING_RESULT_LABELS
	
	string	strConvertedDataLabel(strDataLabel);
	///------ Folger 03/24/09 QA80-13331-P1 CUSTOMIZED_OUTPUT_COLUMN_LONGNAME_FORMAT_SUPPORT
	//ConvertEscapedString(strConvertedDataLabel);
	MakeFullRangeEscapeString(strConvertedDataLabel);
	///------ End CUSTOMIZED_OUTPUT_COLUMN_LONGNAME_FORMAT_SUPPORT
		
	///Arvin 12/11/06 ADD_RESIDUAL_ANALYSIS_FOR_FITTING
	bool		bResRegular = GUIHasWhatTypeResidualTables(trOp, REGULAR_RESIDUAL);
	bool		bResStand = GUIHasWhatTypeResidualTables(trOp, STANDARDIZED_RESIDUAL);
	bool		bResStud = GUIHasWhatTypeResidualTables(trOp, STUDENTIZED_RESIDUAL);
	bool		bResStudDel = GUIHasWhatTypeResidualTables(trOp, STUDENTIZED_DELETED_RESIDUAL);
	///-------
	bool		bResHist = GUIHasResidualTable(trOp, GRAPH_RESIDUALS_HISTOGRAM);
	bool		bResFit = GUIHasResidualTable(trOp, GRAPH_RESIDUALS_VERSUS_FITS_PLOT);
	bool		bResOrder = GUIHasResidualTable(trOp, GRAPH_RESIDUALS_VERSUS_ORDER_PLOT);
	bool		bResLag = GUIHasResidualTable(trOp, GRAPH_RESIDUALS_LAG_PLOT);
	///Arvin 12/11/06 ADD_RESIDUAL_ANALYSIS_FOR_FITTING
	//if (bResDataTbl || bResHist || bResFit || bResOrder || bResLag)
	if (bResRegular || bResStand || bResStud || bResStudDel || bResDataTbl || bResHist || bResFit || bResOrder || bResLag)
	///------- 
	{
		///Arvin 01/17/06 CALC_RESIDUAL_WITH_REPLICA
		/*
		vector vRe, vFitY;
		if(!getResidualData(trOp, index, psFitParameter, vX, vY, vFitY, vRe, mXs, grLayAppar))
			return false;
		///Arvin 12/11/06 ADD_RESIDUAL_ANALYSIS_FOR_FITTING
		vector vStand, vStud, vStudDel;
		int nResGraphType = GUIHasWhatTypeResidualGraph(trOp);
		if(bResStand || bResStud || bResStudDel || nResGraphType>0) 
		{
			if(!GetAllTypeResidualData(trOp, vX, vRe, vStand, vStud, vStudDel, index, 0, vY, vWeights, mXs))
				error_report("Can not get selected type residual data!");
		}
		*/
		vector vRe, vFitY, vStand, vStud, vStudDel;
		int nResGraphType = GUIHasWhatTypeResidualGraph(trOp);
		///------ Folger 03/23/09 PA_FAILS_TO_MAKE_CORRECT_RESIDUAL_PLOT_WHEN_HAS_ONLY_ONE_PEAK
		//if(nMultiplicity > 1)
		//{
			//matrix mRegular;
			//if(!GetCumRegularResidualData(trOp, vX, vY, psFitParameter, vRe, vFitY, index, nMultiplicity, vWeights, mXs, grLayAppar, mRegular))
				//return false;
			////We can not do residual analysis for muti-peak fitting, so disable it temporarily
			///*
			//if(bResStand || bResStud || bResStudDel || nResGraphType>0) 
			//{
				//if(!GetDiffCumResidualData(trOp, vX, vY, mRegular, psFitParameter, vStand, vStud, vStudDel, index, nMultiplicity, vWeights, mXs))
					//error_report("Can not get selected type residual data!");
			//}
			//*/
		//}
		//else
		//{
			//if(!getResidualData(trOp, index, psFitParameter, vX, vY, vFitY, vRe, mXs, grLayAppar))
				//return false;
		//}
		matrix mRegular;
		if ( !GetCumRegularResidualData(trOp, vX, vY, psFitParameter, vRe, vFitY, index, nMultiplicity, vWeights, mXs, grLayAppar, mRegular) )
			return false;
		//if(bResStand || bResStud || bResStudDel || nResGraphType>0) 
		//{
			//if(!GetDiffCumResidualData(trOp, vX, vY, mRegular, psFitParameter, vStand, vStud, vStudDel, index, nMultiplicity, vWeights, mXs))
				//error_report("Can not get selected type residual data!");
		//}
		///------ End PA_FAILS_TO_MAKE_CORRECT_RESIDUAL_PLOT_WHEN_HAS_ONLY_ONE_PEAK
	
		if(bResStand || bResStud || bResStudDel || nResGraphType>0) 
		{
			if(!GetAllTypeResidualData(trOp, vX, vRe, vStand, vStud, vStudDel, index, 0, vY, vWeights, mXs))
			{
				///Arvin 05/23/07 v8.0624 EMPTY_DATA_SET_RUNTIME_ERROR
				//vStand.SetSize(vRe.GetSize()); vStud.SetSize(vRe.GetSize()); vStudDel.SetSize(vRe.GetSize());
				//vStand = NANUM; vStud = NANUM; vStudDel = NANUM;
				//error_report("Can not get selected type residual data!");
				if(vRe.GetSize() > 0)
				{
					vStand.SetSize(vRe.GetSize()); vStud.SetSize(vRe.GetSize()); vStudDel.SetSize(vRe.GetSize());
					vStand = NANUM; vStud = NANUM; vStudDel = NANUM;
					error_report("Can not get selected type residual data!");
				}
				///end EMPTY_DATA_SET_RUNTIME_ERROR
			}
		}
		///end CALC_RESIDUAL_WITH_REPLICA
		if(bResRegular || bResStand || bResStud || bResStudDel)
		{			
			//--- Iris 3/16/2009 QA80-13285-P2 CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
			//TreeNode trTable = CheckCreateOneResultCurvesTable(trOp, index, nTotalNumData, GRAPH_RESIDUALS_SCATTER, STR_DIFF_RESIDUALS_DATA_TABLE, IDST_FIT_RESIDUAL_ANALYSIS, _L("Residuals"), strDataLabelCurve);
			TreeNode trTable = CheckCreateOneResultCurvesTable(trOp, index, nTotalNumData, GRAPH_RESIDUALS_SCATTER, STR_DIFF_RESIDUALS_DATA_TABLE, IDST_FIT_RESIDUAL_ANALYSIS, GetResidualDataTableLabel(), strDataLabelCurve);
			//---CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
			
			///Arvin 02/13/07 ADD_X_DATA_TO_RESIDUAL_DATA_TABLE by max's suggestion
			///Kyle 03/18/2009 QA80-13305 FIX_APPARENT_LINEAR_FIT_OUTPUT_WRONG_X_VALUES_FOR_RESIDUAL
			//AddXDataTable(trTable, vX);
			if(grLayAppar)
			{
				vector vXTemp; vXTemp = vX;
				_covert_vector_apparent(vXTemp, grLayAppar, OKAXISTYPE_X);
				AddXDataTable(trTable, vXTemp);
			}
			else
				AddXDataTable(trTable, vX);
			///End FIX_APPARENT_LINEAR_FIT_OUTPUT_WRONG_X_VALUES_FOR_RESIDUAL
			///end ADD_X_DATA_TO_RESIDUAL_DATA_TABLE
			///Sophy 1/15/2009 v8.0957 QA80-12918 FITCURVE_X_COLULMN_FORMAT_MUST_BE_CONSISTENT_WITH_SOURCE_DATA
			string strResidualX = "X";
			TreeNode trX = trTable.GetNode(strResidualX);
			if ( trX )
			{
				UpdateOneXColumnFormat(trX, index); //only one x column	
			}
			///end FITCURVE_X_COLULMN_FORMAT_MUST_BE_CONSISTENT_WITH_SOURCE_DATA

			if(	bResRegular)
				AddDiffTypeResidualDataTable(trTable, strConvertedDataLabel, vRe, REGULAR_RESIDUAL);
			
			if(	bResStand)
				AddDiffTypeResidualDataTable(trTable, strConvertedDataLabel, vStand, STANDARDIZED_RESIDUAL);
		
			if(	bResStud)
				AddDiffTypeResidualDataTable(trTable, strConvertedDataLabel, vStud, STUDENTIZED_RESIDUAL);
			
			if(	bResStudDel)
				AddDiffTypeResidualDataTable(trTable, strConvertedDataLabel, vStudDel, STUDENTIZED_DELETED_RESIDUAL);
				
		}
	
		switch(nResGraphType)
		{
		case STANDARDIZED_RESIDUAL:
			vRe = vStand;
			break;
		case STUDENTIZED_RESIDUAL:
			vRe = vStud;
			break;
		case STUDENTIZED_DELETED_RESIDUAL:
			vRe = vStudDel;
			break;
		}
		
   		vector 	vRowNum;
		///Arvin 05/23/07 v8.0624 EMPTY_DATA_SET_RUNTIME_ERROR
		//if (bResHist || bResOrder)
		if ( (bResHist || bResOrder) && vRe.GetSize() > 0)
		///end EMPTY_DATA_SET_RUNTIME_ERROR
			vRowNum.Data(1, vRe.GetSize(), 1);
		
		//--- Iris 3/16/2009 QA80-13285-P2 CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
		/*
		string	strConvertedDataLabel(strDataLabel);
		ConvertEscapedString(strConvertedDataLabel);
		///Cheney 2007-10-27 CLEAN_UP_LOCALIZATION_THINGS
		//strConvertedDataLabel = "Residual of " + strConvertedDataLabel;
		strConvertedDataLabel = _L("Residual of") + " " + strConvertedDataLabel;
		///end CLEAN_UP_LOCALIZATION_THINGS
		*/
		strConvertedDataLabel = GetResidualDataTableYDataLabel(nResGraphType, strConvertedDataLabel);
		string strTableLabel = GetResidualDataTableLabel(); // keep Parameters label of report table is empty
		string strTableSubLabel = GetResidualDataTableYDataSubLabel();
		//---CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS

		//--- Iris 3/16/2009 QA80-13285-P1 FIX_DUPLICATE_RESIDUAL_DATA_REPORT_FOR_DIFF_RESIDUAL_REPORT_AND_PLOT		
		//if(bResDataTbl)
		if( bResDataTbl  && !UseResidualAnalysisDataReportForPlotting(trOp))
		//---
		{
			vector		vxTransf(vX.GetSize());
			vector		*pvxUse;
			if (grLayAppar && grLayAppar.ConvertByAxis(vX, vX.GetSize(), OKAXISTYPE_X, FALSE, vxTransf))
				pvxUse = &vxTransf;
			else
				pvxUse = &vX;
			///Arvin 06/07/07 CENTRALIZE_FITTING_RESULT_LABELS as max's suggestion
			//AddGraphDataOneTable(trOp, index, nTotalNumData, strDataLabel, "ResidualData", strTableLabel,
			//	"Residual vs. Independent Variable", IDST_FIT_RESIDUALS_SCATTER, IDST_REPORT_RESIDUAL_SCATTER_ONE_SET, *pvxUse, "Independent Variable", vRe, strConvertedDataLabel, GRAPH_RESIDUALS_SCATTER, false);
			//--- Iris 3/16/2009 QA80-13285-P2 CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
			// subHeader attribute will be put into Column Parameters label when do report, not good, so remove
			/*
			AddGraphDataOneTable(trOp, index, nTotalNumData, strDataLabelCurve, STR_RESIDUALS_DATA_TABLE, strTableLabel,
				_L("Residual vs. Independent Variable"), IDST_FIT_RESIDUALS_SCATTER, IDST_REPORT_RESIDUAL_SCATTER_ONE_SET, *pvxUse, _L("Independent Variable"), vRe, strConvertedDataLabel, GRAPH_RESIDUALS_SCATTER, false);
			*/
			AddGraphDataOneTable(trOp, index, nTotalNumData, strDataLabelCurve, STR_RESIDUALS_DATA_TABLE, strTableLabel,
				strTableSubLabel, IDST_FIT_RESIDUALS_SCATTER, IDST_REPORT_RESIDUAL_SCATTER_ONE_SET, *pvxUse, STR_REPORT_X_COL_LONG_NAME, vRe, strConvertedDataLabel, GRAPH_RESIDUALS_SCATTER, false);
			//---end CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
			///end CENTRALIZE_FITTING_RESULT_LABELS
		}
		///Arvin 10/23/06 FITTING_RESIDUALS_HISTOGRAM_PLOT_CENTRALIZED
		/*
		if (bResHist)
			AddGraphDataOneTable(trOp, index, nTotalNumData, strDataLabel, STR_RESIDUALS_HISTOGRAM_TABLE, 
					"Histogram of the Residuals", IDST_FIT_RESIDUALS_DATA, IDST_REPORT_RESIDUAL_HISTOGRAM_ONE_SET, vRowNum, "Frequency", vRe, "Residual", GRAPH_RESIDUALS_HISTOGRAM, false);
		*/
		if (bResHist)
			///Arvin 06/07/07 CENTRALIZE_FITTING_RESULT_LABELS as max's suggestion
			//AddGraphDataOneTable(trOp, index, nTotalNumData, strDataLabel, STR_RESIDUALS_HISTOGRAM_TABLE, strTableLabel,
					//"Histogram of the Residual", IDST_FIT_RESIDUALS_DATA, IDST_REPORT_RESIDUAL_HISTOGRAM_ONE_SET, NULL, NULL, vRe, strConvertedDataLabel, GRAPH_RESIDUALS_HISTOGRAM, false);
			//--- Iris 3/16/2009 QA80-13285-P2 CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
			/*
			AddGraphDataOneTable(trOp, index, nTotalNumData, strDataLabelCurve, STR_RESIDUALS_HISTOGRAM_TABLE, strTableLabel,
					_L("Histogram of the Residual"), IDST_FIT_RESIDUALS_DATA, IDST_REPORT_RESIDUAL_HISTOGRAM_ONE_SET, NULL, NULL, vRe, strConvertedDataLabel, GRAPH_RESIDUALS_HISTOGRAM, false);
			*/
			AddGraphDataOneTable(trOp, index, nTotalNumData, strDataLabelCurve, STR_RESIDUALS_HISTOGRAM_TABLE, strTableLabel,
					strTableSubLabel, IDST_FIT_RESIDUALS_DATA, IDST_REPORT_RESIDUAL_HISTOGRAM_ONE_SET, NULL, NULL, vRe, strConvertedDataLabel, GRAPH_RESIDUALS_HISTOGRAM, false);
			//---end CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
			///end CENTRALIZE_FITTING_RESULT_LABELS
			///end FITTING_RESIDUALS_HISTOGRAM_PLOT_CENTRALIZED
		
		if (bResFit)
			///Arvin 06/07/07 CENTRALIZE_FITTING_RESULT_LABELS as max's suggestion
			//AddGraphDataOneTable(trOp, index, nTotalNumData, strDataLabel, STR_RESIDUALS_FIT_GRAPH_TABLE, strTableLabel, "Residual vs. Predicted Values", IDST_FIT_RESIDUALS_VERSUS_FITS_DATA,
				//IDST_REPORT_RESIDUAL_FIT_ONE_SET, vFitY, "Fitted Y", vRe, strConvertedDataLabel, GRAPH_RESIDUALS_VERSUS_FITS_PLOT, false);
			//--- Iris 3/16/2009 QA80-13285-P2 CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
			/*
			AddGraphDataOneTable(trOp, index, nTotalNumData, strDataLabelCurve, STR_RESIDUALS_FIT_GRAPH_TABLE, strTableLabel, _L("Residual vs. Predicted Values"), IDST_FIT_RESIDUALS_VERSUS_FITS_DATA,
				IDST_REPORT_RESIDUAL_FIT_ONE_SET, vFitY, _L("Fitted Y"), vRe, strConvertedDataLabel, GRAPH_RESIDUALS_VERSUS_FITS_PLOT, false);
			*/
			AddGraphDataOneTable(trOp, index, nTotalNumData, strDataLabelCurve, STR_RESIDUALS_FIT_GRAPH_TABLE, strTableLabel, 
					strTableSubLabel, IDST_FIT_RESIDUALS_VERSUS_FITS_DATA,  IDST_REPORT_RESIDUAL_FIT_ONE_SET, vFitY, _L("Fitted Y"), vRe, strConvertedDataLabel, GRAPH_RESIDUALS_VERSUS_FITS_PLOT, false);
			//---end CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
			
			///end CENTRALIZE_FITTING_RESULT_LABELS
			if (bResOrder)	// the same values as bResHist 
			///Arvin 06/07/07 CENTRALIZE_FITTING_RESULT_LABELS as max's suggestion
			//AddGraphDataOneTable(trOp, index, nTotalNumData, strDataLabel, STR_RESIDUALS_ORDER_GRAPH_TABLE, strTableLabel, "Residual vs. the Order of the Data", IDST_FIT_RESIDUALS_VERSUS_ORDER_DATA,
				//IDST_REPORT_RESIDUAL_ORDER_ONE_SET, vRowNum, "Order", vRe, strConvertedDataLabel, GRAPH_RESIDUALS_VERSUS_ORDER_PLOT, false);
			//--- Iris 3/16/2009 QA80-13285-P2 CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
			/*
			AddGraphDataOneTable(trOp, index, nTotalNumData, strDataLabelCurve, STR_RESIDUALS_ORDER_GRAPH_TABLE, strTableLabel, _L("Residual vs. the Order of the Data"), IDST_FIT_RESIDUALS_VERSUS_ORDER_DATA,
				IDST_REPORT_RESIDUAL_ORDER_ONE_SET, vRowNum, _L("Order"), vRe, strConvertedDataLabel, GRAPH_RESIDUALS_VERSUS_ORDER_PLOT, false);
			*/
			AddGraphDataOneTable(trOp, index, nTotalNumData, strDataLabelCurve, STR_RESIDUALS_ORDER_GRAPH_TABLE, strTableLabel, 
					strTableSubLabel, IDST_FIT_RESIDUALS_VERSUS_ORDER_DATA, IDST_REPORT_RESIDUAL_ORDER_ONE_SET, vRowNum, _L("Order"), vRe, strConvertedDataLabel, GRAPH_RESIDUALS_VERSUS_ORDER_PLOT, false);
			//---end CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
			
			///end CENTRALIZE_FITTING_RESULT_LABELS
		if (bResLag)
		{
			vector 	vReX;
			///Arvin 05/23/07 v8.0624 EMPTY_DATA_SET_RUNTIME_ERROR
			//vReX = vRe;
			//vReX.RemoveAt(vReX.GetSize()-1);
			//vRe.RemoveAt(0);
			if(vRe.GetSize() > 0)
			{
				vReX = vRe;
				vReX.RemoveAt(vReX.GetSize()-1);
				vRe.RemoveAt(0);
			}
			///end EMPTY_DATA_SET_RUNTIME_ERROR
			///Arvin 06/07/07 CENTRALIZE_FITTING_RESULT_LABELS as max's suggestion
			//AddGraphDataOneTable(trOp, index, nTotalNumData, strDataLabel, STR_RESIDUALS_LAG_GRAPH_TABLE, strTableLabel, "Residual Lag Plot", IDST_FIT_RESIDUALS_LAG_DATA,
				//IDST_REPORT_RESIDUAL_LAG_ONE_SET, vReX, "Residual(I-1)", vRe, strConvertedDataLabel, GRAPH_RESIDUALS_LAG_PLOT, false);
			//--- Iris 3/16/2009 QA80-13285-P2 CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
			/*
			AddGraphDataOneTable(trOp, index, nTotalNumData, strDataLabelCurve, STR_RESIDUALS_LAG_GRAPH_TABLE, strTableLabel, _L("Residual Lag Plot"), IDST_FIT_RESIDUALS_LAG_DATA,
				IDST_REPORT_RESIDUAL_LAG_ONE_SET, vReX, _L("Residual(I-1)"), vRe, strConvertedDataLabel, GRAPH_RESIDUALS_LAG_PLOT, false);
			*/
			AddGraphDataOneTable(trOp, index, nTotalNumData, strDataLabelCurve, STR_RESIDUALS_LAG_GRAPH_TABLE, strTableLabel, 
					strTableSubLabel, IDST_FIT_RESIDUALS_LAG_DATA, IDST_REPORT_RESIDUAL_LAG_ONE_SET, vReX, _L("Residual(I-1)"), vRe, strConvertedDataLabel, GRAPH_RESIDUALS_LAG_PLOT, false);
			//---end CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
			
			///end CENTRALIZE_FITTING_RESULT_LABELS
		}
	}

	return true;
}
/// end RESIDUAL_TABLES_CONSOLIDATION_AND_APPARENT_FIT
///Arvin 06/07/07 CENTRALIZE_FITTING_RESULT_LABELS as max's suggestion
//bool	FitterOperation::AddResidualTables(bool bDataTbl, TreeNode &trOp, int index, int nTotalNumData, const string &strDataLabel, FitParameter *psFitParameter, matrix &mXs, matrix &mYs)
bool	FitterOperation::AddResidualTables(bool bDataTbl, TreeNode &trOp, int index, int nTotalNumData, const string &strDataLabel, FitParameter *psFitParameter, matrix &mXs, matrix &mYs, LPCSTR lpcsDataLabelCurves)
///end CENTRALIZE_FITTING_RESULT_LABELS
{
	bool		bResDataTbl = bDataTbl;
	//--- 
	bool		bResHist = GUIHasResidualTable(trOp, GRAPH_RESIDUALS_HISTOGRAM);
	bool		bResFit = GUIHasResidualTable(trOp, GRAPH_RESIDUALS_VERSUS_FITS_PLOT);
	bool		bResOrder = GUIHasResidualTable(trOp, GRAPH_RESIDUALS_VERSUS_ORDER_PLOT);
	bool		bResLag = GUIHasResidualTable(trOp, GRAPH_RESIDUALS_LAG_PLOT);
	int nResType = REGULAR_RESIDUAL; // hardcode here since Multi Indep & Multi Dep case not support choose residual analysis method in Residual Plot branch, so use its default method.

	///Arvin 06/07/07 CENTRALIZE_FITTING_RESULT_LABELS as max's suggestion
	string 		strDataLabelCurve = strDataLabel;
	if(lpcsDataLabelCurves)
		strDataLabelCurve = lpcsDataLabelCurves;
	///end CENTRALIZE_FITTING_RESULT_LABELS
	if (bResDataTbl || bResHist || bResFit || bResOrder || bResLag)
	{
		matrix	mFitYs, mResiduals;
		if( !getResidualData(trOp, index, psFitParameter, mXs, mYs, mFitYs, mResiduals) )
			return false;
		
		if(bResDataTbl)
		{
			string	strConvertedDataLabel(strDataLabel);
			ConvertEscapedString(strConvertedDataLabel);
			///Arvin 06/07/07 CENTRALIZE_FITTING_RESULT_LABELS as max's suggestion
			//AddGraphDataOneTable(trOp, index, nTotalNumData, strDataLabel, "ResidualData", "Residuals",
			//	"Residual vs. Independent Variable", IDST_FIT_RESIDUALS_SCATTER, IDST_REPORT_RESIDUAL_SCATTER_ONE_SET, mXs, "Independent Variable", mResiduals, "Residual of " + strConvertedDataLabel, GRAPH_RESIDUALS_SCATTER);
			//--- Iris 3/16/2009 QA80-13285-P2 CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
			/*
			AddGraphDataOneTable(trOp, index, nTotalNumData, strDataLabelCurve, "ResidualData", "Residuals",
				"Residual vs. Independent Variable", IDST_FIT_RESIDUALS_SCATTER, IDST_REPORT_RESIDUAL_SCATTER_ONE_SET, mXs, "Independent Variable", mResiduals, "Residual of " + strConvertedDataLabel, GRAPH_RESIDUALS_SCATTER);
			*/
			AddGraphDataOneTable(trOp, index, nTotalNumData, strDataLabelCurve, "ResidualData", "Residuals",
				GetResidualDataTableYDataSubLabel(), IDST_FIT_RESIDUALS_SCATTER, IDST_REPORT_RESIDUAL_SCATTER_ONE_SET, mXs, STR_REPORT_X_COL_LONG_NAME, mResiduals, GetResidualDataTableYDataLabel(nResType, strConvertedDataLabel), GRAPH_RESIDUALS_SCATTER);
			//---end CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
		}
		///end CENTRALIZE_FITTING_RESULT_LABELS
	}
	return true;
}

//--- CPY 9/22/05 QA70-8015-P15 USE_SET_REPORT_TREE_TO_INTERNALLY_PUT_TREE_INTO_FLAT_SHEET
/*
TreeNode FitterOperation::getOneResidualTable(const TreeNode& trOp, int nDataIndex, int nTotalNumData, int nGraphIndex)
{
	TreeNode trSubTable;
	TreeNode trCalc = trOp.Calculation;
	if( !trCalc )
	{
		error_report("Fail to get Calculation node in getOneResidualTable");
		return trSubTable;
	}
	
	string strTable;
	switch(nGraphIndex)
	{
	case GRAPH_RESIDUALS_SCATTER:
		strTable = "ResidualData";
		break;
	case GRAPH_RESIDUALS_HISTOGRAM:
		strTable = STR_RESIDUALS_HISTOGRAM_TABLE;
		break;
	case GRAPH_RESIDUALS_VERSUS_FITS_PLOT:
		strTable = STR_RESIDUALS_FIT_GRAPH_TABLE;
		break;
	case GRAPH_RESIDUALS_VERSUS_ORDER_PLOT:
		strTable = STR_RESIDUALS_ORDER_GRAPH_TABLE;
		break;
	default:
		break;
	}
	
	TreeNode trTable = trCalc.GetNode(strTable);		
	
	if( nTotalNumData <= 0 )
		nTotalNumData = GetTotalNumData(trOp);
	if( nTotalNumData <= 0 )
	{
		error_report("nTotalNumData is less and equal 0 in getOneResidualTable");
		return trSubTable;
	}
		
	bool bHaveSubLevel = (1 < nTotalNumData);
	if (bHaveSubLevel)
	{
		string	strCuvTable = CALCULATION_RESIDUAL_GRAPH_PREIX;
		strCuvTable += (nDataIndex + 1);
		if(trTable)
			trSubTable = tree_check_get_node(trTable, strCuvTable);
	}
	else
	{
		ASSERT(0 == nDataIndex);
		trSubTable = trTable;
	}

	///Iris noneed report this since there is not residual table for xyz data
	//if(!trSubTable)
	//	error_report("Fail to get graph table in getOneResidualTable");
	
	return trSubTable;
}
*/

//--- Iris 3/16/2009 QA80-13285-P1 FIX_DUPLICATE_RESIDUAL_DATA_REPORT_FOR_DIFF_RESIDUAL_REPORT_AND_PLOT
BOOL	FitterOperation::GetResultTableData(TreeNode& trOp, int nResultTableID, int nDataIndex, int nGraphIndex, DataRange& drTable, DataRange& drFitCurvesRange)
{		
	if( !StatsOpBase::GetResultTableData(trOp, nResultTableID, nDataIndex, nGraphIndex, drTable, drFitCurvesRange) )
		return error_report("Error in StatsOpBase::GetResultTableData");
	
	// for Residual Scatter type, if already report result in Residual Analysis Data table, then no need report again, just use this data for report graph.
	int nYIndexInResidualDataTable;
	if( GRAPH_RESIDUALS_SCATTER == nGraphIndex && UseResidualAnalysisDataReportForPlotting(trOp, &nYIndexInResidualDataTable) )
	{
		// put all types of residual analysis data into one table and shared same X col, need to find one Y column for residual graph
		Worksheet wks;
		int c1, c2;
		drTable.GetRange(wks, c1, c2);
		
		int nXCol = c1;
		int nYCol = c1+nYIndexInResidualDataTable+1;
		ASSERT( nYCol<=c2 );
		
		DataRange drOneTypeResidual;
		drOneTypeResidual.Add(wks, nXCol, "X");
		drOneTypeResidual.Add(wks, nYCol, "Y");
		if( drOneTypeResidual && drOneTypeResidual.GetNumRanges() > 0 )
			drTable = drOneTypeResidual;
	}
	return true;	
}
//---FIX_DUPLICATE_RESIDUAL_DATA_REPORT_FOR_DIFF_RESIDUAL_REPORT_AND_PLOT

/// Iris 10/20/05 MOVE_REPORT_GRAPH_CODES_TO_BASE_CLASS
//string	FitterOperation::getOneResultCurvesTableTagName(int nGraphIndex)
//virtual
string		FitterOperation::GetOneResultCurvesTableTagName(int nGraphIndex)
{
	/// YuI 11/09/05 QA70-8279 REPORT_TREE_AND_REPORT_DATA_XVARIABLES
	/*
	string strTable;
	switch(nGraphIndex)
	{
	case GRAPH_RESIDUALS_SCATTER:
		strTable = "ResidualData";
		break;
	case GRAPH_RESIDUALS_HISTOGRAM:
		strTable = STR_RESIDUALS_HISTOGRAM_TABLE;
		break;
	case GRAPH_RESIDUALS_VERSUS_FITS_PLOT:
		strTable = STR_RESIDUALS_FIT_GRAPH_TABLE;
		break;
	case GRAPH_RESIDUALS_VERSUS_ORDER_PLOT:
		strTable = STR_RESIDUALS_ORDER_GRAPH_TABLE;
		break;
	default:
		strTable = STR_FIT_CURVES_TABLE;//"FitCurves";
		break;
	}
	return strTable;
	*/	
	
	return get_fitter_results_curve_table_tagname(nGraphIndex);
	/// end REPORT_TREE_AND_REPORT_DATA_XVARIABLES
}

/// Iris 10/20/05 MOVE_REPORT_GRAPH_CODES_TO_BASE_CLASS
/*
TreeNode FitterOperation::CheckCreateOneResultCurvesTable(TreeNode& trOp, int nDataIndex, int nTotalNumData, int nGraphIndex, const string& strDataLabel, LPCSTR lpcszTableName, int nTableID, LPCSTR lpcszTableLabel)
{
	TreeNode trRC = GetResultCurvesBranch(trOp, nDataIndex, nTotalNumData, strDataLabel);
	if(!trRC)
		return trRC;

	TreeNode 	trOneTable = tree_check_get_node(trRC, lpcszTableName, nTableID, STR_LABEL_ATTRIB, lpcszTableLabel);
	
	bool bCreateGraph = IsCreateReportGraph(trOp, nGraphIndex);
	tree_check_set_hidden(trOneTable, !bCreateGraph);

	int nSingleTable = GetTableStringDatasets();
	trOneTable.SetAttribute(TREE_Table, nSingleTable);
	return trOneTable;
}

TreeNode FitterOperation::GetResultCurvesBranch(TreeNode& trOp, int nDataIndex, int nTotalNumData, LPCSTR lpcszDataLabel)
{
	TreeNode trSubTable;
	TreeNode trRC = RESULT_CURVE_BRANCH(trOp);
	if( !trRC )
	{
		error_report("Fail to get ResultCurves node");
		return trSubTable;
	}
	if( nTotalNumData <= 0 )
		nTotalNumData = GetTotalNumData(trOp);
	if( nTotalNumData <= 0 )
	{
		error_report("nTotalNumData is less and equal 0 in getResultCurvesBranch");
		return trSubTable;
	}
		
	bool bHaveSubLevel = (1 < nTotalNumData);
	if (bHaveSubLevel)
	{
		if(lpcszDataLabel) // to indicate to create
		{
			int nGroupID = IDST_REPORT_FITDATA_ONE_SET;
			trSubTable = check_add_enumerated_node(trRC, RESULT_CURVE_DATA_SET_PREFIX, nDataIndex + 1, make_one_set_ID(nGroupID, nDataIndex), STR_LABEL_ATTRIB, lpcszDataLabel);
			int nSingleTable = GetTableStringSupport(false);
			nSingleTable |= GETNBRANCH_CHANGE_LABEL_TYPES_IN_FLAT;
			//trRC.SetAttribute(TREE_Table, nSingleTable);
			trSubTable.SetAttribute(TREE_Table, nSingleTable);
		}
		else
		{
			string strCuvTable;
			strCuvTable.Format("%s%d", RESULT_CURVE_DATA_SET_PREFIX, nDataIndex + 1);
			trSubTable = trRC.GetNode(strCuvTable);
		}
	}
	else
	{
		ASSERT(0 == nDataIndex);
		trSubTable = trRC;
	}
	return trSubTable;
}

TreeNode FitterOperation::GetOneResultCurvesTable(const TreeNode& trOp, int nDataIndex, int nTotalNumData, int nGraphIndex)
{
	TreeNode trRC = GetResultCurvesBranch(trOp, nDataIndex, nTotalNumData);
	if(!trRC)
		return trRC;
	
	TreeNode trTable;
	string strTable = getOneResultCurvesTableTagName(nGraphIndex);
	if(strTable.IsEmpty())
	{
		error_report("getOneResultCurvesTable found invalid graph index");
		return trTable;
	}	
	trTable = trRC.GetNode(strTable);		
	return trTable;
}
*/
///End MOVE_REPORT_GRAPH_CODES_TO_BASE_CLASS

/// Iris 9/19/05 QA70-7889 PASTE_CUSTOM_TABLE_TO_FIT_CURVE_GRAPH_TABLE
bool	FitterOperation::IsPasteCustomTableToReportGraph(int nGraphIndex)
{
	if(GRAPH_FIT_CURVE == nGraphIndex)
		return true;
	
	return false;
}
//---- CPY 9/22/05 QA70-8015-P15 USE_SET_REPORT_TREE_TO_INTERNALLY_PUT_TREE_INTO_FLAT_SHEET
/*
/// Iris 9/19/05 QA70-8015-P15 OUTPUT_RESULT_CURVE_TO_WKS
bool 	FitterOperation::GetReportDatasInOneTable(TreeNode& trOp, TreeNode& trTable, int nIndex, int nTotalNumData)
{
	TreeNode	trFit = getFitCuvesTable(trOp, nIndex, nTotalNumData);
	if(!trFit)
		return error_report("FitterOperation::GetReportDatasInOneTable found fit curves table missing");
	
	trTable = trFit.Clone();
	
	//append all residual data into Fit Curve branch, in order to insert FitCurve table including residual data in source wks
	for(int nGraph = GRAPH_RESIDUALS_SCATTER; nGraph<=GRAPH_RESIDUALS_VERSUS_ORDER_PLOT; nGraph++)
	{
		TreeNode trResidual = getOneResidualTable(trOp, nIndex, nTotalNumData, nGraph);
		if(trResidual && IsCreateReportGraph(trOp,nGraph) )
		{
			foreach(TreeNode trSubNode in trResidual.Children)
				trTable.AddNode(trSubNode.Clone());	
		}
	}	
	octree_delete_nodes_by_attribute(&trTable, STR_SHOW_ATTRIB, false);
	
	return true;
}
///End OUTPUT_RESULT_CURVE_TO_WKS
*/

///End PASTE_CUSTOM_TABLE_TO_FIT_CURVE_GRAPH_TABLE
/*
#define			LINK_LABEL_INPUT_Y_SOURCE			"?$cell=/2097160/3330/110592"
#define			LINK_LABEL_INPUT_X_SOURCE			"?$cell=/2097160/3330/106496"

#define			LINK_LABEL_REDUCED_CHISQ			"?$cell=/2101760/3330/366"
#define			LINK_LABEL_COEF_DETER				"?$cell=/2101760/3330/355"
#define			LINK_LABEL_PARAM_NAMES				"?$cell=/2102304/536871812/3330[-1:-1]"




// virtual
BOOL	FitterOperation::GetCustomTableDefaultTheme(TreeNode &treeTh)
{
	TreeNode			trRoot = treeTh.AddNode("Root");
	trRoot.Dimensions.Horizontal.GridLines.nVal = 0;
	trRoot.Dimensions.Vertical.GridLines.nVal = 0;
	
	
	vector<string>		vData1 = {LINK_LABEL_INPUT_Y_SOURCE, "?$cell=/2097160/536871912/110592[-1]", "",
								LINK_LABEL_REDUCED_CHISQ, LINK_LABEL_COEF_DETER, "", LINK_LABEL_PARAM_NAMES};
	trRoot.Vectors.Vector1.Data.strVals = vData1;
	trRoot.LinkStyles.LinkStyle1.Name.strVal = LINK_LABEL_INPUT_Y_SOURCE;
	trRoot.LinkStyles.LinkStyle1.Style.Font.Bold.nVal = 1;

	vector<string>		vData2 = {LINK_LABEL_INPUT_X_SOURCE, "?$cell=/2097160/536871912/106496[-1]", "",
								"?$cell=/2101760/536871930/366", "?$cell=/2101760/536871930/355", "", "?$cell=/2102304/536871812/320[-1]"};
	trRoot.Vectors.Vector2.Data.strVals = vData2;
	trRoot.LinkStyles.LinkStyle2.Name.strVal = LINK_LABEL_INPUT_X_SOURCE;
	trRoot.LinkStyles.LinkStyle2.Style.Font.Bold.nVal = 1;
	
	trRoot.LinkStyles.LinkStyle3.Name.strVal = LINK_LABEL_REDUCED_CHISQ;
	trRoot.LinkStyles.LinkStyle3.Style.Font.Bold.nVal = 1;
	
	trRoot.LinkStyles.LinkStyle4.Name.strVal = LINK_LABEL_COEF_DETER;
	trRoot.LinkStyles.LinkStyle4.Style.Font.Bold.nVal = 1;
	
	trRoot.LinkStyles.LinkStyle5.Name.strVal = LINK_LABEL_PARAM_NAMES;
	trRoot.LinkStyles.LinkStyle5.Style.Font.Bold.nVal = 1;
	
	vector<string>		vData3;
	vData3.SetSize(7);
	vData3[6] = "?$cell=/2102304/536871812/321[-1]";
	trRoot.Vectors.Vector3.Data.strVals = vData3;
	
	return TRUE;
}
*/


/// ML 11/13/2006 THEME_DIGITS_PARAMETERS_TBL
bool	FitterOperation::makeParamsTblTheme(TreeNode &trOp, TreeNode &treeTh, int numData)
{
	//------ Folger 12/11/08 QA80-12766 v8.0985 SIGNIFICANT_DIGITS_FAILS_TO_APPLY_TO_NLSF_FITTING_REPORT
	//vector<string>	vstrParameterNames;
	//int			numParams = GetParameters(trOp, 0, vstrParameterNames);
	//
	///*
	//if (numParams <= 0)
		//return false;
	//
	//vector<string>			vstrDigits(numParams);
	//for (int ii = 0; ii < numParams; ii++)
	//{
		//string	str;
		//str.Format("*%u", 3 + ii);		// just to test
		//vstrDigits[ii] = str;
	//}
	//*/
	//
	//vector<int>	vnSignDigits;
	//TreeNode	trFitWorkArea = trOp.FitWorkArea;
	//if(trFitWorkArea)
	//{
		//TreeNode trSignDigtes = trFitWorkArea.Parameters.SignificantDigit;
		/////Arvin 01/29/08 GENERATE_REPORT_FOR_LT_NLFit
		////A bug cause this code runtime error, folger has fixed it.
		////So, I just add this check valid code
		////vnSignDigits = trSignDigtes.nVals;
		//if(trSignDigtes)
			//vnSignDigits = trSignDigtes.nVals;
		/////end GENERATE_REPORT_FOR_LT_NLFit
	//}
	//
	//TreeNode			trRoot = treeTh.AddNode("Root");
	//TreeNode			trRootStyles = trRoot.AddNode("RangeStyles"); 
	//int					iRS = 0;
	//
	//if (vnSignDigits.GetSize() >= numData * numParams)
	//{
		//for (int idata = 0; idata < numData; idata++)
		//{
			//for (int ip = 0; ip < numParams; ip++)
			//{
				//int			ii = ip + numParams*idata;
				//int			nSigDigits = vnSignDigits[ii];
				//if (nSigDigits <= 0)
					//continue;		// "free"
				//
				//string		strRS;
				//strRS.Format("RangeStyle%u", iRS + 1);
				//TreeNode	trRS = trRootStyles.AddNode(strRS);
				//trRS.Left.nVal = 0; 
				//trRS.Right.nVal = 0; 
				//trRS.Top.nVal = 2 + ii; 	// 1 offset + 1 for column labels ("Value", "Standard Error", etc.)
				//trRS.Bottom.nVal = trRS.Top.nVal;
				//string	strFormat;
				//strFormat.Format("*%u", nSigDigits);
				//trRS.Style.Format.strVal = strFormat;
				//++iRS;
			//}
		//}
	//}
	//return 0 < iRS;		// return false if no styles added
	
	TreeNode	trParams = trOp.Calculation.Parameters;
	if ( !trParams )
		return false;
	
	TreeNode			trRoot = treeTh.AddNode("Root");
	TreeNode			trRootStyles = trRoot.AddNode("RangeStyles");
	int					iRS = 0;
	
	foreach ( TreeNode trParam in trParams.Children )
	{
		int		nSinificantDigits = 0;
		if ( trParam.GetAttribute(STR_SIGNIFICANT_DIGITS_FOR_PRARMETER_TABLE, nSinificantDigits) )
		{
			if ( nSinificantDigits > 0 )
			{
				trParam.RemoveAttribute(STR_SIGNIFICANT_DIGITS_FOR_PRARMETER_TABLE);
				string		strRS;
				strRS.Format("RangeStyle%u", iRS + 1);
				TreeNode	trRS = trRootStyles.AddNode(strRS);
				trRS.Left.nVal = 0; 
				trRS.Right.nVal = 0; 
				trRS.Top.nVal = 2 + iRS; 	// 1 offset + 1 for column labels ("Value", "Standard Error", etc.)
				trRS.Bottom.nVal = trRS.Top.nVal;
				string	strFormat;
				strFormat.Format("*%u", nSinificantDigits);
				trRS.Style.Format.strVal = strFormat;
			}
			++iRS;
		}
	}
	
	return 0 < iRS;		// return false if no styles added
	//------ End SIGNIFICANT_DIGITS_FAILS_TO_APPLY_TO_NLSF_FITTING_REPORT
	
	/// RVD 10/30/2007 v8.0737 qa7-10609 REPORT_FOOTNOTE_STYLE_THEME
	/*
	if( iRS == 0 )
		trRoot.RemoveChild(trRootStyles);
		
	trRoot.NameStyles.NameStyle1.Name.strVal = "ogFootNote";
	trRoot.NameStyles.NameStyle1.Style.Color.nVal = 3;
	trRoot.NameStyles.NameStyle1.Style.Font.Size.nVal = 22;
	trRoot.NameStyles.NameStyle1.Style.Font.Bold.nVal = 1;
	return true;
	*/
	/// end REPORT_FOOTNOTE_STYLE_THEME
}

void	FitterOperation::OnAfterCreateReport(TreeNode &trOp, Worksheet& wksReport, DataRange& rngInput, DataRange &rgReportSheetOutput, int nExeMode, bool bNewResultBookCreatedHidden, int nTotalNumData)
{
	/// Iris 02/27/2007 v8.0571 CHANGE_PARAM_TO_OPEN_DLG_FIT_BUTTON_IS_GRAY
	//if ( OEXEM_ON_CREATE == nExeMode )
	///Cheney 2007-6-15 IF_CHANGE_PARAM_SHOULD_ALSO_UPDATE_TBL_THEME
	//if ( OEXEM_ON_CREATE == nExeMode || OEXEM_ON_CREATE_OPEN_GUI == nExeMode)
	if(OEXEM_ON_CREATE == nExeMode || OEXEM_ON_CREATE_OPEN_GUI == nExeMode || OEXEM_ON_CHANGEPARAM == nExeMode)
	///end IF_CHANGE_PARAM_SHOULD_ALSO_UPDATE_TBL_THEME
	{
		Tree		trParamsTblTheme;
		///Cheney 2007-6-15 IF_CHANGE_PARAM_SHOULD_ALSO_UPDATE_TBL_THEME
		//if ( makeParamsTblTheme(trOp, trParamsTblTheme, nTotalNumData) )
		//can not know last time if use tbl theme, so if change param, should always update
		///Arvin 09/06/07 SHOULD_CHECK_REPORT_SHEET_AVAILABLE
		//if( makeParamsTblTheme(trOp, trParamsTblTheme, nTotalNumData) || OEXEM_ON_CHANGEPARAM == nExeMode)
		if( (makeParamsTblTheme(trOp, trParamsTblTheme, nTotalNumData) || OEXEM_ON_CHANGEPARAM == nExeMode) && rgReportSheetOutput.IsValid())
		///END 	SHOULD_CHECK_REPORT_SHEET_AVAILABLE
		///end IF_CHANGE_PARAM_SHOULD_ALSO_UPDATE_TBL_THEME
		{		
			Grid		grid;
			if ( grid.Attach(rgReportSheetOutput, IDST_FIT_PARAMETER) )
			{
				int			nn = grid.UpdateThemeIDs(trParamsTblTheme.Root, "Error", "Unknown tag");
				if (nn <= 0 )
				{
					grid.ApplyFormat(trParamsTblTheme, TRUE, TRUE);
				}
				else
					ASSERT(FALSE);		// bad tree
			}
		}
	}
	
	WksReportOperation::OnAfterCreateReport(trOp, wksReport, rngInput, rgReportSheetOutput, nExeMode, bNewResultBookCreatedHidden, nTotalNumData);
}

/// end THEME_DIGITS_PARAMETERS_TBL

/// Iris 04/03/2007 RESET_DATA_MODE_AFTER_APPLIED_THEME_AND_CHOOSE_DATA
/// ML 4/4/2007 FOR_FIT_MODE_FIGURING_OUT_MUST_NOT_USE_COMBINED_SINCE_COMBINED_GetNumData_ALWAYS_1
//static void _check_reset_fit_mode(TreeNode & trInputData, int nTotalNumData)
//{
//	int		nOldMode;
//	string	strOldValueAttribute = "OldFitMode";
//	
//	if( nTotalNumData <= 1 && trInputData.Use > DATA_MODE_INDEP_CONSOLID )
//	{
//		trInputData.SetAttribute(strOldValueAttribute, trInputData.Use);
//		trInputData.Use = DATA_MODE_INDEP_CONSOLID;
//	}
//	else if( trInputData.GetAttribute(strOldValueAttribute, nOldMode) && nTotalNumData > 1 && nOldMode > DATA_MODE_INDEP_CONSOLID)
//	{
//		trInputData.Use = nOldMode;
//	}
//	
//}
///Sophy 10/28/2008 SHOULD_REARRANGE_LAYERS_WHEN_SWITCH_BETWEEN_SINGLE_INDEP_N_DEP_AND_MULTI_IDEP_N_DEP moved to analysis_utils.h rename as stats_check_reset_fit_mode
//static void _check_reset_fit_mode(TreeNode & trInputData, int nTotalNumData, int numSubData = 0)
//{
	//int		nOldMode;
	//string	strOldValueAttribute = "OldFitMode";
	//bool	bMultipleData = 1 < nTotalNumData || (1 == nTotalNumData && 1 < numSubData);
	//
	//if( !bMultipleData && trInputData.Use > DATA_MODE_INDEP_CONSOLID )
	//{
		//trInputData.SetAttribute(strOldValueAttribute, trInputData.Use);
		//trInputData.Use = DATA_MODE_INDEP_CONSOLID;
	//}
	//else if( trInputData.GetAttribute(strOldValueAttribute, nOldMode) && bMultipleData && nOldMode > DATA_MODE_INDEP_CONSOLID)
	//{
		//trInputData.Use = nOldMode;
		//trInputData.RemoveAttribute(strOldValueAttribute);
	//}
	//
//}
///end SHOULD_REARRANGE_LAYERS_WHEN_SWITCH_BETWEEN_SINGLE_INDEP_N_DEP_AND_MULTI_IDEP_N_DEP
/// end FOR_FIT_MODE_FIGURING_OUT_MUST_NOT_USE_COMBINED_SINCE_COMBINED_GetNumData_ALWAYS_1

///Cheney 2007-10-15 QA70-10522-P4 CLEAN_CODE_AND_ADD_AUTO_FOR_OUTPUT_SETTING 
/////Cheney 2007-8-23 QA70-10290 FITCURVE_AND_REPORT_SHOULD_BE_SAME_BOOK_IF_SRC_DATA_FROM_DIFF_BOOK
//static string  _get_source_page_name(DataRange& dr, DWORD dwRules)
//{
	//string strBook;	
	//DataRange drSub;
	//dr.GetSubRange(drSub, dwRules, 0);
	//if( !drSub.IsValid() || drSub.GetNumRanges() == 0)
		//return strBook;
	//
	//Worksheet wks;
	//drSub.GetParent(wks);
	//if(!wks)
		//return strBook;
	//
	//WorksheetPage wp = wks.GetPage();
	//
	/////Cheney QA70-10315 IF_SOURCE_DATA_FROM_EXCEL_SHOULD_NOT_ADD_FIT_CURVE_TO_SOURCE
	//if(wp.m_bIsExcel)
		//return strBook;
	/////end IF_SOURCE_DATA_FROM_EXCEL_SHOULD_NOT_ADD_FIT_CURVE_TO_SOURCE
	//
	//strBook = page_get_display_name(wp, true);
	//return strBook;
//}
/////end FITCURVE_AND_REPORT_SHOULD_BE_SAME_BOOK_IF_SRC_DATA_FROM_DIFF_BOOK
///end CLEAN_CODE_AND_ADD_AUTO_FOR_OUTPUT_SETTING

///Sophy 12/11/2008 v8.984d NLFIT_XDATATYPE_SHOULD_BE_SOURCE_GRAPH_SCALE_TYPE_AS_LR_WHEN_DATA_FROM_GRAPH
///Sophy 7/8/2009 v8.1060 CLEAN_CODE_SUPPORT_UPDATE_Y_DATATYPE_BRANCH move to event_utils.c
/*
void check_set_xdatatype_on_source_graph(TreeNode& trGUI)
{
	TreeNode trInput = tree_get_node_by_dataid(trGUI, IDST_INPUT_DATA_OPTIONS, true);
	if ( !trInput )
		trInput = tree_get_node_by_tagname(trGUI, "InputData", true);
	
	DataRange drInput;
	drInput.Create();
	drInput.SetTree(trInput);
	
	vector<uint> vPlotUIDs;
	drInput.GetPlots(vPlotUIDs);
	if( vPlotUIDs.GetSize() < 1 )
		return;
	
	DataPlot dp;
	dp = (DataPlot)Project.GetObject((int)vPlotUIDs[0]);
	if ( !dp )
		return;
	
	GraphLayer gl;
	dp.GetParent(gl);
	if ( !gl )
		return;
	
	TreeNode trSrcSetting = gl.GetFormat(FPB_SCALE, FOB_SCALE, true, true);
	TreeNode trXType = trSrcSetting.Root.Axes.X.Scale.Type;
	if ( !trXType )
		return;
	
	if( SCALE_TYPE_LINEAR != trXType.nVal )
	{
		TreeNode trGraph1 = trGUI. Graph1;
		if ( trGraph1 )
			trGraph1.XDataType.SetAttribute(STR_USE_ATTRIB, FIT_CURVE_SAME_AS_SOURCE_GRAPH);
	}
	return;
}
*/
///end CLEAN_CODE_SUPPORT_UPDATE_Y_DATATYPE_BRANCH
///end NLFIT_XDATATYPE_SHOULD_BE_SOURCE_GRAPH_SCALE_TYPE_AS_LR_WHEN_DATA_FROM_GRAPH

///Sophy 12/11/2008 v8.984d NLFIT_XDATATYPE_SHOULD_BE_SOURCE_GRAPH_SCALE_TYPE_AS_LR_WHEN_DATA_FROM_GRAPH
//static void	_check_set_xdatatype(TreeNode& trGUI, const vector<uint>& vPlotUID)
///Sophy 7/8/2009 v8.1060 CLEAN_CODE_SUPPORT_UPDATE_Y_DATATYPE_BRANCH move to event_utils.c
/*
static void	_check_set_xdatatype(TreeNode& trGUI)
///end NLFIT_XDATATYPE_SHOULD_BE_SOURCE_GRAPH_SCALE_TYPE_AS_LR_WHEN_DATA_FROM_GRAPH
{
	//----------- Iris 11/20/2008 v8.0975d QA80-12591-P4 REMOVE_LOG_DATA_TYPE_WHEN_DATA_FROM_MATRIX
	change_indep_data_type_combo_on_source_page_type(trGUI); 
	//-----------	
	///Sophy 11/24/2008 v8.978c CHECK_SET_XDATATYPE_VALUE_ON_APPLY_THEME
	check_set_xdatatype_value(trGUI);
	///end CHECK_SET_XDATATYPE_VALUE_ON_APPLY_THEME
	///Sophy 12/11/2008 v8.984d NLFIT_XDATATYPE_SHOULD_BE_SOURCE_GRAPH_SCALE_TYPE_AS_LR_WHEN_DATA_FROM_GRAPH
	//_check_set_xdatatype_on_source_graph(trGUI, vPlotUID);
	check_set_xdatatype_on_source_graph(trGUI);
	///end NLFIT_XDATATYPE_SHOULD_BE_SOURCE_GRAPH_SCALE_TYPE_AS_LR_WHEN_DATA_FROM_GRAPH
}
*/
///end CLEAN_CODE_SUPPORT_UPDATE_Y_DATATYPE_BRANCH
///Sophy 12/11/2008 v8.984d NLFIT_XDATATYPE_SHOULD_BE_SOURCE_GRAPH_SCALE_TYPE_AS_LR_WHEN_DATA_FROM_GRAPH
// move to graph_utils.h
///Cheney 2007-10-26 QA70-3479-p6 IF_GRAPH_AXIS_IS_LOG_SHOULD_SET_XDATATYPE_AS_LOG_WHEN_LR_PR
//---- Iris 11/24/2008 v8.0978 old funciton not good, this function to check and set scale type to same as source graph
//static void	_check_set_xdatatype(TreeNode& trGUI, const vector<uint>& vPlotUID)
//static void	_check_set_xdatatype_on_source_graph(TreeNode& trGUI, const vector<uint>& vPlotUID)
////---- 
//{
	//if(vPlotUID.GetSize() < 1)
		//return;
	//
	////according to the 1st input data
	//DWORD	dwPlotUID = vPlotUID[0];
	//DataPlot	dp;
	//dp = (DataPlot)Project.GetObject((int)dwPlotUID);
	//if(!dp)
		//return;
	//
	//GraphLayer gl;
	//dp.GetParent(gl);
	//if(!gl)
		//return;
	//
	//TreeNode trSrcSetting = gl.GetFormat(FPB_SCALE, FOB_SCALE, true, true);
	//TreeNode trXType = trSrcSetting.Root.Axes.X.Scale.Type;
	//if(!trXType)
		//return;	
	//
	////----------- Iris 11/20/2008 v8.0975d QA80-12591-S1 SET_TO_USE_SOURCE_GRAPH_SCALE_TYPE_IF_NOT_LINEAR_SCALE_TYPE
	///*
	//if(trXType.nVal == FIT_CURVE_UNIFORM_LOG)
	////------ Folger 06/17/08 QA80-11723 REMOVE_UNWANTED_GRAPH1_NODE_FOR_NLFIT_WITH_CHANGED_AXIS
		////trGUI.Graph1.XDataType.SetAttribute( STR_USE_ATTRIB, FIT_CURVE_UNIFORM_LOG );
	//{
		//TreeNode trGraph1 = trGUI.Graph1;
		//if ( trGraph1 )
		//{
			//trGraph1.XDataType.SetAttribute( STR_USE_ATTRIB, FIT_CURVE_UNIFORM_LOG);
		//}
	//}
	////------ End REMOVE_UNWANTED_GRAPH1_NODE_FOR_NLFIT_WITH_CHANGED_AXIS
	//*/
	//if(SCALE_TYPE_LINEAR != trXType.nVal)
	//{
		//TreeNode trGraph1 = trGUI.Graph1;
		//if ( trGraph1 )
		//{
			//trGraph1.XDataType.SetAttribute( STR_USE_ATTRIB, FIT_CURVE_SAME_AS_SOURCE_GRAPH);
		//}
	//}
	////-----------
//}
///end IF_GRAPH_AXIS_IS_LOG_SHOULD_SET_XDATATYPE_AS_LOG_WHEN_LR_PR
///end NLFIT_XDATATYPE_SHOULD_BE_SOURCE_GRAPH_SCALE_TYPE_AS_LR_WHEN_DATA_FROM_GRAPH
///end RESET_DATA_MODE_AFTER_APPLIED_THEME_AND_CHOOSE_DATA
///Arvin 05/21/07 INPUT_DATA_CHANGE_CAN_NOT_TRIGGER_EVENT_FUNCTION_IN_MR
//static bool _on_input_data_change(TreeNode& tr, int nRow, int nCol, TreeNode& trNode, DWORD nEventInfo, int nCntrlType, WndContainer& getNContainer)
bool on_input_data_change(TreeNode& tr, int nRow, int nCol, TreeNode& trNode, DWORD nEventInfo, int nCntrlType, WndContainer& getNContainer)
///end INPUT_DATA_CHANGE_CAN_NOT_TRIGGER_EVENT_FUNCTION_IN_MR
{
	/// Iris 06/27/2007 v8.0650 ACCESS_NODE_BY_DATAID_TO_AVOLID_RUNTIME_ERR
	//TreeNode 	trInput = tr.InputData;
	TreeNode trInput = tree_get_node_by_dataid(tr, IDST_INPUT_DATA_OPTIONS, true);
	///end ACCESS_NODE_BY_DATAID_TO_AVOLID_RUNTIME_ERR
	///Sophy 9/19/2008 FIX_RUNTIME_WHEN_RUN_FROM_UNIT_TESTING_PROJECT MR
	if( !trInput )
		trInput = tree_get_node_by_tagname( tr, "InputData", true );
	///end FIX_RUNTIME_WHEN_RUN_FROM_UNIT_TESTING_PROJECT
	DataRange dr;
	dr.Create();
	dr.SetTree(trInput);
	string		str;
	if( !trInput.GetAttribute("DataRules", str) )
		return false;
	DWORD	dwRules = atoi(str);	
	/// ML 4/4/2007 FOR_FIT_MODE_FIGURING_OUT_MUST_NOT_USE_COMBINED_SINCE_COMBINED_GetNumData_ALWAYS_1
	//int 	nNumData = dr.GetNumData(dwRules);
	int		numSubData = 0;
	vector<int> vFactorSizes;
	int 	nNumData = dr.GetNumData(dwRules, NULL, NULL, &vFactorSizes, &numSubData);		
	/// end FOR_FIT_MODE_FIGURING_OUT_MUST_NOT_USE_COMBINED_SINCE_COMBINED_GetNumData_ALWAYS_1
	
	///Cheney 2007-8-31 QA70-10330 CLEAN_UP_PLOT_SETTING_BRANCH_IN_OUTPUT_RESULT_NODE
	TreeNode trRCSheet = tr.Output.RCSheet;
	if(trRCSheet)
		trRCSheet.Show = nNumData > 1; 
	
	vector<uint> vPlotUID;
	dr.GetPlots(vPlotUID);
	///Sophy 12/11/2008 v8.984d NLFIT_XDATATYPE_SHOULD_BE_SOURCE_GRAPH_SCALE_TYPE_AS_LR_WHEN_DATA_FROM_GRAPH
	//vector vtemp; 
	//vtemp = vPlotUID;
	//double dUIDSum;
	//vtemp.Sum(dUIDSum);
	double dUIDSum;
	vPlotUID.Sum(dUIDSum);
	///end NLFIT_XDATATYPE_SHOULD_BE_SOURCE_GRAPH_SCALE_TYPE_AS_LR_WHEN_DATA_FROM_GRAPH
	
	/// Iris 10/29/2009 QA81-14546 OP_DLG_NEW_STRUCTURE
	//TreeNode trPasteResultTable = tr.Output.PlotSettings.PasteResultTable;
	TreeNode trPasteResultTable = OP_GUI_GRAPH_ARRANGEMENT_NODE(tr).PasteResultTable;
	///end OP_DLG_NEW_STRUCTURE
	if(trPasteResultTable)
		trPasteResultTable.Enable = dUIDSum > 0;
	///end CLEAN_UP_PLOT_SETTING_BRANCH_IN_OUTPUT_RESULT_NODE
	
	// update the number of columns accorind to the number of dataset
	/// Iris 10/29/2009 QA81-14546 OP_DLG_NEW_STRUCTURE
	//TreeNode 	trGraphNumCols = tr.Output.PlotSettings.GraphNumCols;
	TreeNode 	trGraphNumCols = OP_GUI_GRAPH_ARRANGEMENT_NODE(tr).GraphNumCols;
	///end OP_DLG_NEW_STRUCTURE
	
	if(trGraphNumCols)
	{
		/// Iris 07/30/2007 FIX_GRAPH_NUM_OF_COLS_CHANGED_IN_CHANGE_PARAM, in Change Parameter Plot Settings branch is hidden.
		TreeNode	trPlotSettings = trGraphNumCols.Parent();
		if(trPlotSettings && trPlotSettings.Show && trGraphNumCols.Show)
		///end FIX_GRAPH_NUM_OF_COLS_CHANGED_IN_CHANGE_PARAM
		{
			///Cheney 2007-11-19 ARRANGE_GRAPH_COLS_NUM_NOT_WORK
			/////Cheney 2007-8-31 QA70-10330 CLEAN_UP_PLOT_SETTING_BRANCH_IN_OUTPUT_RESULT_NODE
			//int nAutoCheck = octree_get_auto_support(&trGraphNumCols);
			//if( nAutoCheck == 1 && trGraphNumCols.nVal > 0) )
			/////end CLEAN_UP_PLOT_SETTING_BRANCH_IN_OUTPUT_RESULT_NODE
			//trGraphNumCols.nVal = get_report_graph_num_cols(nNumData);
			if(1 == octree_get_auto_support(&trGraphNumCols))
			{
				/// Iris 9/10/2009 QA80-11710-P2 IMPROVE_REPORT_GRAPH_WHEN_PLOT_IN_ONE_GRAPH_WITH_GROUPING_DATA
				//trGraphNumCols.nVal = get_report_graph_num_cols(nNumData);
				int nNumFactors = vFactorSizes.GetSize() > 0 ? vFactorSizes[0] : 0;
				/// Iris 10/29/2009 QA81-14546 OP_DLG_NEW_STRUCTURE
				//TreeNode trPlotInOne = tr.Output.PlotSettings.PlotInOneGraph;
				TreeNode trPlotInOne = trPlotSettings.PlotInOneGraph;
				///end OP_DLG_NEW_STRUCTURE
				bool bPlotInOne = trPlotInOne && trPlotInOne.Show && trPlotInOne.nVal;
				trGraphNumCols.nVal = get_report_graph_num_cols(nNumData, nNumFactors, bPlotInOne);
				///end IMPROVE_REPORT_GRAPH_WHEN_PLOT_IN_ONE_GRAPH_WITH_GROUPING_DATA
			}
			///end ARRANGE_GRAPH_COLS_NUM_NOT_WORK
		}
	}

	///Cheney 2007-9-18 IF_FROM_THEME_SHOULD_NOT_UPDATE_CUSTOM_RANGE
	//_update_fitted_curve_on_input_data_change(tr, dr, dwRules, nNumData);
	_update_fitted_curve_on_input_data_change(tr, dr, dwRules, nNumData, nEventInfo);
	///end IF_FROM_THEME_SHOULD_NOT_UPDATE_CUSTOM_RANGE
	
	/// ML 4/4/2007 FOR_FIT_MODE_FIGURING_OUT_MUST_NOT_USE_COMBINED_SINCE_COMBINED_GetNumData_ALWAYS_1
	///// Iris 04/03/2007 RESET_DATA_MODE_AFTER_APPLIED_THEME_AND_CHOOSE_DATA
	//_check_reset_fit_mode(trInput, nNumData);
	/////end RESET_DATA_MODE_AFTER_APPLIED_THEME_AND_CHOOSE_DATA
	///Sophy 10/28/2008 SHOULD_REARRANGE_LAYERS_WHEN_SWITCH_BETWEEN_SINGLE_INDEP_N_DEP_AND_MULTI_IDEP_N_DEP
	//_check_reset_fit_mode(trInput, nNumData, numSubData);
	stats_check_reset_fit_mode(trInput, nNumData, numSubData);
	///end SHOULD_REARRANGE_LAYERS_WHEN_SWITCH_BETWEEN_SINGLE_INDEP_N_DEP_AND_MULTI_IDEP_N_DEP
	/// end FOR_FIT_MODE_FIGURING_OUT_MUST_NOT_USE_COMBINED_SINCE_COMBINED_GetNumData_ALWAYS_1

	///Sophy 12/11/2008 v8.984d NLFIT_XDATATYPE_SHOULD_BE_SOURCE_GRAPH_SCALE_TYPE_AS_LR_WHEN_DATA_FROM_GRAPH
	//_check_set_xdatatype(tr, vPlotUID); ///Cheney 2007-10-26 QA70-3479-p6 IF_GRAPH_AXIS_IS_LOG_SHOULD_SET_XDATATYPE_AS_LOG_WHEN_LR_PR
	///Sophy 7/8/2009 v8.1060 CLEAN_CODE_SUPPORT_UPDATE_Y_DATATYPE_BRANCH
	//_check_set_xdatatype(tr); ///Cheney 2007-10-26 QA70-3479-p6 IF_GRAPH_AXIS_IS_LOG_SHOULD_SET_XDATATYPE_AS_LOG_WHEN_LR_PR
	///Sophy 7/22/2009 v8.1073 NANOSIZER_NEED_TO_GET_ORIGINAL_INPUTDATA
	//check_set_datatype(tr, true); //true for XDataType, false for YDataType
	///Jasmine 05/24/10 SRVC-12 ALLOW_SAME_AS_INPUT_FOR_ALL_SURFACE_FIT
	//check_set_datatype(tr, trInput, true); //true for XDataType, false for YDataType
	check_set_datatype(tr, trInput, -1, true); 
	///End ALLOW_SAME_AS_INPUT_FOR_ALL_SURFACE_FIT
	///end NANOSIZER_NEED_TO_GET_ORIGINAL_INPUTDATA
	///end CLEAN_CODE_SUPPORT_UPDATE_Y_DATATYPE_BRANCH
	///end NLFIT_XDATATYPE_SHOULD_BE_SOURCE_GRAPH_SCALE_TYPE_AS_LR_WHEN_DATA_FROM_GRAPH

	///Cheney 2007-4-24 SHOULD_SET_ONLY_ONCE_EVENT_HANDLER_IN_ONE_TREENODE	
	 _update_plot_type_shown(tr, trInput);
	///end SHOULD_SET_ONLY_ONCE_EVENT_HANDLER_IN_ONE_TREENODE
	
	/// Iris 05/14/2007 v8.0617 CHANGE_ERR_AS_WEIGHT_FROM_CHECKBOX_TO_COMBO
	///Kyle 03/31/2009 QA80-3224 NEW_OPTION_TO_SUPPORT_LINEAR_FIT_WITH_ERROR_BAR
	//_update_err_as_weight_status_on_has_or_no_err_col(tr, trInput);
	if(!tr.option || !tr.option.nVal)
		_update_err_as_weight_status_on_has_or_no_err_col(tr, trInput);
	///End NEW_OPTION_TO_SUPPORT_LINEAR_FIT_WITH_ERROR_BAR
	///end CHANGE_ERR_AS_WEIGHT_FROM_CHECKBOX_TO_COMBO
	///Cheney 2007-8-23 QA70-10290 FITCURVE_AND_REPORT_SHOULD_BE_SAME_BOOK_IF_SRC_DATA_FROM_DIFF_BOOK
	///Cheney 2007-10-15 QA70-10522-P4 CLEAN_CODE_AND_ADD_AUTO_FOR_OUTPUT_SETTING 
	//string strSrcPageName = _get_source_page_name(dr, dwRules);
	/// Iris 3/21/2008 v8.0829 QA80-10934 ADD_EDITBOX_TO_SPECIFICATION_BOOK_SHEET_NAME
	//string strSrcPageName = get_source_page_name(tr.Parent());
	string strSrcPageName = get_source_page_name(tr);
	///end ADD_EDITBOX_TO_SPECIFICATION_BOOK_SHEET_NAME
	///end CLEAN_CODE_AND_ADD_AUTO_FOR_OUTPUT_SETTING
	///Cheney 2007-10-16 QA70-10536 CLEAN_CODE_AND_FIX_BUG_OF_ADD_AUTO_FOR_OUTPUT_SETTING
	//if( !strSrcPageName.IsEmpty() )		///Cheney QA70-10315 IF_SOURCE_DATA_FROM_EXCEL_SHOULD_NOT_ADD_FIT_CURVE_TO_SOURCE	
	//{
	//output_curve_book_event(tr, strSrcPageName);
	//output_report_book_event(tr, strSrcPageName);
	/////Cheney QA70-10315 IF_SOURCE_DATA_FROM_EXCEL_SHOULD_NOT_ADD_FIT_CURVE_TO_SOURCE
	//}
	//else
	//{
		//output_curve_book_event(tr, NULL);
		//output_report_book_event(tr, NULL);	
	//}
	
#ifndef _MOVE_FIT_OUTPUT_TO_OC_CLASS /// Iris 3/26/2008 v8.0832 CLEANUP_OUTPUT_BOOK_SHEET_AREA_TO_CLASS
	update_output_report_and_curve_setting(tr, strSrcPageName);
#else
    
    ///Sophy 04/11/2008 GET_OUTPUT_GUI_MANAGER_POINTER
	//int nn;
	//if( tr.Output && tr.Output.GetAttribute(STR_OUTPUT_MANAGER_POINTER, nn) )
	//{
		//OutputGUIManagerBase*	pOutputGUIObj = (OutputGUIManagerBase*)nn;
		//if( NULL != pOutputGUIObj)
			/////Sophy 04/09/2008 UPDATEOUTPUT_ON_DATA_CHANGE
			////pOutputGUIObj->UpdateOutputReportAndCurveSetting(tr,strSrcPageName);
			//pOutputGUIObj->UpdateOutputOnDataChange(tr);
			/////UPDATEOUTPUT_ON_DATA_CHANGE
	//}
	OutputGUIManagerBase* pOutputGUIObj = get_output_GUI_manager_pointer(tr);
	if(tr.Output && (NULL != pOutputGUIObj ))
	{
		pOutputGUIObj->UpdateOutputOnDataChange(tr);
	}
	///end GET_OUTPUT_GUI_MANAGER_POINTER
#endif //_MOVE_FIT_OUTPUT_TO_OC_CLASS
	
	///end CLEAN_CODE_AND_FIX_BUG_OF_ADD_AUTO_FOR_OUTPUT_SETTING
	///end IF_SOURCE_DATA_FROM_EXCEL_SHOULD_NOT_ADD_FIT_CURVE_TO_SOURCE
	///end FITCURVE_AND_REPORT_SHOULD_BE_SAME_BOOK_IF_SRC_DATA_FROM_DIFF_BOOK
	//----- CPY 10/12/07 10522-P3 CLEANUP_IF_LOOSE_DATASET_SHOULD_NOT_PUT_REPORT_SHEET_TO_SOURCE
	/*
	///Cheney 2007-10-12 IF_LOOSE_DATASET_SHOULD_NOT_PUT_REPORT_SHEET_TO_SOURCE
#ifdef NLFIT_CHECK_LOOSE_DATASET
	string strClassName;
	tr.GetAttribute(  STR_CLASS_NAME, strClassName);
	//non linear fit will get empty string here
	if(!strClassName.IsEmpty())
	{
		bool bLooseDataset = false;
		FUNC_IS_LOOSE_DATASET pfn = Project.FindFunction("is_loose_dataset", "OriginLab\\Event_utils", true);
		if(pfn)
			bLooseDataset = pfn(tr.InputData.Range1); 
			
		TreeNode trReport = tr.OutPut.Report;
		if(trReport)
		{
			string 	strReportCombo = strSrcPageName.IsEmpty()? STR_LOOSEDATASET_XYFITTING_REPORTOUT_BOOK_COMBO 
						: STR_NONE + STR_TOKEN_SEP + STR_SOURCE_BOOK + strSrcPageName + STR_TOKEN_SEP + STR_NEW + STR_TOKEN_SEP + STR_CUSTOM + STR_THREE_DOTS;
			if(bLooseDataset)
			{
				strReportCombo = STR_LOOSEDATASET_XYFITTING_REPORTOUT_BOOK_COMBO;
				if(trReport.Book.strVal.Find( STR_SOURCE_BOOK) > -1)
					trReport.Book.strVal = STR_NEW;
			}
			trReport.SetAttribute(STR_COMBO_ATTRIB, strReportCombo)
		}
	}
#endif //NLFIT_CHECK_LOOSE_DATASET
	///end IF_LOOSE_DATASET_SHOULD_NOT_PUT_REPORT_SHEET_TO_SOURCE
	*/
	string strClassName;
	tr.GetAttribute(STR_CLASS_NAME, strClassName);
	TreeNode trReport = tr.OutPut.Report;
	if(!strClassName.IsEmpty() && trReport)
	{
		string 	strReportCombo;
		if(strSrcPageName.IsEmpty()) // we should make sure this is the case for loose dataset
			strReportCombo = STR_OUTPUT_REPORT_BOOK_COMBO;
		else
			strReportCombo = STR_OUTPUT_BOOK_COMBO_WITH_SOURCE(strSrcPageName);
		trReport.SetAttribute(STR_COMBO_ATTRIB, strReportCombo);
	}
	//------------ end IF_LOOSE_DATASET_SHOULD_NOT_PUT_REPORT_SHEET_TO_SOURCE
	return true;
}

/// Iris 05/14/2007 v8.0617 CHANGE_ERR_AS_WEIGHT_FROM_CHECKBOX_TO_COMBO
static void _update_err_as_weight_status_on_has_or_no_err_col(TreeNode& tr, TreeNode& trInput)
{
	// if not select error col, then should disable Error as Weight control
	///Arvin 05/21/07 INPUT_DATA_CHANGE_CAN_NOT_TRIGGER_EVENT_FUNCTION_IN_MR
	bool		bHasErr = false;
	foreach(TreeNode trRange in trInput.Children)
	{
		///------ Folger 03/24/10 QA81-15218-P2 SHOULD_TAKE_CARE_OF_ERROR_WHEN_SWITCH_TO_LINEAR_FIT
		//if(trRange.ED && !trRange.ED.IsEmpty() )
		if ( trRange.ED && !trRange.ED.IsEmpty() || trRange.W && !trRange.W.IsEmpty() )
		///------ End SHOULD_TAKE_CARE_OF_ERROR_WHEN_SWITCH_TO_LINEAR_FIT
		{
			bHasErr = true;
			break;
		}
	}
	///end INPUT_DATA_CHANGE_CAN_NOT_TRIGGER_EVENT_FUNCTION_IN_MR
	TreeNode	trErrWT = tr.Fit.ErrBarWeight;
	if(trErrWT )
	{
		///Arvin 05/21/07 INPUT_DATA_CHANGE_CAN_NOT_TRIGGER_EVENT_FUNCTION_IN_MR
		/*
		bool		bHasErr = false;
		foreach(TreeNode trRange in trInput.Children)
		{
			if(trRange.ED && !trRange.ED.IsEmpty() )
			{
				bHasErr = true;
			}
		}			
		*/
		///end INPUT_DATA_CHANGE_CAN_NOT_TRIGGER_EVENT_FUNCTION_IN_MR
		/// Iris 11/24/2009 QA81-3224-P5 FIX_ERRBARWEIGHT_IS_ENABLE_WHEN_CHANGE_PARAM_MORE
		int nFitType;
		if( tr.InputData.GetAttribute(STR_FIT_LINEAR_TYPE, nFitType) && FIT_LINEAR_WITH_X_ERROR == nFitType )
			bHasErr = false;
		///End FIX_ERRBARWEIGHT_IS_ENABLE_WHEN_CHANGE_PARAM_MORE
		trErrWT.Enable = bHasErr;
	}
	
	///Arvin 05/21/07 INPUT_DATA_CHANGE_CAN_NOT_TRIGGER_EVENT_FUNCTION_IN_MR
	TreeNode trUseRedChiSq = tr.Fit.UseReducedChiSq;
	if(trUseRedChiSq)
	{
		trUseRedChiSq.Enable = bHasErr;
	}
	///end INPUT_DATA_CHANGE_CAN_NOT_TRIGGER_EVENT_FUNCTION_IN_MR
}
///end CHANGE_ERR_AS_WEIGHT_FROM_CHECKBOX_TO_COMBO

///Cheney 2007-4-24 SHOULD_SET_ONLY_ONCE_EVENT_HANDLER_IN_ONE_TREENODE	
static bool _update_plot_type_shown(TreeNode& tr, TreeNode& trInput)
{
	if(!trInput)
		return false;
	
	//surface fit and fit matrix no data mode 
	int nReportControl;
	if(!trInput.GetAttribute(STR_USE_ATTRIB, nReportControl))
		return true;

	//find graph node
	TreeNode trGraph;
	/// Iris 11/03/2009 QA81-14546 OP_DLG_NEW_STRUCTURE
	// fix not show Plot Type in NLFit
	//if(tr.DataID == IDST_INPUT_DATA_OPTIONS) //in NLF, variable tr is InputData tree node
	if(tr.DataID == IDST_DATA_SELECTION) //in NLF, variable tr is Data Selection tree node
	///end OP_DLG_NEW_STRUCTURE
	{
		TreeNode trGUI = tr.Parent();
		if(trGUI)
			trGraph = trGUI.FittedCurve.Graph1;
	}
	else
	{
		/// Iris 10/29/2009 QA81-14546 OP_DLG_NEW_STRUCTURE
		//trGraph = tr.Graph1;
		trGraph = OP_GUI_FITCURVE_PLOT_SETTINGS(tr);
		///end OP_DLG_NEW_STRUCTURE
	}
	
	if(!trGraph)
		return false;
	
	//if Concatenate, PlotType node will show
	//else not show it.
	if(trGraph.PlotType)
	{
		int nAttrib = (nReportControl == DATA_MODE_CONCATENATE) ? 1 : 0;
		trGraph.PlotType.SetAttribute(STR_SHOW_ATTRIB, nAttrib);
	}
	return true;
}
///end SHOULD_SET_ONLY_ONCE_EVENT_HANDLER_IN_ONE_TREENODE

///Cheney 2007-9-18 IF_FROM_THEME_SHOULD_NOT_UPDATE_CUSTOM_RANGE
//static bool _update_fitted_curve_on_input_data_change(TreeNode& tr, DataRange& dr, DWORD dwRules, int nNumData)
static bool _update_fitted_curve_on_input_data_change(TreeNode& tr, DataRange& dr, DWORD dwRules, int nNumData, DWORD nEventInfo)
///end IF_FROM_THEME_SHOULD_NOT_UPDATE_CUSTOM_RANGE
{
	bool		bIsNLSF = false;
	TreeNode	trFitCurve = tr.Graph1;
	if( !trFitCurve )
	{
		trFitCurve = tr.Parent();
		trFitCurve = trFitCurve.FittedCurve.Graph1;
		if(trFitCurve)
			bIsNLSF = true;
	}
	bool		bIsFitCurveTrue = trFitCurve && trFitCurve.Enable && trFitCurve.Show && trFitCurve.Use;
	if(!bIsFitCurveTrue)
		return false;	

	/// Iris 01/23/2007 v8.0546 TO_CONTRL_NOT_OR_HOW_PLOT_FIT_CURVE
	bool		bInputDataFromGraph = false;
	///end TO_CONTRL_NOT_OR_HOW_PLOT_FIT_CURVE
	
	/// Iris 01/25/2007 v8.0547 INIT_CUSTOM_CHANGE_FOR_UNIFORM_X_DATA_TYPE
	/// Iris 11/02/2009 QA81-14546 OP_DLG_NEW_STRUCTURE
	//TreeNode 	trRange = trFitCurve.XDataType.Range;
	TreeNode	trXDataType = OP_GUI_FIT_X_DATA_BRANCH(tr);
	/// Iris 11/03/2009 QA81-14546 OP_DLG_NEW_STRUCTURE
	if( !trXDataType && bIsNLSF )
		trXDataType = trFitCurve.XDataType;
	///end OP_DLG_NEW_STRUCTURE
	ASSERT(trXDataType);
	TreeNode 	trRange = trXDataType.Range;
	///end OP_DLG_NEW_STRUCTURE
	vector		vXs;
	///end INIT_CUSTOM_CHANGE_FOR_UNIFORM_X_DATA_TYPE
	
	///Arvin 11/15/07 ADD_CHECKBOX_USE_SOURCE_GRAPH_COLOR_TO_SET_FITCURVES_COLOR
	vector<uint> vPlotUID;
	///end ADD_CHECKBOX_USE_SOURCE_GRAPH_COLOR_TO_SET_FITCURVES_COLOR
	for(int index = 0; index < nNumData; index++)
	{
		/// Iris 01/23/2007 v8.0546 TO_CONTRL_NOT_OR_HOW_PLOT_FIT_CURVE
		DWORD	dwPlotUID;
		///end TO_CONTRL_NOT_OR_HOW_PLOT_FIT_CURVE
		
		/// Iris 01/25/2007 v8.0547 INIT_CUSTOM_CHANGE_FOR_UNIFORM_X_DATA_TYPE
		vector	vXTemp;
		vector	*pvX;
		if( trRange )//if the treenode is not existed, no need to update it.
			pvX = &vXTemp;
		///end INIT_CUSTOM_CHANGE_FOR_UNIFORM_X_DATA_TYPE
		
		int 	nRet;
		if(bIsNLSF)
		{
			vector	vY;
			nRet = dr.GetNLFitData(dwRules, index, &dwPlotUID, 1, &vY, 1, pvX, NULL);
		}
		else
		{
			nRet = dr.GetData(dwRules, index, &dwPlotUID, NULL, NULL, pvX);
		}
		if(0 <= nRet)			
		{
			/// Iris 01/23/2007 v8.0546 TO_CONTRL_NOT_OR_HOW_PLOT_FIT_CURVE			
			DataPlot	dp;
			dp = (DataPlot)Project.GetObject((int)dwPlotUID);
			if(dp)
			{
				///Arvin 11/15/07 ADD_CHECKBOX_USE_SOURCE_GRAPH_COLOR_TO_SET_FITCURVES_COLOR
				vPlotUID.Add((uint)dwPlotUID);
				///end ADD_CHECKBOX_USE_SOURCE_GRAPH_COLOR_TO_SET_FITCURVES_COLOR	
				bInputDataFromGraph = true;
			}			
			///end TO_CONTRL_NOT_OR_HOW_PLOT_FIT_CURVE
			
			/// Iris 01/25/2007 v8.0547 INIT_CUSTOM_CHANGE_FOR_UNIFORM_X_DATA_TYPE
			if(NULL != pvX)
			{
				vXs.Append(*pvX);
			}
			///end INIT_CUSTOM_CHANGE_FOR_UNIFORM_X_DATA_TYPE
		}
		
	}

	/// Iris 01/23/2007 v8.0546 TO_CONTRL_NOT_OR_HOW_PLOT_FIT_CURVE
	// Update the state(Enable or Disable) of Fitted Curves -> Plot on Original Graph node according to input data from graph or worksheet
	TreeNode 	trHowPlot = trFitCurve.PlotFit;
	if(trHowPlot)
	{
		/// Iris 02/07/2007 JUST_DISABLE_NOT_CHANGE_VALUE, may be will select data back to graph, so need to remember this setting, just disable it.
		//if(!bInputDataFromGraph)
		//	trHowPlot.nVal = 0;
		///end JUST_DISABLE_NOT_CHANGE_VALUE
		trHowPlot.Enable = bInputDataFromGraph;
	}
	///Jasmine 05/30/08 QA80-11630 ADD_OPTION_FOR_SHOW_MARKER_IN_SRC_PLOT_AFTER_FIT
	#ifdef	MARKER_VISIBILITY_OPTIONS
	TreeNode 	trShowMarker = trFitCurve.ShowMarker;
	if(trShowMarker)
		trShowMarker.Enable = bInputDataFromGraph;
	#endif//	MARKER_VISIBILITY_OPTIONS
	///End ADD_OPTION_FOR_SHOW_MARKER_IN_SRC_PLOT_AFTER_FIT
	
	TreeNode 	trUpdateLegend = trFitCurve.UpdateLegend;	
	if(trUpdateLegend)
	{
		/// Iris 02/07/2007 JUST_DISABLE_NOT_CHANGE_VALUE
		//if(!bInputDataFromGraph)
		//	trUpdateLegend.nVal = 0;
		///end JUST_DISABLE_NOT_CHANGE_VALUEs
		trUpdateLegend.Enable = bInputDataFromGraph;
	}
	///end TO_CONTRL_NOT_OR_HOW_PLOT_FIT_CURVE
	
	///Arvin 11/15/07 ADD_CHECKBOX_USE_SOURCE_GRAPH_COLOR_TO_SET_FITCURVES_COLOR
	TreeNode 	trSetColor = trFitCurve.SetColor;
	if(trSetColor && trSetColor.Show)
	{
		//TreeNode trReplicaNum = tr.Fit.Replica.Number;
		//if(trReplicaNum &&  trReplicaNum.nVal > 0)
		//	trSetColor.Enable = false;
		//else 
		vector<string> vGPNames;
		int nChangeParam = 0;
		get_graph_page_names_by_plot_id(vPlotUID, vGPNames);
		bool bMulitPlotFit = has_two_same_strings(vGPNames);
		tr.InputData.GetAttribute(STR_CHANGE_PARAM_ATTRIB, nChangeParam);
		trSetColor.Enable = (bMulitPlotFit&& !nChangeParam);
		if(!trSetColor.Enable)
			trSetColor.nVal = 0;
	}
	///end ADD_CHECKBOX_USE_SOURCE_GRAPH_COLOR_TO_SET_FITCURVES_COLOR
	
	///Arvin 01/31/07 APPARENT_FIT_ONLY_SHOWS_WHEN_GRAPH_WINDOW_IS_ACTIVE by max's suggestion
	TreeNode trApparentFit = tr.Fit.ApparentFit;
	if(trApparentFit && trApparentFit.Show)
	{
		if(bInputDataFromGraph)
			trApparentFit.Enable = true;
		else
		{
			trApparentFit.nVal = 0;
			trApparentFit.Enable = false;
		}
		
	}
	///end APPARENT_FIT_ONLY_SHOWS_WHEN_GRAPH_WINDOW_IS_ACTIVE

	/// Iris 01/25/2007 v8.0547 INIT_CUSTOM_CHANGE_FOR_UNIFORM_X_DATA_TYPE
	// Init the Min & Max in Fitted Curve branch when X Data Type is Uniform and Range is Custom
	if( trRange )
	{
		///Cheney 2007-9-18 IF_FROM_THEME_SHOULD_NOT_UPDATE_CUSTOM_RANGE
		//double		dMin, dMax;
		//vXs.GetMinMax(dMin, dMax);
		//trFitCurve.XDataType.Min.dVal = dMin;
		//trFitCurve.XDataType.Max.dVal = dMax;	
		bool bUpdateCustomRange = (nEventInfo & GETNEVENT_ON_THEME) || 
				( (nEventInfo & GETNEVENT_ON_INIT) && trXDataType.Min.dVal != FITTING_CUSTOM_RANGE_MIN_VAL_DEFAULT && trXDataType.Max.dVal != FITTING_CUSTOM_RANGE_MAX_VAL_DEFAULT)? false : true;
		if(bUpdateCustomRange)
		{
			double	dMin, dMax;
			vXs.GetMinMax(dMin, dMax);
			trXDataType.Min.dVal = dMin;
			trXDataType.Max.dVal = dMax;	
		}
		///end IF_FROM_THEME_SHOULD_NOT_UPDATE_CUSTOM_RANGE
	}	
	///end INIT_CUSTOM_CHANGE_FOR_UNIFORM_X_DATA_TYPE
	
	/// Iris 02/02/2007 v8.0553 SHOW_HIDDEN_PLOTTYPE_ON_DATA_MODE
	TreeNode 	trPlotType = trFitCurve.PlotType;
	if( trPlotType )
	{
		// Plot Type should be hidden except Data Mode is Concatenate
		trPlotType.Show = false;
		if(DATA_MODE_CONCATENATE == tr.InputData.Use)
		{
			trPlotType.Show = true;
		}
		
		// Add more one item "Fitted Curve + "+ trPlotType.strVal when Data Mode is Concatenate
		if( trHowPlot )
		{
			string 			str;
			trHowPlot.GetAttribute(STR_COMBO_ATTRIB, str);
			vector<string> 	vs;
			str.GetTokens(vs, '|');
			
			if(!trPlotType.Show)
			{
				if(3 == vs.GetSize() )
				{
					vs.RemoveAt(2); //remove the 3th item "Fitted Curve + Raw Data"
				}
			}
			else
			{
				vs.SetSize(3);
				vs[2] = ("Fitted Curve + " + trPlotType.strVal); 
			}
			str.SetTokens(vs, '|');
			trHowPlot.SetAttribute(STR_COMBO_ATTRIB, str);			
		}
	}
	///end SHOW_HIDDEN_PLOTTYPE_ON_DATA_MODE
	
	return true;
}



bool 	FitterOperation::OnInputDataSelectionChange(TreeNode& trOperation)
{
	TreeNode	trInput = trOperation.GUI.InputData;
	
	trInput.SetAttribute("DataRules", (string)GetDataRules(trOperation));
	///Cheney 2007-4-24 SHOULD_SET_ONLY_ONCE_EVENT_HANDLER_IN_ONE_TREENODE
	//GETN_SET_EVENT_EX_HANDLER(trInput, _on_input_data_change)		
	///end SHOULD_SET_ONLY_ONCE_EVENT_HANDLER_IN_ONE_TREENODE
	return true;
}

///Cheney 2007-4-24 SHOULD_SET_ONLY_ONCE_EVENT_HANDLER_IN_ONE_TREENODE
bool	FitterOperation::setTreeInputEvent(TreeNode &trInput)
{
	if(!trInput)
		return false;
	///Arvin 05/21/07 INPUT_DATA_CHANGE_CAN_NOT_TRIGGER_EVENT_FUNCTION_IN_MR
	//GETN_SET_EVENT_EX_HANDLER(trInput, _on_input_data_change);
	GETN_SET_EVENT_EX_HANDLER(trInput, on_input_data_change);
	///end INPUT_DATA_CHANGE_CAN_NOT_TRIGGER_EVENT_FUNCTION_IN_MR
	return true;
}
///end SHOULD_SET_ONLY_ONCE_EVENT_HANDLER_IN_ONE_TREENODE	

#ifdef OP_DLG_TOTALLY_NEW_STRUCTURE
//virtual
void 	FitterOperation::RebuildFitCurvePlotOptions(TreeNode& trOp)
{
	int nGraphIndex = GRAPH_FIT_CURVE;
	TreeNode trGraph = GetGUIGraphNodes(trOp, nGraphIndex);
	ASSERT( trGraph );
	ASSERT( trGraph.GetNodeCount() > 0 );
	
	string strNodeName = trGraph.tagName; //Iris: temp use same node name with fit curve setting branch, change later
	TreeNode trGraphOptions = trOp.GUI.Plots.GetNode(strNodeName);
	ASSERT( !trGraphOptions );
	
	// move Fit Curves Plot branch inside Plots branch. Move DoPlot from Fit Curves Plot branch to Output Tables branch.
	if( trGraph && trGraph.GetNodeCount() > 0 && !trGraphOptions )
	{		
		trGraphOptions = trOp.GUI.Plots.AddNode(strNodeName);
		trGraphOptions.Replace(trGraph);
		
		trGraph.Reset();
		trGraph.ID = TRGP_CHECK;
		trGraph.nVal = trGraphOptions.DoPlot.nVal;			
		trGraph.DataID = trGraphOptions.DoPlot.DataID;
		string strLabel;
		if( trGraphOptions.GetAttribute(STR_LABEL_ATTRIB, strLabel))
		{
			trGraph.SetAttribute(STR_LABEL_ATTRIB, strLabel);
		}
		
		// copy DataID from DoPlot to Fit Curve Plots CheckBox to support old theme file.
			TreeNode trDoPlot = trGraphOptions.DoPlot;
		_check_apply_repeat_ID(trDoPlot, trGraphOptions);

		trGraphOptions.DoPlot.Remove();	
	}
		
	// move X Data Type outside to main level
		TreeNode trFit = trOp.GUI.Fit;
		ASSERT(trFit);
		if( trFit )
		{
		ConstructFitXDataBranch(trOp.GUI);
		TreeNode trXData = trOp.GUI.XDataType;
		ASSERT(trXData);
		
		TreeNode trNewXData = trOp.GUI.InsertNode(trFit, "junk");
		ASSERT(trNewXData);		
		
		trNewXData.Replace(trXData);
		trXData.Remove();
		
		// apply repeat ID
		TreeNode trGraphOptions = OP_GUI_FITCURVE_PLOT_SETTINGS(trOp.GUI);
		_check_apply_repeat_ID(trNewXData, trGraphOptions);
		foreach(TreeNode trN in trNewXData.Children)
		{
			_check_apply_repeat_ID(trN, trGraphOptions);
		}
	}
}

static void _check_apply_repeat_ID(TreeNode& trNode, TreeNode& trRepeatIDBranch)
{
	int nParentRepeatID, nNodeRepeatID;
	if( trRepeatIDBranch.GetAttribute(STR_REPEAT_ID_ATTRIB, nParentRepeatID))
	{
		int nID = trNode.DataID;
		trNode.GetAttribute(STR_REPEAT_ID_ATTRIB, nNodeRepeatID);
		int nRet = octree_combine_treenode_id_with_repeat_id(&trNode, &nID, &nNodeRepeatID, nParentRepeatID); 
		trNode.DataID = nID;
	}	
}
#endif //OP_DLG_TOTALLY_NEW_STRUCTURE

#ifdef OP_DLG_TOTALLY_NEW_STRUCTURE_OUTPUT_PART
//virtual
void 	FitterOperation::RebuildOutputBranch(TreeNode& trOp)
{
	// move fit curve branch outside of Output
	TreeNode trGUI = trOp.GUI;
	TreeNode trOutput = trGUI.Output;
	string strJunkName = "Junk";
	if( trOutput.Data && !trGUI.Data )
	{
		TreeNode trNew = trGUI.AddNode(strJunkName);
		trNew.Replace(trOutput.Data);			
		trOutput.Data.Remove();
	}
	
	// move Residual branch outside of Output
	if( trOutput.Residual && !trGUI.Residual )
	{
		TreeNode trNew = trGUI.AddNode(strJunkName);
		trNew.Replace(trOutput.Residual);
		trOutput.Residual.Remove();
		
		ASSERT(trNew.FirstNode);
		TreeNode trNewResAnalysis = trNew.InsertNode(trNew.FirstNode, strJunkName);
		trNewResAnalysis.Replace(trGUI.ResAnalysis);
		trGUI.ResAnalysis.Remove();
	}
	
	///Sophy 11/2/2009 QA81-14546 OP_DLG_NEW_STRUCTURE
	//PartialCurves
	if ( trOutput.PartialCurves && !trGUI.PartialCurves )
	{
		TreeNode trNew = trGUI.AddNode(strJunkName);
		trNew.Replace(trOutput.PartialCurves);
		trOutput.PartialCurves.Remove();
	}
	///end OP_DLG_NEW_STRUCTURE
	// move Find XY branch outside of Output
	if( trOutput.FindXY && !trGUI.FindXY )
	{
		TreeNode trNew = trGUI.AddNode(strJunkName);
		trNew.Replace(trOutput.FindXY);
		trOutput.FindXY.Remove();
		
		ASSERT(trNew.FirstNode);
		TreeNode trCalibration = trNew.InsertNode(trNew.FirstNode, strJunkName);
		trCalibration.Replace(trGUI.Calibration);
		trGUI.Calibration.Remove();
	}	
}
#endif //OP_DLG_TOTALLY_NEW_STRUCTURE_OUTPUT_PART

void	FitterOperation::UpdateGUIGraphs(TreeNode& trOp)
{
	int 		nGraphIndex = 0;
	TreeNode 	trGUI = trOp.GUI;
	/// Iris 10/29/2009 QA81-14546 OP_DLG_NEW_STRUCTURE
	//TreeNode 	trCreate = op_get_optional_tables(trGUI);
	TreeNode	trCreate = OP_GUI_OUTPUT_TABLES_BRANCH(trGUI);
	///end OP_DLG_NEW_STRUCTURE
	
#ifndef OP_DLG_TOTALLY_NEW_STRUCTURE

	GETN_USE(trGUI)		
	//add new Fitted Curves Branch and clone the sub nodes from Create Branch
	///Cheney 2007-10-27 CLEAN_UP_LOCALIZATION_THINGS
	//GETN_BEGIN_BRANCH(Graph1, "Fitted Curves")
	GETN_BEGIN_BRANCH(Graph1, _L("Fitted Curves") )
	///end CLEAN_UP_LOCALIZATION_THINGS
	GETN_END_BRANCH(Graph1)	
	TreeNode	trFitCurves = trCreate.GetNode(op_get_graph_tag_name(GRAPH_FIT_CURVE));
	trGUI.Graph1.Replace( trFitCurves.Clone() );
	
#else //OP_DLG_TOTALLY_NEW_STRUCTURE

	RebuildFitCurvePlotOptions(trOp);	
	
#endif //OP_DLG_TOTALLY_NEW_STRUCTURE
	
#ifndef OP_DLG_TOTALLY_NEW_STRUCTURE
	///Joseph 09/18/06 MOVE_CALIBRATION_TABLE_OUT_OUTPUT
	//add Calibration Table here to suitable place by Max said
	if(IsReportCalibrationTable())
	{
		constructCalibrationBranch( trOp ); 		
	}
	///End MOVE_CALIBRATION_TABLE_OUT_OUTPUT
#endif //OP_DLG_TOTALLY_NEW_STRUCTURE
	
#ifdef OP_DLG_TOTALLY_NEW_STRUCTURE
	GETN_USE(trGUI.Quantities)
#endif

	// Add Residual Branch and clone the sub nodes fron Create Branch
	///Cheney 2007-10-27 CLEAN_UP_LOCALIZATION_THINGS
	//GETN_BEGIN_BRANCH(Residuals, "Residual Plots") GETN_ID(IDE_FIT_RESIDUALS_BRANCH)
	//GETN_OPTION_BRANCH(GETNBRANCH_KEEP_SIZE_ON_COLLAPSE)//Alex 06/05/06 MODIFY_MULTIPLE_REGRESSION_CLOSE_PLOT_BRANCH
	//GETN_LIST(ResType, "Residual Type", 0, "Regular|Standardized|Studentized|Studentized Deleted")  GETN_ID(IDE_RESIDUAL_TYPE) ///Arvin 12/08/06 ADD_RESIDUAL_ANALYSIS_FOR_FITTING
	GETN_BEGIN_BRANCH(Residuals, _L("Residual Plots") ) GETN_ID(IDE_FIT_RESIDUALS_BRANCH)
	///end SHOULD_NOT_PLOT_ANY_RESIDUAL_GRAPH_WHEN_USER_HAVE_NOT_SELECT_ANY_TYPE_RESIDUAL
	GETN_OPTION_BRANCH(GETNBRANCH_KEEP_SIZE_ON_COLLAPSE)//Alex 06/05/06 MODIFY_MULTIPLE_REGRESSION_CLOSE_PLOT_BRANCH
	//------ Folger 11/08/07 CATEGORY_NEEDED_WHEN_LOCALIZE
	//GETN_LIST(ResType, _L("Residual Type"), 0, _L("Regular|Standardized|Studentized|Studentized Deleted") )  GETN_ID(IDE_RESIDUAL_TYPE) ///Arvin 12/08/06 ADD_RESIDUAL_ANALYSIS_FOR_FITTING
	GETN_LIST(ResType, _L("Residual Type"), 0, _LC("Regular|Standardized|Studentized|Studentized Deleted", STR_CAT_STATS) )  GETN_ID(IDE_RESIDUAL_TYPE) 
	///end SHOULD_NOT_PLOT_ANY_RESIDUAL_GRAPH_WHEN_USER_HAVE_NOT_SELECT_ANY_TYPE_RESIDUAL
	//------ End CATEGORY_NEEDED_WHEN_LOCALIZE
	///end CLEAN_UP_LOCALIZATION_THINGS
	GETN_END_BRANCH(Residuals)			

	for(nGraphIndex = GRAPH_RESIDUALS_SCATTER; nGraphIndex<GRAPH_FITTING_MAX_NODES_IN_REPORT; nGraphIndex++)
	{
		/// Iris 10/29/2009 QA81-14546 OP_DLG_NEW_STRUCTURE
		//TreeNode 	trResiduals = trGUI.Residuals;
		TreeNode 	trResiduals = OP_GUI_BRANCH_OF_RESIDUAL_PLOTS_CHECKBOX(trGUI);
		///end OP_DLG_NEW_STRUCTURE
		TreeNode 	trN = tree_check_get_node(trResiduals, op_get_graph_tag_name(nGraphIndex), IDE_RESULT_GRAPHS+nGraphIndex);
		trN.Replace(tree_check_get_node(trCreate, op_get_graph_tag_name(nGraphIndex)));
		trN.nVal = GRAPH_RESIDUALS_SCATTER == nGraphIndex? 1 : 0;   //initialize all Residual check box to unchecked except Residual Scatter
		trN.ID = TRGP_CHECK;
		trN.RemoveAttribute(STR_USE_ATTRIB);			
	}		
	
#ifndef OP_DLG_TOTALLY_NEW_STRUCTURE
	//remove the original graph nodes in Create Branch
	for(nGraphIndex = GRAPH_FIT_CURVE; nGraphIndex<GRAPH_FITTING_MAX_NODES_IN_REPORT; nGraphIndex++)
	{
		TreeNode trGraph = tree_check_get_node(trCreate, op_get_graph_tag_name(nGraphIndex));
#else
	for(nGraphIndex = GRAPH_RESIDUALS_SCATTER; nGraphIndex<GRAPH_FITTING_MAX_NODES_IN_REPORT; nGraphIndex++)
	{
		TreeNode trGraph = OP_GUI_OUTPUT_TABLES_BRANCH(trGUI).GetNode(op_get_graph_tag_name(nGraphIndex));
#endif
		if(trGraph)
			trGraph.Remove();
	}				
}

///Cheney 2007-4-13 FIX_BUG_OF_CUSTOM_TABLE_DISAPPEAR_WHEN_CONCATENATE	
int 	FitterOperation::GetDelColNum(TreeNode& trOp, int nGraphIndex)
{
	//if not concatenate, no need to del col
	TreeNode 	trInput = trOp.GUI.InputData;
	int nDataMode;
	if(!trInput.GetAttribute( STR_USE_ATTRIB, nDataMode) || nDataMode != DATA_MODE_CONCATENATE)
		return -1;
	
	TreeNode 	trGUIGraph = GetGUIGraphNodes(trOp, nGraphIndex);
	TreeNode	trHowPlot = trGUIGraph.PlotFit;
	if(!trHowPlot || trHowPlot.nVal != 1) //1 for fitted curve
		return -1;
	
	return 2; //hard code. when Concatenate, 1st two columns are concatenate data
}
///end FIX_BUG_OF_CUSTOM_TABLE_DISAPPEAR_WHEN_CONCATENATE

///Cheney 2007-4-12 ALL_FITTING_TOOLS_NEED_FOOTNOTE_FOR_MISSING_AND_MASKED_DATA
bool 	FitterOperation::AddHintsForMissingAndMasked(TreeNode& trOperation)
{
	TreeNode 	trFootNote = tree_check_get_node(trOperation.Calculation.Parameters, "Footnote", IDE_FOOTNOTE_BEGIN, TREE_Footnote, "1"); // just need the TREE_Footnote attribute, value does not matter, so 1 is good
	bool bEmptyFootnote = trFootNote.strVal.IsEmpty()? true : false;
	if(IsHasMaskedData())
		trFootNote.strVal += bEmptyFootnote? STR_FOOTNOTE_HAS_MASKED : "\r\n" + STR_FOOTNOTE_HAS_MASKED;
	bEmptyFootnote = trFootNote.strVal.IsEmpty()? true : false;
	if(IsHasMissingData())
		trFootNote.strVal += bEmptyFootnote? STR_FOOTNOTE_HAS_MISSING : "\r\n" + STR_FOOTNOTE_HAS_MISSING;
	
	return true;
}
///end ALL_FITTING_TOOLS_NEED_FOOTNOTE_FOR_MISSING_AND_MASKED_DATA

/// Iris 4/16/2008 REMOVE_PARAM_TABLE_IF_IT_IS_EMPTY
// We will remove empty table before report. But if NOT choose any parameter values in GUI.Quantities.Parameters, still have not empty node .Footnote in Parameters table,
// this cause fail to remove Parameters table. So need to check if append Footnote.
bool	FitterOperation::IsAppendParamFootnote(TreeNode& trOp)
{
	TreeNode trParamGUI = trOp.GUI.Quantities.Parameters;
	if( trParamGUI )
	{
		foreach(TreeNode trN in trParamGUI.Children)
		{
			if( tree_is_true(trN) && TRGP_CHECK == trN.ID )
				return true;  
		}
	}
	return false;
}
///end REMOVE_PARAM_TABLE_IF_IT_IS_EMPTY

/// Iris 4/30/2008 QA80-10442 WANT_REMEMBER_X_DATA_TYPE_IN_THEME
/*
///Arvin 12/24/07 QA70-10442 XDATATYPE_SHOULD_NOT_SAVE_DATATYPE_ATTRIB_INTO_THEME
void  remove_datatype_attrib_from_theme(TreeNode& trGUI)
{
	TreeNode trXDataType = trGUI.Graph1.XDataType;
	if(trXDataType)
		trXDataType.RemoveAttribute(STR_USE_ATTRIB);
	
	TreeNode trYDataType = trGUI.Graph1.YDataType;
	if(trYDataType)
		trYDataType.RemoveAttribute(STR_USE_ATTRIB);
}
///end XDATATYPE_SHOULD_NOT_SAVE_DATATYPE_ATTRIB_INTO_THEME
*/
///end WANT_REMEMBER_X_DATA_TYPE_IN_THEME

///Cheney 2007-9-28 QA70-10442 XDATATYPE_SHOULD_NOT_SAVE_INTO_THEME_AS_MAX_SAID
void	FitterOperation::ThemeUpdateLastUsed(LPCSTR lpcszClassName, TreeNode& tr, bool bThemesTree)
{
	///Arvin 09/29/07 SHOULD_NOT_REMOVE_XDATATYPE_TREE_NODE_FROM_OPERATION_TREE
	/*
	TreeNode trXDataType = tr.Graph1.XDataType;
	if(trXDataType)
		trXDataType.Remove();
	theme_update_last_used(lpcszClassName, tr, bThemesTree);
	*/
	/// Iris 4/30/2008 QA80-10442 WANT_REMEMBER_X_DATA_TYPE_IN_THEME
	/*
	///Arvin 12/24/07 QA70-10442 XDATATYPE_SHOULD_NOT_SAVE_DATATYPE_ATTRIB_INTO_THEME
	//TreeNode trGUI = tr.Clone();
	//TreeNode trXDataType = trGUI.Graph1.XDataType;
	//if(trXDataType)
		//trXDataType.Remove();
	TreeNode trGUI = tr.Clone();
	remove_datatype_attrib_from_theme(trGUI);
	///end XDATATYPE_SHOULD_NOT_SAVE_DATATYPE_ATTRIB_INTO_THEME
	
	theme_update_last_used(lpcszClassName, trGUI, bThemesTree);
	///end SHOULD_NOT_REMOVE_XDATATYPE_TREE_NODE_FROM_OPERATION_TREE
	*/
	theme_update_last_used(lpcszClassName, tr, bThemesTree);
	///end WANT_REMEMBER_X_DATA_TYPE_IN_THEME
	
}
///end XDATATYPE_SHOULD_NOT_SAVE_INTO_THEME_AS_MAX_SAID

///Sophy 9/13/2010 ORG-1037-S1 NO_APPARENT_FIT_FOOTNOTE_WHEN_BOTH_XY_AXES_LINEAR_ON_SRC_GRAPH
bool	FitRegression::isSourceGraphLinearScale(TreeNode& trOp)
{
	if ( !trOp )
		return false;
	TreeNode trInput = trOp.GUI.InputData;
	if ( !trInput )
		return false;
	DataRange drInput;
	drInput.Create();
	drInput.SetTree(trInput);
	if ( !drInput )
		return false;
	
	vector<uint> vPlotUIDs;
	drInput.GetPlots(vPlotUIDs);
	if( vPlotUIDs.GetSize() < 1 )
		return false;
	
	DataPlot dp;
	dp = (DataPlot)Project.GetObject((int)vPlotUIDs[0]);
	if ( !dp )
		return false;
	
	GraphLayer gl;
	dp.GetParent(gl);
	if ( !gl )
		return false;
	
	TreeNode trSrcSetting = gl.GetFormat(FPB_SCALE, FOB_SCALE, true, true);
	TreeNode trXType = trSrcSetting.Root.Axes.X.Scale.Type;
	TreeNode trYType = trSrcSetting.Root.Axes.Y.Scale.Type;
	if ( !trXType || !trYType )
		return false;
	int nXType = trXType.nVal;
	int nYType = trYType.nVal;
	return (SCALE_TYPE_LINEAR == nXType && SCALE_TYPE_LINEAR == nYType);
}
///end NO_APPARENT_FIT_FOOTNOTE_WHEN_BOTH_XY_AXES_LINEAR_ON_SRC_GRAPH

///Arvin 08/02/07 CHECK_WEIGHT_DATA_HAS_MISSING_AND_NEGATIVE_VALUES
void 	FitRegression::appendFitFootnoteToParamTable(TreeNode& trOp)
{
	TreeNode 	trParams = tree_get_node_by_id(trOp.Calculation, IDST_FIT_PARAMETER, true);
	if(!trParams)
		return;
	
	/// Iris 4/16/2008 REMOVE_PARAM_TABLE_IF_IT_IS_EMPTY
	if( !IsAppendParamFootnote(trOp) )
		return;
	///end REMOVE_PARAM_TABLE_IF_IT_IS_EMPTY
	
	string	strErrMsg;
	/// Hong 13/05/08 QA80-11541 ADD_FOOTNODE_IF_UNCHECK_USE_REDUCED_CHISQR
	//if(check_get_weight_data_err_msg(trOp.GUI, strErrMsg) && !strErrMsg.IsEmpty())
	if ( !check_get_weight_data_err_msg(trOp.GUI, strErrMsg) )
	{
		TreeNode 	trUseReducedChiSq = tree_get_node_by_id(trOp.GUI, IDE_FIT_REDUCED_CHISQR, true);
		if ( trUseReducedChiSq && 0 == trUseReducedChiSq.nVal )	
			ocu_load_msg_str(FOOTNOTE_NOT_SCALED_BY_REDUCED_CHISQR, &strErrMsg);
	}
	
	/// Iris 5/19/2009 QA80-13596 ADD_APPERENT_FIT_MSG_IN_PARAM_TABLE_FOOTNOTE
//#ifdef ADD_APPERENT_FIT_MSG_IN_FOOTNOTE_FOR_81 /// Iris 5/25/2009 QA80-13596 INCLUDE_APPEART_FIT_FOOTNOTE_IN_SR6
	///Sophy 9/13/2010 ORG-1037-S1 NO_APPARENT_FIT_FOOTNOTE_WHEN_BOTH_XY_AXES_LINEAR_ON_SRC_GRAPH
	//if( IsApparentFit(trOp) )
	if ( IsApparentFit(trOp) && !isSourceGraphLinearScale(trOp) )
	///end NO_APPARENT_FIT_FOOTNOTE_WHEN_BOTH_XY_AXES_LINEAR_ON_SRC_GRAPH
	{
		if( !strErrMsg.IsEmpty() )
			strErrMsg += "\n";
		///Sophy 9/16/2010 ORG-1037-S2 CHANGE_APPARENT_FIT_FOOTNOTE_COLOR_BLUE
		//strErrMsg += _L("An apparent fit is performed.");
		string strApparentFit;
		ocu_load_err_msg_str(FOOTNOTE_APPARENT_FIT_PERFORMED, &strApparentFit);
		strErrMsg += strApparentFit;
		///end CHANGE_APPARENT_FIT_FOOTNOTE_COLOR_BLUE
	}
//#endif //ADD_APPERENT_FIT_MSG_IN_FOOTNOTE_FOR_81 /// Iris 5/25/2009 QA80-13596 INCLUDE_APPEART_FIT_FOOTNOTE_IN_SR6
	///end ADD_APPERENT_FIT_MSG_IN_PARAM_TABLE_FOOTNOTE	
	
	if ( !strErrMsg.IsEmpty() )
	/// end ADD_FOOTNODE_IF_UNCHECK_USE_REDUCED_CHISQR
	{
		TreeNode 	trFooter = tree_check_get_node(trParams, "Footnote", IDE_FOOTNOTE_BEGIN, TREE_Footnote, "1"); // just need the TREE_Footnote attribute, value does not matter, so 1 is good
		trFooter.strVal = strErrMsg;
	}
	
}
///end CHECK_WEIGHT_DATA_HAS_MISSING_AND_NEGATIVE_VALUES

//BOOL	CalcOneData(TreeNode &trOp, int index, LPCSTR lpcszDescriptive, const vector<int> &vFactorSizes,
/// Iris 05/17/2007 v8.0619 GET_ROW_INDEX_FOR_STATS_EXTREME_VAL_TABLE
//BOOL	FitRegression::CalcOneData(TreeNode &trOp, int index, int nTotalNumData, const vector<int> &vFactorSizes,
//					const vector<string> &vstrFactors, vector &vY, vector &vX, matrix &mMultiIndep, vector &vWeights, DWORD dwPlotObjUID, int nRowColIndex)
BOOL	FitRegression::CalcOneData(TreeNode &trOp, int index, int nTotalNumData, const vector<int> &vFactorSizes,
					const vector<string> &vstrFactors, vector &vY, vector &vX, matrix &mMultiIndep, vector &vWeights, DWORD dwPlotObjUID, int nRowColIndex, const vector<int>& vintRowsInSource)
{
	int				nRet = 0;
	////////////////////////
	// Result structs:
	FitParameter	sFitParameter[MAX_MR_PARAMS+1];		// max num parameters (9 + 1 for constant term)
	RegStats		sRegStats;
	RegANOVA		sRegANOVA;
	RegCalcInternal	sReg;
	
	/// Iris 9/23/04 ADD_COV_AND_CORR_REPORT
	//nRet = CallLLOC(trOp, vY, vX, mMultiIndep, vWeights, sFitParameter, MAX_MR_PARAMS+1, &sRegStats, &sRegANOVA, &sReg);
	matrix			mCov;
	matrix			mCorr;
	//--------- CPY 11/26/04 OUTPUT_FIT_CURVES_TO_SOURCE_SHEET
	//nRet = CallLLOC(trOp, vY, vX, mMultiIndep, vWeights, sFitParameter, MAX_MR_PARAMS+1, &sRegStats, &sRegANOVA, &sReg, mCov, mCorr);	
	// ocmath_linear_fit is modifying vX, so temp solution to make a copy
//	vector vXTemp,vYTemp;
//	vXTemp = vX;
//	vYTemp = vY;
//	nRet = CallLLOC(trOp, vYTemp, vXTemp, mMultiIndep, vWeights, sFitParameter, MAX_MR_PARAMS+1, &sRegStats, &sRegANOVA, &sReg, mCov, mCorr);
	///Arvin 12/04/06 ADD_CONF_PRED_BANDS_FOR_MR
	//nRet = CallLLOC(trOp, vY, vX, mMultiIndep, vWeights, sFitParameter, MAX_MR_PARAMS+1, &sRegStats, &sRegANOVA, &sReg, mCov, mCorr);	
	vector vSerr;
	///Arvin 05/18/07 USE_REDUCED_CHISQ_CHECKBOX_NOT_WORK
	//nRet = CallLLOC(trOp, vY, vX, mMultiIndep, vWeights, sFitParameter, MAX_MR_PARAMS+1, &sRegStats, &sRegANOVA, &sReg, mCov, mCorr, vSerr);	
	nRet = CallLLOC(trOp, vY, vX, mMultiIndep, vWeights, sFitParameter, MAX_MR_PARAMS+1, &sRegStats, &sRegANOVA, &sReg, mCov, mCorr, vSerr, index);	
	///end USE_REDUCED_CHISQ_CHECKBOX_NOT_WORK
	///end ADD_CONF_PRED_BANDS_FOR_MR
	//---------
	/// End ADD_COV_AND_CORR_REPORT
	///Cheney 2007-5-17 LINEAR_FIT_SHOULD_CONSISTENT_WITH_FIT_NL
	//if (nRet)
		//return error_report("Fitter Operation call LLOC failed");
	/////end LINEAR_FIT_SHOULD_CONSISTENT_WITH_FIT_NL
	///Cheney 2007-5-21 NEED_UPDATE_ERROR_CHECKING_OF_REPORT_TABLE_FOR_OPERATION_BASED_TOOLS
	if (nRet)
	{
		string strErr;
		if( ocu_load_err_msg_str(CER_FAILED_GET_STATS_AND_ANOVA_TABLES, &strErr) )
			///Cheney 2007-9-26 USE_ERROR_REPORT_TO_SHOW_OPERATION_ERR
			//okoc_out_msg(strErr);
			error_report(strErr);
			///end USE_ERROR_REPORT_TO_SHOW_OPERATION_ERR
	}
	///end NEED_UPDATE_ERROR_CHECKING_OF_REPORT_TABLE_FOR_OPERATION_BASED_TOOLS
			
	
	///////////////////////
	// Report tree:
	string			strDataLabel;
	GetEscapedMainDataString(trOp, strDataLabel, index + 1);
	///Arvin 02/15/08 QA70-11097 KEEP_ESCAPED_STRINGS
	//ConvertEscapedString(strDataLabel); /// Iris 2/06/06 QA70-8388 INDEP_DATA_CONSOLID_OR_SEP_REPORT, only use to fix show the same DataLabel on separate output table 
	///end KEEP_ESCAPED_STRINGS 
	
	/// Iris 12/30/2006 v8.0534 CORRECT_DERIVED_PARAMS_ORDER_FOR_REPLICA_CASE
	/////Iris 4/02/05 ADD_VY_VX_AS_ARGUMENT
	/////// Iris 9/23/04 ADD_COV_AND_CORR_REPORT
	//////AddOneDataStatsResultsToReportTree(trOp, index, strDataLabel, nTotalNumData, vstrFactors, sFitParameter, sRegANOVA, sRegStats);
	////AddOneDataStatsResultsToReportTree(trOp, index, strDataLabel, nTotalNumData, vstrFactors, sFitParameter, sRegANOVA, sRegStats, mCov, mCorr);
	//AddOneDataStatsResultsToReportTree(trOp, index, strDataLabel, nTotalNumData, vstrFactors, vY, vX, mMultiIndep, sFitParameter, sRegANOVA, sRegStats, mCov, mCorr);
	vector<string> 		vsParamNames, vsParamNamesPostfix;
	vector<string>		vsParamUnits;			///Kyle 08/10/2009 QA80-14077 ADD_PARAMETER_UNIT_TO_FITTING_REPORT
	GetParameters(trOp, index, vsParamNamesPostfix, true);
	GetParameters(trOp, index, vsParamNames, false);	
	GetParamUnits(trOp, index, vsParamUnits);				///Kyle 08/10/2009 QA80-14077 ADD_PARAMETER_UNIT_TO_FITTING_REPORT
	/// Iris 4/23/2008 NOT_GENERAGE_TABLE_IF_NOT_REPORT_TO_IMPROVE_NLSF_SPEED
	//AddOneDataStatsResultsToReportTree(trOp, index, strDataLabel, nTotalNumData, vstrFactors, vY, vX, mMultiIndep, sFitParameter, vsParamNames, vsParamNamesPostfix, sRegANOVA, sRegStats, mCov, mCorr);
	bool 	bReportStats = !tree_GUI_are_all_uncheck(trOp.GUI.Quantities.Statistics);
	/// Iris 9/25/2009 FIX_LR_STILL_REPORT_EMPTY_ANOVA_TABLE_IF_NOT_CHECKED_ON_GUI
	//bool 	bReportANOVA = trOp.GUI.Quantities.ANOVAtable.nVal;
	TreeNode trANOVA = trOp.GUI.Quantities.ANOVAtable;
	bool	bReportANOVA = (trANOVA && trANOVA.Show && trANOVA.nVal);
	///end FIX_LR_STILL_REPORT_EMPTY_ANOVA_TABLE_IF_NOT_CHECKED_ON_GUI
	///Kyle 08/10/2009 QA80-14077 ADD_PARAMETER_UNIT_TO_FITTING_REPORT
	//AddOneDataStatsResultsToReportTree(trOp, index, strDataLabel, nTotalNumData, vstrFactors, vY, vX, mMultiIndep, sFitParameter, vsParamNames, vsParamNamesPostfix, sRegANOVA, sRegStats, mCov, mCorr, NULL, 0, NULL,  bReportStats, bReportANOVA);
	FITPARAMSINFO stParamInfo;
	stParamInfo.pvsParamNames = &vsParamNames;
	stParamInfo.pvsParamNamesPostfix = &vsParamNamesPostfix;
	stParamInfo.pvsParamUnits = &vsParamUnits;
	AddOneDataStatsResultsToReportTree(trOp, index, strDataLabel, nTotalNumData, vstrFactors, vY, vX, mMultiIndep, sFitParameter, stParamInfo, sRegANOVA, sRegStats, mCov, mCorr, NULL, 0, NULL,  bReportStats, bReportANOVA);
	///End ADD_PARAMETER_UNIT_TO_FITTING_REPORT
	///end NOT_GENERAGE_TABLE_IF_NOT_REPORT_TO_IMPROVE_NLSF_SPEED
	///end CORRECT_DERIVED_PARAMS_ORDER_FOR_REPLICA_CASE
	
///---Sim 06-17-2009 QA80-13786-P2-P4 SPEEP_UP_LINEAR_FIT_WITHOUT_REPORT_TABLE
#ifdef __SPEED_UP_FIT_WITHOUT_REPORT_TABLE__
	if ( IsNeedReportTable(trOp) )
#endif // __SPEED_UP_FIT_WITHOUT_REPORT_TABLE__
///---END QA80-13786-P2-P4 SPEEP_UP_LINEAR_FIT_WITHOUT_REPORT_TABLE
	///Arvin 08/02/07 CHECK_WEIGHT_DATA_HAS_MISSING_AND_NEGATIVE_VALUES
	appendFitFootnoteToParamTable(trOp);
	///end CHECK_WEIGHT_DATA_HAS_MISSING_AND_NEGATIVE_VALUES
	
	/// Iris 05/14/2007 v8.0617 SHOW_WEIGHT_IN_OUTPUT_FOR_LR_PR_MR
	TreeNode	trWTGUI = trOp.GUI.Fit.ErrBarWeight;
	if(trWTGUI)
	{
		TreeNode	trOutWT = trOp.Calculation.Notes.Weight;
		if(!trOutWT)
		{
			trOp.Calculation.Notes.Weight.ID = IDE_NOTES_WEIGHT;
			trOutWT = trOp.Calculation.Notes.Weight;
		}
		trOutWT.Show = true; /// Iris 3/12/2009 QA80-13268 NOTES_TABLE_ADD_SPECIAL_INPUT_HANDLING
		///Cheney 2007-10-27 CLEAN_UP_LOCALIZATION_THINGS
		//trOutWT.SetAttribute(STR_LABEL_ATTRIB, "Weight");
		trOutWT.SetAttribute(STR_LABEL_ATTRIB, _L("Weight") );
		///end CLEAN_UP_LOCALIZATION_THINGS
		///Arvin 06/22/07 v8.0647 WRONG_WEIGHT_NOTES_WHILE_FIT_WITHOUT_DIALOG_OPEN
		//if(trWTGUI.Enable)
		TreeNode trInput = trOp.GUI.InputData;
		///Kyle 04/09/2009 QA80-3224-P1 SHOW_WEIGHTING_MODE
		//if(trWTGUI.Enable && IsDatasetHasWeight(trInput, index))
		int nOption = GetOptionIndex(trOp.GUI);
		/// Iris 11/24/2009 QA81-3224-P2 FIX_WEIGHT_NOT_CORRECT_IN_NOTES_TABLE
		//if( nOption || (trWTGUI.Enable && IsDatasetHasWeight(trInput, index)) )
		if( nOption || (trWTGUI.Show && IsDatasetHasWeight(trInput, index)) )
		///End FIX_WEIGHT_NOT_CORRECT_IN_NOTES_TABLE
		///End SHOW_WEIGHTING_MODE
		///END WRONG_WEIGHT_NOTES_WHILE_FIT_WITHOUT_DIALOG_OPEN
		{
			///Arvin 08/10/07 QA70-10197 ADD_NONE_OPTION_FOR_ERROR_AS_WEIGHT_IN_LR_PR_AND_MR
			//trOutWT.strVal = 0 == trWTGUI.nVal? "Direct Weighting" : "Instrumental";
			int nWTMethod = trWTGUI.nVal;
			string strWT; 
			switch(nWTMethod)
			{
			case ERRBARWEIGHT_NO_WEIGHTING:	
				///Cheney 2007-10-27 CLEAN_UP_LOCALIZATION_THINGS
				//strWT = "No Weighting";
				strWT = _L("No Weighting");
				///end CLEAN_UP_LOCALIZATION_THINGS
				break;
			case ERRBARWEIGHT_DIRECT_WEIGHTING:
				///Cheney 2007-10-27 CLEAN_UP_LOCALIZATION_THINGS
				//strWT = "Direct Weighting";
				strWT = _L("Direct Weighting");
				///end CLEAN_UP_LOCALIZATION_THINGS
				break;
			case ERRBARWEIGHT_INSTRUMENTAL:
				///Cheney 2007-10-27 CLEAN_UP_LOCALIZATION_THINGS
				//strWT = "Instrumental";
				strWT = _L("Instrumental");
				///end CLEAN_UP_LOCALIZATION_THINGS
				break;
			}	
			trOutWT.strVal = strWT;
			///end ADD_NONE_OPTION_FOR_ERROR_AS_WEIGHT_IN_LR_PR_AND_MR
		}
		else
		{
			///Cheney 2007-10-27 CLEAN_UP_LOCALIZATION_THINGS
			//trOutWT.strVal = "No Weighting";
			trOutWT.strVal = _L("No Weighting");
			///end CLEAN_UP_LOCALIZATION_THINGS
		}				
	}
	///end SHOW_WEIGHT_IN_OUTPUT_FOR_LR_PR_MR
	
	
	////////////////////////
	/// YuI 8/13/04 QA70-4387 NLFITTER_OPERATION_IMPLEMENTATION
	//	return constructCurvesAndGraphs(trOp, index, strDataLabel, vX, vY, sFitParameter, &sRegStats, &sRegANOVA, &sReg, dwPlotObjUID);
	//--- CPY 8/18/04 no longer need to get DOF from ANOVA table, should be already calculated
	//sRegStats.DOF = sRegANOVA.AnovaTable[ANOVA_ERR].DOF;
	//printf("sRegStats.DOF = %f, sRegANOVA.AnovaTable[ANOVA_ERR].DOF = %f\n", sRegStats.DOF, sRegANOVA.AnovaTable[ANOVA_ERR].DOF);
	//---
	/// ML 11/11/2004 QA70-6845 CELL_VALUE_LINKING
	//return ConstructCurvesAndGraphs(trOp, index, nTotalNumData, strDataLabel, vX, vY, sFitParameter, &sRegStats, &sReg, dwPlotObjUID);
	///Arvin 12/04/06 ADD_CONF_PRED_BANDS_FOR_MR
	//BOOL		bOK = ConstructCurvesAndGraphs(trOp, index, nTotalNumData, strDataLabel, vX, vY, mMultiIndep, sFitParameter, &sRegStats, &sReg, dwPlotObjUID);
	///Arvin 12/12/06 ADD_RESIDUAL_ANALYSIS_FOR_FITTING
	//BOOL		bOK = ConstructCurvesAndGraphs(trOp, index, nTotalNumData, strDataLabel, vX, vY, mMultiIndep, sFitParameter, &sRegStats, &sReg, dwPlotObjUID, 1, NULL, vSerr);
	///Arvin 06/07/07 CENTRALIZE_FITTING_RESULT_LABELS as max's suggestion
	//BOOL		bOK = ConstructCurvesAndGraphs(trOp, index, nTotalNumData, strDataLabel, vX, vY, mMultiIndep, sFitParameter, &sRegStats, &sReg, dwPlotObjUID, 1, NULL, vSerr, vWeights);
	//--- Iris 3/16/2009 QA80-13285-P2-d CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
	//string			strDataLabelCurves = _L("Fit Curve");
	//strDataLabelCurves += " ";
	//strDataLabelCurves += index + 1;
	//if(IsSeparateSheetForDataset(trOp) || 1 == nTotalNumData)
	//strDataLabelCurves = " ";
	string			strDataLabelCurves = GetResultCurveMainTableLabel(trOp, nTotalNumData, strDataLabel);
	//---CLEANUP_FIT_TOOLS_REPORT_DATA_COLUMN_LABELS
	
	BOOL		bOK = ConstructCurvesAndGraphs(trOp, index, nTotalNumData, strDataLabel, vX, vY, mMultiIndep, sFitParameter, &sRegStats, &sReg, dwPlotObjUID, 1, NULL, vSerr, vWeights, strDataLabelCurves);
	///end CENTRALIZE_FITTING_RESULT_LABELS
	///end ADD_RESIDUAL_ANALYSIS_FOR_FITTING
	///end ADD_CONF_PRED_BANDS_FOR_MR
	//AddToCustomTables(trOp, index, nTotalNumData, IDST_REPORT_CUSTOM_TABLE2); // CPY, will need to remove later, only for Marko's testing
	
	///Arvin 10/23/06 FITTING_RESIDUALS_HISTOGRAM_PLOT_CENTRALIZED
   	if(!CalcAddStatsHistPlotData(trOp, index, sFitParameter, vY, vX, vstrFactors, mMultiIndep, vWeights, strDataLabelCurves, dwPlotObjUID))
   		return false;
   	///end FITTING_RESIDUALS_HISTOGRAM_PLOT_CENTRALIZED
	
	return bOK;
	/// end CELL_VALUE_LINKING
	/// end NLFITTER_OPERATION_IMPLEMENTATION
}




//--- CPY 11/13/06 SHOULD_NEVER_ROUND_PARAM_VALUES_INTERNALLY
/*
///Cheney 2006-11-13 SET_PARAMS_VALUE_WITH_SIGNIFICENT_DIGITS
static bool _set_param_value_by_significant_digit(FitParameter&	param, int nSignDigit)
{
	if(param == NULL)
		return false;
	
	if(nSignDigit == 0) //means set "free" in params control
		return true;
	
	param.Value = round(param.Value, nSignDigit);
	param.Error = round(param.Error, nSignDigit);
	param.LCL = round(param.LCL, nSignDigit);
	param.UCL = round(param.UCL, nSignDigit);
	param.ConfInterval = round(param.ConfInterval, nSignDigit);
	return true;
}
///end SET_PARAMS_VALUE_WITH_SIGNIFICENT_DIGITS 
*/

///Arvin 11/10/07 XOP_NEED_SUPPORT_CHANGE_FUNCTION	
void  FitterOperation::ClearOutputTables(TreeNode& trOperation)	
{
	StatsOpBase::ClearOutputTables(trOperation);	
	
	bool		bKeepAttrib = true;
	TreeNode 	trOut = trOperation.Calculation;
	if(trOut.Parameters)
		trOut.Parameters.Reset(bKeepAttrib);
	if(trOut.RegStats)
		trOut.RegStats.Reset(bKeepAttrib);
	if(trOut.Summary)
		trOut.Summary.Reset(bKeepAttrib);
	///Arvin 05/31/07 CLEAR_COVARIANCE_AND_CORRELATION_MATRIX_TABLE
	if(trOut.Covariance)
		trOut.Covariance.Reset(bKeepAttrib);
	if(trOut.Correlation)
		trOut.Correlation.Reset(bKeepAttrib);
	///end CLEAR_COVARIANCE_AND_CORRELATION_MATRIX_TABLE
	///Cheney 2007-4-12 CLEAR_DATA_MODE_IN_NOTES_TABLE_WHEN_CHANGE_PARAMS
	if(trOut.Notes.DataMode)
		trOut.Notes.DataMode.Remove();
	///end CLEAR_DATA_MODE_IN_NOTES_TABLE_WHEN_CHANGE_PARAMS
	
	/// Iris 3/26/2009 QA80-13353 NEED_SURPLUS_RESULT_CURVE_TABLE_WHEN_CHANGE_PARAM_OR_RECALCULATE
	// remove surplus report data according to current gui settings.
	int nTotalNumData = GetTotalNumData(trOperation);
	for(int index = 0; index < nTotalNumData; index++ )
	{
		for(int nGraphIndex = GRAPH_FIT_CURVE; nGraphIndex < GRAPH_FITTING_MAX_NODES_IN_REPORT; nGraphIndex++)
		{
			TreeNode trRC = GetResultCurvesBranch(trOperation, index, nTotalNumData, GetOutputRangeIndex(trOperation, nGraphIndex));
			if( trRC )
			{
				TreeNode 	trTable;
				bool 		bScatterResidualGraph = (GRAPH_RESIDUALS_SCATTER == nGraphIndex);
				if( bScatterResidualGraph )
				{
					TreeNode trDiffRes = trRC.GetNode(STR_DIFF_RESIDUALS_DATA_TABLE);
					if(trDiffRes)
					{
						int begin = REGULAR_RESIDUAL, end = STUDENTIZED_DELETED_RESIDUAL;
						int count = end - begin + 1;
						for(int nResType = begin; nResType <= end; nResType++)
						{
							trTable = trDiffRes.GetNode( GetDiffResidualDataTableTagName(nResType) );
							bool bOut = GUIHasWhatTypeResidualTables(trOperation, nResType);
							if( trTable && !bOut )
								trTable.Remove();
							if( !bOut )
								count--;
						}
						if(0 == count)
							trDiffRes.Remove();
					}
				}
				
				trTable = trRC.GetNode(GetOneResultCurvesTableTagName(nGraphIndex));
				// if already exist regular residual data in Diff Residual Data Table, then no need report more same one for residual scatter plot.
				bool bShareResidualWithDiffResTable = bScatterResidualGraph && UseResidualAnalysisDataReportForPlotting(trOperation);
				if( trTable )
					if( !GUIHasResidualTable(trOperation, nGraphIndex) || bShareResidualWithDiffResTable )
						trTable.Remove();
			}
		}
	}
	///end NEED_SURPLUS_RESULT_CURVE_TABLE_WHEN_CHANGE_PARAM_OR_RECALCULATE
}
///end XOP_NEED_SUPPORT_CHANGE_FUNCTION

///------ Folger 03/19/10 QA81-15218 ADD_LINEAR_FIT_AND_POLYNOMIAL_FIT_TO_QUICKFIT_CONTEXT_MENU
#define	STR_FILE_QUICKFIT		"OriginLab\\QuickFit.c"
typedef int (*QUICK_FIT_GET_ORDER)(int nFitMode, LPCSTR lpcszFunc);

class FitRegressionUpdateFromQuickfitHelper : public FitterOperationUpdateFromQuickfitHelper
{
public:
	FitRegressionUpdateFromQuickfitHelper(TreeNode&				trGUI
										, DWORD					dwParam
										, DWORD&				dwExeCtrl
										) :
	FitterOperationUpdateFromQuickfitHelper(trGUI
											, dwParam
											, dwExeCtrl
											)
	{
	}

	///------ Folger 03/24/10 QA81-15218-P3 BRING_UP_POLYNOMIAL_FIT_FROM_QUICK_FIT_SHOULD_APPLY_CURRECT_ORDER
	void		UpdateOrder()
	{
		TreeNode	trOrder = m_trGUI.Order;
		if ( trOrder )
		{
			QUICK_FIT_GET_ORDER		pfn = Project.FindFunction("quick_fit_get_order", STR_FILE_QUICKFIT, TRUE);
			if ( pfn )
				trOrder.nVal = pfn(0, m_strFunc);
		}
		else
		{
			ASSERT(FALSE);
		}
	}
	///------ End BRING_UP_POLYNOMIAL_FIT_FROM_QUICK_FIT_SHOULD_APPLY_CURRECT_ORDER

private:
	virtual	void	GetIndepsAndDeps(vector<string>& vsIndeps, vector<string>& vsDeps)
	{
		vsIndeps.Add("X");
		vsDeps.Add("Y");
	}

	///------ Folger 03/24/10 QA81-15218-P2 SHOULD_TAKE_CARE_OF_ERROR_WHEN_SWITCH_TO_LINEAR_FIT
	virtual	int		GetDataNodeID()			{ return ONODETYPE_XY_DATA_RANGE; }
	///------ End SHOULD_TAKE_CARE_OF_ERROR_WHEN_SWITCH_TO_LINEAR_FIT
};

BOOL	FitRegression::OperationtoGUI(TreeNode& trOperation, bool bInit, string* pstrSelectedTheme/* = NULL*/, bool bSetDefaultInputOnInit/* = true*/, DWORD dwExeCtrl/* = 0*/, DWORD dwParam/* = 0*/)
{
	if ( bInit && O_QUERY_BOOL(dwExeCtrl, LTXF_FROM_CONTEXT_MENU) )
	{
		FitRegressionUpdateFromQuickfitHelper		clHelper(trOperation.GUI, dwParam, dwExeCtrl);
		
		if ( clHelper.UpdateData() )
		{
			OnInputDataSelectionChange(trOperation);
			///------ Folger 03/24/10 QA81-15218-P3 BRING_UP_POLYNOMIAL_FIT_FROM_QUICK_FIT_SHOULD_APPLY_CURRECT_ORDER
			clHelper.UpdateOrder();
			///------ End BRING_UP_POLYNOMIAL_FIT_FROM_QUICK_FIT_SHOULD_APPLY_CURRECT_ORDER
			clHelper.UpdateConditions(pstrSelectedTheme, bSetDefaultInputOnInit);
		}
	}

	return FitterOperation::OperationtoGUI(trOperation, bInit, pstrSelectedTheme, bSetDefaultInputOnInit, dwExeCtrl, dwParam);
}

typedef	int (*FUNC_CHECK_GET_QUICK_FIT_RESULT)(GraphLayer& gl, QuickFitPlotInfo& stPlotInfo, string& strFunc, vector& vParams, string* pstrCateg = NULL, vector<string>* pvstrParamNames = NULL, bool bNLFitOnly = true);
bool	fitter_check_get_quick_fit_result(QuickFitPlotInfo& stPlotInfo, string& strFunc, string& strCateg, vector& vParams, vector<string>& vstrParamNames)
{
	GraphLayer		gl = Project.ActiveLayer();
	if ( !gl )
		return false;
	FUNC_CHECK_GET_QUICK_FIT_RESULT		pFunc = Project.FindFunction("check_get_quick_fit_result", STR_FILE_QUICKFIT, TRUE);
	if ( !pFunc )
		return false;
	return (0 == pFunc(gl, stPlotInfo, strFunc, vParams, &strCateg, &vstrParamNames));
}

typedef bool (*FUNC_CHECK_GET_QUICKFIT_SETTINGS)(DWORD dwQuickFitToolPtr, QuickFitPlotInfo& qfInfo, string& strFunc, string& strCateg, vector& vParams, vector<string>& vstrParamNames);
bool	fitter_check_get_quick_fit_settings(DWORD dwQuickFitToolPtr, QuickFitPlotInfo& qfInfo, string& strFunc, string& strCateg, vector& vParams, vector<string>& vstrParamNames)
{
	FUNC_CHECK_GET_QUICKFIT_SETTINGS pfn = Project.FindFunction("check_get_quick_fit_settings", STR_FILE_QUICKFIT, TRUE);
	if ( !pfn )
		return false;
	
	return pfn(dwQuickFitToolPtr, qfInfo, strFunc, strCateg, vParams, vstrParamNames);
}

FitterOperationUpdateFromQuickfitHelper::FitterOperationUpdateFromQuickfitHelper(TreeNode&				trGUI
																				, DWORD					dwParam
																				, DWORD&				dwExeCtrl
																				)
{
	m_trGUI = trGUI;
	m_dwExeCtrl = dwExeCtrl;

	BOOL	bb = FALSE;
	if ( O_QUERY_BOOL(dwExeCtrl, LTXF_FROM_HOTKEY) )
	{
		bb = fitter_check_get_quick_fit_result(m_stPlotInfo, m_strFunc, m_strCateg, m_vParams, m_vstrParamNames);
	}
	else if ( O_QUERY_BOOL(dwExeCtrl, LTXF_FROM_CONTEXT_MENU) )
	{
		bb = fitter_check_get_quick_fit_settings(dwParam, m_stPlotInfo, m_strFunc, m_strCateg, m_vParams, m_vstrParamNames);
		if ( 0 == m_stPlotInfo.nFrom && -1 == m_stPlotInfo.nTo )
			dwExeCtrl &= ~LTXF_FROM_CONTEXT_MENU;
	}
	
	if ( bb )
	{
		m_dp = Project.GetObject(m_stPlotInfo.nUID);
	}
}

BOOL	FitterOperationUpdateFromQuickfitHelper::UpdateData()
{
	if ( m_dp )
	{
		XYRange		dr;
		m_dp.GetDataRange(dr, m_stPlotInfo.nFrom, m_stPlotInfo.nTo);
		Tree		trRange;
		dr.GetTree(trRange);

		vector<string>		vsIndeps, vsDeps;
		GetIndepsAndDeps(vsIndeps, vsDeps);
		okutil_create_fitter_data_node_ex(&trRange, NULL, STR_INPUT_RANGE_NAME, STR_INPUT_RANGE_LABEL, &vsIndeps, &vsDeps, 0);
		
		m_trGUI.InputData.Replace(trRange, TRUE, TRUE, TRUE);
		m_trGUI.InputData.ID = GetDataNodeID();
		
		if ( O_QUERY_BOOL(m_dwExeCtrl, LTXF_FROM_CONTEXT_MENU) && m_trGUI.InputData.FirstNode )
		{
			vector<int> vBegins, vEnds;
			vector<uint> vIDs;
			m_dp.GetDataMarkers(vBegins, vEnds, vIDs);
			int nMarkerIndex = vIDs.GetSize() - 1;
			if ( nMarkerIndex >= 0 )
				m_trGUI.InputData.FirstNode.SetAttribute(STR_DATA_MARKER_ID_ATTRIB, vIDs[nMarkerIndex]);
		}
		
		return TRUE;
	}

	return FALSE;
}

void	FitterOperationUpdateFromQuickfitHelper::UpdateConditions(string*&				pstrSelectedTheme
																 , bool&				bSetDefaultInputOnInit
																)
{
	if ( pstrSelectedTheme )
	{
		pstrSelectedTheme->Empty();
		pstrSelectedTheme = NULL;
	}
	bSetDefaultInputOnInit = false;
}
///------ End ADD_LINEAR_FIT_AND_POLYNOMIAL_FIT_TO_QUICKFIT_CONTEXT_MENU