/*------------------------------------------------------------------------------*
 * File Name:				 													*
 * Creation: 																	*
 * Purpose: OriginC Source C file												*
 * Copyright (c) Originlab Corp.	2005, 2006, 2007, 2008, 2009, 2010			*
 * All Rights Reserved															*
 * 																				*
 * Modification Log:															*
 * DG 2/17/05 CENTRALIZE_XFO_AND_NFO											*
 * DG 3/9/05 v8.0201 DISABLE_GUI_INTERFACE_IN_FO								*
 *	CPY 3/17/05 XF_USE_EXTERNAL_TREE_NODE										*
 *  Iris 3/18/05 QA70-7493 BUILD_XVAR_DATA_BRANCH								*
 *	CPY 3/18/05 QA70-7518 XF_LT_COMMAND_USE_OC									*
 * EJP 2005-03-22 v8.0208 QA70-7502 XFUNC_DLG_ACCESS_FILE_IMPORT_VARS			*
 *	ML 3/24/2005 CONTEXT_MENU_X_FUNCS											*
 * DG 3/30/05 v8.0212 CLEAN_DUPLICATE_MORE										*
 * Frank 3/31/05	FIXED_MISTERIOU_FOLDER_UNDER_USRE_FOLDER					*
 * Frank 4/1/05	ADD_INSERT_AND_OPERATOR_PANE_SIZE_MENU							*
 * Frank 4/2/05		NEW_METHOD_CHECK_NODE_EMPTY									*
 *	CPY 4/5/05 XF_LT_CHECK_USAGE_CONTEXT										*
 * Frank 4/7/05		MOVE_DATA_RANGE_SETTINGS_MEMBER_FUNCTION					*
 * DG 4/7/05 v8.0217 VC_FUNCTION_SUPPORT										*
 *	CPY 4/14/05 INTERNAL_XF_DUPLICATE_NAMES_FROM_DIFF_COLS						*
 *	RVD 4/15/2005 QA70-7597 v8.0223 MARKER_GROBJ								*
 *	ML 4/18/2005 XFUNCTION_TREE_MANIPULATION_IN_VC								*
 *	ML 4/29/2005 RETURNING_VALUE_FROM_XFUNCTION									*
 *	CPY 6/2/05 XF_MADE_INTERNAL_OUTSIDE_DIALOG									*
 *	TD 6-14-05 QA70-7803 XF_NO_LIMIT_EDITABLE_BLOCKS_SUPPORT					*
 *  DG 6/17/05 v8.0252 PAGEBASE_MISSING_IN_GRAPHEVENT							*
 *  DG 6/17/05 v8.0252 GETNGRAPH_SUPPORTED										*
 *	TD 6-23-05 QA70-7834 LOAD_DEPENDS_ON_XFCALLS								*
 *  CPY 6/27/05 XF_LT_ACTIVE_NEW_FIX											*
 *  DG 7/1/05 QA70-7785 v8.0261 CHECK_FOR_UPDATE								*
 *	TD 7-5-05 QA70-7834 LOAD_DEPENDS_ON_XFCALLS									*
 *	DSC 6/27/05 CONSTRUCT_THEME_FILE_FROM_COMPOSITE_NAME						*
 *	CPY QA70-7895 7/15/05 XF_LT_FUNC_CALLS, added nXVT and lpRetData for XF call
 *	DSC 7/19/05 MAKE_GET_RETURN_TYPE_PUBLIC										*
 *	Frank 7/26/05 ADD_EVENT_OF_NOT_AUTO_GETN_DIALOG								*
 *	DSC 7/26/05 FIND_EO_DEFAULT_OTH												*
 *	DSC 7/25/05 MORE_EVENT_ORGANIZER											*
 *	DSC 7/28/05 SUPPORT_HELP_XF_IF_NOT_LT										*
 *  DG 8/3/05 v8.0279 BUG_GETN_DLG_NOT_BASE_ON_LABTALK							*
 *	CPY 8/11/05 MOVE_ALL_CODES_TO_SUB_BRANCH									*
 *	EJP 2005-08-23 v8.0292 QA70-7996 IMPWIZ_SUPPORT_XFUNC						*
 *	EJP 2005-08-24 v8.0293 QA70-7996 IMPWIZ_SUPPORT_XFUNC						*
 *		Rename: GetTempInfo to GetRunTimeInfo									*
 *				WipeTempInfo to WipeRunTimeInfo									*
 *				TempInfoGetValue to GetRunTimeValue								*
 *				TempInfoSetValue to SetRunTimeValue								*
 *				GetBookSheetInfo to GetRunTimeBookSheetInfo						*
 *				SetBookSheetInfo to SetRunTImeBookSheetInfo						*
 *				UpdateBookSheetInfo to UpdateRunTimeBookSheetInfo				*
 *	YuI 08/24/05 SIMPLIFIED_RANGE_SPECIFICATION_FOR_LT_XFUNCTION				*
 *	DSC 08/25/2005 GET_XF_INFO_STRINGS											*
 *	ML 8/29/2005 QA70-7547 UNDOABLE_XF_EXECUTION								*
 *	Kevin 09/02/05 MODIFY_XF_VARIABLE_EQUAL_SIGN								*
 *  Kevin 09/12/05 AUTO_COMPLETE_OBJ											*
 *  Iris 9/13/05 XFUNCTION_ADD_REPORT_TREE										*
 *  Iris 9/14/05 QA70-8101 ADD_CONTROL_OUTPUT_RESULT_TREE_OR_NOT				*
 *  Iris 9/15/05 MAKE_XF_AC_SWTICH_WORK_MORE									*
 *  Iris 9/16/05 OUTPUT_XF_ERR_MESSAGE											*
 *	Jasmine 09/17/05 SET_AND_GET_THEME_FILE_NAME								*
 *  Iris 9/19/05 MAKE_AC_THEME_SWITCH_WORK										*
 *	YuI 09/19/05 QA70-8119 SUPPORT_FOR_OUTPUT_TO_BE_SAME_AS_INPUT				*
 *	CPY 9/22/05 USE_VAR_OLD_DESC_TO_EDIT_LANGUAGE_DISPLAY_NAME					*
 *  Iris 9/29/05 ONLY_DUMP_OUTPUT_VARIABLE_NODE									*
 *	CPY 10/4/05 QA70-7895 STR_VAR_FROM_XF_ALLOW_NO_$							*
 *	DSC 10/5/05 DISPLAY_VARIABLE_INFO											*
 *	CPY 10/8/05 QA70-8132 XFN_EVENT_BREAKUP_FOR_2_3_ONLY						*
 *	CPY 10/10/05 CENTRALIZED_XF_ARG_QUOTE_HANDLING								*
 *	CPY 10/10/05 XF_EXEC_FROM_GUI_ALSO_NEED_RESULTS_LOG							*
 *	CPY 10/20/05 XF_NOT_FOR_GETN_SHOULD_NOT_EXECUTE_WHEN_DASH_D					*
 *	CPY 10/21/05 XF_DEFAULT_STR_VAR_SHOULD_WORK_SAME_AS_WHEN_SPECIFIED			*
 *	Kevin 11/11/05	ADD_MORE_ERROR_MSG											*
 *	Kevin 11/11/05	HANDLE_EXCEPTION_ERROR										*
 *	Iris 11/12/05 SUPPORT_OUTPUT_REPORTTREE										*
 *	CPY 11/12/05 XF_RESULTS_LOG_DUMP_MORE_USFUL_INFO							* 
 *	Frank 11/21/05 HIDE_NODE_NAME_OUTPUT_TO_STR									*
 *	CPY 11/21/05 STR_COMBO_SHOULD_STAY_AS_STR									*
 *	CPY 11/22/05 CURVE_MAKER_NEED_TREE_INPUT_AND_OUTPUT							*
 *	CPY 11/22/05 XF_INPUT_VAR_SHOULD_NOT_BE_SET_OUTPUT							*
 *	DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION						*
 *	Jasmine 01/24/06 v8.0361 SHOW_XF_CONTEXT_MENU								*
 *	ML 1/13/2006 XVARIABLEBASE_TO_VC											*
 *	ML 2/16/2006 DYNACONTROL_BASED_GetNImageBox									*
 *	Jasmine 02/24/06 MOVE_FROM_XFUNCTIONWIZ										*
 *	Jasmine 02/27/06 GET_XF_STRUCTURE											*
 *	DSC 1/28/06 SUPPORT_PROJECT_AND_CUSTOM_PATH									*
 *	Jasmine 03/01/06 REDUCE_SIMILAR_CODE										*
 *	ML 3/6/2006 AUTOUPDATE_MORE_WORK											*
 *	ML 3/13/2006 DONT_SHOW_DLG_IF_FROM_MENU_AND_XFTHEME							*
 *	ML 4/28/2006 NO_GETN_IDS_FOR_STATIC_TEXTS									*
 *	EJP 2006-06-30 v8.0436 ALWAYS_ASSIGN_ARGS_FROM_CMDLINE						*
 *	ML 7/12/2006 REPORT_DATA_WITH_XF_WORKSHEET_GRAPHS_HANDLING					*
 *	ML 7/17/2006 GETTING_INPUT_DATA_DESCRIPTION_FROM_WITHIN_XFUNCTION_EXECUTION	*
 *	ML 7/19/2006 REMEMBERING_SETTINGS_IN_XFOPERATION_FOR_AUTO_UPDATE			*
 *  Iris 8/04/06 APPLY_XF_DEFAULT_THEME											*
 * CPY 8/27/2006 XF_OPTION_INDEX_NOT_WORKING_FOR_LT_TYPE_XF						*
 * EJP 2006-09-11 v8.0480 SAVE_XF_TO_MISC_WHEN_NO_CATEGORY_SPECIFIED			*
 *	CPY 12/2/06 ALLOW_LT_TO_ATTACH_XF_TO_XFBAR									*
 *	ML 12/7/2006 ADDING_INPUT_TABLE_FROM_WITHIN_XF								*
 *	ML 12/15/2006 AUTO_SIZING_REPORT_TREE_ON_CONNECTING_OPERATION				*
 *  Joseph 12/19/06 SET_THEME_DEFAULT_TO_FACTORY_DEFAULT						*
 *	CPY 12/23/06 FROM_MENU_XF_NOT_FOR_DIALOG_SHOULD_ALSO_RUN					*
 *	CPY 1/27/2007  XF_RESULTS_LOG_OUTPUT_OPTIONS								*
 *	ML 2/27/2007 SHOULD_NOT_GET_AUTOUPDATE_MODE_FROM_THEME_UNLESS_FROM_MENU		*
 *	AW 03/01/07 QA80-9426 v8.0273 ASSIGN_TREE_VARABILE_FOR_XF_IN_LT				*
 * Justin 03/11/07 v8.0578 DISPLAY_DIFF_LANGUAGE_HELP_FOR_DIFF_LANGUAGE_VERSION *
 *	CPY 3/17/2007 MAX_FOUND_OPTION_INDEX_FROM_MENU_ALSO_OPENS_DLG_IF_THEME_USED_IN_DIALOG	*
 *	CPY 3/20/08 SIM_FOUND_OPTION_INDEX_CHANGE_BROKEN_ASCII_FROM_MENU			*
 *	Hong 03/24/07 QA80-9529 NOT_UPDATE_LAST_USED_IF_NO_SHOW_DIALOG				*
 *	CPY 4/9/07 INTEG_PEAKS_SHOULD_ALWAYS_USE_XF_BAR								*
 *	Jasmine 04/13/07 PRINT_XF_MSG_TO_SCRIPT_WINDOW								*
 *	Joseph 04/16/07 SUPPORT_ZERO_FOR_THEME_LAST_USED							*
 *	Jasmine QA70-9623 REPLACE_BY_OKOC_OUT_MSG									*
 *	AW 04/18/07 QA80-9646 v8.0604 MORE_ON_ASCII_IMPORT_MESSAGE					*
 *	CPY 4/21/2007 QA70-9627 XF_BEFORE_EXEC_TO_ASK_DLG_TO_OPEN_FAILED_FROM_THEME_LUNCH
 *	CPY 5/3/07 QA70-9718 RECENT_IMPORT_EXPORT_WITH_THEME						*
 *	ML 5/18/2007 XFUNCTION_CLASS_NEW_ARRANGEMENT								*
 *	CPY 6/5/2007 QA70-9803 SHIFT_SELECT_SHOULD_FORCE_DIALOG_TO_OPEN				*
 *	Joseph 06/06/07 MOVE_SOME_FUNCTIONS_AND_DEFINITIONS_TO_XFUNCTION_HEADER_FILE*
 *  SY 2007-06-06 QA70-9426 v8.0634 ASSIGN_TREE_VARABILE_FOR_XF_IN_LT			*
 *	CPY 6/7/2007 QA70-9426 v8.0634 ASSIGN_TREE_VARABILE_FOR_XF_IN_LT			*
 *	CPY 6/8/2007 QA70-9894 IMP_ASC_PREFER_THEME_FROM_BOOK_SHEET_OVER_FACTORY_DEFAULT
 *	YuI 06/12/07 QA70-9913 XYRNAGE_EVEN_SAMPLING_PROPER_SUPPORT					*
 * 	Justin 2007-06-13 REMOVE_FIRST_COLON_IN_DESCRIPITON							*
 *	Hong 06/18/07 v8.0643 FIX_XF_SHOW_HELP_BY_LT_ERROR_SHOW_HIDDEN_NODE			*
 *	CPY 6/27/2007 EXP_GRAPH_SLOWNESS_DUE_TO_MAKE_TREE_CALL_3_TIMES				*
 *	CPY 6/28/07 FILE_RECENT_IMPORT_SHOULD_USE_LAST_USED_THEME					*
 *	Sim 06-30-2007 FIX_FACTORY_DEFAULT_THEME_APPIED_ISSUE						*
 *	Sim 06-30-2007 PUT_OUT_GLOBAL_FUNC											*
 *	CPY 7/11/2007 QA70-10010 LAST_USED_THEME_WHEN_RUN_FROM_MOST_RECENT_COMMAND	*
 *	CPY 7/11/2007 QA70-10010 MOST_RECENT_IMPORT_EXPORT_NEED_LTXF_FROM_MRU_MENU	*
 *	CPY 7/11/2007 CURVE_TRANSLATE_BROKEN										*
 *	CPY 7/11/2007 CURVE_TRANSLATE_NEED_OPTION_INDEX_PASSED_IN					*
 *	RVD 7/13/2007 UNDO_ATTACH_XF_WHEN_CURVE_TRANSLATE_NOT_PROCEED				*
 *	CPY 8/23/2007 QA70-10010 RECENT_EXPORT_CHECK_SHIFT_SELECT_TO_OPEN_DIALOG	*
 *	CPY 8/24/2007 QA70-10231 ALLOW_THEME_TO_BE_REMEMBER_IF_USER_CHANGED_FROM_DIALOG
 *	Hong 08/28/07 QA80-10310 MORE_VARIABLE_INFO_FOR_XF2GUI						*
 *	CPY 8/31/07 KITKIT_FOUND_XF_AND_OP_NOT_CONSISTENT_WITH_MRM_NO_THEME			*
 *	Hong 09/08/07 v8.0699 MORE_OPTION_TO_DUMP_MAP_INFO_FOR_COMBO_NODE			*
 *	CPY 11/1/2007 QA70-10638 CMD_WND_OUTPUT_ERR_BY_DEFAULT						*
 *	CPY 11/3/2007 LANGUAGE_CHAR_FROM_OC											*
 *	Sim 11-05-2007 CLEAN_LOCALIZATION_CODE										*
 *	CPY 12/5/07 QA70-10782 REPORT_FOR_J_SHOW_JUNK								*
 *	Hong 12/13/07 v8.0768 FIX_GET_GARBAGE_DESCRIPTION_WHEN_EMPTY				*
 *	Folger 02/29/08 QA80-11192 IMPROVE_IMPASC_THEME_MECHANISM					*
 *	Folger 03/06/08 QA80-11192 SHOULD_NOT_APPLY_BOOK_SHEET_THEME_IF_ACTIVE_BOOK_SHEET_NOT_HAVE
 *	CPY 3/13/08 QA70-11192 OPEN_DIALOG_SHOULD_USE_DEFAULT_THEME_IF_PRESENT		*
 *	CPY 3/13/08 QA70-11192 PREFER_DEFAULT_IF_PRESENT							*
 *	Hong 03/18/08 QA80-8966 FIX_DRAG_DROP_XF_FAIL_PUT_IN_CORRECT_CATEGORY		*
 *	Folger 03/31/08 QA80-11333 SHOULD_USE_LAST_USED_WHEN_OPEN_IMPASC_FROM_TOOLBAR_BUTTON
 *	Folger 04/01/08 QA80-11333 SHOULD_CHECK_DEFAULT_THEME_BEFORE_USE_LAST_USED	*
 *	CPY 4/17/08 QA70-11438 PA_NEED_THEME_SUPPORT_FROM_MENU						*
 *	Folger 05/29/08 USE_DEFAULT_THEME_FROM_FLY_OUT_MENU_SHOULD_OPEN_XF_DIALOG_IF_INPUT_IS_INVALID
 *	YuI 06/06/08 QA70-8966 XF_DRAG_AND_DROP_PROBLEM								*
 *	Folger 06/16/08 FIX_DEFAULT_THEME_DISPLAY_IN_IMPORT_ASCII_FROM_FILE_IMPORT_MENU
 *	Folger 07/16/08 QA80-11855 BETTER_FORMATTING_FOR_XF_HELP_DUMPING			*
 *	YuI 07/31/08 QA70-11930 P3 SAMPLING_INTERVAL_CALCULATION_ISSUES				*
 *	RVD 8/11/2008 qa70-10944 REMOVE_EVEN_SAMPLING								*
 *	Folger 08/22/08 QA80-12075 SHOULD_NOT_HIDE_EMPTY_TREE_NODE_IN_DASH_H_HELP	*
 *	Folger 09/25/08 QA80-12276 SET_SAMPLING_INTERVAL_FOR_YXRANGE_OUTPUT			*
 *	ML 9/25/2008 QA70-12276 MISSING_RETURN_VALUE								*
 *	YuI 10/01/08 QA70-12321 LOAD_AND_COMPILE_XF_AND_NOTHING_MORE				*
 *	Folger 10/13/08 MISSING_AUTO_UPDATE_SHOULD_NOT_SKIP_XF_THEME_APPLY			*
 *	Folger 10/29/08 v8.0962 GET_XF_NAME_FROM_COMPOSITE_NAME_BEFORE_CHECKING_DEFAULT_THEME
 *	ML 11/10/2008 QA70-12356 RANGE_GET_DATA_PROVIDE_MAP_OF_MISSING_VALUES		*
 *	Folger 11/21/08 QA80-12631 v8.0977 WARNING_MESSAGE_NOT_SHOWING_WHEN_SET_AUTO_UPDATE_TO_NONE
 *	Folger 11/24/08 QA80-12639 v8.0978 SHOULD_ONLY_UPDATE_OUTPUT_Y_COLUMN_SAMPLING_INTERVAL_WHEN_INPUT_RANGE_IS_EVEN_SAMPLING
 *	Folger 12/02/08 v8.0981b SHOULD_ALLOW_IMP_EXP_XF_THEME_FILE_NAME_TO_BE_ONE_CHARACTER
 *	Folger 01/09/09 v8.0995 CHANGE_PARAM_SHOULD_DO_EVALUATE_EXACTLY_THE_SAME_AS_NORMAL_EXECUTE
 *	Folger 01/19/09 PA_RUNS_SCRIPT_MODE_AS_DEFAULT								*
 *	Kyle 02/01/2009 QA80-13042 NUMERIC_COMBO_LIST_IN_XF_HELP_SHOULD_NOT_SHOW_INDICES
 *	Folger 02/12/09 UPDATE_EXECUTION_INFO_AFTER_CREATE_XF_OP					*
 *	Folger 03/10/09 QA80-11855 LT_XF_HELP_DUMPING_NEEDS_SUPPORT_DISPLAY_RELATED_XF
 *	Folger 03/11/09 QA80-13258 OPEN_DIALOG_FROM_MRU_WITHOUT_THEME_NAME_SHOULD_USE_DEFAULT_SETTINGS
 *	Folger 03/12/09 QA80-13258 SUPPORT_OPEN_DIALOG_WITH_LAST_USED_FROM_MRU		*
 *	YuI 04/09/09 QA70-13435 OPTION_TO_SUPPRESS_LT_ERROR_FOR_XF_INVOCATION		*
 *	Folger 04/22/09 QA80-10889 SUPPORT_COPY_DATA_FORMAT_AS_NEW_XF_SWITCH		*
 *	Sim 06-05-2009 CENTRALIZE_ERROR_MSG											*
 *  Iris 6/10/2009 QA80-13741 REMOVE_AND_OP_IN_LIST_XF_RESULT					*
 *	Folger 06/16/09 QA80-13787 XF_XYRANGE_OUTPUT_FAILS_TO_SET_EVEN_SAMPLING_WHEN_INPUT_X_USED_PARTIAL_ROW_NUMBER
 *	YuI 07/27/09 QA70-14023 EVEN_SAMPLING_LOOSE_DATASET_XYRANGE_ACCESS			*
 *	Folger 07/29/09 XF_AUTO_GETN_SUPPORT_ERROR_MESSAGE_CLEAN_UP					*
 *	Max 7/31/09 v8.063c.988 QA70-13435 SUPPRESS_SHOWING_IN_SET_COLUMN_VALUES_DLG
 *	Folger 08/12/09 QA80-14112 NEED_OPTION_STRING_TO_HIDE_XF_VARIABLE_FROM_LT	*
 *	Folger 08/24/09 QA80-10703 RUN_XFM_NOT_WORK_FOR_XF_WITHOUT_DIALOG			*
 *	Folger 08/25/09 QA80-14145 SUPPORT_FOLDER_LAST_USED_THEME_IN_PE_XFS			*
 *	Folger 09/02/09 QA80-14086 BETTER_FIX_AUTOX_FAILS_TO_BE_RESOLVED_WHEN_RUN_XF_FROM_SCRIPT_WITHOUT_THEME
 *	Kyle 09/22/2009 QA80-14023 FIX_SAMPLING_IS_NOT_RESET_IF_SET_INPUT_AS_OUTPUT	*
 *	YuI 09/30/09 QA70-14399 UNNECESARY_AUTOUPDATE_IN_CASE_OF_INPUT_NEW			*
 *	Kyle 10/09/2009 QA80-14127-P6 UPDATE_THE_OUTPUT_X_IN_CASE_OF_INPUT_INPUT	*
 *	Folger 10/09/09 PA_FAILS_TO_GET_CORRECT_DATA_FROM_AUTOX						*
 *	YuI 10/13/09 QA70-14023 OPTION_TO_FORCE_SAMPLING_INTERVAL_RECALCULATION		*
 *	Kyle 10/14/2009 SET_EVEN_SAMPLING_SUPPORT_UNDO								*
 *	Folger 10/20/09 QA81-14500 XF_SHOULD_CLEAR_OUTPUT_DATA_BY_DEFAULT_WHEN_TOTALLY_INTERSECTED_WITH_INPUT
 *	Folger 11/13/09 QA81-14654 UNCHECK_OUTPUT_RESULT_LOG_WHEN_CHANGE_PARAM_FOR_OP_CREATED_FROM_SCRIPT_BY_SL_SWITCH
 *	Folger 12/11/09 QA81-14831-P2 OPEN_XF_DIALOG_FROM_LT_SUPPRESS_ERROR_WHEN_USER_CANCEL
 *	Folger 11/11/09 QA81-14630 SUPPORT_DUMPING_XF_SETTINGS_FROM_GETN_DIALOG		*
 *	Folger 02/02/10 QUICKFIT_SUPPORT_WITHOUT_ROI_BOX_WITH_CNTRL_KEY_DOWN		*
 *	Folger 03/19/10 QA81-15221 CNORMALIZE_FAILED_IF_SET_OUTPUT_AS_INPUT_FOR_MULTIPLE_DATA
 *	Folger 03/31/10 QA81-15258 XF_GETPTS_NEEDED									*
 *	Folger 04/23/10 QA81-14023-P4 SMOOTH_OUTPUT_WRONG_SAMPLING_INTERVAL_ON_PARTIAL_RANGE_OF_LOOSE_DATASET
 *	Folger 04/27/10 QA81-15361 PROPER_TRIMMING_AMPERSAND_FOR_XF_VAR_COMBO_THAT_MAKES_MENU_ITEMS
 *	Folger 05/25/10 QA81-14630-P11 GENERATE_SCRIPT_FAILED_ON_IMPASC_IF_USE_SEMICOLON_AS_DELIMITER
 *	Folger 06/25/10 ORG-122-P9 SUPPORT_ALWAYS_GENERATE_XF_LT_SCRIPT				*
 *	Folger 08/02/10 ORG-672 INTEG1_SUPPORT_MULTIPLE_XYRANGES					*
 *	Folger 08/05/10 ORG-702-P1 CLEAR_OUTPUT_DATA_WITHOUT_ERROR_FOR_XF_OPERATION_RECALCULATE_IF_INPUT_IS_EMPTY
 *	Folger 08/26/2010 ORG-920-P1 ONE_SAMPLE_TTEST_BETTER_HANDLING_OF_OUTPUT_PLOT_AND_REPORT_DATA
 *	Folger 09/03/2010 WEB2FILE_FAILED_WITH_GENERATED_SCRIPT						*
 *	Folger 10/08/2010 ORG-1207-P1 IMPORT_ASCII_NUMERIC_SEPARATOR_AUTO_SUPPORT	*
 *	Folger 10/20/2010 ORG-1286-P1 MORE_TOOLS_FAILED_TO_COPY_SAMPLING_INTERVAL_FROM_INPUT
 *------------------------------------------------------------------------------*/
 
////////////////////////////////////////////////////////////////////////////////////
// Including the system header file Origin.h should be sufficient for most Origin
// applications and is recommended. Origin.h includes many of the most common system
// header files and is automatically pre-compiled when Origin runs the first time.
// Programs including Origin.h subsequently compile much more quickly as long as
// the size and number of other included header files is minimized. All NAG header
// files are now included in Origin.h and no longer need be separately included.
//
// Right-click on the line below and select 'Open "Origin.h"' to open the Origin.h
// system header file. 
#include <Origin.h>

#pragma labtalk(0) //--- CPY 7/26/05 hide all functions in this file from LT access, as XF should be used instead

//#include <OC_Res.h> ///DG FOLDER_WITH_DISPLAY_ICON
#include <GetNBox.h>
#include <..\\originlab\\XFunctionEx.h>  //CPY 4/17/08 QA70-11438 PA_NEED_THEME_SUPPORT_FROM_MENU
#include <xfutils.h>
#include <..\\originlab\\theme_utils.h>
#include <ReportTree.h>
#include <okocUtils.h>

#define DEFAULT_EVENT_BODY   "return false;"
#define STR_WIZARD	"wiz"
#define STR_ZERO	"0"	///Joseph 04/16/07 SUPPORT_ZERO_FOR_THEME_LAST_USED

#define	SHOW_TIME(_STR) //show_time(_STR) //---- CPY 4/23/07 GRAPH_EXPORT_SPEED_TESTING

/// Justin 2007-03-11 v8.0578 DISPLAY_DIFF_LANGUAGE_HELP_FOR_DIFF_LANGUAGE_VERSION
//static int _get_current_language()
//{
	//return IDRS_HELP_C;// will do this later
//}
int _get_current_language()
{
	//----- CPY 11/3/2007 LANGUAGE_CHAR_FROM_OC
	/*
	stWCBUSERINFO UserInfo;
	int nRet = GetUserInfo(&UserInfo);
	
	if ( 'E' == *(UserInfo.lpstrLanguageCharater) )
		return IDRS_HELP_E;
	else if ('J' == *(UserInfo.lpstrLanguageCharater) )
		return IDRS_HELP_J;
	else if ('G' == *(UserInfo.lpstrLanguageCharater) )
		return IDRS_HELP_G;
	else if ('C' == *(UserInfo.lpstrLanguageCharater) )
		return IDRS_HELP_C;
	*/
	char szTemp[10];
	get_current_language(szTemp);
	switch(szTemp[0])
	{
	case 'E':
		return IDRS_HELP_E;
	case 'J':
		return IDRS_HELP_J;
	case 'G':
		return IDRS_HELP_G;
	case 'C':
		return IDRS_HELP_C;
	}
	//----- end LANGUAGE_CHAR_FROM_OC
	return IDRS_HELP_E;
}
/// End DISPLAY_DIFF_LANGUAGE_HELP_FOR_DIFF_LANGUAGE_VERSION

/// YuI 09/22/06 GETN_TREE_FOR_VARS_SET_EXTERNALLY_SHOULD_BE_CORRECT
/*
bool	_update_xfunction_last_used(TreeNode& trXF, int nAutoUpdate)
{
	Tree trTemp;
	if( xfunction_tree_to_getn_tree(trTemp, trXF, TRUE) )
	{
		trTemp.AutoUpdate.nVal = nAutoUpdate;
		theme_update_last_used(trXF.XFName.strVal, trTemp);
		
		return true;
	}
	
	return false;
}
*/

bool	_update_xfunction_last_used(TreeNode& trGetN, TreeNode& trXF, int nAutoUpdate, DWORD dwCntrlFromXF)
{
	if(trGetN) ///Iris 11/09/06 FIX_GET_RUNTIME_ERR_WHEN_SEL_XF_THEME_FROM_MENU
	{
		//-----	CPY 4/27/07 QA70-9693 BETTER_OC_CALLING_CONTROL
		//	trGetN.AutoUpdate.nVal = nAutoUpdate;
		//	trGetN.AutoUpdate.DataID = IDE_AUTO_UPDATE;	 //--- CPY 3/17/2007 XF_THEME_SAVING_FOUND_WRONG_ID_FOR_AUTO_UDATE
		if(trGetN.AutoUpdate)
		{
			if(nAutoUpdate >= 0)
				trGetN.AutoUpdate.nVal = nAutoUpdate;
			trGetN.AutoUpdate.DataID = IDE_AUTO_UPDATE;	 //--- CPY 3/17/2007 XF_THEME_SAVING_FOUND_WRONG_ID_FOR_AUTO_UDATE
		}
		//------ CPY 8/24/2007 QA70-10231 ALLOW_THEME_TO_BE_REMEMBER_IF_USER_CHANGED_FROM_DIALOG
		//theme_update_last_used(trXF.XFName.strVal, trGetN);
		theme_update_last_used(trXF.XFName.strVal, trGetN, false, NULL, dwCntrlFromXF);
		//------
		///------ Folger 08/25/09 QA80-14145 SUPPORT_FOLDER_LAST_USED_THEME_IN_PE_XFS
		theme_update_xf_folder_last_used(trGetN, trXF);
		///------ End SUPPORT_FOLDER_LAST_USED_THEME_IN_PE_XFS
		//------ CPY 6/28/07 FILE_RECENT_IMPORT_SHOULD_USE_LAST_USED_THEME
		string strThemeName = STR_LAST_USED;
		on_theme_save_as(trGetN, strThemeName);
		//------
		return true;
	}
	return false;
}
/// end GETN_TREE_FOR_VARS_SET_EXTERNALLY_SHOULD_BE_CORRECT

static bool _xf_get_event_body(TreeNode& trXF, int nEvent, string& strBody)
{
	return okutil_xft_get_event_body(&trXF, nEvent, &strBody);
}
static string _xf_get_name(TreeNode& trXF, bool bConvertToCname = false)
{
	return okutil_xft_get_function_name(&trXF, bConvertToCname, false);
}


#define EVENT_NAME			   "%s_event%d"

static string _xf_get_event_name(TreeNode& trXF, int nEvent)
{
	string strName;
	strName.Format(EVENT_NAME, _xf_get_name(trXF, true), nEvent); 
	return strName;
}
static 	bool _xf_get_source_path(TreeNode& trXF, string& strFullpath, bool bPrepareFile = false)
{
	return okutil_xft_get_source_path(&trXF, &strFullpath, bPrepareFile);
}

Function xf_get_event(TreeNode& trXF, int nEvent)
{
	Function fnNull;
	bool bSimpleGetNeventHandler = (nEvent < 2)? true:false;//CPY 10/8/05 QA70-8132 XFN_EVENT_BREAKUP_FOR_2_3_ONLY
	
	if(bSimpleGetNeventHandler)
	{
		string strBody;
		if( _xf_get_event_body(trXF, nEvent, strBody) )
		{
			strBody.TrimLeft();
			strBody.TrimRight();
			if(0 == strBody.Compare(DEFAULT_EVENT_BODY))
				return fnNull;
			string strEvntName = _xf_get_event_name(trXF, nEvent);
			string strSrcPath;
			if(!_xf_get_source_path(trXF, strSrcPath, true))
				return fnNull;
			bool bLoadDependents = trXF.AutoDependent.nVal? true:false;
			return Project.FindFunction(strEvntName, strSrcPath, bLoadDependents, true, true);
		}
		return fnNull;
	}
	//#else// CALL_NEW_EVENTS

	//CPY 10/8/05 QA70-8132 XFN_EVENT_BREAKUP_FOR_2_3_ONLY
	// these are using new event handler that are in vector<string> with template c files
	string strEvntName; 
	if(okutil_xft_get_event_name(&trXF, false, nEvent, &strEvntName) && !strEvntName.IsEmpty())
	{
		string strSrcPath;
		if(!_xf_get_source_path(trXF, strSrcPath, true))
			return fnNull;
		bool bLoadDependents = trXF.AutoDependent.nVal? true:false;
		return Project.FindFunction(strEvntName, strSrcPath, bLoadDependents, true, true);
	}	
	return fnNull;
}



TreeNode xf_get_help_node(TreeNode& trXF, int nNodeID = IDV_HELP_SUMMARY, int nLanguage = IDRS_HELP_E) 
{
	/// YuI 04/06/06 BETTER_XFUNCTION_ERROR_HANDLING
	/*
	if(nLanguage < IDRS_HELP_E || nLanguage > IDRS_HELP_C)
		nLanguage = _get_current_language();

	//--- English description is at a diff location for better visibility
	if(IDRS_HELP_E == nLanguage && IDV_HELP_DESCRIPTION == nNodeID)
		return tree_find_node_by_dataID(trXF, IDXF_DESCRIPTION);
	//---
	
	/// ----AW 11/03/05 ADD_HELP_SCREEN_SHOT
	/*
	/// 
	///DG 9/16/05 : For See Also node
	if(IDV_HELP_SEE_ALSO == nNodeID)
		return tree_find_node_by_dataID(m_tree, nNodeID);
	///end

	//---- Kevin 09/30/05 MODIFY_HELP_INFO
	if(IDXF_SYNTAX == nNodeID)
		return tree_find_node_by_dataID(m_tree, nNodeID);
	//----
	*/
	/*
	if ( IDV_HELP_SEE_ALSO == nNodeID || IDXF_SYNTAX == nNodeID || IDV_HELP_SCREEN_SHOT == nNodeID )
		return tree_find_node_by_dataID(trXF, nNodeID);
	/// END ADD_HELP_SCREEN_SHOT

	return tree_find_node_by_dataID(trXF, nNodeID, IDV_HELP_BRANCH, nLanguage);
	*/
	TreeNode trHelp;
	okxf_get_help_node(&trHelp, &trXF, nNodeID, nLanguage);
		
	return trHelp;
	/// end BETTER_XFUNCTION_ERROR_HANDLING
}

///Joseph 06/06/07 MOVE_SOME_FUNCTIONS_AND_DEFINITIONS_TO_XFUNCTION_HEADER_FILE
//move function from xfdocument.c to xfunction.c file
string xf_get_language_string(int nIDLang)
{
	switch(nIDLang)
	{
	case IDRS_HELP_E:
		return STR_LANGUAGE_ENGLISH;
	case IDRS_HELP_J:
		return STR_LANGUAGE_JAPANESE;
	case IDRS_HELP_G:
		return STR_LANGUAGE_GERMAN;
	case IDRS_HELP_C:
		return STR_LANGUAGE_CHINESE;
	default:
		return "";
	}
	return "";
}
///End MOVE_SOME_FUNCTIONS_AND_DEFINITIONS_TO_XFUNCTION_HEADER_FILE

//--- CPY 3/3/05 INTERNAL_XF_EDIT
bool	check_x_function_tree(const TreeNode& trFunc , bool bMustHaveVaris)
{
	// more codes needed later for check ID as well
	if(bMustHaveVaris)
	{
		TreeNode trVars = trFunc.vars;
		if(!trVars.IsValid() || trVars.GetNodeCount() <= 0)
			return false;
	}
	if(trFunc.XFname)
	{
		if(trFunc.codes.code)
			return true;
	}
	return false;
}
//---	



/// ML 3/16/2005 QA70-7498 NEW_GROBJ_BASED_X_VARIABLE_TYPES
/*
static	TreeNode	xvargrobj_get_node_from_aux_tree(TreeNode &trAux, int nAuxIndex)
{
	TreeNode		tr;
	if (!trAux.IsValid())
	{
		error_report("Invalid Graph Object Data tree!");
		return tr;
	}
	// Per Roman's idea, for now just assume the correct index:
	tr = trAux.Children.Item(nAuxIndex); 
	return tr;
}
*/
/// end NEW_GROBJ_BASED_X_VARIABLE_TYPES





/// YuI 01/31/06 DOCUMENT_FUNCTIONS_SHOULD_DEAL_WITH_TREE_ONLY
void	xf_get_variables(TreeNode& trXF, vector<string>& vsNames, vector<string>& vsValData, vector<string>& vsValTypes, bool bVarTypesAddRef, vector<int>& vnIO, BOOL bInternal)
{
	XFBase xf(trXF);
	xf.GetVariables(vsNames, vsValData, vsValTypes, bVarTypesAddRef, vnIO);
}

TreeNode 	xf_get_variable_tree_node(TreeNode& trXF, LPCSTR lpcszName)
{
	TreeNode trVars;
	okutil_xft_GetVarsNode(&trVars, &trXF);
	foreach( TreeNode trOneVar in trVars.Children )
	{
		string strName = trOneVar.name.strVal;
		///Joseph 02/28/07 SHOULD_SUPPORT_VARIABLE_NO_CASE
		//if( strName.Compare(lpcszName) == 0 )
		if( strName.CompareNoCase(lpcszName) == 0 )
		///End SHOULD_SUPPORT_VARIABLE_NO_CASE
		{
			return trOneVar ;
		}
	}
	
	TreeNode trInvalid;
	return trInvalid;
}
/// end DOCUMENT_FUNCTIONS_SHOULD_DEAL_WITH_TREE_ONLY

//----- CPY 12/1/2007 QA70-10765 DEFAULT_CODE_PAGE_CONTROL
	/*
	XFunction()
	{
		//m_bInternal = false;
	}
	XFunction(TreeNode& trXF, bool bInternal, BOOL bCompile = false, BOOL bPrepareVars = true) : XFBase(trXF, bCompile, bPrepareVars, bInternal)
	{
		//m_bInternal = bInternal;
		m_tree = trXF;
	}
	~XFunction() {}
	*/
XFunction::XFunction()
{
	//---- CPY 12/5/07 QA70-10782 REPORT_FOR_J_SHOW_JUNK
	// this change is problematic since tree values might have J but not having J code page attribute, so will need current code page to convert
	// I will just put Germen help under ANSI code page in oUtils.cpp
	//m_nSaveXMLStrCodePage = octree_set_default_code_page(CP_US_ANSI);
	//----
}
XFunction::XFunction(TreeNode& trXF, bool bInternal, BOOL bCompile, BOOL bPrepareVars) : XFBase(trXF, bCompile, bPrepareVars, bInternal)
{
	//---- CPY 12/5/07 QA70-10782 REPORT_FOR_J_SHOW_JUNK
	//m_nSaveXMLStrCodePage = octree_set_default_code_page(CP_US_ANSI);
	//----
	m_tree = trXF;
}
XFunction::~XFunction()
{
	//---- CPY 12/5/07 QA70-10782 REPORT_FOR_J_SHOW_JUNK
	//octree_set_default_code_page(m_nSaveXMLStrCodePage);
	//----
}
//----- end DEFAULT_CODE_PAGE_CONTROL


/// ML 3/6/2006 AUTOUPDATE_MORE_WORK
//BOOL open_XF_getn_dialog(TreeNode& trXF, XFBase& xf, bool bExecute, bool bCheckUseAutoUpdate, bool bUpdateLastUsed)
BOOL	XFunction::Run(int nAutoUpdate, TreeNode& trGetN)
{
	//----- CPY 7/12/06 QA70-8731 AUTO_UPDATE_LOST_FROM_GUI
	//if ( bAutoUpdate )
	//	return CreateInternalOperation();
	if ( nAutoUpdate != AU_NONE )
		//----- CPY 3/1/07 THEME_AUTOUPDATE_CLEAN_UP
		//return CreateInternalOperation(AU_AUTO == nAutoUpdate? true:false);
		return CreateInternalOperation(AU_AUTO == nAutoUpdate? true:false,LTXF_EXECUTE,NULL, trGetN);
		//-----
	//-----
	return XFBase::Run(nAutoUpdate, trGetN);		// bAutoUpdate not really used here 
}




/*
BOOL open_XF_getn_dialog(TreeNode& trXF, XFunction& xf, bool bExecute, bool bCheckUseAutoUpdate, bool bUpdateLastUsed)
/// end AUTOUPDATE_MORE_WORK
{
	//----------------------
	return okxf_open_XF_getn_dialog(&trXF, &xf, bExecute, bCheckUseAutoUpdate, bUpdateLastUsed);
	//----------------------*/
/*
	TreeNode trVars = trXF.vars;
	if( !trVars )
		return false;
	
	/// DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
	//	XFunctionOrganizer xfo;
	/// end SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION

	/// YuI 08/17/05 TREE_CONSITENCY_ADDITIONAL_CHECK
	//	xfo.CheckUpdateVarTypeControlConsistency(trXF);
	/// end TREE_CONSITENCY_ADDITIONAL_CHECK

	/// DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
	//string strFilename = xfo.GetFuncFileName(trXF, true);	
	string strFilename = okutil_fo_GetFuncFileName(&trXF, true);
	///end SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
	
	string strCompositeName = okutil_composite_name_from_file_path(strFilename, STR_XF_FILE_FOLDER);
	string strTag, strLabel;
	int ii = 1;

	string strTagName = trXF.UsageCtxt.mainmenu.Theme.nVal ? "XFGUI" : "GetNBox";
	GETN_NAMED_TREE2(tr, strTagName);

	GETN_OPTION_GRIDLINE(flexGridFlatVert)
	GETN_OPTION_EDIT_ALIGN("0|0|0")

	bool bAddAutoUpdate = false;
	///// DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
	//// if(bCheckUseAutoUpdate)
	////	bAddAutoUpdate = xfo.IsAutoupdatePossible(trXF);
	//if(bCheckUseAutoUpdate)
	//	bAddAutoUpdate = xf_is_autoupdate_possible(trXF);
	///// end SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
	if(bCheckUseAutoUpdate)
		bAddAutoUpdate = xf.IsAutoUpdatePossible();

	if( !xfunction_tree_to_getn_tree(tr, trXF, bAddAutoUpdate) )
		return false;
	
	
	string strTitle = strCompositeName;
	string strDescription = trXF.xFdescription.strVal;
    Function fnEvent1 = xf_get_event(trXF, 1);//xf.GetEvent(1);
    int nEventId = trXF.UsageCtxt.mainmenu.GetN.nVal;
    BOOL bUserInputArgs = FALSE;
    //--- CPY 9/16/05 GET_N_IMAGE_DIALOG
	PEVENT_FUNC pfnEvent = (PEVENT_FUNC)fnEvent1;
	HWND hWndParent = GetWindow();
    if(3 == nEventId)
    {
    	Function fnEvent2 = xf_get_event(trXF, 3);
	    //Function fnGetNImageBox = Project.FindFunction("GetNImageBox", "OriginLab\\GetNGraphDlg", true, false);
	    /// ML 2/16/2006 DYNACONTROL_BASED_GetNImageBox
	    //Function fnGetNImageBox = Project.FindFunction("GetNImageBox", "OriginLab\\GetNImageDlg", true, false);
	    Function fnGetNImageBox;
//	    if ( MessageBox(GetWindow(), "Do you want to use new GetNImageBox?", "open_XF_getn_dialog", MB_YESNO) == IDYES )
	    	fnGetNImageBox = Project.FindFunction("GetNImageBox", "OriginLab\\GetNImageDlg", true, false);
//	    else
//	    	fnGetNImageBox = Project.FindFunction("GetNImageBoxOld", "OriginLab\\GetNImageDlgOld", true, false);
	    /// end DYNACONTROL_BASED_GetNImageBox
	    FUNC_GETNIMAGEBOX pfnGetNImageBox = fnGetNImageBox;
		if(pfnGetNImageBox)
		{
			PIMAGE_FUNC pfnImage = (PIMAGE_FUNC)fnEvent2;
			bUserInputArgs = pfnGetNImageBox(tr, strTitle, strDescription, pfnImage, hWndParent);
		}
		else
			return error_report("failed to load GetNGraphBox"); 
    }
    //----
    else if(nEventId == 2 || nEventId == 4)
    {
    	Function fnEvent2 = xf_get_event(trXF, nEventId);
	    Function fnGetNGraphBox;
	    if(nEventId == 4)
	    	fnGetNGraphBox = Project.FindFunction("GetNBoxEx", "OriginLab\\GetNPrevwDlg.c", false, true);
	    else	    	
	    	fnGetNGraphBox = Project.FindFunction("GetNGraphBox", "OriginLab\\GetNGraphDlg.c", false, true);
	    
		FUNC_GETNGRAPHBOX	pfnGetNGraphBox = fnGetNGraphBox;
		if(pfnGetNGraphBox)
		{
			PGRAPH_FUNC pfnGraph = (PGRAPH_FUNC)fnEvent2;
			//PEVENT_FUNC pfnEvent = (PEVENT_FUNC)fnEvent1;
			bUserInputArgs = pfnGetNGraphBox(tr, strTitle, strDescription, pfnGraph, hWndParent, nEventId);
		}
		else
			return error_report("failed to load GetNGraphBox"); 
    }
    else if(nEventId == 1)
	{
		//PEVENT_FUNC pfnEvent = (PEVENT_FUNC)fnEvent1;
	    bUserInputArgs = GetNBox(tr, strTitle, strDescription, NULL, pfnEvent, hWndParent);
	}
	else		///If nEventId = 0, mean not need any dialog.
		bUserInputArgs = true;

	
    if(bUserInputArgs)
    {
		//if( getn_tree_to_xfunction_tree(trXF, tr) )
		if(okxf_getn_to_xf(&trXF, &tr, false))
		{
			/// YuI 07/29/05 QA70-7953 XF_THEME_SUPPORT
			if( bUpdateLastUsed )
			{
				BOOL bAutoupdate = FALSE;
				if( tr.AutoUpdate )
					 bAutoupdate = tr.AutoUpdate.nVal;
				
				_update_xfunction_last_used(trXF, bAutoupdate);
			}
			/// end XF_THEME_SUPPORT
			if(!bExecute)
				return true;
			
			///---DG 7/13/05 run time error when there is not autoupdate node
			//BOOL bAutoUpdate = tr.AutoUpdate.nVal;
			TreeNode trAutoUpdate = tr.AutoUpdate;
			bool bAutoUpdate = trAutoUpdate.IsValid() ? trAutoUpdate.nVal : false;
			///---end
			//------ CPY 10/10/05 XF_EXEC_FROM_GUI_ALSO_NEED_RESULTS_LOG
			//if( bAutoUpdate )
			//	xf.CreateInternalOperation(false);
			//else
			//return xf.Evaluate();
			
			
			return xf.Run(bAutoUpdate, tr);
			//------ end XF_EXEC_FROM_GUI_ALSO_NEED_RESULTS_LOG
		}
		
		return true;
    }
    return false;
*/
//}

BOOL	xf_check_update_var_type_control_consistency(TreeNode& tr, bool bDisableGUI)
{
	TreeNode trVars;
	okutil_xft_GetVarsNode(&trVars, &tr, NULL);
	
	if( !trVars )
		return FALSE;
	
	foreach(TreeNode trVar in trVars.Children )
	{
		okutil_xft_UpdateVar(&trVar, bDisableGUI);
	}
	
	return TRUE;
}


// BOOL	XFunctionOrganizer::CheckUpdateTreeConsistency(TreeNode& tr, bool bInternalXF)
BOOL	xf_check_update_tree_consistancy(TreeNode& tr, bool bInternalXF, bool bDisableGUI)
{
	//---- CPY 4/11/05 INTERNAL_XF_NO_NEED_FOR_USAGE_CONTEXT
	TreeNode trN = tr.UsageCtxt;
	if(trN)
	{
		if(bInternalXF)
			trN.Show = false;
		else
			trN.RemoveAttribute(STR_SHOW_ATTRIB);
	}	
	//----

	// return 	CheckUpdateVarTypeControlConsistency(tr);// &&
	// 		//CheckUpdateInternalAutoUpdateConsistency(tr);
	return	xf_check_update_var_type_control_consistency(tr, bDisableGUI);
}
///--- end SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION

//----- CPY 2/20/2007 QA70-9335 XF_RESULTS_LOG_DUMP_GLOBAL_CONTROL_AND_XF_CONTROL, added dwCntrl
void xf_update_results_cmd_log_output_options(TreeNode& trXF, DWORD& dwControl)
{
	double dResultsLog = -1;
	LT_get_var("@XFR",&dResultsLog);
	dwControl &= ~LTXF_OUT_RESULTS_LOG_MASK;
	int nResultsLogOptn;
	
	if(dResultsLog < 0)
		nResultsLogOptn = trXF.outResultsLog.nVal;
	else
		nResultsLogOptn = dResultsLog;

	dwControl |= nResultsLogOptn;
		
	
	int nCreateLTTree = trXF.outTree.nVal;
	if(nCreateLTTree)
		dwControl &=~LTXF_NO_CREATE_LT_TREE;
	else
		dwControl |= LTXF_NO_CREATE_LT_TREE;
	
	double dOutCmdLog = 0;
	LT_get_var("@XFC",&dOutCmdLog);
	if(dOutCmdLog > 0)
		dwControl |= LTXF_OUT_COMMAND_LOG;
}
//-----

/// YuI 07/29/05 QA70-7953 XF_THEME_SUPPORT

///------ Folger 12/11/09 QA81-14831-P2 OPEN_XF_DIALOG_FROM_LT_SUPPRESS_ERROR_WHEN_USER_CANCEL
//BOOL CallXFunction(LPCSTR lpcszOxfName, LPCSTR lpcszArgs, DWORD dwControl, int nParam, LPVOID lpRetData, int nXVT)
//{
	//return CallXFunctionEx(lpcszOxfName, lpcszArgs, dwControl, nParam, lpRetData, nXVT, NULL);
//}
BOOL CallXFunction(LPCSTR lpcszOxfName, LPCSTR lpcszArgs, DWORD dwControl, int nParam, LPVOID lpRetData, int nXVT, int* pnExecuteErr/* = NULL*/)
{
	return CallXFunctionEx(lpcszOxfName, lpcszArgs, dwControl, nParam, lpRetData, nXVT, NULL, NULL, pnExecuteErr);
}
///------ End OPEN_XF_DIALOG_FROM_LT_SUPPRESS_ERROR_WHEN_USER_CANCEL
/// end XF_THEME_SUPPORT

/// YuI 08/12/05 QA70-8006 XFUNCTION_AND_TREE_VARIABLE

/// YuI 04/09/09 QA70-13435 OPTION_TO_SUPPRESS_LT_ERROR_FOR_XF_INVOCATION
enum
{
	XF_SILENT_RESULTS_LOG = 0x00000001,
	XF_SILENT_LT_ERROR = 0x00000002,
	XF_SILENT_INFO_MSG = 0x00000004, //---- CPY 8/14/09 QA70-14154 XF_CMD_LINE_OPTN_TO_SUPRESS_INFO_MSG
};
/// end OPTION_TO_SUPPRESS_LT_ERROR_FOR_XF_INVOCATION

///------ Folger 04/22/09 QA80-10889 SUPPORT_COPY_DATA_FORMAT_AS_NEW_XF_SWITCH
enum
{
	XF_COPY_DATA_FORMAT			= 1,
};
///------ End SUPPORT_COPY_DATA_FORMAT_AS_NEW_XF_SWITCH

static		int		_tolower(char c)
{
	return c | (1 << 5);
}

//---- CPY 8/14/09 QA70-14154 XF_CMD_LINE_OPTN_TO_SUPRESS_INFO_MSG
static DWORD _get_xf_silient_mode_bits(LPCSTR lpcsz)
{
	LPCSTR pp = lpcsz;pp++;//skip 1st letter which is 'S'
	char cc1;
	DWORD dw = 0;
	while(cc1 = *pp++)
	{
		int cc = _tolower(cc1);
		switch ( cc )
		{
		case 'l': // -sl silent log
			dw |= XF_SILENT_RESULTS_LOG;
			break;
		case 'e': // -se silent error
			dw |= XF_SILENT_LT_ERROR;
			break;
		case 'b': // -sb silent both
			dw |= XF_SILENT_LT_ERROR | XF_SILENT_RESULTS_LOG;
			break;
		case 's':
			dw |= XF_SILENT_INFO_MSG;
			break;
		}
	}
	return dw;
}
//---- end XF_CMD_LINE_OPTN_TO_SUPRESS_INFO_MSG

/// YuI 11/25/06 BIN_WKS_AUTOUPDATE
//	static int	_preparse_XF_command_line(string& strCmd, string& strTheme, string& strInput, string& strOutput, string& strRedirect, BOOL& bDialog, BOOL& bHelp, BOOL& bFromMenu)
// CPY 12/2/06 ALLOW_LT_TO_ATTACH_XF_TO_XFBAR, added bXFBar 
/// YuI 01/17/07 QA70-9285 SILENT_XF_INVOCATION
//	static int _preparse_XF_command_line(string& strCmd, string& strTheme, string& strInput, string& strOutput, int& nRecalculate, BOOL& bDialog, BOOL& bHelp, BOOL& bFromMenu, BOOL& bXFBar)
//------ Folger 07/16/08 QA80-11855 BETTER_FORMATTING_FOR_XF_HELP_DUMPING
//static int _preparse_XF_command_line(string& strCmd, string& strTheme, string& strInput, string& strOutput, int& nRecalculate, BOOL& bDialog, BOOL& bHelp, BOOL& bFromMenu, BOOL& bXFBar, BOOL& bSilent
/// YuI 04/09/09 QA70-13435 OPTION_TO_SUPPRESS_LT_ERROR_FOR_XF_INVOCATION
//	static int _preparse_XF_command_line(string& strCmd, string& strTheme, string& strInput, string& strOutput, int& nRecalculate, BOOL& bDialog, int &nHelpList, BOOL& bFromMenu, BOOL& bXFBar, BOOL& bSilent
static int _preparse_XF_command_line(string& strCmd, string& strTheme, string& strInput, string& strOutput, int& nRecalculate, BOOL& bDialog, int &nHelpList, BOOL& bFromMenu, BOOL& bXFBar, DWORD& dwSilentMode
/// end OPTION_TO_SUPPRESS_LT_ERROR_FOR_XF_INVOCATION
//------
,BOOL& bFromMRC //---- CPY 7/11/2007 QA70-10010 MOST_RECENT_IMPORT_EXPORT_NEED_LTXF_FROM_MRU_MENU
, int& nCopyCntrl	///------ Folger 04/22/09 QA80-10889 SUPPORT_COPY_DATA_FORMAT_AS_NEW_XF_SWITCH
)
/// end SILENT_XF_INVOCATION
{
	StringArray arrPresentSwitches;
	StringArray arrPresentValues;
	IntArray 	arrPresentSwitchesIndices;
	StringArray arrAbsentSwitches;

	string strRemaining;
	LPSTR pstr = strCmd.GetBuffer(strCmd.GetLength() + 10);
	int nRet = okutil_parse_XF_command_line(pstr, &arrPresentSwitches, &arrPresentValues, &arrAbsentSwitches, &arrPresentSwitchesIndices,  &strRemaining);
	strCmd.ReleaseBuffer();
	
	if( nRet >= 0 )
	{
		strCmd = strRemaining;
		for( int ii = 0; ii < arrPresentSwitchesIndices.GetSize(); ii++ )
		{
			int nSwitch = arrPresentSwitchesIndices[ii];
			switch( nSwitch )
			{
			case XFSW_THEME:
				strTheme = arrPresentValues[ii];
				//---- CPY 10/10/05 CENTRALIZED_XF_ARG_QUOTE_HANDLING
				string strTemp;
				/// ML 1/13/2006 XVARIABLEBASE_TO_VC
				//check_cvt_str(strTheme, strTemp, true);
				check_cvt_str(strTheme, &strTemp, true);
				/// end XVARIABLEBASE_TO_VC
				strTheme = strTemp;
				//---- end 
				break;
				
			case XFSW_INPUT:
				strInput = arrPresentValues[ii];
				break;
				
			case XFSW_OUTPUT:
				strOutput = arrPresentValues[ii];
				break;
				
			case XFSW_RECALCULATE:
				/// YuI 11/25/06 BIN_WKS_AUTOUPDATE
				//	strRedirect = arrPresentValues[ii];
				nRecalculate = atoi(arrPresentValues[ii]);
				/// end BIN_WKS_AUTOUPDATE
				break;
				
			case XFSW_DIALOG:
				//--- CPY 10/1/06 XF_SWITCH_ALLOW_MORE_CHARS
				{
					string strTemp = arrPresentValues[ii];
					if(strTemp.GetLength() > 1)
					{
						///------ Folger 12/11/09 QA81-14831-P2 OPEN_XF_DIALOG_FROM_LT_SUPPRESS_ERROR_WHEN_USER_CANCEL
						//switch(strTemp[1])
						int	cc = _tolower(strTemp[1]);
						switch ( cc )
						///------ End OPEN_XF_DIALOG_FROM_LT_SUPPRESS_ERROR_WHEN_USER_CANCEL
						{
						case 'm':// -dm
							bFromMenu = true;
							break;
						case 'b': // -db
							bXFBar = true;
							break;
						//---- CPY 7/11/2007 QA70-10010 MOST_RECENT_IMPORT_EXPORT_NEED_LTXF_FROM_MRU_MENU
						case 'r': // -dr
							bFromMenu = true;
							bFromMRC = true;
							break;
						///------ Folger 12/11/09 QA81-14831-P2 OPEN_XF_DIALOG_FROM_LT_SUPPRESS_ERROR_WHEN_USER_CANCEL
						/// already handle in VC, see same code mark in UtilSDK.cpp
						case 'c':
							break;
						///------ End OPEN_XF_DIALOG_FROM_LT_SUPPRESS_ERROR_WHEN_USER_CANCEL
						//----
						}
					}
				}
				//---
				bDialog = TRUE;
				break;

			case XFSW_HELP:
				//------ Folger 07/16/08 QA80-11855 BETTER_FORMATTING_FOR_XF_HELP_DUMPING
				//bHelp = TRUE;
				nHelpList = XF_HELP_LIST_ALL;
				if ( arrPresentValues[ii].GetLength() > 1 )
				{
					int cc = _tolower(arrPresentValues[ii][1]);
					switch ( cc )
					{
						case 's':
							nHelpList = XF_HELP_LIST_USAGE;
							break;
							
						case 'v':
							nHelpList = XF_HELP_LIST_VARIABLES;
							break;

						case 't':
							nHelpList = XF_HELP_LIST_TREENODE_DETAILS;
							break;

						/// YuI 10/01/08 QA70-12321 LOAD_AND_COMPILE_XF_AND_NOTHING_MORE
						case 'n':
							nHelpList = XF_HELP_LIST_NONE;
							break;
						/// end LOAD_AND_COMPILE_XF_AND_NOTHING_MORE
						
						///------ Folger 03/10/09 QA80-11855 LT_XF_HELP_DUMPING_NEEDS_SUPPORT_DISPLAY_RELATED_XF
						case 'x':
							nHelpList = XF_HELP_LIST_RELATED_XF;
							break;
						///------ End LT_XF_HELP_DUMPING_NEEDS_SUPPORT_DISPLAY_RELATED_XF
						
						default:
							break;								
					}
				}
				//------ End BETTER_FORMATTING_FOR_XF_HELP_DUMPING
				break;
				
			/// YuI 01/17/07 QA70-9285 SILENT_XF_INVOCATION
			case XFSW_SILENT:
				/// YuI 04/09/09 QA70-13435 OPTION_TO_SUPPRESS_LT_ERROR_FOR_XF_INVOCATION
				//	bSilent = TRUE;
				{
					dwSilentMode = XF_SILENT_RESULTS_LOG;
					if ( arrPresentValues[ii].GetLength() > 1 )
					{
						//---- CPY 8/14/09 QA70-14154 XF_CMD_LINE_OPTN_TO_SUPRESS_INFO_MSG
						/*
						int cc = _tolower(arrPresentValues[ii][1]);
						switch ( cc )
						{
						case 'l': // -sl silent log
							dwSilentMode = XF_SILENT_RESULTS_LOG;
							break;
						case 'e': // -se silent error
							dwSilentMode = XF_SILENT_LT_ERROR;
							break;
						case 'b': // -sb silent both
							dwSilentMode = XF_SILENT_LT_ERROR | XF_SILENT_RESULTS_LOG;
							break;
						}
						*/
						dwSilentMode = _get_xf_silient_mode_bits(arrPresentValues[ii]);
						//----- end XF_CMD_LINE_OPTN_TO_SUPRESS_INFO_MSG
					}
				}
				/// end OPTION_TO_SUPPRESS_LT_ERROR_FOR_XF_INVOCATION
				break;
			/// end SILENT_XF_INVOCATION
			///------ Folger 04/22/09 QA80-10889 SUPPORT_COPY_DATA_FORMAT_AS_NEW_XF_SWITCH
			case XFSW_COPY:
				if ( arrPresentValues[ii].GetLength() > 1 )
				{
					int cc = _tolower(arrPresentValues[ii][1]);
					switch ( cc )
					{
					case 'f':
						nCopyCntrl = XF_COPY_DATA_FORMAT;
						break;
					default:
						nCopyCntrl = 0;
						break;
					}
				}
				break;
			///------ End SUPPORT_COPY_DATA_FORMAT_AS_NEW_XF_SWITCH
			}
			nRet = nSwitch;  ///Iris 9/15/05 MAKE_XF_AC_SWTICH_WORK_MORE
		}
	}

	return nRet;
}
/// end XFUNCTION_AND_TREE_VARIABLE

/// YuI 04/06/06 BETTER_XFUNCTION_ERROR_HANDLING
//---- CPY 7/6/06 QA70-8088 CENTRALIZED_ERR_MSG_DLL
/*
void	get_global_xf_errors(vector<int>& vIDs, vector<string>& vMessages)
{
	static vector<int> l_vIDs = {
		XFERR_RUNTIME_EXCEPTION,
		XFERR_MATOBJ_COPY_FAILED, 
		XFERR_INTOPTN_OUT_OF_RANGE,
		XFERR_MATOBJ_FAILED_LT_BMP,
		XFERR_UI_USER_CANCEL,
		XFERR_INVALID_ARG,
		XFERR_NO_ACTIVE_SHEET,
		
		///Echo 6/22/06 GLOBAL_ERROR_HANDLING
		CER_NO_DATA,
		CER_DATA_TOO_FEW, 
		CER_DATA_TOO_MANY,
		CER_COL_NUM_NOT_ONE,
		CER_COL_NUM_NOT_TWO,
		CER_GROUP_NUM_NOT_TWO
		// adding constants? don't forget to add messages to l_vMessages
	};
	
	static vector<string> l_vMessages = 
	{
		"Runtime exceptions", // user will never see this one, but has to be there
		"Failed to copy MatrixObject",
		"Invalid option specified",
		"Failed to construct bitmap",
		"Canceled by user",
		"Invalid argument",
		"No Active Sheet found",
		
		///Echo 6/22/06 GLOBAL_ERROR_HANDLING
		"You must have data to run an analysis", 
		"Too few data points, data points should not be less than %d for analysis",
		"Too many data points, data points should be more than %d for analysis",
		"Please select one column",
		"Please select two column",
		"Group range should has only two levels"		
		// adding messages? don't forget to add constants to l_vIDs
	};
	vIDs 		= l_vIDs;
	vMessages 	= l_vMessages;
}*/
/// end BETTER_XFUNCTION_ERROR_HANDLING

///Iris 9/16/05 OUTPUT_XF_ERR_MESSAGE
/// YuI 04/06/06 BETTER_XFUNCTION_ERROR_HANDLING
//	vector<string> g_vsXFErrors;
/// end BETTER_XFUNCTION_ERROR_HANDLING
// CPY 9/20/05, change this to return false in all cases so caller can just return this function

/// YuI 04/06/06 BETTER_XFUNCTION_ERROR_HANDLING
/*
bool xf_err(int nErr, int nOutputWnd)
{
	string strErr = "X-Function Error unknown";
	if(nErr >= XF_COMMON_ERR_BEGIN && nErr <= XF_COMMON_ERR_END)
	{
		// global list, will move this to a DLL later
		switch(nErr)
		{
		case MATOBJ_COPY_FAILED:
			strErr = "failed to copy MatrixObject";
			break;
		case INTOPTN_OUT_OF_RANGE:
			strErr = "invalid option specified";
			break;
		case MATOBJ_FAILED_LT_BMP:
			strErr = "failed to construct bitmap";
			break;
		///Kevin 11/11/05	ADD_MORE_ERROR_MSG
		case XFERR_UI_USER_CANCEL:
			strErr = "canceled by user";
			break;
		case XFERR_INVALID_ARG:
			strErr = "invalid argument";
			break;
		///End ADD_MORE_ERROR_MSG
		}
	}
	else if(nErr >= 0 && nErr < g_vsXFErrors.GetSize() )	
		strErr = g_vsXFErrors[nErr];
	
	if(nOutputWnd<0)
		nOutputWnd = WRITE_SCRIPT_WINDOW;
	
	strErr.WriteLine(nOutputWnd);
	return false;
}
*/

bool xf_err(int nErr, int nOutputWnd)
{
	throw(nErr);
	return FALSE;
}
/// end BETTER_XFUNCTION_ERROR_HANDLING
///End OUTPUT_XF_ERR_MESSAGE

//---- CPY 5/7/20006 PASSWORD_PREFERS_DIALOG
static bool _xf_is_prefer_open_dialog(TreeNode& trXF, bool bFromMenuOptionIndex)
{
	TreeNode trVars;
	okutil_xft_GetVarsNode(&trVars, &trXF, NULL);
	
	if(!trVars)
		return false;

	int nMaxVarCheck = 3;
	int nn = 0;
	foreach(TreeNode trVar in trVars.Children)
	{
		string strCombo = trVar.comboString.strVal;
		strCombo.MakeLower();
		if(strCombo.Find("password")==0)
			return true;
		//---- CPY 3/20/08 SIM_FOUND_OPTION_INDEX_CHANGE_BROKEN_ASCII_FROM_MENU
		if(bFromMenuOptionIndex && strCombo.Find("...") == 0)
			return true;
		if(++nn >= nMaxVarCheck) // to speed things up, no need to check all vars
			break;
		//----
	}
	return false;
}
//----- end PASSWORD_PREFERS_DIALOG

//------- CPY 5/3/07 QA70-9718 RECENT_IMPORT_EXPORT_WITH_THEME
static bool	XF_on_run_from_menu(const TreeNode& trXF, const string& strThemeName)
{
	if(xf_get_category_name(trXF) == STR_CAT_IMPORT)
	{
		string strTemp;
		string strName = strThemeName;
		if(strName.IsEmpty())
			strName = STR_LAST_USED;
		//----------------- CPY 6/28/07 FILE_RECENT_IMPORT_SHOULD_USE_LAST_USED_THEME
		// do not add to Recent Import if <factory default> or <sheet>
		////------ CPY 6/5/2007 QA70-9803 SHIFT_SELECT_SHOULD_FORCE_DIALOG_TO_OPEN
		//else if(strName == STR_THEME_FACTORY_DEFAULT)
		//	strName = THEME_FILENAME_FACTORY_DEFAULT;
		///---Sim 06-30-2007 PUT_OUT_GLOBAL_FUNC
		//else if(strName == STR_THEME_FACTORY_DEFAULT || strName == STR_SHEET)
		///---Sim 11-05-2007 CLEAN_LOCALIZATION_CODE
		//else if(is_theme_factory_default(strName) || strName == STR_SHEET)
		else if(is_theme_default(strName) || PDS_SHEET == cvt_str_to_predefined_type(strName) )
		///---END CLEAN_LOCALIZATION_CODE
		///---END PUT_OUT_GLOBAL_FUNC
			return false;
		//-----------------
		strTemp.Format("%s: %s", trXF.XFname.strVal, strName);
		okoc_AddToRecentFileList(strTemp);
		return true;
	}
	return false;
}
bool on_theme_save_as(TreeNode& trGetN, const string& strThemeName)
{
	string strXFname;
	// strXFname.GetLength() > 3 need impSomething
	///---Sim 06-30-2007 PUT_OUT_GLOBAL_FUNC
	//if(is_xf_gui_getn_tree(trGetN, &strXFname) && strXFname.GetLength() > 3 && strThemeName.GetLength() > 1 && strThemeName != STR_THEME_FACTORY_DEFAULT)
	//------ Folger 12/02/08 v8.0981b SHOULD_ALLOW_IMP_EXP_XF_THEME_FILE_NAME_TO_BE_ONE_CHARACTER
	//if(is_xf_gui_getn_tree(trGetN, &strXFname) && strXFname.GetLength() > 3 && strThemeName.GetLength() > 1 && !is_theme_default(strThemeName))
	if(is_xf_gui_getn_tree(trGetN, &strXFname) && strXFname.GetLength() > 3 && strThemeName.GetLength() > 0 && !is_theme_default(strThemeName))
	//------
	///---END PUT_OUT_GLOBAL_FUNC
	{
		string strTemp = strXFname.Left(3);
		if(strTemp == "imp" || strTemp == "exp")
		{
			XFBase xf; Tree trXF;
			if(xf.Load(strXFname, 0, trXF, false, true, false))
			{
				if(xf_get_category_name(trXF) == STR_CAT_IMPORT)
				{
					strTemp.Format("%s: %s", strXFname, strThemeName);
					okoc_AddToRecentFileList(strTemp);
					return true;
				}
			}
		}
	}
	return false;
}
//-------

//---- CPY 7/11/2007 CURVE_TRANSLATE_NEED_OPTION_INDEX_PASSED_IN
#define STR_XF_OPTION_INDEX_ATTRIB "OptnIndexWhenCalled"
//----


//---- CPY 3/13/08 QA70-11192 PREFER_DEFAULT_IF_PRESENT
static string _get_prefered_default_theme(LPCSTR lpczXFname)
{
	if(theme_get_default_settings(lpczXFname))
		return STR_DEFAULT_E;
	
	return STR_LAST_USED;
}
//----

//------ CPY Folger 02/29/08 QA80-11192 IMPROVE_IMPASC_THEME_MECHANISM
// check if sheet/book has theme and only if it does not, we will use the theme remember from last time
// or use default theme
//------ Folger 03/31/08 QA80-11333 SHOULD_USE_LAST_USED_WHEN_OPEN_IMPASC_FROM_TOOLBAR_BUTTON
//static bool _check_book_sheet_theme(string& strTheme, TreeNode& trTheme, LPCSTR lpczXFname)
static bool _check_book_sheet_theme(string& strTheme, TreeNode& trTheme, LPCSTR lpczXFname, bool bFromGUIPrompt)
//------
{
	Tree tr;
	
	if(trTheme.SaveInSheet && trTheme.SaveInSheet.nVal && theme_active_book_sheet_storage(tr, lpczXFname, PDS_SHEET, true) )
	{
		strTheme = STR_SHEET;
		return true;
	}
	if(trTheme.SaveInBook && trTheme.SaveInBook.nVal && theme_active_book_sheet_storage(tr, lpczXFname, PDS_BOOK, true) )
	{
		strTheme = STR_BOOK;
		return true;
	}
	
	//------ Folger 03/06/08 QA80-11192 SHOULD_NOT_APPLY_BOOK_SHEET_THEME_IF_ACTIVE_BOOK_SHEET_NOT_HAVE
	int nThemeType = cvt_str_to_predefined_type(strTheme);
	if ( nThemeType == PDS_SHEET || nThemeType == PDS_BOOK )
	{
		//---- CPY 3/13/08 QA70-11192 PREFER_DEFAULT_IF_PRESENT
		//strTheme = STR_LAST_USED;		//active book/sheet doesn't have any theme, reset to <last used>
		strTheme = _get_prefered_default_theme(lpczXFname);
		//----
		return true;
	}
	//------
	
	if(strTheme.IsEmpty())
	{
		//CPY checked with Max on 3/10 and he think better prefer <last used>
		//if(theme_get_default_settings(lpczXFname, NULL))
		//	strTheme = STR_DEFAULT_E;
		//else
		//---- CPY 3/13/08 QA70-11192 PREFER_DEFAULT_IF_PRESENT
		//strTheme = STR_LAST_USED;
		
		//need to restore default when open xf from fly-out menu "XFName ==> Open Dialog"
		//strTheme = _get_prefered_default_theme(lpczXFname);
		//if ( theme_get_default_settings(lpczXFname) )
			//strTheme = STR_DEFAULT_E;
		
		//------ Folger 03/31/08 QA80-11333 SHOULD_USE_LAST_USED_WHEN_OPEN_IMPASC_FROM_TOOLBAR_BUTTON
		
		//------ Folger 04/01/08 QA80-11333 SHOULD_CHECK_DEFAULT_THEME_BEFORE_USE_LAST_USED
		//if ( bFromGUIPrompt )
		
		//------ Folger 06/16/08 FIX_DEFAULT_THEME_DISPLAY_IN_IMPORT_ASCII_FROM_FILE_IMPORT_MENU
		/*
		if ( !theme_get_default_settings(lpczXFname) && bFromGUIPrompt )
		//------
		{
			string strThemeFile = okutil_theme_get_settings_file(THEME_FILENAME_LAST_USED, lpczXFname);
			if ( strThemeFile.IsFile() )
				strTheme = STR_LAST_USED;
		}
		else
		//------
			strTheme = STR_DEFAULT_E;
		//----
		*/
		//------ Folger 10/29/08 v8.0962 GET_XF_NAME_FROM_COMPOSITE_NAME_BEFORE_CHECKING_DEFAULT_THEME
		//if ( theme_get_default_settings(lpczXFname) )
		string		strXFName = okutil_separate_composite_name(lpczXFname);
		if ( theme_get_default_settings(strXFName) )
		//------
		{
			strTheme = STR_DEFAULT_E;
		}
		else
		{
			if ( bFromGUIPrompt )
			{
				//------ Folger 10/29/08 v8.0962 GET_XF_NAME_FROM_COMPOSITE_NAME_BEFORE_CHECKING_DEFAULT_THEME
				//string strThemeFile = okutil_theme_get_settings_file(THEME_FILENAME_LAST_USED, lpczXFname);
				string strThemeFile = okutil_theme_get_settings_file(THEME_FILENAME_LAST_USED, strXFName);
				//------
				if ( strThemeFile.IsFile() )
					strTheme = STR_LAST_USED;
			}
		}
		//------ End FIX_DEFAULT_THEME_DISPLAY_IN_IMPORT_ASCII_FROM_FILE_IMPORT_MENU
	}
	
	return false;
}
//------ end IMPROVE_IMPASC_THEME_MECHANISM


///------ Folger 04/22/09 QA80-10889 SUPPORT_COPY_DATA_FORMAT_AS_NEW_XF_SWITCH
class	XFOutputDataFormatCopyHelper
{
public:
	XFOutputDataFormatCopyHelper(bool bCopyAll)
	{
		m_strYPA = "@YPA";
		m_rYPACache = -1.0;
		if ( bCopyAll )
		{
			LT_get_var(m_strYPA, &m_rYPACache);
			LT_set_var(m_strYPA, 0.0);
		}
	}
	~XFOutputDataFormatCopyHelper()
	{
		if ( m_rYPACache >= 0.0 )
			LT_set_var(m_strYPA, m_rYPACache);
	}
	
private:
	string	m_strYPA;
	double	m_rYPACache;
};
///------ End SUPPORT_COPY_DATA_FORMAT_AS_NEW_XF_SWITCH
			
			
			
/// TD 3-4-05 QA70-7412 COMMAND_XF_TO_CALL_XFUNTION_FROM_LABTALK
/// YuI 07/29/05 QA70-7953 XF_THEME_SUPPORT
//	BOOL CallXFunction(LPCSTR lpcszOxfName, LPCSTR lpcszArgs, DWORD dwControl, int nOption, LPVOID lpRetData, int nXVT)
/// YuI 08/19/05 EXECUTE_LABTALK_WITH_STRING_ARRAY
//	BOOL CallXFunctionEx(LPCSTR lpcszOxfName, LPCSTR lpcszArgs, DWORD dwControl, int nOption, LPVOID lpRetData, int nXVT, LPCSTR lpcszTheme)
///------ Folger 12/11/09 QA81-14831-P2 OPEN_XF_DIALOG_FROM_LT_SUPPRESS_ERROR_WHEN_USER_CANCEL
//BOOL CallXFunctionEx(LPCSTR lpcszOxfName, LPCSTR lpcszArgs, DWORD dwControl, int nOption, LPVOID lpRetData, int nXVT, LPCSTR lpcszTheme, vector<string>* pvVarValues)
BOOL CallXFunctionEx(LPCSTR lpcszOxfName, LPCSTR lpcszArgs, DWORD dwControl, int nOption, LPVOID lpRetData, int nXVT, LPCSTR lpcszTheme, vector<string>* pvVarValues, int* pnExecuteErr/* = NULL*/)
///------ End OPEN_XF_DIALOG_FROM_LT_SUPPRESS_ERROR_WHEN_USER_CANCEL
/// end EXECUTE_LABTALK_WITH_STRING_ARRAY
/// end XF_THEME_SUPPORT
{
//---- CPY 8/18/2007 QA70-10246 XF_UNDO_NEED_TO_BE_AT_LOWER_LEVEL
//	UndoBlock _ub; // YuI 08/16/07 added undo block here, may need to be moved deeper or even to VC - not sure
//----
	///------ Folger 02/02/10 QUICKFIT_SUPPORT_WITHOUT_ROI_BOX_WITH_CNTRL_KEY_DOWN
	//if(dwControl & LTXF_LIST) //CPY 3/22/05, for now, we only have one LTXF_LIST and it is not exposed to OC, so 0 to execute, >0 to do listing is good enough
	DWORD	dwPossibleBitsCombinedWithList = LTXF_BY_FILENAME;
	if ( 0 == (~dwPossibleBitsCombinedWithList & dwControl) )
	///------ End QUICKFIT_SUPPORT_WITHOUT_ROI_BOX_WITH_CNTRL_KEY_DOWN
	{
		BOOL bNoLTCheck = false;
		if((OC_CAN_RETURN_ANY & dwControl) == OC_CAN_RETURN_ANY)
			bNoLTCheck = true;
		
		/// DSC 7/28/05 SUPPORT_HELP_XF_IF_NOT_LT
		// list_x_functions(lpcszOxfName, lpcszArgs);
		DWORD dwCtrl;
		if(bNoLTCheck)
			dwCtrl = LXF_NO_LT_CHECK;
		
		list_x_functions(lpcszOxfName, lpcszArgs, NULL, ORIGIN_PATH_UNDEF, dwCtrl);
		/// end SUPPORT_HELP_XF_IF_NOT_LT
		
		return true;
	}
	
	if( !(dwControl & LTXF_EXECUTE) )
	{
		out_str("calling CallXFunction with invalid argument");
		return false;
	}
	
	SHOW_TIME(NULL);//---- CPY 4/23/07 GRAPH_EXPORT_SPEED_TESTING
	
	BOOL bFromMenu = NULL==lpcszArgs? true:false;
	BOOL bXFBar = (dwControl & LTXF_XFBAR)?true:false; //CPY 12/2/06 ALLOW_LT_TO_ATTACH_XF_TO_XFBAR
	//--------------- CPY 3/17/2007 MAX_FOUND_OPTION_INDEX_FROM_MENU_ALSO_OPENS_DLG_IF_THEME_USED_IN_DIALOG
	if(!bFromMenu)
		nOption = -1;// somehow when called from LT, nOption was init to 0
	//---------------
	
	/// YuI 08/12/05 QA70-8006 XFUNCTION_AND_TREE_VARIABLE
	string strTheme;
	string strInput;
	string strOutput;
	
	/// YuI 11/25/06 BIN_WKS_AUTOUPDATE
	//	string strRedirect;
	int nRecalculate = -1;//AU_NONE; CPY 4/12/07 QA70-9618 RECALCULATE_SHOULD_BE_CONTROLLED_FROM_COMMAND_LINE_WITH_HIGHER_PRECEDENCE_THEN_THEME, changed to init as -1
	/// end BIN_WKS_AUTOUPDATE
	BOOL bDialog = FALSE;
	//------ Folger 07/16/08 QA80-11855 BETTER_FORMATTING_FOR_XF_HELP_DUMPING
	//BOOL bHelp = FALSE;
	int		nHelpList = 0;
	//------
	/// YuI 01/17/07 QA70-9285 SILENT_XF_INVOCATION
	/// YuI 04/09/09 QA70-13435 OPTION_TO_SUPPRESS_LT_ERROR_FOR_XF_INVOCATION
	//	BOOL bSilent = FALSE;
	DWORD dwSilentMode = 0;
	/// end OPTION_TO_SUPPRESS_LT_ERROR_FOR_XF_INVOCATION
	/// end SILENT_XF_INVOCATION
	BOOL bFromMRC = false; //CPY 7/11/2007 QA70-10010 MOST_RECENT_IMPORT_EXPORT_NEED_LTXF_FROM_MRU_MENU

	int		nCopyCntrl = 0;		///------ Folger 04/22/09 QA80-10889 SUPPORT_COPY_DATA_FORMAT_AS_NEW_XF_SWITCH
	
	string strArguments = lpcszArgs;
	int nPreparseResult;
	if( !strArguments.IsEmpty() )
	{
		/// YuI 11/25/06 BIN_WKS_AUTOUPDATE
		//	nPreparseResult = _preparse_XF_command_line(strArguments, strTheme, strInput, strOutput, strRedirect, bDialog, bHelp, bFromMenu);
		/// YuI 01/17/07 QA70-9285 SILENT_XF_INVOCATION
		//	nPreparseResult = _preparse_XF_command_line(strArguments, strTheme, strInput, strOutput, nRecalculate, bDialog, bHelp, bFromMenu, bXFBar);
		//------ Folger 07/16/08 QA80-11855 BETTER_FORMATTING_FOR_XF_HELP_DUMPING
		//nPreparseResult = _preparse_XF_command_line(strArguments, strTheme, strInput, strOutput, nRecalculate, bDialog, bHelp, bFromMenu, bXFBar, bSilent, bFromMRC);
		/// YuI 04/09/09 QA70-13435 OPTION_TO_SUPPRESS_LT_ERROR_FOR_XF_INVOCATION
		//	nPreparseResult = _preparse_XF_command_line(strArguments, strTheme, strInput, strOutput, nRecalculate, bDialog, nHelpList, bFromMenu, bXFBar, bSilent, bFromMRC);
		///------ Folger 04/22/09 QA80-10889 SUPPORT_COPY_DATA_FORMAT_AS_NEW_XF_SWITCH
		//nPreparseResult = _preparse_XF_command_line(strArguments, strTheme, strInput, strOutput, nRecalculate, bDialog, nHelpList, bFromMenu, bXFBar, dwSilentMode, bFromMRC);
		nPreparseResult = _preparse_XF_command_line(strArguments, strTheme, strInput, strOutput, nRecalculate, bDialog, nHelpList, bFromMenu, bXFBar, dwSilentMode, bFromMRC, nCopyCntrl);
		///------ End SUPPORT_COPY_DATA_FORMAT_AS_NEW_XF_SWITCH
		/// end OPTION_TO_SUPPRESS_LT_ERROR_FOR_XF_INVOCATION
		//------
		/// end SILENT_XF_INVOCATION
		/// end BIN_WKS_AUTOUPDATE
		if( nPreparseResult < 0 )
		{ 
			switch( nPreparseResult )
			{
			case -1:
				return error_report("Invalid XFunction command line. Switch is not followed by value");
				
			case -2:
				return error_report("Invalid XFunction command line. Unknown switch");
			}
		}
	}
	
	///------ Folger 04/22/09 QA80-10889 SUPPORT_COPY_DATA_FORMAT_AS_NEW_XF_SWITCH
	XFOutputDataFormatCopyHelper		clHelper(XF_COPY_DATA_FORMAT == nCopyCntrl);
	///------ End SUPPORT_COPY_DATA_FORMAT_AS_NEW_XF_SWITCH
	
	TreeNode trInput;
	if( !strInput.IsEmpty() )
		Project.GetTree(strInput, trInput);
	/// end XFUNCTION_AND_TREE_VARIABLE

	/// YuI 08/12/05 QA70-8006 XFUNCTION_AND_TREE_VARIABLE
	//	if( !_load_xf(xf, trXF, lpcszOxfName, dwControl, lpcszTheme) )
	//		return false;
	
	/// Iris 9/19/05 MAKE_AC_THEME_SWITCH_WORK
	//if( !_load_xf(xf, trXF, lpcszOxfName, dwControl, lpcszTheme, trInput) )
	//	return false;
	//------ CPY 6/5/2007 QA70-9803 SHIFT_SELECT_SHOULD_FORCE_DIALOG_TO_OPEN
	//	if(lpcszTheme != NULL)
	//		strTheme = lpcszTheme;
	bool bThemeGiven = false;
	if(!strTheme.IsEmpty())
		bThemeGiven = true;
	else if(lpcszTheme != NULL)
	{
		strTheme = lpcszTheme;
		bThemeGiven = true;
	}
	//------

	//------ Folger 07/16/08 QA80-11855 BETTER_FORMATTING_FOR_XF_HELP_DUMPING
	//if( bHelp )
	if ( nHelpList > 0 )
	//------
	{
		//--------- CPY 5/17/07 QA70-9794 XF_SEPARATE_INTO_TWO_CLASSES_AND_CACHE
		// use this bit only if bCompile = true, which is the case here to ensure make_tree is called
		dwControl |= LTXF_USE_FAST_ACCESS;
		//---------
		XFunction xf;
		/// AW 03/01/07 QA80-9426 v8.0273 ASSIGN_TREE_VARABILE_FOR_XF_IN_LT
		//if(!xf.Load(NULL, lpcszOxfName, dwControl))
		if(!xf.Load(NULL, lpcszOxfName, dwControl, true, false, true))   // so, it will go through make_tree event
		/// END ASSIGN_TREE_VARABILE_FOR_XF_IN_LT
			return false;
		//------ Folger 07/16/08 QA80-11855 BETTER_FORMATTING_FOR_XF_HELP_DUMPING
		//return xf.DisplayHelp();
		return xf.DisplayHelp(nHelpList);
		//------
	} 
	
	/// ---- AW 09/28/06 MORE_ON_CALL_XF_FROM_MENU
	if ( bFromMenu )
		dwControl |= LTXF_FROM_GUI_MENU;	
	/// ---- END MORE_ON_CALL_XF_FROM_MENU
	//------- CPY 7/11/2007 QA70-10010 MOST_RECENT_IMPORT_EXPORT_NEED_LTXF_FROM_MRU_MENU
	//----- CPY 8/23/2007 QA70-10010 RECENT_EXPORT_CHECK_SHIFT_SELECT_TO_OPEN_DIALOG
	//if(bFromMRC)
	if(bFromMRC && !SHIFT_DOWN)
	//-----
		dwControl |= LTXF_FROM_MRU_MENU;
	//-------
	//--------- CPY 5/17/07 QA70-9794 XF_SEPARATE_INTO_TWO_CLASSES_AND_CACHE
	if(bXFBar)
		dwControl |= LTXF_XFBAR;
	//---------
	
	/// ML 3/6/2006 AUTOUPDATE_MORE_WORK
	//XFBase xf;
	XFunction xf;
	/// end AUTOUPDATE_MORE_WORK
	TreeNode trXF;
	bool bSkipHelpNodes = bDialog || bFromMenu? false:true;
	
	//--------- CPY 5/17/07 QA70-9794 XF_SEPARATE_INTO_TWO_CLASSES_AND_CACHE
	//---- CPY 6/27/2007 EXP_GRAPH_SLOWNESS_DUE_TO_MAKE_TREE_CALL_3_TIMES
	//if(!bDialog && !bFromMenu && !(dwControl & (LTXF_XFBAR | LTXF_EXEC_RECALCULATE | LTXF_SHOW_DIALOG | LTXF_CHANGE_PARAM | LTXF_LIST)))
	///------ Folger 02/02/10 QUICKFIT_SUPPORT_WITHOUT_ROI_BOX_WITH_CNTRL_KEY_DOWN
	//if(!(dwControl & (LTXF_XFBAR | LTXF_EXEC_RECALCULATE | LTXF_CHANGE_PARAM | LTXF_LIST)))
	/// I found that if LTXF_LIST is on, execution will return from start and never reach here !
	if(!(dwControl & (LTXF_XFBAR | LTXF_EXEC_RECALCULATE | LTXF_CHANGE_PARAM)))
	///------ End QUICKFIT_SUPPORT_WITHOUT_ROI_BOX_WITH_CNTRL_KEY_DOWN
	//----
		dwControl |= LTXF_USE_FAST_ACCESS;
	//---------

	/// ML 3/6/2006 AUTOUPDATE_MORE_WORK
	//if(!xf.Load(lpcszOxfName, dwControl, trXF, true, bSkipHelpNodes))
	//	return false;
	if(!xf.Load(&trXF, lpcszOxfName, dwControl, true, bSkipHelpNodes, true))
		return false;
	/// end AUTOUPDATE_MORE_WORK
	
	//----- CPY 7/11/2007 CURVE_TRANSLATE_BROKEN
	if(trXF.UsageCtxt.GrObj.Use && trXF.UsageCtxt.windows.graph.nVal)
	{
		GraphLayer grl = Project.ActiveLayer();
		if(grl)
		{
			//-------- CPY 11/16/2007 QA70-10703 RUN_XF_THAT_ARE_NOT_SUPPOSED_TO_BE_RUN_FROM_LT
			if(nOption < 0 && lpcszArgs) // allow using LT to set option index
			{
				nOption = atoi(lpcszArgs);
				nOption--; // 1,2,3 LT index
				if(nOption < 0) nOption = 0;
			}
			//-------- end RUN_XF_THAT_ARE_NOT_SUPPOSED_TO_BE_RUN_FROM_LT
			switch(trXF.attachTo.nVal)
			{
			case XFATTACH_COL:
				DataPlot dp = grl.DataPlots();
				if(dp)
				{
					trXF.SetAttribute(STR_XF_OPTION_INDEX_ATTRIB, nOption);//---- CPY 7/11/2007 CURVE_TRANSLATE_NEED_OPTION_INDEX_PASSED_IN
					/// RVD 7/13/2007 UNDO_ATTACH_XF_WHEN_CURVE_TRANSLATE_NOT_PROCEED
					//dp.AttachXFunction(trXF);
					dp.AttachXFunction(trXF, OCD_INITDATA|OCD_UNDO);
					/// end UNDO_ATTACH_XF
					return true;
				}
			}
		}
		return false;
	}
	//----- end CURVE_TRANSLATE_BROKEN
	
	int		nGetN = 0;
	BOOL	bXFTheme = FALSE;
	nGetN = trXF.UsageCtxt.mainmenu.GetN.nVal;
	/// ---- AW 10/03/06 QA80-9015 v8.0493 ADD_THEME_BRANCH_IN_XF
	//bXFTheme = trXF.UsageCtxt.mainmenu.Theme.nVal;
	bXFTheme = trXF.UsageCtxt.Theme.UseInDialog.nVal;
	/// ---- END ADD_THEME_BRANCH_IN_XF
	if(!bFromMenu && bDialog && !bXFBar) // integPeaks -d, while user should really have type integPeaks -db, so we will force it if XF is intended to be used in XFbar
	{	// nGetN = None|Simple GetNBox|GetNGraphBox with Preview|GetNImageBox|GetNGraphBox
		if(1 == nGetN && trXF.UsageCtxt.mainmenu.AddAsTool.nVal) // Simple GetN + Add_As_Tool => XFBar
			bXFBar = true;
	}
	
	BOOL bXFWizard = XF_GETN_WIZARD == nGetN? true:false;//----- CPY 4/17/08 QA70-11438 PA_NEED_THEME_SUPPORT_FROM_MENU
	
	BOOL bFromMenuOptionIndex = nOption >= 0? true:false; //---CPY MAX_FOUND_OPTION_INDEX_FROM_MENU_ALSO_OPENS_DLG_IF_THEME_USED_IN_DIALOG
	//----- CPY 4/21/08 QA70-11438 PA_THEME_FROM_MENU_NO_DIALOG
	BOOL bFromMenuOpenDialog = (dwControl & LTXF_FROM_MENU_OPEN_DLG)? true:false;
	if(!bFromMenuOpenDialog && SHIFT_DOWN)
		bFromMenuOpenDialog = true;
	//-----
		
	//----- CPY 4/24/07 LT_OPEN_DLG_USE_LAST_USED_THEME
	// instead of testing arg string again for -t/-d (case be uppper case), we should just do this simple test
	if(bDialog && strTheme.IsEmpty())
		strTheme = STR_ZERO;
	//-----
	if(bXFTheme && (bFromMenu || !strTheme.IsEmpty()|| trInput.IsValid()) )
	///End DEFAULT_DO_NOT_USE_THEME_FROM_LT
	{
		int nn = -1;
		//------ CPY 6/5/2007 QA70-9803 SHIFT_SELECT_SHOULD_FORCE_DIALOG_TO_OPEN
		if(!bThemeGiven)
		//---------------------- CPY 6/8/2007 QA70-9894 IMP_ASC_PREFER_THEME_FROM_BOOK_SHEET_OVER_FACTORY_DEFAULT
		//	strTheme = STR_THEME_FACTORY_DEFAULT; // Open Dialog... should use factory default
		{
			string strXFname = xf.GetFunctionName(false);
			strTheme.Empty();
			BOOL bFromToolbarButtonOrGenericMenu = false;
			//----- CPY 8/31/07 KITKIT_FOUND_XF_AND_OP_NOT_CONSISTENT_WITH_MRM_NO_THEME
			//if((dwControl & LTXF_FROM_MRU_MENU) || !(dwControl & LTXF_FROM_MENU_OPEN_DLG))
			if(dwControl & LTXF_FROM_MRU_MENU)
			{
				///------ Folger 03/11/09 QA80-13258 OPEN_DIALOG_FROM_MRU_WITHOUT_THEME_NAME_SHOULD_USE_DEFAULT_SETTINGS
				//strTheme = STR_LAST_USED;
				strTheme = STR_DEFAULT;
				///------ eND OPEN_DIALOG_FROM_MRU_WITHOUT_THEME_NAME_SHOULD_USE_DEFAULT_SETTINGS
			}
			else if(!bFromMenuOpenDialog)
			//-----
			{
				theme_get_registry_settings(strXFname, NULL, strTheme);
				bFromToolbarButtonOrGenericMenu = true;				//------ CPY Folger 02/29/08 QA80-11192 IMPROVE_IMPASC_THEME_MECHANISM

			}
			//--------- CPY 3/13/08 QA70-11192 OPEN_DIALOG_SHOULD_USE_DEFAULT_THEME_IF_PRESENT
			else  //LTXF_FROM_MENU_OPEN_DLG
			{
				if(theme_get_default_settings(strXFname))
					strTheme = STR_DEFAULT_E;
			}
			//---------
			
			if(strTheme.IsEmpty() || bFromToolbarButtonOrGenericMenu)
				//------ Folger 03/31/08 QA80-11333 SHOULD_USE_LAST_USED_WHEN_OPEN_IMPASC_FROM_TOOLBAR_BUTTON
				//_check_book_sheet_theme(strTheme, trXF.UsageCtxt.Theme, lpcszOxfName);
				_check_book_sheet_theme(strTheme, trXF.UsageCtxt.Theme, lpcszOxfName, dwControl & LTXF_FROM_GUI_PROMPT);
				//------
		
			//----- end IMPROVE_IMPASC_THEME_MECHANISM
		}
		//----------------------
		//------
			
		if(! strTheme.Compare(STR_ZERO))
			strTheme.Empty();// once we have passed here, strTheme if empty will be considered last used, better not to explicitly say THEME_FILENAME_LAST_USED
		//----- CPY 4/17/08 QA70-11438 PA_NEED_THEME_SUPPORT_FROM_MENU	
		//if(theme_get_recalculate(nn, trXF.XFName.strVal, strTheme)) //if strTheme empty, will look up <last used>
		if(bXFWizard)
			nn = nRecalculate = AU_NONE; // this is until we actually support recalculate in PA etc wizard, so must be NONE for now
		
		//------ Folger 10/13/08 MISSING_AUTO_UPDATE_SHOULD_NOT_SKIP_XF_THEME_APPLY
		/*
		if(!bXFWizard && theme_get_recalculate(nn, trXF.XFName.strVal, strTheme))
		//----
		{
			///---Sim 06-30-2007 FIX_FACTORY_DEFAULT_THEME_APPIED_ISSUE
			//	xf.ApplyTheme(strTheme, trInput);
			//	dwControl |= LTXF_THEME_USED;	/// AW 11/16/06 ADD_LTXF_THEME_USED
			// has real theme file or external input theme tree
			xf.ApplyTheme(strTheme, trInput);
			//------ Folger 05/29/08 USE_DEFAULT_THEME_FROM_FLY_OUT_MENU_SHOULD_OPEN_XF_DIALOG_IF_INPUT_IS_INVALID
			//if ( !is_theme_default(strTheme) || trInput.IsValid() )
			if ( !strTheme.IsEmpty() || trInput.IsValid() )
				dwControl |= LTXF_THEME_USED;	/// AW 11/16/06 ADD_LTXF_THEME_USED
			///---END FIX_FACTORY_DEFAULT_THEME_APPIED_ISSUE
		}
		else
			tree_set_theme_file_name(trXF, STR_THEME_NONE);
		*/
		if(!bXFWizard )
		{
			theme_get_recalculate(nn, trXF.XFName.strVal, strTheme);
			
			if ( !xf.ApplyTheme(strTheme, trInput) )
				tree_set_theme_file_name(trXF, STR_THEME_NONE);
			
			if ( !strTheme.IsEmpty() || trInput.IsValid() )
				dwControl |= LTXF_THEME_USED;	/// AW 11/16/06 ADD_LTXF_THEME_USED
		}
		//------ End MISSING_AUTO_UPDATE_SHOULD_NOT_SKIP_XF_THEME_APPLY
		///------ Folger 10/09/09 PA_FAILS_TO_GET_CORRECT_DATA_FROM_AUTOX
		/// the same reason as running from script
		else
		{
			xf.ApplyTheme("");
		}
		///------ End PA_FAILS_TO_GET_CORRECT_DATA_FROM_AUTOX
		
		if(bFromMenu)
			XF_on_run_from_menu(trXF, strTheme);
		
		if(nn >= AU_NONE && nRecalculate == -1) // specified in theme but not from command line
			nRecalculate = nn;
	}
	//----
	///------ Folger 09/02/09 QA80-14086 BETTER_FIX_AUTOX_FAILS_TO_BE_RESOLVED_WHEN_RUN_XF_FROM_SCRIPT_WITHOUT_THEME
	else
	{
		/// The tricky part here is that Range vars in XF cannot be resolved correctly without invoking ApplyTheme.
		/// When call, okuSetCompositeRangeString in OCXVariableRangeBase::BeforeSetTranslatedTree in VC level will
		/// construct the correct Range nodes.
		xf.ApplyTheme("");
	}
	///------ End BETTER_FIX_AUTOX_FAILS_TO_BE_RESOLVED_WHEN_RUN_XF_FROM_SCRIPT_WITHOUT_THEME
	if(!bFromMenu && bDialog && 0 == nGetN)
	{
		///------ Folger 07/29/09 XF_AUTO_GETN_SUPPORT_ERROR_MESSAGE_CLEAN_UP
		//out_str("X-Function not designed for Auto GetN Dialog.");
		warning_msg_box(XFERR_NO_AUTO_GETN_SUPPORT, false);
		///------ End XF_AUTO_GETN_SUPPORT_ERROR_MESSAGE_CLEAN_UP
		return false;
	}
	
	//------- CPY 8/27/2006 XF_OPTION_INDEX_NOT_WORKING_FOR_LT_TYPE_XF
	if(trXF.optargindex.nVal && bFromMenuOptionIndex) //CPY 12/09/2006 MFLIP_XF_NEED_OPTION_INDEX_BUT_ALSO_NEED_OPEN_DIALOG nOption is changed to -1 if not applicable
		xf.SetVarData(trXF.optargindex.nVal-1, nOption);
	//------
	
	//----- CPY 1/27/2007 QA70-9335 XF_RESULTS_LOG_OUTPUT_OPTIONS
	//int nResultsLogOptn = trXF.outResultsLog.nVal;
	//dwControl &= ~LTXF_OUT_RESULTS_LOG_MASK;
	//dwControl |= nResultsLogOptn;
	xf_update_results_cmd_log_output_options(trXF, dwControl);
	//------
	
	//--------------------------------------- CPY 10/10/06 QA70-9039 XF_WIZARD_BAR
	if(bXFBar)
	{
		Page pg = Project.Pages();
		string strXFName(trXF.XFname.strVal);
		if(pg)
		{
			int nMode = SXFB_OPEN_INDEPENDENT;
			int nLength = lstrlen(STR_WIZARD);
			if(strXFName.GetLength() > nLength)
			{
				string strEnd = strXFName.Right(nLength);
				if(strEnd.CompareNoCase(STR_WIZARD) == 0)
					nMode = SXFB_OPEN_WIZARD;
			}
	
			return show_xf_bar(pg, nMode, lpcszOxfName);
		}
		else
			return error_report("no active page to show XF bar");
	}
	//---------------------------------------
	///------ Folger 08/24/09 QA80-10703 RUN_XFM_NOT_WORK_FOR_XF_WITHOUT_DIALOG
	//BOOL bSupportLT = trXF.UsageCtxt.LabTalk.nVal !=0 ? true:false;
	BOOL bSupportLT = ((LTXF_ALWAYS_SUPPORT_LT & dwControl) || (trXF.UsageCtxt.LabTalk.nVal !=0)) ? true:false;
	///------ End RUN_XFM_NOT_WORK_FOR_XF_WITHOUT_DIALOG
	//------ CPY 4/12/07 QA70-9618 RECALCULATE_SHOULD_BE_CONTROLLED_FROM_COMMAND_LINE_WITH_HIGHER_PRECEDENCE_THEN_THEME
	if(nRecalculate == -1)// not yet set by either theme or command line
		nRecalculate = AU_NONE;
	//------
	/// YuI 11/5/08 seems missing here
	if( !xf.IsAutoUpdatePossible() )
		nRecalculate = AU_NONE;
	/// end YuI
	
	//----- CPY 4/17/08 QA70-11438 PA_NEED_THEME_SUPPORT_FROM_MENU
	//BOOL bFromMenuPreferDlg = (bFromMenu && _xf_is_prefer_open_dialog(trXF, bFromMenuOptionIndex))?true:false;
	BOOL bFromMenuPreferDlg = (bFromMenu && (bXFWizard || _xf_is_prefer_open_dialog(trXF, bFromMenuOptionIndex)) )?true:false;
	//----- end PA_NEED_THEME_SUPPORT_FROM_MENU
	if(	bDialog || (bFromMenu && !bSupportLT) || (bFromMenu && nGetN && bXFTheme) || bFromMenuPreferDlg)
	{
		BOOL bThemeIsSpecified = (nGetN && bXFTheme && lpcszTheme != NULL && lstrlen(lpcszTheme)> 0)? true:false;
		//--------------- CPY 3/17/2007 MAX_FOUND_OPTION_INDEX_FROM_MENU_ALSO_OPENS_DLG_IF_THEME_USED_IN_DIALOG
		//if( (nGetN || bSupportLT) && (!bThemeIsSpecified || SHIFT_DOWN || (bFromMenu && _xf_is_prefer_open_dialog(trXF))))
		///------ Folger 03/12/09 QA80-13258 SUPPORT_OPEN_DIALOG_WITH_LAST_USED_FROM_MRU
		//if( (nGetN || bSupportLT) && ((!bFromMenuOptionIndex && !bThemeIsSpecified) || SHIFT_DOWN || bFromMenuPreferDlg))
		BOOL	bPreferLastUsedWithDialog = dwControl & LTXF_PREFER_LAST_USED_WITH_DIALOG;
		if( (nGetN || bSupportLT) && ((!bFromMenuOptionIndex && !bThemeIsSpecified) || SHIFT_DOWN || bFromMenuPreferDlg || bPreferLastUsedWithDialog))
		///------ End SUPPORT_OPEN_DIALOG_WITH_LAST_USED_FROM_MRU
		//---------------
		{
			dwControl |= LTXF_SHOW_DIALOG;
			///------ Folger 01/19/09 PA_RUNS_SCRIPT_MODE_AS_DEFAULT
			/*
			//----- CPY 4/17/08 QA70-11438 PA_NEED_THEME_SUPPORT_FROM_MENU	
			if(bXFWizard && bFromMenu && strArguments.IsEmpty() && !strTheme.IsEmpty())
			{
				strArguments = "t:=" + "\"" + strTheme + "\""; 
				if(!bFromMenuOpenDialog) // theme fly
					strArguments += " s:=1";	
			}
			//----- end PA_NEED_THEME_SUPPORT_FROM_MENU
			*/
			if ( bXFWizard && bFromMenu && strArguments.IsEmpty() )
			{
				if ( !strTheme.IsEmpty() )
					strArguments = "t:=" + "\"" + strTheme + "\""; 
				if ( bFromMenuOpenDialog ) // theme fly
					strArguments += " s:=0";
			}
			///------ End PA_RUNS_SCRIPT_MODE_AS_DEFAULT
		}
		else
		{
			int nAutoUpdate = nRecalculate;
			int nOCerr = -1;
			dwControl &= ~LTXF_SHOW_DIALOG;
			
			SHOW_TIME("calling XF without dialog");//---- CPY 4/23/07 GRAPH_EXPORT_SPEED_TESTING

			//---- CPY 4/21/2007 QA70-9627 XF_BEFORE_EXEC_TO_ASK_DLG_TO_OPEN_FAILED_FROM_THEME_LUNCH
			//BOOL bReturn = xf.Run(nAutoUpdate, NULL, NULL, XVT_INT, &nOCerr, dwControl);
			//return bReturn;
			int nErr = xf.ExecuteLabTalk(NULL, NULL, lpRetData, nXVT, &nOCerr, dwControl, nRecalculate);
			///------ Folger 12/11/09 QA81-14831-P2 OPEN_XF_DIALOG_FROM_LT_SUPPRESS_ERROR_WHEN_USER_CANCEL
			if ( pnExecuteErr )
				*pnExecuteErr = nErr;
			///------ End OPEN_XF_DIALOG_FROM_LT_SUPPRESS_ERROR_WHEN_USER_CANCEL
			return nErr == 0? true:false;
			//----
		}
	}
	if( bSupportLT || (dwControl & LTXF_SHOW_DIALOG))// CPY, this was above getN, I moved here after david found bitmap not working
	{
		int nOCerr = -1;
		
		/// YuI 04/09/09 QA70-13435 OPTION_TO_SUPPRESS_LT_ERROR_FOR_XF_INVOCATION
		//	if( bSilent )
		//		dwControl &= ~LTXF_OUT_RESULTS_LOG_MASK;
		if( dwSilentMode & XF_SILENT_RESULTS_LOG )
			dwControl &= ~LTXF_OUT_RESULTS_LOG_MASK;
		
		if( dwSilentMode & XF_SILENT_LT_ERROR )
			dwControl |= LTXF_SUPPRESS_ERROR_REPORTING;
		/// end OPTION_TO_SUPPRESS_LT_ERROR_FOR_XF_INVOCATION
			
		//---- CPY 8/14/09 QA70-14154 XF_CMD_LINE_OPTN_TO_SUPRESS_INFO_MSG
		if( dwSilentMode & XF_SILENT_INFO_MSG)
			dwControl |= LTXF_SUPRESS_INFO_MSG;
		//----
		
		SHOW_TIME("calling XF with dialog");//---- CPY 4/23/07 GRAPH_EXPORT_SPEED_TESTING
		
		int nErr = xf.ExecuteLabTalk(strArguments, pvVarValues, lpRetData, nXVT, &nOCerr, dwControl, nRecalculate);
		///------ Folger 12/11/09 QA81-14831-P2 OPEN_XF_DIALOG_FROM_LT_SUPPRESS_ERROR_WHEN_USER_CANCEL
		if ( pnExecuteErr )
			*pnExecuteErr = nErr;
		///------ End OPEN_XF_DIALOG_FROM_LT_SUPPRESS_ERROR_WHEN_USER_CANCEL
		if(0== nErr)
			return true;
	
		/// YuI 04/09/09 QA70-13435 OPTION_TO_SUPPRESS_LT_ERROR_FOR_XF_INVOCATION
		//	return false;
		// if userinvokes XF from labtalk and want script to proceed even if XF failed (threw an exception)
		// we need to return true;
		if( dwSilentMode & XF_SILENT_LT_ERROR )
			return true; 
		
		return false;
		/// end OPTION_TO_SUPPRESS_LT_ERROR_FOR_XF_INVOCATION
	}
	
	return false;
}


///DSC 08/25/2005 GET_XF_INFO_STRINGS
#define LIST_XF_DESCRIPTION "description"
#define LIST_XF_IN "in"
#define LIST_XF_OUT "out"
#define LIST_XF_TYPE "type"
#define LIST_XF_DEFAULT "default"
//#define LIST_XF_HELP_INFO "Help Info on "
#define LIST_XF_RETURN "return"

//------ Folger 07/16/08 QA80-11855 BETTER_FORMATTING_FOR_XF_HELP_DUMPING
#define		HELP_INDENT_STRING		"  "
#define		XF_DESCRIPTION_LINE_LENGTH_LIMITED		80
//------

//------ Folger 07/16/08 QA80-11855 BETTER_FORMATTING_FOR_XF_HELP_DUMPING
/*
static	void	_format_xf_var_description_string(string &strDescription, int nIndentLength)
{
	if ( strDescription.IsEmpty() )
		return;
	
	string strIndent(' ', nIndentLength);
	strIndent = strIndent + HELP_INDENT_STRING + HELP_INDENT_STRING;
	
	int		nPos = 0;
	while ( (nPos = strDescription.Find('\n', nPos)) >= 0 )
	{
		strDescription.Insert(++nPos, strIndent);
	}
}
*/
//------

/// Justin 2007-03-11 v8.0578 DISPLAY_DIFF_LANGUAGE_HELP_FOR_DIFF_LANGUAGE_VERSION
//static string _make_xf_variable_info_str(TreeNode trV, const string& vsVarDefaultVals) 
//------ Folger 07/16/08 QA80-11855 BETTER_FORMATTING_FOR_XF_HELP_DUMPING
//static string _make_xf_variable_info_str(TreeNode trV, const string& vsVarDefaultVals, int nLanguage = IDRS_HELP_E) 
static string _make_xf_variable_info_str(TreeNode trV, const string& vsVarDefaultVals, int nLanguage = IDRS_HELP_E, BOOL bNameOnly = FALSE)
//------
///End DISPLAY_DIFF_LANGUAGE_HELP_FOR_DIFF_LANGUAGE_VERSION
{
	//string str = trV.name.strVal;
	//str += " = [";
	///DSC 10/5/05 DISPLAY_VARIABLE_INFO
	// string str= "[";
	string str = HELP_INDENT_STRING + trV.name.strVal + ": ";
	str += "[";
	///end DISPLAY_VARIABLE_INFO
	
	//int nIO = nIO;
	if(IO_INPUT==trV.io.nVal)
		str += LIST_XF_IN + "] ";
	else if(IO_OUTPUT==trV.io.nVal)
		str += LIST_XF_OUT + "] ";
	else if(IO_INOUTPUT==trV.io.nVal)
		str += LIST_XF_IN + "/" + LIST_XF_OUT + "] \n";
	//------ Folger 07/16/08 QA80-11855 BETTER_FORMATTING_FOR_XF_HELP_DUMPING
	if ( bNameOnly )
		return str;
	//------
	str += "\n" + HELP_INDENT_STRING + HELP_INDENT_STRING + LIST_XF_TYPE + "=" + trV.type.strVal;

	str += "\n" + HELP_INDENT_STRING + HELP_INDENT_STRING + LIST_XF_DEFAULT + "=" + vsVarDefaultVals;
	
	///Joseph 11/30/06	SPLITE_TABLE_CELL_FOR_TREENODE_VARIABLE
	//string strDescription = trV.description.strVal;
	string strDescription = _get_Var_Description(trV, nLanguage); //string strDescription = trV.help.remark.strVal;	/// Justin 2007-03-11 v8.0578 DISPLAY_DIFF_LANGUAGE_HELP_FOR_DIFF_LANGUAGE_VERSION
	/// Hong 12/13/07 v8.0768 FIX_GET_GARBAGE_DESCRIPTION_WHEN_EMPTY
	// should always use localized display name, because language of gobal display name may NOT consistent with current origin
	//if(strDescription.IsEmpty())
	//	strDescription = trV.description.strVal;
	if(strDescription.IsEmpty())
	{
		TreeNode trDesc = tree_find_node_by_dataID(trV, IDV_VAR_HELP_DESCRIPTION, IDV_VAR_LOCAL_HELP_BRANCH, nLanguage);
		if ( trDesc )
			strDescription = trDesc.strVal;
	}
	/// end FIX_GET_GARBAGE_DESCRIPTION_WHEN_EMPTY
	///End SPLITE_TABLE_CELL_FOR_TREENODE_VARIABLE	
	
	if(!strDescription.IsEmpty())
	{
		//------ Folger 07/16/08 QA80-11855 BETTER_FORMATTING_FOR_XF_HELP_DUMPING
		//_format_xf_var_description_string(strDescription, lstrlen(LIST_XF_DESCRIPTION) + 1);	// add 1 for '='
		//------
		/// new wrap text mechanism
		ocu_wrap_text(&strDescription, XF_DESCRIPTION_LINE_LENGTH_LIMITED, 2 * lstrlen(HELP_INDENT_STRING) + lstrlen(LIST_XF_DESCRIPTION) + 1);
		str += "\n" + HELP_INDENT_STRING + HELP_INDENT_STRING + LIST_XF_DESCRIPTION + "=" + strDescription;
	}	
	
	// comboString
	string strCombo = trV.comboString.strVal;		
	if(strCombo[0]=='|')// starts with | means editable, so dont show list
		strCombo="";
	///------ Folger 04/27/10 QA81-15361 PROPER_TRIMMING_AMPERSAND_FOR_XF_VAR_COMBO_THAT_MAKES_MENU_ITEMS
	if ( !strCombo.IsEmpty() )
	{
		int		nOptionArgVar = 0;
		if ( trV.GetAttribute(STR_OPTION_ARG_VAR_ATTRIB, nOptionArgVar) && nOptionArgVar )
			okutil_update_str_remove_empersand(&strCombo);
	}
	///------ End PROPER_TRIMMING_AMPERSAND_FOR_XF_VAR_COMBO_THAT_MAKES_MENU_ITEMS
	
	//------ Folger 07/16/08 QA80-11855 BETTER_FORMATTING_FOR_XF_HELP_DUMPING
	/// no idea why for some xfs which have long combo string, some newline chars will be inserted,
	/// because of auto word warp ? just remove them since they are not supposed to be here
	strCombo.Remove('\n');

	LPCSTR		lpcszAllowValues = "allowed values: ";

	/// combo string for slider like "Slider:0|100|100" needs special handling
	LPCSTR	lpcszSlider = "slider";
	string	strComboCopy = strCombo;		/// better not change original one
	strComboCopy.MakeLower();
	if ( strComboCopy.Find(lpcszSlider) == 0 )
	{
		strComboCopy.Delete(0, lstrlen(lpcszSlider) + 1);		/// include ':'
		if ( strComboCopy[0] != '|' )		/// not editable
		{
			vector<string>	vsItems;
			strComboCopy.GetTokens(vsItems, '|');
			ASSERT(vsItems.GetSize() == 3);
			str += "\n" + HELP_INDENT_STRING + HELP_INDENT_STRING + lpcszAllowValues + '(' + vsItems[0] + ", " + vsItems[1] + ')';
		}
		return str;
	}
	//------ End BETTER_FORMATTING_FOR_XF_HELP_DUMPING
			
	if(!strCombo.IsEmpty())
	{	
		if(strCombo.CompareNoCase("0|1")==0)
			strCombo = "false|true";
		if(strCombo.CompareNoCase("1|0")==0)
			strCombo = "true|false";
		vector<string> vs;
		strCombo.GetTokens(vs, '|');
		//strCombo=", allowed values: ";
		strCombo = "\n" + HELP_INDENT_STRING + HELP_INDENT_STRING + lpcszAllowValues;
		bool bIsNumericList = trV.valdata ? TRGP_NUMERIC_LIST == trV.valdata.ID : false;	///Kyle 02/01/2009 QA80-13042 NUMERIC_COMBO_LIST_IN_XF_HELP_SHOULD_NOT_SHOW_INDICES
		for(int ii=0; ii<vs.GetSize(); ii++)
		{
			///Kyle 02/01/2009 QA80-13042 NUMERIC_COMBO_LIST_IN_XF_HELP_SHOULD_NOT_SHOW_INDICES
			//strCombo+=(string)ii + "=" + vs[ii];
			strCombo += bIsNumericList? vs[ii] : (string)ii + "=" + vs[ii];
			///End NUMERIC_COMBO_LIST_IN_XF_HELP_SHOULD_NOT_SHOW_INDICES
			if(ii<vs.GetSize()-1)
				strCombo += ", "
		}
		if(!strCombo.IsEmpty())
			str+=strCombo;
	}
		
	return str;
}

/// Justin 2007-03-11 v8.0578 DISPLAY_DIFF_LANGUAGE_HELP_FOR_DIFF_LANGUAGE_VERSION
string _get_Var_Description(const TreeNode& trVariable, int nLanguage)
{
	TreeNode trHelp;
	switch(nLanguage)
	{
	case IDRS_HELP_E: 
		trHelp = trVariable.help; 
		break;
	case IDRS_HELP_J: 
		trHelp = trVariable.helpj; 
		break;
	case IDRS_HELP_G: 
		trHelp = trVariable.helpg; 
		break;
	case IDRS_HELP_C: 
		trHelp = trVariable.helpc; 
		break;
	default: 
		trHelp = trVariable.help; 
	}
	string strDescription = trHelp.remark.strVal;
	return strDescription;
}
///End DISPLAY_DIFF_LANGUAGE_HELP_FOR_DIFF_LANGUAGE_VERSION


/// ML 12/7/2006 ADDING_INPUT_TABLE_FROM_WITHIN_XF
///// ML 7/19/2006 REMEMBERING_SETTINGS_IN_XFOPERATION_FOR_AUTO_UPDATE
/////// ML 7/12/2006 REPORT_DATA_WITH_XF_WORKSHEET_GRAPHS_HANDLING
///////// YuI 11/09/05 QA70-8279 REPORT_TREE_AND_REPORT_DATA_XVARIABLES
////////	static bool op_set_x_function(OperationBase& op, XFunction& xf, bool bAutoUpdate, bool bInternal, DataRange *pdrInput = NULL, DataRange *pdrOutput = NULL, uint nCntrl = OPSETXFUNCTION_SET_MODIFIED)
//////static bool op_set_x_function(OperationBase& op, XFunction& xf, bool bAutoUpdate, bool bInternal, DataRange *pdrInput = NULL, Array<DataRange&>* parrOutputs = NULL, uint nCntrl = OPSETXFUNCTION_SET_MODIFIED)
///////// end REPORT_TREE_AND_REPORT_DATA_XVARIABLES
////static bool op_set_x_function(OperationBase& op, XFunction& xf, bool bAutoUpdate, bool bInternal, DataRange *pdrInput = NULL, Array<DataRange&>* parrOutputs = NULL, uint nCntrl = OPSETXFUNCTION_SET_MODIFIED, vector<uint> *pvMapIdsToUIDs = NULL)
/////// end REPORT_DATA_WITH_XF_WORKSHEET_GRAPHS_HANDLING
//static bool op_set_x_function(OperationBase& op, XFunction& xf, bool bAutoUpdate, bool bInternal, DataRange *pdrInput = NULL, Array<DataRange&>* parrOutputs = NULL, uint nCntrl = OPSETXFUNCTION_SET_MODIFIED, vector<uint> *pvMapIdsToUIDs = NULL, TreeNode &trGetN = NULL)
///// end REMEMBERING_SETTINGS_IN_XFOPERATION_FOR_AUTO_UPDATE
static bool op_set_x_function(OperationBase& op, XFunction& xf, bool bAutoUpdate, bool bInternal, DataRange *pdrInput = NULL, Array<DataRange&>* parrOutputs = NULL, uint nCntrl = OPSETXFUNCTION_SET_MODIFIED, vector<uint> *pvMapIdsToUIDs = NULL, TreeNode &trGetN = NULL,
TreeNode &treeAdditionalData = NULL)
/// end ADDING_INPUT_TABLE_FROM_WITHIN_XF
{
	DataRange	drInput;
	op.GetInput(drInput);
	
	/// YuI 11/09/05 QA70-8279 REPORT_TREE_AND_REPORT_DATA_XVARIABLES
	//	DataRange	drOutput;
	//	op.GetOutput(drOutput);
	Array<DataRange&> arrOutputs;
	DataRange dr;
	int nIndex = 0;
	while( op.GetOutput(dr, nIndex) )
	{
		arrOutputs.Add(dr);
		nIndex++;
	}
	/// end REPORT_TREE_AND_REPORT_DATA_XVARIABLES

	
	BOOL		bAddInput = FALSE;
	BOOL		bAddOutput = FALSE;
	if (!drInput)	
	{
		if (pdrInput == NULL)
			return error_report("No input range to update");
		
		Project.AddDataRange(*pdrInput);
		/// YuI 10/13/06 USER_NOTIFICATION_ON_INVALID_OPERATION
		//	op.SetInput(*pdrInput);
		if( op.SetInput(*pdrInput) < 0 )
		{
			Project.RemoveDataRange(*pdrInput);	
			return FALSE;
		}
		/// end USER_NOTIFICATION_ON_INVALID_OPERATION
	}
	else if (pdrInput)
	{
		drInput.Reset();
		drInput.Merge(*pdrInput);
	}

	/// YuI 11/09/05 QA70-8279 REPORT_TREE_AND_REPORT_DATA_XVARIABLES
	/*
	if (!drOutput)	
	{
		if (pdrOutput == NULL)
			return error_report("No output range to update");
		
		Project.AddDataRange(*pdrOutput);
		op.SetOutput(*pdrOutput);
	}
	else if (pdrOutput)
	{
		drOutput.Reset();
		drOutput.Merge(*pdrOutput);
	}
	*/
	
	if( 0 == arrOutputs.GetSize() )
	{
		if (parrOutputs == NULL)
			return error_report("No output ranges to update");
		
		for( int ii = 0; ii < parrOutputs->GetSize(); ii++ )
		{
			DataRange& dr = parrOutputs->GetAt(ii);
			if( dr == NULL )
				continue;
			
			Project.AddDataRange(parrOutputs->GetAt(ii));
			/// YuI 10/13/06 USER_NOTIFICATION_ON_INVALID_OPERATION
			//	op.SetOutput(parrOutputs->GetAt(ii), ii);
			if( op.SetOutput(parrOutputs->GetAt(ii), ii) < 0 )
			{
				for( int jj = 0; jj <= ii; jj++ )
					Project.RemoveDataRange(parrOutputs->GetAt(jj));
				
				return FALSE;
			}
			/// end USER_NOTIFICATION_ON_INVALID_OPERATION
		}
	}
	else
	{
		ASSERT(FALSE);
		return FALSE; // not done yet
	}
	/// end REPORT_TREE_AND_REPORT_DATA_XVARIABLES
	
	
	// Old stuff:
	TreeNode trOp;
	op.GetTree(trOp);
	//--- CPY 3/3/05 INTERNAL_XF_EDIT
	//TreeNode trGUI = trOp.AddNode("GUI");
	//foreach(TreeNode trTemp in  trXF.Children )
	//	trGUI.AddNode(trTemp.Clone());
	if(bInternal)
	{
		TreeNode trXFop = tree_check_get_node(trOp, STR_OP_XF_NODE);
		TreeNode trXF = xf.GetTree();
		trXFop.Replace(trXF, true, true);
	}
	else
	{
		TreeNode trOpXFname = tree_check_get_node(trOp, STR_OP_XF_EXTERNAL_NODE);
		trOpXFname.strVal = xf.GetFunctionName(false);
		/// ML 7/19/2006 REMEMBERING_SETTINGS_IN_XFOPERATION_FOR_AUTO_UPDATE
		if (trGetN)		// store GetN in op
		{
			TreeNode trOpGetN = tree_check_get_node(trOp, STR_OP_XF_GETN_NODE);
			trOpGetN.Replace(trGetN, true, true);
		}
		else
			ASSERT(FALSE);
		/// end REMEMBERING_SETTINGS_IN_XFOPERATION_FOR_AUTO_UPDATE
	}
	
	//---- CPY 07/24/06 QA70-8847 COLUMN_FORMULA_FROM_ORIGIN_C_REVAMP
	//trOp.Operation.AutoUpdate.nVal = bAutoUpdate; /// CPY 3/18/05 KEEP_XF_NAME_FOR_INTERNAL, added bAutoUpdate
	trOp.Operation.AutoUpdate.nVal = bAutoUpdate? AU_AUTO : AU_ON_COMMAND;
	//----
	//---
	
	/// ML 12/7/2006 ADDING_INPUT_TABLE_FROM_WITHIN_XF
	if ( treeAdditionalData.IsValid() )
	{
		TreeNode trAdditionalData = tree_check_get_node(trOp, TREE_INPUTRANGE_ADDITIONAL_DATA_NODE_NAME);
		trAdditionalData.Replace(treeAdditionalData, TRUE, TRUE);
	}
	/// end ADDING_INPUT_TABLE_FROM_WITHIN_XF
	/// ML 1/9/2008 QA70-10917 MAKE_XFVERSION_USED_WHEN_XFOP_WAS_RUN_LAST_TIME_AVAILABLE_TO_ORIGINC
	TreeNode		trXF = xf.GetTree();
	if ( trXF.IsValid() )
	{
		double			rXFVersion = trXF.version.dVal;
		trOp.SetAttribute(STR_ATT_OP_XFVER, rXFVersion);
	}
	/// end MAKE_XFVERSION_USED_WHEN_XFOP_WAS_RUN_LAST_TIME_AVAILABLE_TO_ORIGINC

	op.SetTree(trOp);
	
	/// YuI 10/12/07 QA70-10529 DATA_MARKERS_REVAMP
	op.DestroyInputDataMarkers();
	/// end DATA_MARKERS_REVAMP
	/// ML 7/12/2006 REPORT_DATA_WITH_XF_WORKSHEET_GRAPHS_HANDLING
	if (pvMapIdsToUIDs)
		op.SetIdsToUIDsMap(*pvMapIdsToUIDs);		// remember the auxiliary UIDs (if any) into the operation
	/// end REPORT_DATA_WITH_XF_WORKSHEET_GRAPHS_HANDLING
	/// ML 12/15/2006 AUTO_SIZING_REPORT_TREE_ON_CONNECTING_OPERATION
	xf.OnConnectOperation();
	/// end AUTO_SIZING_REPORT_TREE_ON_CONNECTING_OPERATION
	
	/// YuI 04/11/05 XFOPERATION_CHANGE_PARAM
	//	if( bSetModified )
	//		op.SetModified();
	if( nCntrl == OPSETXFUNCTION_SET_MODIFIED )
		op.SetModified();
	else if( nCntrl == OPSETXFUNCTION_EXECUTE )
	{
		op.SetModified();
		Project.Run(op.GetUID());
	}
	/// end XFOPERATION_CHANGE_PARAM
	
	return true;
}
/// end OPERATIONTREE_UPDATING_BACK_AND_FORTH


bool XFunction::UpdateInternalOperation(uint uidOp, uint nCntrl)
{
	OperationBase& op = Project.GetOperationObject(uidOp);
	if(op)
		return op_set_x_function(op, *this, true, true, NULL, NULL, nCntrl);
	
	return false;
}

/// Hong 08/28/07 QA80-10310 MORE_VARIABLE_INFO_FOR_XF2GUI
string XFunction::GetVarHelpText(LPCSTR lpcszVar, int nNodeID, int nLanguage, bool bUseEwhenEmpty) // = IDV_HELP_SUMMARY, IDRS_HELP_E, true
{
	string strHelp;
	TreeNode tn = GetVarHelp(lpcszVar, nNodeID, nLanguage);
	strHelp = tn.strVal; // must be valid, no need to check, if not valid node, then must be coding err
	
	if ( bUseEwhenEmpty && IDRS_HELP_E != nLanguage && strHelp.IsEmpty() )
	{
		tn = GetVarHelp(lpcszVar, nNodeID, IDRS_HELP_E);
		strHelp = tn.strVal;	
	}
	
	return strHelp;
}

bool XFunction::SetHelpText(LPCSTR lpcszVal, int nNodeID, int nLanguage) // = IDV_HELP_SUMMARY, IDRS_HELP_E
{
	TreeNode tn = GetHelp(nNodeID, nLanguage);
	
	if ( !tn )
		return false;
	
	tn.strVal = lpcszVal;
	return true;
}
	
bool XFunction::SetVarHelpText(LPCSTR lpcszVar, LPCSTR lpcszVal, int nNodeID, int nLanguage) // = IDV_HELP_SUMMARY, IDRS_HELP_E
{
	TreeNode tn = GetVarHelp(lpcszVar, nNodeID, nLanguage);
	
	if ( !tn )
		return false;
	
	tn.strVal = lpcszVal;
	return true;
}	
/// end MORE_VARIABLE_INFO_FOR_XF2GUI

//----- Kevin 09/30/05 MODIFY_HELP_INFO
/// SY 2007-06-06 QA70-9426 v8.0634 ASSIGN_TREE_VARABILE_FOR_XF_IN_LT
///	string XFunction::GetVarsHelpInfo(int nLanguage) // = IDRS_HELP_E
//------ Folger 07/16/08 QA80-11855 BETTER_FORMATTING_FOR_XF_HELP_DUMPING
//string XFunction::GetVarsHelpInfo(int nLanguage, BOOL bComplete) // = IDRS_HELP_E, FALSE
string XFunction::GetVarsHelpInfo(int nLanguage, BOOL bComplete, int nHelpList) // = IDRS_HELP_E, FALSE, XF_HELP_LIST_ALL
//------
/// end ASSIGN_TREE_VARABILE_FOR_XF_IN_LT
{
	string str;
	
	TreeNode trVars;
	okutil_xft_GetVarsNode(&trVars, &m_tree, NULL);

	vector<string> vsVarNames, vsVarDefaultVals, vsVarTypes;
	//------ Folger 07/16/08 QA80-11855 BETTER_FORMATTING_FOR_XF_HELP_DUMPING
	/*
	/// AW 03/01/07 QA80-9426 v8.0273 ASSIGN_TREE_VARABILE_FOR_XF_IN_LT
	//GetVariables(vsVarNames, vsVarDefaultVals, vsVarTypes);
	Tree trRuntime;
	//----- CPY 6/7/2007 QA70-9426 v8.0634 ASSIGN_TREE_VARABILE_FOR_XF_IN_LT
	//GetVariables(vsVarNames, vsVarDefaultVals, vsVarTypes, false, NULL, trRuntime);
	TreeNode trVarTreeNodes = trRuntime.AddNode("TreeNode_Details");
	/// AW 01/29/08 QA80-11002 GET_SAME_DEFAULT_VALUE_FOR_XF_VAR
	//int nTrees = GetVariables(vsVarNames, vsVarDefaultVals, vsVarTypes, false, NULL, trVarTreeNodes);
	int nTrees = GetVariables(vsVarNames, vsVarDefaultVals, vsVarTypes, false, NULL, trVarTreeNodes, XF_GET_SIMPLE_DEFAULT_VALUE);
	/// END2 GET_SAME_DEFAULT_VALUE_FOR_XF_VAR
	*/
	int nTrees = GetVariables(vsVarNames, vsVarDefaultVals, vsVarTypes, false, NULL, NULL, XF_GET_SIMPLE_DEFAULT_VALUE);
	//------ End BETTER_FORMATTING_FOR_XF_HELP_DUMPING
	//----
//---- CPY 6/7/2007 should not dump tree in Get function
//	okutil_out_tree(&trRuntime, 0, NULL, OTR_DISPLAY_HIDDEN_TREENODE); /// SY 2007-06-06 QA70-9426 v8.0634 ASSIGN_TREE_VARABILE_FOR_XF_IN_LT
//----
	//out_tree(trRuntime);  // out_tree result is not good,not domorethings later.
	/// END ASSIGN_TREE_VARABILE_FOR_XF_IN_LT
	
	int ii=0;
	foreach(TreeNode trV in trVars.Children)
	{	
		///------ Folger 08/12/09 QA80-14112 NEED_OPTION_STRING_TO_HIDE_XF_VARIABLE_FROM_LT
		XFVariable	var(trV);
		if ( !var.IsAccessibleFromLT() )
			continue;
		///------ End NEED_OPTION_STRING_TO_HIDE_XF_VARIABLE_FROM_LT
		/// DSC 2/14/06 QA70-7518 ALLOW_SEARCH_XF_BY_KEYWORDS
		///GetVariables not getting all vars...need to see why
		if( ii>=vsVarDefaultVals.GetSize() )
			break;
		/// end ALLOW_SEARCH_XF_BY_KEYWORDS

		//------ Folger 07/16/08 QA80-11855 BETTER_FORMATTING_FOR_XF_HELP_DUMPING
		//str += _make_xf_variable_info_str(trV, vsVarDefaultVals[ii++], nLanguage); //str += _make_xf_variable_info_str(trV, vsVarDefaultVals[ii++]); 		/// Justin 2007-03-11 v8.0578 DISPLAY_DIFF_LANGUAGE_HELP_FOR_DIFF_LANGUAGE_VERSION
		str += _make_xf_variable_info_str(trV, vsVarDefaultVals[ii++], nLanguage, nHelpList == XF_HELP_LIST_VARIABLES);
		//------
		str += "\n";
	}
	//------ Folger 07/16/08 QA80-11855 BETTER_FORMATTING_FOR_XF_HELP_DUMPING
	/*
	/// SY 2007-06-06 QA70-9426 v8.0634 ASSIGN_TREE_VARABILE_FOR_XF_IN_LT
	if( bComplete && nTrees > 0)
	{
		string 	strOptions;
		vector<int> vnTableDisplayFormat = { DISPLAY_CENTER, DISPLAY_RIGHT, DISPLAY_RIGHT};
		//----- CPY 6/7/2007 QA70-9426 v8.0634 ASSIGN_TREE_VARABILE_FOR_XF_IN_LT
		//tree_to_str(trRuntime.Options, strOptions, vnTableDisplayFormat, true, true, false);
		//------ Folger 07/16/08 QA80-11855 BETTER_FORMATTING_FOR_XF_HELP_DUMPING
		//str += "-------\r\n";// better have a separator
		str += '\n';
		//------
		/// Hong 06/18/07 v8.0643 FIX_XF_SHOW_HELP_BY_LT_ERROR_SHOW_HIDDEN_NODE
		//tree_hide_empty_nodes(trVarTreeNodes);
		tree_hide_empty_nodes(trVarTreeNodes, true, false);
		/// end FIX_XF_SHOW_HELP_BY_LT_ERROR_SHOW_HIDDEN_NODE
		/// Hong 09/08/07 v8.0699 MORE_OPTION_TO_DUMP_MAP_INFO_FOR_COMBO_NODE
		//tree_to_str(trVarTreeNodes, strOptions, vnTableDisplayFormat, true, true, false);
		tree_to_str(trVarTreeNodes, strOptions, vnTableDisplayFormat, TREE2STR_SKIP_HIDDEN | TREE2STR_SIMPLE_TYPE_ONLY | TREE2STR_INCLUDE_COMBO_MAP_INFO);
		/// end MORE_OPTION_TO_DUMP_MAP_INFO_FOR_COMBO_NODE
		//-----
		
		//------ Folger 07/16/08 QA80-11855 BETTER_FORMATTING_FOR_XF_HELP_DUMPING
		strOptions.Replace("TreeNode_Details", _L("TreeNode Details:"));
		//------
		
		str += strOptions;
	}
	/// end ASSIGN_TREE_VARABILE_FOR_XF_IN_LT
	*/
	if ( bComplete )
		str += getHelpTreeNodeDetailsInfo();
	//------ End BETTER_FORMATTING_FOR_XF_HELP_DUMPING
	return str;
}

static string _format_all_arg_str(const vector<string>& vsVarNames, const vector<string>& vsVarDefaultVals, const vector<string>& vsVarTypes, DWORD dwDisplayOptions)
{
	string strArgs="\t";
	for(int jj = 0; jj < vsVarNames.GetSize(); jj++)
	{   
		if(jj > 0) 
			strArgs +=" ";
		if(LIST_XF_ARG_TYPES & dwDisplayOptions)
		{
			string strSep;
			if(LIST_XF_ARG_NAME & dwDisplayOptions)
				strSep = ":";
			strArgs += vsVarTypes[jj] + strSep;	
		}
		if(LIST_XF_ARG_NAME & dwDisplayOptions)	
			strArgs += vsVarNames[jj];
		if(LIST_XF_ARG_DEFAULTS & dwDisplayOptions)
		{	
			if(!vsVarDefaultVals[jj].IsEmpty())
			///Kevin 09/02/05 MODIFY_XF_VARIABLE_EQUAL_SIGN
				//strArgs += "="+vsVarDefaultVals[jj];
				strArgs += "=:"+vsVarDefaultVals[jj];
			///End MODIFY_XF_VARIABLE_EQUAL_SIGN
		}
	}
	
	return strArgs;
}

string XFunction::GetHelpBriefInfo()
{
	//IDV_HELP_BRIEF_INFO
	string strHelp;
	int nLanguage = _get_current_language();
	TreeNode tn = GetHelp(IDV_HELP_BRIEF_INFO, nLanguage);
	strHelp = tn.strVal;

	bool bRequireSimpleText = true;
	if(!bRequireSimpleText && IDRS_HELP_E != nLanguage && strHelp.IsEmpty())
	{
		tn = GetHelp(IDV_HELP_SUMMARY, IDRS_HELP_E);	
		strHelp = tn.strVal;	
	}

	return strHelp;
}

string XFunction::GetHelpText(int nNodeID, int nLanguage, bool bUseEwhenEmpty)
{
	string strHelp;
	TreeNode tn = GetHelp(nNodeID, nLanguage);
	
	///------ Folger 03/10/09 QA80-11855 LT_XF_HELP_DUMPING_NEEDS_SUPPORT_DISPLAY_RELATED_XF
	if ( !tn )
	{
		ASSERT(false);
		return "";
	}
	///------ End LT_XF_HELP_DUMPING_NEEDS_SUPPORT_DISPLAY_RELATED_XF
	
	strHelp = tn.strVal; // must be valid, no need to check, if not valid node, then must be coding err
	
	/// Iris 6/10/2009 QA80-13741 REMOVE_AND_OP_IN_LIST_XF_RESULT
#ifdef FIX_LIST_XF_BUG_FOR_81
	char chAnd = '&';
	int nPos = 0; 	
	while( (nPos = strHelp.Find(chAnd, nPos)) >= 0 )
	{
		if( strHelp.GetAt(nPos+1) != chAnd )
			strHelp.Delete(nPos);
		else
			nPos += 2;
	}
#endif //FIX_LIST_XF_BUG_FOR_81
	///end REMOVE_AND_OP_IN_LIST_XF_RESULT
	
	if ( bUseEwhenEmpty && IDRS_HELP_E != nLanguage && strHelp.IsEmpty() )
	{
		tn = GetHelp(nNodeID, IDRS_HELP_E);	/// Hong 08/28/07 QA80-10310 MORE_VARIABLE_INFO_FOR_XF2GUI
		if(tn)
			strHelp = tn.strVal;
		else
			error_report("XFunction::GetHelpText failed getting E node");
	}
	return strHelp;
}

static void _format_usage_string(string &strUsage)
{
	if ( strUsage.IsEmpty() )
		return;
	
	int		nPos = -1;
	do
	{
		strUsage.Insert(++nPos, HELP_INDENT_STRING);
	}while ( (nPos = strUsage.Find('\n', nPos)) >= 0 );
}

//------ Folger 07/16/08 QA80-11855 BETTER_FORMATTING_FOR_XF_HELP_DUMPING
//string	XFunction::GetHelpInfo(bool bComplete, int nLanguage)
string	XFunction::GetHelpInfo(bool bComplete, int nLanguage, int nHelpList)
//------
{
	string str;	
	//------ Folger 07/16/08 QA80-11855 BETTER_FORMATTING_FOR_XF_HELP_DUMPING
	/*
	string strBrief, strUsage, strVarInfo, strSeeAlso, strReturnType;

	GetReturnType(strReturnType);	///DSC 7/19/05 MAKE_GET_RETURN_TYPE_PUBLIC	
	strBrief = GetHelpText(IDV_HELP_DESCRIPTION, nLanguage);
	strUsage = GetHelpText(IDXF_SYNTAX, nLanguage);
	strSeeAlso = GetHelpText(IDV_HELP_SEE_ALSO, nLanguage);
	strVarInfo = GetVarsHelpInfo(nLanguage, bComplete); // strVarInfo = GetVarsHelpInfo(); 	/// Justin 2007-03-11 v8.0578 DISPLAY_DIFF_LANGUAGE_HELP_FOR_DIFF_LANGUAGE_VERSION

	///DSC 10/5/05 DISPLAY_VARIABLE_INFO
	//---------- CPY 3/19/2007 XF_HELP_NEED_CATEGORY_INFO
	//str = "\n" + LIST_XF_HELP_INFO + ": " + m_tree.XFname.strVal;
	str = "\n" + m_tree.category.strVal + ": " + m_tree.XFname.strVal;
	//----------
	str += "\n------------------\n";
	
	///Justin 2007-06-13 REMOVE_FIRST_COLON_IN_DESCRIPITON
	if(!strBrief.IsEmpty() && ':' == strBrief.GetAt(0))
		strBrief.Delete(0);
	///End REMOVE_FIRST_COLON_IN_DESCRIPITON	
	if(!strBrief.IsEmpty())
		str += strBrief + "\n";
	if(!strUsage.IsEmpty())
		str += "\nUsage: \n" + strUsage + "\n";
	if(!strReturnType.IsEmpty() && strReturnType.CompareNoCase("void")!=0)
		str += "\nReturn Type:\n" + strReturnType + "\n";
	if(!strVarInfo.IsEmpty())
		str += "\nVariables Info:\n" + strVarInfo;
	if(!strSeeAlso.IsEmpty())
	{
		strSeeAlso.TrimLeft();strSeeAlso.TrimRight();
		str += "\nSee Also:\n" + strSeeAlso + "\n";
	}
	str += "\n------------------\n";
	///end DISPLAY_VARIABLE_INFO
//------
	*/

	switch ( nHelpList )
	{
		case XF_HELP_LIST_ALL:
		{
			str = "\n" + _L("Category") + ":   " + m_tree.category.strVal + '\n';

			string strBrief = GetHelpText(IDV_HELP_DESCRIPTION, nLanguage);
			vector<string>		vsInfo;
			strBrief.GetTokens(vsInfo, ':');
			if ( vsInfo.GetSize() > 0 )
				strBrief = vsInfo[vsInfo.GetSize()-1];
			str += _L("Brief Info") + ": " + strBrief + "\n\n";
			
			str += getHelpUsageInfo(nLanguage) + '\n';

			str += getHelpVariablesInfo(nLanguage, bComplete, nHelpList);
			
			str += "\n" + getRelatedXFInfo(nLanguage);		///------ Folger 03/10/09 QA80-11855 LT_XF_HELP_DUMPING_NEEDS_SUPPORT_DISPLAY_RELATED_XF
		}
		break;

		case XF_HELP_LIST_USAGE:
			str = "\n" + getHelpUsageInfo(nLanguage);
			break;

		case XF_HELP_LIST_VARIABLES:
			str = "\n" + getHelpVariablesInfo(nLanguage, FALSE, XF_HELP_LIST_VARIABLES);
			break;

		case XF_HELP_LIST_TREENODE_DETAILS:
			str = getHelpTreeNodeDetailsInfo();
			break;
			
		///------ Folger 03/10/09 QA80-11855 LT_XF_HELP_DUMPING_NEEDS_SUPPORT_DISPLAY_RELATED_XF
		case XF_HELP_LIST_RELATED_XF:
			str = getRelatedXFInfo(nLanguage);
			break;
		///------ End LT_XF_HELP_DUMPING_NEEDS_SUPPORT_DISPLAY_RELATED_XF
		
		default:
			break;
	}
	
	//------ End BETTER_FORMATTING_FOR_XF_HELP_DUMPING

	return str;
}

/// DSC 2/14/06 QA70-7518 ALLOW_SEARCH_XF_BY_KEYWORDS
//-- get a string to search for lx search:=<search keyword>.
//   Only description and autohint are searched. 
//   We may want to add a keyword field in the xf tree to help searches.
string XFunction::GetKeywordSearchText(string* p_strDisplayStr)
{
	// IDXF_DESCRIPTION, IDV_VAR_AUTOCOMPLETE_HINT, IDV_HELP_BRIEF_INFO, IDV_HELP_SUMMARY
	string strSummary = GetHelpText(IDV_HELP_DESCRIPTION, 0);
		//strBrief = GetHelpText(IDV_VAR_AUTOCOMPLETE_HINT, 0); fail
		//strBrief = GetHelpText(IDV_HELP_BRIEF_INFO, 0);
		//strBrief = GetHelpText(IDV_HELP_SUMMARY, 0);
		// TreeNode tn = GetHelp(IDV_HELP_SUMMARY, IDRS_HELP_E);	
		// strBrief = tn.strVal;
		//strBrief = GetHelpText(IDXF_DESCRIPTION, 0);
	
	
	string strAutoHint = GetHelpBriefInfo();
	string strSearchStr = strAutoHint + " " + strSummary;
	
	// this is brief string for displaying if successful search
	if(p_strDisplayStr)
		//*p_strDisplayStr = strAutoHint.IsEmpty()? strSummary : strAutoHint;
		*p_strDisplayStr = strSummary;

	//strSearchStr += "\n ";
	//strSearchStr += GetHelpText();
	// strSearchStr += "\n ";
	// strVarInfo = GetVarsHelpInfo();

	return strSearchStr;
	
}
/// end ALLOW_SEARCH_XF_BY_KEYWORDS


string XFunction::GetVarsInfo(DWORD dwDisplayOptions, int nLanguage)// = IDRS_HELP_E)
{
	string str;
	vector<string> vsVarNames, vsVarDefaultVals, vsVarTypes;
	GetVariables(vsVarNames, vsVarDefaultVals, vsVarTypes);
	string strArgs = _format_all_arg_str(vsVarNames, vsVarDefaultVals, vsVarTypes, dwDisplayOptions);
	
	//strXFname.MakeValidCName();	//-- strip space etc
	string strXFname = GetFunctionName(true);
	
	if( (LIST_XF_ARG_MORE_INFO & dwDisplayOptions) ) //?? && 1==trXF.UsageCtxt.LabTalk.nVal)	
	{		
		string strVarsInfo = GetVarsHelpInfo();
		
		
		//trVars.SetAttribute(STR_LABEL_ATTRIB, strNameToShow);
		string strReturnType;
		GetReturnType(strReturnType);	///DSC 7/19/05 MAKE_GET_RETURN_TYPE_PUBLIC
		
		string strDescription = m_tree.xFdescription.strVal;
		string strTitle = strXFname;//strNameToShow;
		
		if(!strReturnType.IsEmpty() && strReturnType.CompareNoCase("void")!=0)
		 	strTitle += " " + LIST_XF_RETURN + "=" + strReturnType;
				
		if(!strDescription.IsEmpty())
		 	strTitle += " " + LIST_XF_DESCRIPTION + "=" + strDescription;
		
		printf("%s\n", strTitle);
		printf("%s\n", strVarsInfo);
		
		
		
	}
	else
	{
		str = strXFname +  " " + strArgs;
	}

	return str;
	
}
/*
#define STR_DEFAULT_WKS_SEL_CHANGE_EVENT "Show Sum of Selected Cells"

static string _get_default_XF_event_handler(int nEventID, LPCSTR lpcszDefault)
{
	if(IDXF_USGCTXT_WKS_SEL_CHANGE != nEventID)
		return (string)lpcszDefault;
	
	string strDefault = STR_DEFAULT_WKS_SEL_CHANGE_EVENT;

	int nIDXF = nEventID;
	
	vector<string> vsNames, vsFiles;
	
	int nNumFiles = okutil_find_files_from_map(&vsNames, &vsFiles, SUPPORTFILE_XF, 0, &nIDXF, 1);
	for (int ii = 0; ii < nNumFiles; ii++)
	{
		string	strName = GetFileName(vsFiles[ii], true);
		if(strName.CompareNoCase(strDefault) == 0)
			return vsNames[ii];
	}
	return "";
	///end USE_FIND_FILE_NOT_FIND_FILES 
	
}
*/
///DSC 3/14/05 v8.0204 QA70-7500 EVENT_ORGANIZER_DLG
#define STR_GLOBAL_HANDLER_FILE "OriginLab\\GlobalEvents"

//---- CPY 4/6/05 XF_ON_WKS_SEL_CHANGE_AVOID_COMPILE
static	vector<int>		s_vnEventIDs;
static	int				s_nEventIDLoadCount = 0;
static	vector<string>	s_vsHandlerNames;

/// ML 4/28/2006 NO_GETN_IDS_FOR_STATIC_TEXTS
#define		GETN_ID_STATIC(_nID)
/// end NO_GETN_IDS_FOR_STATIC_TEXTS


static void _construct_XF_events_handler_tree(Tree& tr)
{
	//GETN_NAMED_TREE(trFD, GUI);
	GETN_USE(tr)

	tr.SetAttribute(STR_THEME_TYPE_ATTRIB, THTYPE_EVENT_ORGANIZER);

	string strInfo = _L("Select X-Function from the lists below.\n");
	strInfo += _L("To add to these lists, create X-Functions with a single Input vector.\n");
	strInfo += _L("You will also need to set the Usage Context for the various Selection Events.");
	//-- load this info only if theme == <none>  or factory default, otherwise load from theme
	/// ML 4/28/2006 NO_GETN_IDS_FOR_STATIC_TEXTS
	//GETN_MULTILINE_TEXT(Info,"",strInfo) GETN_INFO	GETN_ID(IDEO_EVENTORG_INFO)
	GETN_MULTILINE_TEXT(Info,"",strInfo) GETN_INFO	GETN_ID_STATIC(IDEO_EVENTORG_INFO)
	/// end NO_GETN_IDS_FOR_STATIC_TEXTS
	GETN_STRLIST(OnWksSelectionChange, "Cell Selection by Clicking", "", "")	GETN_ID(IDXF_USGCTXT_WKS_SEL_CHANGE)
	GETN_STRLIST(OnWksSelectionTracking, "Cell Selection by Clicking and Dragging", "", "")	GETN_ID(IDXF_USGCTXT_WKS_SEL_TRACKING)
	GETN_STR(Info5," ","   ") GETN_READ_ONLY_COLOR	GETN_ID(IDEO_EVENTORG_INFO5)
	
	///DSC 4/1/05 QA70-7500 v8.215 GET_XF_FROM_ACCELERATOR
	/// ML 4/28/2006 NO_GETN_IDS_FOR_STATIC_TEXTS
	//GETN_STR(Info6,"",_L("Select hotkeys to Worksheet X-Functions")) GETN_INFO	GETN_ID(IDEO_EVENTORG_WKSINFO)
	GETN_STR(Info6,"",_L("Select hotkeys to Worksheet X-Functions")) GETN_INFO	GETN_ID_STATIC(IDEO_EVENTORG_WKSINFO)
	/// end NO_GETN_IDS_FOR_STATIC_TEXTS
	GETN_BEGIN_BRANCH(wks, _L("Worksheet hotkeys"))		GETN_ID_BRANCH(IDEO_EVENTORG_WKS)
		GETN_STRLIST(CtrlF1, _L("Ctrl F1"), "", "") 	GETN_ID(IDEO_EVENTORG_WKSHOTKEY1)
		GETN_STRLIST(CtrlF2, _L("Ctrl F2"), "", "") 	GETN_ID(IDEO_EVENTORG_WKSHOTKEY2)
		GETN_STRLIST(CtrlF3, _L("Ctrl F3"), "", "") 	GETN_ID(IDEO_EVENTORG_WKSHOTKEY3)
		GETN_STRLIST(CtrlF7, _L("Ctrl F7"), "", "") 	GETN_ID(IDEO_EVENTORG_WKSHOTKEY4)
		GETN_STRLIST(CtrlF8, _L("Ctrl F8"), "", "") 	GETN_ID(IDEO_EVENTORG_WKSHOTKEY5)
		GETN_STRLIST(CtrlF9, _L("Ctrl F9"), "", "") 	GETN_ID(IDEO_EVENTORG_WKSHOTKEY6)
	GETN_END_BRANCH(wks)
	
	/// ML 4/28/2006 NO_GETN_IDS_FOR_STATIC_TEXTS
	//GETN_STR(Info7," ",_L("Select hotkeys to Graph X-Functions")) GETN_INFO	GETN_ID(IDEO_EVENTORG_GRINFO)
	GETN_STR(Info7," ",_L("Select hotkeys to Graph X-Functions")) GETN_INFO	GETN_ID_STATIC(IDEO_EVENTORG_GRINFO)
	/// end NO_GETN_IDS_FOR_STATIC_TEXTS
	GETN_BEGIN_BRANCH(graph, _L("Graph hotkeys"))		GETN_ID_BRANCH(IDEO_EVENTORG_GR)
		GETN_STRLIST(CtrlF1, _L("Ctrl F1"), "", "") 	GETN_ID(IDEO_EVENTORG_GRHOTKEY1) 
		GETN_STRLIST(CtrlF2, _L("Ctrl F2"), "", "") 	GETN_ID(IDEO_EVENTORG_GRHOTKEY2)
		GETN_STRLIST(CtrlF3, _L("Ctrl F3"), "", "") 	GETN_ID(IDEO_EVENTORG_GRHOTKEY3)
		GETN_STRLIST(CtrlF7, _L("Ctrl F7"), "", "") 	GETN_ID(IDEO_EVENTORG_GRHOTKEY4)
		GETN_STRLIST(CtrlF8, _L("Ctrl F8"), "", "") 	GETN_ID(IDEO_EVENTORG_GRHOTKEY5)
		GETN_STRLIST(CtrlF9, _L("Ctrl F9"), "", "") 	GETN_ID(IDEO_EVENTORG_GRHOTKEY6)
	GETN_END_BRANCH(graph)
	///end GET_XF_FROM_ACCELERATOR
	
	///DSC 7/25/05 MORE_EVENT_ORGANIZER matrix xf hotkeys

	/// ML 4/28/2006 NO_GETN_IDS_FOR_STATIC_TEXTS
	//GETN_STR(Info8," ",_L("Select hotkeys to Matrix X-Functions")) GETN_INFO	GETN_ID(IDEO_EVENTORG_MATINFO)
	GETN_STR(Info8," ",_L("Select hotkeys to Matrix X-Functions")) GETN_INFO	GETN_ID_STATIC(IDEO_EVENTORG_MATINFO)
	/// end NO_GETN_IDS_FOR_STATIC_TEXTS
	GETN_BEGIN_BRANCH(matrix, _L("Matrix hotkeys"))		GETN_ID_BRANCH(IDEO_EVENTORG_MAT)
		GETN_STRLIST(CtrlF1, _L("Ctrl F1"), "", "") 	GETN_ID(IDEO_EVENTORG_MATHOTKEY1) 
		GETN_STRLIST(CtrlF2, _L("Ctrl F2"), "", "") 	GETN_ID(IDEO_EVENTORG_MATHOTKEY2)
		GETN_STRLIST(CtrlF3, _L("Ctrl F3"), "", "") 	GETN_ID(IDEO_EVENTORG_MATHOTKEY3)
		GETN_STRLIST(CtrlF7, _L("Ctrl F7"), "", "") 	GETN_ID(IDEO_EVENTORG_MATHOTKEY4)
		GETN_STRLIST(CtrlF8, _L("Ctrl F8"), "", "") 	GETN_ID(IDEO_EVENTORG_MATHOTKEY5)
		GETN_STRLIST(CtrlF9, _L("Ctrl F9"), "", "") 	GETN_ID(IDEO_EVENTORG_MATHOTKEY6)
	GETN_END_BRANCH(matrix)	
	///end MORE_EVENT_ORGANIZER
	
	// temp : for now, just set the default values to the previously choosen values from last time the OK button was pushed.
	// These values will not last to the next session.
	if(s_vnEventIDs.GetSize()>0)
	{
		int nn = octree_set_values_by_ids(&tr, &s_vnEventIDs, &s_vsHandlerNames, 0);
	}
	else
	{
		//-- set default selections 
		string strHandlerName = STR_NONE;
		tr.OnWksSelectionChange.strVal 		= strHandlerName;//_get_default_XF_event_handler(IDXF_USGCTXT_WKS_SEL_CHANGE, STR_NONE);
		tr.OnWksSelectionTracking.strVal 	= strHandlerName;//_get_default_XF_event_handler(IDXF_USGCTXT_WKS_SEL_CHANGE, STR_NONE);
		foreach(TreeNode trN in tr.wks.Children)
			trN.strVal = strHandlerName;
		foreach(TreeNode trNG in tr.graph.Children)
			trNG.strVal = strHandlerName;
		/*
		tr.wks.CtrlF1.strVal = strHandlerName;
		tr.wks.CtrlF2.strVal = strHandlerName;
		tr.wks.CtrlF3.strVal = strHandlerName;
		tr.wks.CtrlF7.strVal = strHandlerName;
		tr.wks.CtrlF8.strVal = strHandlerName;
		tr.wks.CtrlF9.strVal = strHandlerName;
		
		tr.graph.CtrlF1.strVal = strHandlerName;
		tr.graph.CtrlF2.strVal = strHandlerName;
		tr.graph.CtrlF3.strVal = strHandlerName;
		tr.graph.CtrlF7.strVal = strHandlerName;
		tr.graph.CtrlF8.strVal = strHandlerName;
		tr.graph.CtrlF9.strVal = strHandlerName;
		*/
	}

	
	//-- clean up names
	//check_xf_missing_indicator_in_reg(SUPPORTFILE_XF, IDXF_USGCTXT_WKS_SEL_CHANGE);
	//check_xf_missing_indicator_in_reg(SUPPORTFILE_XF, IDXF_USGCTXT_WKS_SEL_TRACKING);	
}
static string _make_default_events_filepath()
{
	string strDefaultThemeFile;
	///DSC 7/26/05 FIND_EO_DEFAULT_OTH
	//okutil_make_file_path(strDefaultThemeFile, ORIGIN_PATH_SYSTEM, "Themes\\EventOrganizer", "default.oth", NULL, false);
	okutil_find_theme_file(strDefaultThemeFile, ORIGIN_PATH_UNDEF, THTYPE_EVENT_ORGANIZER, "default.oth");
	///end FIND_EO_DEFAULT_OTH
	
	return strDefaultThemeFile;
}
//-- to save users choices between sessions without saving/loading theme
bool load_XF_events_handler_tree(TreeNode& tr)
{
	bool bRet;
	
	string strSysThemeFile = okutil_theme_get_system_theme_file_name(THTYPE_EVENT_ORGANIZER);
	string strDefaultThemeFile = _make_default_events_filepath();
	
	_construct_XF_events_handler_tree(tr);//init the tree
	if(  (strSysThemeFile.IsEmpty() || !theme_load_settings(tr, strSysThemeFile)) && strDefaultThemeFile.IsFile()  )
		bRet = theme_load_settings(tr, strDefaultThemeFile);
	
	return bRet;
}
bool save_XF_events_handler_tree(TreeNode& tr)
{
		//-- for now, update selections here
		// later, if we allow themes, update from theme organizer, not here
	tree_get_values_with_ids(tr, s_vnEventIDs, s_vsHandlerNames);
	
	//-- for now, save as default name when user clicks OK button.
	// GetNBoxTree_tr.Save(strThemeDefaultFile);	
	return theme_save_settings(tr, _make_default_events_filepath());
}

bool	get_xf_name(string& strName, int nEventId)
{
	if (nEventId < 0 || (s_vnEventIDs.GetSize() <= 0 && 0==s_nEventIDLoadCount))
	{
		GETN_NAMED_TREE(tr, GUI);
		load_XF_events_handler_tree(tr);
		tree_get_values_with_ids(tr, s_vnEventIDs, s_vsHandlerNames);
		s_nEventIDLoadCount++;
		//------- CPY 5/8/06 F11_DIALOG_SHOWS_NONE_BUT_EVENTS_IS_TRIGGED
		// this happens if you move XF folder from system to user
		for(int ii=0; ii < s_vnEventIDs.GetSize(); ii++)
		{
			string str = s_vsHandlerNames[ii];
			///---Sim 11-05-2007 CLEAN_LOCALIZATION_CODE
			//if(str == STR_NONE)
			///Sophy 4/25/08 ROW_STATS_PUT_RESULTS_COL_TO_BEGINNING_OF_SRC_SHEET
			//if ( PDS_NONE == cvt_str_to_predefined_type(str) )
			if ( PDS_NONE == str_to_predefined_type(str) )
			///end ROW_STATS_PUT_RESULTS_COL_TO_BEGINNING_OF_SRC_SHEET
			///---END CLEAN_LOCALIZATION_CODE
				continue;
			if(IDST_TREE_BRANCH_MASK & s_vnEventIDs[ii])
				continue;
			string strFullpath;
			int nn = okutil_find_file_from_composite_name(&strFullpath, str, SUPPORTFILE_XF);
			if(nn == ORIGIN_PATH_UNDEF || !strFullpath.IsFile())
				s_vsHandlerNames[ii] = STR_NONE;
		}
		//-------
	}
	
	// Search, should be moved to okutil
	for(int ii=0; ii < s_vnEventIDs.GetSize(); ii++)
	{
		if(IDST_TREE_BRANCH_MASK & s_vnEventIDs[ii])
			continue;
		
		if(s_vnEventIDs[ii] == nEventId)
		{
			strName = s_vsHandlerNames[ii];
			///---Sim 11-05-2007 CLEAN_LOCALIZATION_CODE
			//if(strName == STR_NONE)
			///Sophy 4/25/08 ROW_STATS_PUT_RESULTS_COL_TO_BEGINNING_OF_SRC_SHEET
			//if ( PDS_NONE == cvt_str_to_predefined_type(strName) )
			if ( PDS_NONE == str_to_predefined_type(strName) )			
			///end ROW_STATS_PUT_RESULTS_COL_TO_BEGINNING_OF_SRC_SHEET
			///---END CLEAN_LOCALIZATION_CODE
				return false;
			return true;
		}
	}
	return false;
}

//typedef string (*PFN_GET_XF_FROM_ID)(int nId);	
void  OnWksSelectionChange(DataRange &dr, int nEventID)// = NULL)
{
	/*
	//DWORD dw = GetTickCount();
	Function fn = Project.FindFunction("OnSelChange", STR_GLOBAL_HANDLER_FILE, false, true);
	//out_int("time = ", GetTickCount() - dw);
	FUNC_OCEVENTS pfn = fn;
	if(pfn)
		pfn(dr, EXIST_WKS, lpcszEventType);
	*/
	
	string strName;
	if( get_xf_name(strName, nEventID) && !strName.IsEmpty() )
	{
		vector vv;
		DWORD dwPlotID;
		if( dr.GetData(DRR_GET_MISSING | DRR_COMBINED_SIMPLE, 0, (DWORD*)NULL, NULL, &vv)>= 0 )
		{
			XFBase xf(strName);
			if( xf )
			{
				if( xf.SetArg(0, vv) )
					xf.Evaluate();
			}
		}
	}
}




////////////////////////////////////////////////////////////////////////////////////
// Start your functions here.


int get_xvar_type_from_type_name(LPCSTR lpcszTypeName)
{
	int		nXVarType = okutil_XVarTypeName_to_XVarType(lpcszTypeName);
	return nXVarType;
}


/// YuI 08/24/05 SIMPLIFIED_RANGE_SPECIFICATION_FOR_LT_XFUNCTION
#define	RANGE_SHORT_NOTATION_PREFIX		"RANGE"
#define	XYRANGE_SHORT_NOTATION_PREFIX	"XYRANGE"
#define	XYZRANGE_SHORT_NOTATION_PREFIX	"XYZRANGE"
#define	RANGE_SHORT_NOTATION_MATLAB_DELIMITER	':'
BOOL	_is_matlab_notation(LPCSTR lpcszStr)
{
	//string str = lpcszStr;
	//return (str.Find(RANGE_SHORT_NOTATION_MATLAB_DELIMITER) >= 0);
	
	// need better support for matlab notation
	// for now just do not support it
	return FALSE;
}





static void	_translate_XF_error(string& strTranslated, int nErrCode)
{
	switch( nErrCode )
	{
	case PRS_ERROR_GENERAL:
		strTranslated = _L("General XFunction error");
		break;
		
	case PRS_ERROR_PARETHESIS_MISMATCH:
		strTranslated = _L("%s: parenthesis mismatch");
		break;
		
	case PRS_ERROR_INVALID_PREFIX:
		strTranslated = _L("%s: invalid prefix for complex notation");
		break;
		
	case PRS_ERROR_EMPTY_OR_INVALID_BOOK_DESCRIPTOR:
		strTranslated = _L("%s: unable to resolve book");
		break;
		
	case PRS_ERROR_EMPTY_OR_INVALID_SHEET_DESCRIPTOR:
		strTranslated = _L("%s: unable to resolve sheet");
		break;
		
	case PRS_ERROR_EMPTY_OR_INVALID_OBJECT_DESCRIPTOR:
		strTranslated = _L("%s: unable to resolve object");
		break;
		
	case PRS_ERROR_LABTALK_VARIABLE:
		strTranslated = _L("%s: unable to process labtalk variable");
		break;
	
	case PRS_ERROR_SAME_INPUT_NOT_FOUND:
		strTranslated = _L("Unable to resolve previous variable of the same type");
		break;

	default:
		ASSERT(FALSE);
		strTranslated = _L("Unknown XFunction error");
	}
}

bool	XF_error_report(LPCSTR lpcszMessage, LPCSTR lpcszOffendingString)
{
	string strReport;
	strReport.Format(lpcszMessage, lpcszOffendingString);
	return error_report(strReport);
}

bool	XF_error_report(int nErrorCode, LPCSTR lpcszOffendingString)
{
	string strTranslated;
	_translate_XF_error(strTranslated, nErrorCode);
	return XF_error_report(strTranslated, lpcszOffendingString);
}
/// end GENERAL_X_STRING_CONVENTION_TO_ACCESS_OBJECTS


/// DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
// void	XFunctionOrganizer::checkUpdateBeforeSaving(TreeNode &trXFFunc)
// void	XFunction::checkUpdateBeforeSaving(TreeNode &trXFFunc)
/// YuI 06/06/08 QA70-8966 XF_DRAG_AND_DROP_PROBLEM
//	void	xf_check_update_before_saving(TreeNode &trXFFunc)
void	xf_check_update_before_saving(TreeNode &trXFFunc, LPCSTR lpcszPathName)
/// end XF_DRAG_AND_DROP_PROBLEM
/// end SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
{
	// first check usage context
	TreeNode trUseCtxt = trXFFunc.UsageCtxt;
	if(trUseCtxt.GrObj)
	{
		if(trUseCtxt.GrObj.Use)
		{
			vector<int> vnIDs = {IDXF_USGCTXT_LABTALK, IDXF_USGCTXT_WKS_SEL, IDXF_USGCTXT_WKS_SEL_CHANGE, IDXF_USGCTXT_WKS_SEL_TRACKING};
			vector<string> vsVals;
			vsVals.SetSize(vnIDs.GetSize());
			for(int ii = 0; ii < vsVals.GetSize(); ii++)
				vsVals[ii] = "0";
			
			tree_set_values_by_ids(trUseCtxt, vnIDs, vsVals);
		}
	}
	
	/// YuI 06/06/08 QA70-8966 XF_DRAG_AND_DROP_PROBLEM
	TreeNode trCategory = tree_get_node_by_dataid(trXFFunc, IDV_CATEGORY);
	if ( trCategory.IsValid() )
	{
		string strCategory;
		if( okutil_get_category_from_pathname(lpcszPathName, &strCategory, SUPPORTFILE_XF) )
		{
			trCategory.strVal = strCategory;
		}
	}
	/// end XF_DRAG_AND_DROP_PROBLEM
}


/// YuI 03/22/05 LOW_LEVEL_FUNCTION_TO_CHECK_RANGE_REALITY
// fo outoupdate to pe possible following condition must be met
// tree must have at least one input which is good operation input
// there may be no outputs but if present all output variables must be good operation outputs
/// DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
// BOOL	XFunctionOrganizer::IsAutoupdatePossible(const TreeNode& trXF)
// BOOL	XFunction::IsAutoupdatePossible(const TreeNode& trXF)
BOOL	xf_is_autoupdate_possible(const TreeNode& trXF)
/// end SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
{
	// TreeNode trVars = GetVarsNode(trXF);
	TreeNode trVars;
	okutil_xft_GetVarsNode(&trVars, &trXF, NULL);
	
	if(!trVars)
		return error_report("invalid X-Function tree");
	BOOL bInputPresent = FALSE;
/*
	// wait for moving to VC
	foreach(TreeNode trVar in trVars.Children)
	{
		XVariableHelper xVar(trVar);
		XVariableBase* pVar = xVar.Var();
		if( !pVar )
			return error_report("Failed to construct XVariable");

		switch( pVar->GetDesignation() )
		{
		case IO_INPUT:
			if( !pVar->CanBeOperationInput() )
				continue;
			
			bInputPresent = TRUE;
			if( !pVar->IsGoodOperationInput() )
				return FALSE;
			break;
			
		case IO_OUTPUT:
			if( !pVar->CanBeOperationOutput() )
				continue;
			
			if( !pVar->IsGoodOperationOutput() )
				return FALSE;
			break;
			
		case IO_INOUTPUT:
			return FALSE; //autoupdate not allowed if input and output matches
		}
	}
*/	
	return bInputPresent;
}
/// end LOW_LEVEL_FUNCTION_TO_CHECK_RANGE_REALITY

/// end MULTIPLE_XFUNCTION_EVENT_HANDLERS_SUPPORT
/// end SAVE_EDITABLE_LINES


/// DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
// void		XFunctionOrganizer::SetFunctionName(TreeNode &trFunction, string strName, const int *pnPath) //=NULL
//void		xf_set_function_name(TreeNode &trFunction, string strName, const int *pnPath) //=NULL
void		xf_set_function_name(TreeNode &trFunction, string strName, const int *pnPath) //=NULL
/// end SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
{
	/// ML 4/18/2005 XFUNCTION_TREE_MANIPULATION_IN_VC
	okutil_xft_SetFunctionName(&trFunction, strName, pnPath);
	/// end XFUNCTION_TREE_MANIPULATION_IN_VC
	
	/// DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
	// SetLabel(trFunction, strName);
	trFunction.SetAttribute(STR_LABEL_ATTRIB, strName);
	/// end SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
	
}

// if lpcstrFilePath = NULL, save into current func name
/// DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
// bool		XFunctionOrganizer::Save(TreeNode &trFunction, LPCSTR lpcstrFilePath) //=NULL
// bool	XFunction::Save(TreeNode &trFunction, LPCSTR lpcstrFilePath) //=NULL
bool	xf_save(TreeNode &trFunction, LPCSTR lpcstrFilePath) //=NULL
/// end SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
{
	string strFile(lpcstrFilePath), strPath;
	if(strFile.IsEmpty())
	{
		//--- CPY 3/2/05 XF_SAVING_INTO_WRONG_PATH
		/// DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
		// strFile = GetFuncFileName(trFunction, true);	
		strFile = okutil_fo_GetFuncFileName(&trFunction, true);
		/// end SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
		//---
	}
	strPath = GetFilePath(strFile);
	if(!CheckMakePath(strPath))
		return false;
	
	/// DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
	// checkUpdateBeforeSaving(trFunction);//--- CPY 4/5/05 XF_LT_CHECK_USAGE_CONTEXT
	/// YuI 06/06/08 QA70-8966 XF_DRAG_AND_DROP_PROBLEM
	//	xf_check_update_before_saving(trFunction);
	xf_check_update_before_saving(trFunction, strPath);
	/// end XF_DRAG_AND_DROP_PROBLEM
	/// end SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
	
	Tree tr;
	tr=trFunction;
	///DG DISABLE_GUI_INTERFACE_IN_FO : roll back before saving if disable GUI when loading
	/// DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION	
	// if(IsDisableGUIInterface())
	//	DisableGUIInterface(tr, true);
	/// end SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
	///end DISABLE_GUI_INTERFACE_IN_FO
	
	/// DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
	// ClearChanged(tr);
	//tr_clear_changed_attrib(tr);
	tree_node_changed(tr, true);

	/// end SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
	
	//--- CPY 3/7/05
	//SetFunctionName(tr, GetFileName(strFile, true));
	//return tr.Save(strFile);
	
	/// DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
	// string strNewFuncName = GetFunctionNameStr(GetFileName(strFile, true), okutil_get_origin_path_type(strFile));
	// SetFunctionName(tr, strNewFuncName);
	string strNewFuncName = okutil_xft_GetFunctionNameStr( GetFileName(strFile, true), okutil_get_origin_path_type(strFile) );
	xf_set_function_name(tr, strNewFuncName, NULL);
	/// end SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
	
	if(tr.Save(strFile))
	{
		//delete old file? not sure if we should still do this, so comment out for now
		//if(strOldFileName.IsFile())
		//	DeleteFile(strOldFileName);
		/// DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
		// ClearChanged(trFunction);
		//tr_clear_changed_attrib(trFunction);
		tree_node_changed(trFunction, true);
		/// end SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
		///DG 3/9/05
		if(NULL != lpcstrFilePath)
		{
			/// DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
			//SetFunctionName(trFunction, strNewFuncName);
			//SetFuncFileName(trFunction, strFile);
			xf_set_function_name(trFunction, strNewFuncName, NULL);
			okutil_fo_SetFuncFileName(&trFunction, strFile);
			/// end SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
		}
		///end
		
		NOTIFY_XF_FILE_CHANGE
		
		return true;
	}
	return false;

}


/// DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
// bool XFunctionOrganizer::SaveUsingXFname(TreeNode &trXF)
bool xf_save_using_xf_name(TreeNode &trXF)
{
	string strCurrentFile = okutil_fo_GetFuncFileName(&trXF, true);
	string strXFname = trXF.XFname.strVal;
	string strFilename = GetFilePath(strCurrentFile) + strXFname + STR_XF_FILE_EXT;
	if(xf_save(trXF, strFilename))
	{
		return true;
	}
	return false;
}
/// end SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION

/// DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
string		xf_get_category_name(TreeNode &trFunction)
{
	/// Hong 03/18/08 QA80-8966 FIX_DRAG_DROP_XF_FAIL_PUT_IN_CORRECT_CATEGORY
	Tree trCat;
	trCat = tree_get_node_by_dataid(trFunction, IDV_CATEGORY);
	if ( trCat.IsValid() && !trCat.IsEmpty() )
		return trCat.strVal;
	/// end FIX_DRAG_DROP_XF_FAIL_PUT_IN_CORRECT_CATEGORY
	///Frank 3/31/05	FIXED_MISTERIOU_FOLDER_UNDER_USRE_FOLDER
	// string strFilePath=GetFuncFileName(trFunction, true);
	string strFilePath=okutil_fo_GetFuncFileName(&trFunction, true);
	//string strFileName = GetFunctionName(trFunction, true);
	string strFileName = okutil_composite_name_from_file_path(strFilePath, STR_XF_FILE_FOLDER);
	string strCateName; 
	okutil_separate_composite_name(strFileName, NULL, &strCateName);
	return strCateName
}
/// end SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION

/// DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
string		xf_get_function_folder(int nPath, string strSubFolder) //=SYS_FOLDER, ""
{
	///DSC 1/28/06 SUPPORT_PROJECT_AND_CUSTOM_PATH
	// string strPath=okutil_get_origin_path(nPath, STR_XF_FILE_FOLDER);
	string strXFRoot=STR_XF_FILE_FOLDER;
	if(ORIGIN_PATH_PROJECT==nPath || ORIGIN_PATH_CUSTOM==nPath)//these folders have no X_Functions folder or categories.
		strXFRoot="";
	string strPath=okutil_get_origin_path(nPath, strXFRoot);
	///end SUPPORT_PROJECT_AND_CUSTOM_PATH
	if(!strSubFolder.IsEmpty())
	{
		strSubFolder.TrimLeft("\\");
		strPath+=strSubFolder;
	}
	strPath.TrimRight("\\");
	return strPath+"\\";
}
/// end SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION

/// DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
// bool 		XFunctionOrganizer::ConstructXFunction(TreeNode &tr, string strFuncName, vector<string>& vsVarTypes) //= NULL
bool 		xf_construct_xfunction(TreeNode &tr, string strFuncName, vector<string>& vsVarTypes) //= NULL
{
	/// ML 4/18/2005 XFUNCTION_TREE_MANIPULATION_IN_VC
	//MY_PROFILING
	vector<string>		*parrVarTypes = NULL;
	if (vsVarTypes != NULL)
		parrVarTypes = &vsVarTypes;
	/// DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION set IsDisableGUIInterface() ==  false
	// bool bRet = okutil_xft_construct(&tr, strFuncName, parrVarTypes, IsDisableGUIInterface());
	bool bRet = okutil_xft_construct(&tr, strFuncName, parrVarTypes, false);
	/// end SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
	
	return bRet;
	///////////////////////////////////////////////////////////////////////////////////////
	/// end XFUNCTION_TREE_MANIPULATION_IN_VC
}
/// end SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION

/// DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
// void	XFunctionOrganizer::OnAfterAddInsertVar(TreeNode& trFunction)
void	xf_on_after_add_insert_var(TreeNode& trFunction)
{
	/// DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
	// TreeNode trVars=GetVarsNode(trFunction);
	TreeNode trVars;
	okutil_xft_GetVarsNode(&trVars, &trFunction, NULL);
	/// end SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
	
	okutil_xft_prepareVarBranches(&trVars);
}

/// DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
// bool	XFunctionOrganizer::CountVariables(const TreeNode& trXF, int& nInput, int& nOutput, int& nInputOutput)
bool	xf_count_variables(const TreeNode& trXF, int& nInput, int& nOutput, int& nInputOutput)
{
	nInput = nOutput = nInputOutput = 0;
	
	// TreeNode trVars = GetVarsNode(trXF);
	TreeNode trVars;
	okutil_xft_GetVarsNode(&trVars, &trXF, NULL);
	
	if(!trVars)
		return error_report("invalid X-Function tree");

	foreach(TreeNode trVar in trVars.Children)
	{
		TreeNode trIO=trVar.io;
		if(!trIO)
		{
			error_report("X-Function tree has invalid variable node");
			continue;
		}
		switch(trIO.nVal)
		{
		case IO_OUTPUT:
			nOutput++;
			break;
		case IO_INPUT:
			nInput++;
			break;
		default://IO_INOUTPUT
			nInputOutput++;
			break;
		}
	}
	return true;
}
/// end SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION

/// DSC 12/07/05 SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
// bool XFunctionOrganizer::CopyVariableLabelsToDescriptions(TreeNode& trXF, int nLangID)
bool xf_copy_variable_labels_to_descriptions(TreeNode& trXF, int nLangID)//=0
{
	// TreeNode trVars = GetVarsNode(trXF);
	TreeNode trVars;
	okutil_xft_GetVarsNode(&trVars, &trXF, NULL);
	
	if(!trVars)
		return error_report("invalid X-Function tree");
	if(nLangID < IDRS_HELP_E)
		nLangID = _get_current_language();
	foreach(TreeNode trVar in trVars.Children)
	{
		TreeNode trDesc = tree_find_node_by_dataID(trVar, IDV_VAR_HELP_DESCRIPTION, IDV_VAR_LOCAL_HELP_BRANCH, nLangID);
		trDesc.strVal = trVar.description.strVal;
		/// TD 10-20-05
		// The following line when not called from view change 
		// was eventually cleaning up trDesc.strVal
		// by commenting out this line, we hold the 
		// old display value in var, when in advanced view
		//trVar.description.strVal = "";
		//---------------
		trVar.description.Show = false;
	}
	return true;
}

// bool XFunctionOrganizer::CopyVariableDescriptionsToLabels(TreeNode& trXF, int nLangID)
bool xf_copy_variable_descriptions_to_labels(TreeNode& trXF, int nLangID)
{
	// TreeNode trVars = GetVarsNode(trXF);
	TreeNode trVars;
	okutil_xft_GetVarsNode(&trVars, &trXF, NULL);
	
	if(!trVars)
		return error_report("invalid X-Function tree");
	if(nLangID < IDRS_HELP_E)
		nLangID = _get_current_language();
	
	foreach(TreeNode trVar in trVars.Children)
	{
		TreeNode trDesc = tree_find_node_by_dataID(trVar, IDV_VAR_HELP_DESCRIPTION, IDV_VAR_LOCAL_HELP_BRANCH, nLangID);
		trVar.description.strVal = trDesc.strVal;
		trVar.description.Show = true;
	}
	return true;
}

//  was XFunctionOrganizer::SaveToDefaultLocation...
bool	xf_save_to_default_location(TreeNode& trXF, int nLocation)// = USER_FOLDER);
{
	// string strCategory = GetCategoryName(trXF);
	string strCategory = xf_get_category_name(trXF);
	
	if(strCategory.IsEmpty())
		/// EJP 2006-09-11 v8.0480 SAVE_XF_TO_MISC_WHEN_NO_CATEGORY_SPECIFIED, per CP
		///return error_report("SaveToDefaultLocation found no category in trXF");
		strCategory = "Miscellaneous";
		/// end SAVE_XF_TO_MISC_WHEN_NO_CATEGORY_SPECIFIED
	strCategory += "\\";
	// string strPath = GetFunctionFolder(nLocation);
	string strPath = xf_get_function_folder(nLocation);
	strPath += strCategory;
	CheckMakePath(strPath);
	string strXFname = trXF.XFname.strVal;
	string strFilename = strPath + strXFname + STR_XF_FILE_EXT;
	
	// return Save(trXF, strFilename);
	return xf_save(trXF, strFilename);
}

/// end SEPARATE_XFUNCTIONORGANIZER_FROM_XFUNCTION
/////////////////////////////////////
///Jasmine 01/24/06 SHOW_XF_CONTEXT_MENU
//bool IsPopUpMenu(TreeNode &trSel, bool &bAdvanView)
bool xf_is_pop_up_menu(TreeNode &trSel, bool &bAdvanView)
{
	if(bAdvanView)
	{
		string strTemp;
		if(!trSel)
			return false;
		if( trSel.GetAttribute(STR_XF_VARIABLE_NODE_ATTRIB, strTemp))
			return true;
		else
			if(strcmp(trSel.tagName,"vars") == 0)			///Temp , must check as attribute
				return true;
		return false;
	}
	return true;
}
string _get_new_val_name(TreeNode &trVars)
{
	vector<string> vsVarsName;
	tree_get_node_names(trVars, vsVarsName, true);
	string strNamePrefix=STR_XF_VAR_NODE_PREFIX;
	for(int ii=1; -1 != vsVarsName.Find(strNamePrefix+(string)ii); ii++)
		;
	return strNamePrefix+(string)ii	;
}
//TreeNode	XFunctionOrganizer::AddNewVar(TreeNode &trVars)
TreeNode xf_add_new_var(TreeNode &trVars)
{
	string strNewValName  = _get_new_val_name(trVars);

	TreeNode trNewVar=trVars.AddNode(strNewValName, TRGP_BRANCH);

	//trNewVar.SetAttribute(STR_ATTRIB_BRANCH, GETNBRANCH_OPEN); /// YuI moved to prepareVarBranches
	okutil_xft_ConstructVarTree(&trNewVar, "vector");
	okutil_xft_prepareVarBranches(&trVars);
	return trNewVar;
}
//TreeNode	XFunctionOrganizer::InsertNewVar(TreeNode &trVars, TreeNode &trBeforeVal)
TreeNode xf_insert_new_var(TreeNode &trVars, TreeNode &trBeforeVal)
{
	string strNewValName  = _get_new_val_name(trVars);
	
	//TreeNode trBeforeVal =tree_get_node(trVars, nBeforeRow - 1, 0);
	TreeNode trNewVar;
	if(trBeforeVal)
		trNewVar=trVars.InsertNode(trBeforeVal, strNewValName , TRGP_BRANCH);
	else
		trNewVar=trVars.AddNode( strNewValName , TRGP_BRANCH);
	
	okutil_xft_ConstructVarTree(&trNewVar, "vector");
	okutil_xft_prepareVarBranches(&trVars);
	return trNewVar;
}
///End SHOW_XF_CONTEXT_MENU

///Jasmine 02/24/06 MOVE_FROM_XFUNCTIONWIZ
void xf_update_var_node(TreeNode &trVars, const TreeNode &trSettingVar)
{
	TreeNode trInputVar=trSettingVar.input;
	TreeNode trOutputVar=trSettingVar.output;
	TreeNode trVar=trVars.FirstNode;
	xf_set_var_node(trVar, trInputVar, true);
	xf_set_var_node(trVar, trOutputVar, false);
}
void xf_set_var_node(TreeNode &trVar, const TreeNode &trSettingVar, bool bInput)
{
	string strType;
	foreach(TreeNode trVarNode in trSettingVar.Children)
	{
		trVar.name.strVal=trVarNode.name.strVal;
		trVar.io.nVal=bInput ? 0 : 1;
		trVar.type.strVal=trVarNode.type.strVal;
		//trVar.valdata.strVal = trVarNode.GetNode(STR_DATA_NODE).strVal;
#ifndef 	 _XF_LT_CALL_IN_VC
		XVariableHelper xv(trVar);
		XVariableBase* pVar = xv.Var();
		if( !pVar )
		{
			error_report("Failed to construct XVariable");
			return;
		}
		pVar->SetValue(trVarNode.valdata.strVal);
#endif
		trVar=trVar.NextNode;
	}
}
///End MOVE_FROM_XFUNCTIONWIZ

///Jasmine 03/01/06 REDUCE_SIMILAR_CODE, we can use list_x_functions() to do the same thing
/*
///Jasmine 02/27/06 GET_XF_STRUCTURE
int xf_get_xf_category(vector<string>& vsCategory, bool bUser)// = false
{
	vector<string> vsNames, vsFiles;
	int nPathType = bUser? ORIGIN_PATH_USER : ORIGIN_PATH_SYSTEM;
	int nNumFiles = okutil_find_files_from_map(&vsNames, &vsFiles, SUPPORTFILE_XF, 0, NULL, 0, NULL, NULL, nPathType);	
	for(int ii = 0; ii < nNumFiles; ii++)
	{
		string strFileName = okutil_composite_name_from_file_path(vsFiles[ii], STR_XF_FILE_FOLDER);
		string strCateName; 
		okutil_separate_composite_name(strFileName, NULL, &strCateName);
		if(-1 == vsCategory.Find(strCateName) )
			vsCategory.Add(strCateName);
	}
	int nNum = vsCategory.GetSize();
	vsCategory.Sort();
	for(ii = 0; ii < vsCategory.GetSize() - 1; ii++)
	{
		if(vsCategory[ii+1].Find(vsCategory[ii]) > -1 )
			vsCategory.RemoveAt(ii);
	}
	return nNum = vsCategory.GetSize();
}
int xf_get_xf_list(vector<string>& vsXF, LPCSTR lpcszCate, bool bUser)// = false
{
	int nPathType = bUser? ORIGIN_PATH_USER : ORIGIN_PATH_SYSTEM;
	string strPath = xf_get_function_folder(nPathType, lpcszCate);
	FindFiles(vsXF, strPath, "oxf");	
	return vsXF.GetSize();
}
///End GET_XF_STRUCTURE
*/

//---- end XVAR_CHECK_NEW_SHOULD_NOT_USE_TRY_CATCH

BOOL is_xyz_data_range_node(TreeNode& tr)
{
	return tr.Z.IsValid();
}



/// ML 2/1/2006
#ifdef 	 _XF_LT_CALL_IN_VC

// This is called from VC:
int		CallXFunctionWithAuxTree(TreeNode &trXF, TreeNode &trAux, UINT nUID, TreeNode &trUser, UINT wParam, LONG lParam)
/// end ATTACH_XF_USER_TREE
{
	int			nRetValue = OCD_MODIFY | OCD_REPAINT;
	int nOCErr;//CPY 7/11/2007 CURVE_TRANSLATE_BROKEN, also added LTXF_NO_CREATE_LT_TREE
	XFBase		xfun;
	if ( xfun.InitWithInfo(trXF, trAux, nUID, trUser, wParam, lParam) )
		nRetValue = OCD_ERROR;
	//------- CPY 7/11/2007 CURVE_TRANSLATE_NEED_OPTION_INDEX_PASSED_IN
	//else if ( !xfun.Run(FALSE, NULL, &nRetValue, XVT_INT, &nOCErr, LTXF_NO_CREATE_LT_TREE) )
	//	nRetValue = OCD_ERROR;
	else
	{
		int nOption = -1;
		if(trXF.optargindex.nVal && trXF.GetAttribute(STR_XF_OPTION_INDEX_ATTRIB, nOption))
			xfun.SetVarData(trXF.optargindex.nVal-1, nOption);
		if ( !xfun.Run(FALSE, NULL, &nRetValue, XVT_INT, &nOCErr, LTXF_NO_CREATE_LT_TREE) )
			nRetValue = OCD_ERROR;
	}
	//-------
	return nRetValue;
}

#endif
/// end ML 2/1/2006



//BOOL	XFunction::UpdateFromOperationRanges(DataRange *pdrInput, Array<DataRange&>* parrOutputs)
//{
	/*
	if (pdrInput && !pdrInput->IsValid())
		pdrInput = NULL;
	
	if (pdrInput == NULL && parrOutputs == NULL)
		return TRUE;
	Tree trInput;
	Tree trOutput;
	if (pdrInput)
		pdrInput->GetTree(trInput, FALSE);
	if( parrOutputs )
	{
		DataRange dr;
		dr = parrOutputs->GetAt(INDEX_OF_NON_REPORT_TREE_VARS_IN_OUTPUT_ARRAY);
		if( dr.IsValid() )
			dr.GetTree(trOutput, FALSE);
	}
	int nInputTreeIndex = 0;
	int nOutputTreeIndex = 0;
	int nOutputArrayIndex = REPORT_TREE_VARS_IN_OUTPUT_ARRAY_BEGIN;
	
#ifndef 	 _XF_LT_CALL_IN_VC
	// In reverse because that is how they were added inside Evaluate():
	for(int ii = m_arrXVar.GetSize() - 1; ii >= 0; ii--)
	{
		XVariableBase& xVar = m_arrXVar.GetAt(ii);
		xVar.SetValueFromOpRange(trInput, trOutput, parrOutputs, nInputTreeIndex, nOutputTreeIndex, nOutputArrayIndex);
	}
#endif	
	return TRUE;
	*/
//	return XFBase::UpdateFromOperationRanges(pdrInput, parrOutputs);
//}



/// ML 7/12/2006 REPORT_DATA_WITH_XF_WORKSHEET_GRAPHS_HANDLING
//BOOL	XFunction::Evaluate(DataRange *pdrInput, Array<DataRange&>* parrOutputs, DWORD dwCtrl)
/// YuI 07/26/06 XFOPERATION_CHANGE_PARAM_PROBLEM
//	BOOL	XFunction::Evaluate(DataRange *pdrInput, Array<DataRange&>* parrOutputs, DWORD dwCtrl, vector<uint> *pvMapIdsToUIDs)
///------ Folger 01/09/09 v8.0995 CHANGE_PARAM_SHOULD_DO_EVALUATE_EXACTLY_THE_SAME_AS_NORMAL_EXECUTE
//BOOL	XFunction::Evaluate(DataRange *pdrInput, Array<DataRange&>* parrOutputs, DWORD dwCtrl, vector<uint> *pvMapIdsToUIDs, TreeNode* pGetN)
///------ Folger 08/05/10 ORG-702-P1 CLEAR_OUTPUT_DATA_WITHOUT_ERROR_FOR_XF_OPERATION_RECALCULATE_IF_INPUT_IS_EMPTY
//BOOL	XFunction::Evaluate(DataRange *pdrInput, Array<DataRange&>* parrOutputs, DWORD dwCtrl, vector<uint> *pvMapIdsToUIDs, TreeNode* pGetN, double rXFVersionLastTime/* = DEFAULT_XFVERSION_LAST_TIME_RUN*/)
BOOL	XFunction::Evaluate(DataRange *pdrInput, Array<DataRange&>* parrOutputs, DWORD dwCtrl, vector<uint> *pvMapIdsToUIDs, TreeNode* pGetN, double rXFVersionLastTime/* = DEFAULT_XFVERSION_LAST_TIME_RUN*/, OUID nOpUID/* = 0*/)
///------ End CLEAR_OUTPUT_DATA_WITHOUT_ERROR_FOR_XF_OPERATION_RECALCULATE_IF_INPUT_IS_EMPTY
///------ End CHANGE_PARAM_SHOULD_DO_EVALUATE_EXACTLY_THE_SAME_AS_NORMAL_EXECUTE
/// end XFOPERATION_CHANGE_PARAM_PROBLEM
/// end REPORT_DATA_WITH_XF_WORKSHEET_GRAPHS_HANDLING
{
	UndoBlock		ub;
	if( parrOutputs && parrOutputs->GetSize() == 0 )
	{
		DataRange* pDr = new DataRange;
		parrOutputs->Add(*pDr);
	}
	
	/// ML 7/12/2006 REPORT_DATA_WITH_XF_WORKSHEET_GRAPHS_HANDLING
	//return XFBase::Evaluate(pdrInput, parrOutputs, dwCtrl); 
	/// YuI 07/26/06 XFOPERATION_CHANGE_PARAM_PROBLEM
	//	return XFBase::Evaluate(pdrInput, parrOutputs, dwCtrl, pvMapIdsToUIDs); 
	///------ Folger 01/09/09 v8.0995 CHANGE_PARAM_SHOULD_DO_EVALUATE_EXACTLY_THE_SAME_AS_NORMAL_EXECUTE
	//return XFBase::Evaluate(pdrInput, parrOutputs, dwCtrl, pvMapIdsToUIDs, pGetN); 
	///------ Folger 08/05/10 ORG-702-P1 CLEAR_OUTPUT_DATA_WITHOUT_ERROR_FOR_XF_OPERATION_RECALCULATE_IF_INPUT_IS_EMPTY
	//return XFBase::Evaluate(pdrInput, parrOutputs, dwCtrl, pvMapIdsToUIDs, pGetN, rXFVersionLastTime); 
	return XFBase::Evaluate(pdrInput, parrOutputs, dwCtrl, pvMapIdsToUIDs, pGetN, rXFVersionLastTime, nOpUID); 
	///------ End CLEAR_OUTPUT_DATA_WITHOUT_ERROR_FOR_XF_OPERATION_RECALCULATE_IF_INPUT_IS_EMPTY
	///------ End CHANGE_PARAM_SHOULD_DO_EVALUATE_EXACTLY_THE_SAME_AS_NORMAL_EXECUTE
	/// end XFOPERATION_CHANGE_PARAM_PROBLEM
	/// end REPORT_DATA_WITH_XF_WORKSHEET_GRAPHS_HANDLING
}

//--------- CPY 7/12/06 QA70-8731 AUTO_UPDATE_LOST_FROM_GUI
//	BOOL	CreateInternalOperation(BOOL bAutoUpdate = false, DWORD dwCntrl = LTXF_EXECUTE | LTXF_OUT_RESULTS_LOG, uint* pOpUID = NULL);
/// ML 7/19/2006 REMEMBERING_SETTINGS_IN_XFOPERATION_FOR_AUTO_UPDATE
BOOL XFunction::CreateInternalOperation(BOOL bAutoUpdate, DWORD dwCntrl, uint* pOpUID, TreeNode& trGetN)
/// end REMEMBERING_SETTINGS_IN_XFOPERATION_FOR_AUTO_UPDATE
{
	/// ML 3/6/2006 AUTOUPDATE_MORE_WORK
	bool	bIsInternal = IsInternal();
	/// end AUTOUPDATE_MORE_WORK
	bool bSuccess;
	DataRange	drInput;
	drInput.Create();
	
	/// YuI 11/09/05 QA70-8279 REPORT_TREE_AND_REPORT_DATA_XVARIABLES
	//	DataRange	drOutput;
	//	drOutput.Create();
	Array<DataRange&> arrOutputs;
	arrOutputs.SetAsOwner(TRUE);
	/// end REPORT_TREE_AND_REPORT_DATA_XVARIABLES

	int nSetXF = OPSETXFUNCTION_SET_MODIFIED;

	/// ML 7/12/2006 REPORT_DATA_WITH_XF_WORKSHEET_GRAPHS_HANDLING
	vector<uint>		vMapIdsToUIDs;
	/// end REPORT_DATA_WITH_XF_WORKSHEET_GRAPHS_HANDLING

	if(dwCntrl & LTXF_EXECUTE)
	{
		///// YuI 11/09/05 QA70-8279 REPORT_TREE_AND_REPORT_DATA_XVARIABLES
		//	bSuccess = Evaluate(&drInput, &drOutput);
		///// end REPORT_TREE_AND_REPORT_DATA_XVARIABLES
		/// ML
		/// ML 7/12/2006 REPORT_DATA_WITH_XF_WORKSHEET_GRAPHS_HANDLING
		//bSuccess = Evaluate(&drInput, &arrOutputs, dwCntrl);
		/// YuI 07/26/06 XFOPERATION_CHANGE_PARAM_PROBLEM
		//bSuccess = Evaluate(&drInput, &arrOutputs, dwCntrl, &vMapIdsToUIDs);
		bSuccess = Evaluate(&drInput, &arrOutputs, dwCntrl, &vMapIdsToUIDs, &trGetN);
		/// end XFOPERATION_CHANGE_PARAM_PROBLEM
		/// end REPORT_DATA_WITH_XF_WORKSHEET_GRAPHS_HANDLING
		nSetXF = OPSETXFUNCTION_NOT_MODIFIED; // CPY 4/14/05 I found just clicking update check without clicking execute failed to add op
	}
	else
	{
		///// YuI 11/09/05 QA70-8279 REPORT_TREE_AND_REPORT_DATA_XVARIABLES
		////	Evaluate(&drInput, &drOutput, true, NULL, false);// walk through Evaluate but not actually calling XF
		//Evaluate(&drInput, &arrOutputs, true, NULL, false);
		///// end REPORT_TREE_AND_REPORT_DATA_XVARIABLES
		/// YuI 07/26/06 XFOPERATION_CHANGE_PARAM_PROBLEM
		//	Evaluate(&drInput, &arrOutputs, LTXF_NO_CALL);
		Evaluate(&drInput, &arrOutputs, LTXF_NO_CALL, NULL, &trGetN);
		/// end XFOPERATION_CHANGE_PARAM_PROBLEM
		
		bSuccess = true;
	}
//	updateShowButtons();

	/// ML 12/7/2006 ADDING_INPUT_TABLE_FROM_WITHIN_XF
	Tree			treeAdditionalData;
	/// ML 5/18/2007 XFUNCTION_CLASS_NEW_ARRANGEMENT
	//TreeNode		trNodeAdditionalData = GetNode(TREE_INPUTRANGE_ADDITIONAL_DATA_NODE_NAME);
	TreeNode		trNodeAdditionalData;
	GetInputRangeAdditionalDataNode(trNodeAdditionalData);	// may not exist (like, if the xfunction didn't create input tbl in a hier. report sheet).
	/// end XFUNCTION_CLASS_NEW_ARRANGEMENT
	TreeNode		trChildAD;
	if (trNodeAdditionalData.IsValid())
	{
		trChildAD = treeAdditionalData.AddNode(TREE_INPUTRANGE_ADDITIONAL_DATA_NODE_NAME);
		trChildAD.Replace(trNodeAdditionalData);
		/// ML 5/18/2007 XFUNCTION_CLASS_NEW_ARRANGEMENT
		//RemoveChild(TREE_INPUTRANGE_ADDITIONAL_DATA_NODE_NAME);
		RemoveInputRangeAdditionalDataNode();
		/// end XFUNCTION_CLASS_NEW_ARRANGEMENT
	}
	/// end ADDING_INPUT_TABLE_FROM_WITHIN_XF

	
	if( bSuccess )
	{
		bool bInitOk;
		OperationBase& op = op_create("XFOperation", bInitOk);
		if( op && bInitOk )
		{
			op.UpdateExecutionInfo();		///------ Folger 02/12/09 UPDATE_EXECUTION_INFO_AFTER_CREATE_XF_OP
			
			/// YuI 04/10/07 REVERTING_DATA_SELECTOR_TO_EXPANDED_OLD
			okutil_destroy_data_markers(&drInput);
			/// end REVERTING_DATA_SELECTOR_TO_EXPANDED_OLD

			if(pOpUID)
				*pOpUID = op.GetUID();

			//return updateOperation(op, xf, &drInput, &drOutput, nSetXF);
			/// YuI 11/09/05 QA70-8279 REPORT_TREE_AND_REPORT_DATA_XVARIABLES
			//	return op_set_x_function(op, *this, bAutoUpdate, true, &drInput, &drOutput, nSetXF);
			/// ML 7/19/2006 REMEMBERING_SETTINGS_IN_XFOPERATION_FOR_AUTO_UPDATE
			///// ML 7/12/2006 REPORT_DATA_WITH_XF_WORKSHEET_GRAPHS_HANDLING
			/////// ML 3/6/2006 AUTOUPDATE_MORE_WORK
			//////return op_set_x_function(op, *this, bAutoUpdate, true, &drInput, &arrOutputs, nSetXF);
			////return op_set_x_function(op, *this, bAutoUpdate, bIsInternal, &drInput, &arrOutputs, nSetXF);
			/////// end AUTOUPDATE_MORE_WORK
			/////// end REPORT_TREE_AND_REPORT_DATA_XVARIABLES
			//return op_set_x_function(op, *this, bAutoUpdate, bIsInternal, &drInput, &arrOutputs, nSetXF, (dwCntrl & LTXF_EXECUTE) ? &vMapIdsToUIDs : NULL);
			///// end REPORT_DATA_WITH_XF_WORKSHEET_GRAPHS_HANDLING
			/// YuI 10/13/06 USER_NOTIFICATION_ON_INVALID_OPERATION
			//	return op_set_x_function(op, *this, bAutoUpdate, bIsInternal, &drInput, &arrOutputs, nSetXF, (dwCntrl & LTXF_EXECUTE) ? &vMapIdsToUIDs : NULL, trGetN);
			/// ML 12/7/2006 ADDING_INPUT_TABLE_FROM_WITHIN_XF
			//if( op_set_x_function(op, *this, bAutoUpdate, bIsInternal, &drInput, &arrOutputs, nSetXF, (dwCntrl & LTXF_EXECUTE) ? &vMapIdsToUIDs : NULL, trGetN) )
			//	return TRUE;
			///------ Folger 11/13/09 QA81-14654 UNCHECK_OUTPUT_RESULT_LOG_WHEN_CHANGE_PARAM_FOR_OP_CREATED_FROM_SCRIPT_BY_SL_SWITCH
			if ( !O_GET_NBITS(LTXF_OUT_RESULTS_LOG_MASK, dwCntrl) )
			{
				if ( trGetN.OutResultsLog )
					trGetN.OutResultsLog.nVal = 0;
			}
			///------ End UNCHECK_OUTPUT_RESULT_LOG_WHEN_CHANGE_PARAM_FOR_OP_CREATED_FROM_SCRIPT_BY_SL_SWITCH
			if( op_set_x_function(op, *this, bAutoUpdate, bIsInternal, &drInput, &arrOutputs, nSetXF, (dwCntrl & LTXF_EXECUTE) ? &vMapIdsToUIDs : NULL, trGetN, trChildAD) )
				return TRUE;
			/// end ADDING_INPUT_TABLE_FROM_WITHIN_XF
			/// end USER_NOTIFICATION_ON_INVALID_OPERATION
			
			/// end REMEMBERING_SETTINGS_IN_XFOPERATION_FOR_AUTO_UPDATE
		}
		
		if( op )
		{
			///---Sim 06-05-2009 CENTRALIZE_ERROR_MSG
			/*
			/// YuI 10/13/06 USER_NOTIFICATION_ON_INVALID_OPERATION
			//	op.DestroyInternal();
			string strMessage = _L("Unable to establish autoupdate. Recalculate mode is set to NONE.\n");
			//------ Folger 11/21/08 QA80-12631 v8.0977 WARNING_MESSAGE_NOT_SHOWING_WHEN_SET_AUTO_UPDATE_TO_NONE
			//printf(strMessage);
			warning_msg_box(strMessage, false);
			//------
			*/
			warning_msg_box(CER_NOT_ESTABLISH_AUTO_UPDATE, false);
			///---END CENTRALIZE_ERROR_MSG
			op.DestroyInternal();
			return TRUE; // this is actually valid outcome. operation is not created but XF is executed ok
			/// end USER_NOTIFICATION_ON_INVALID_OPERATION
		}
	}
	/// end REPORT_TREE_AND_REPORT_DATA_XVARIABLES
	
	return false;
}

//------ Folger 07/16/08 QA80-11855 BETTER_FORMATTING_FOR_XF_HELP_DUMPING
string		XFunction::getHelpUsageInfo(int nLanguage)
{
	string strUsage = GetHelpText(IDXF_SYNTAX, nLanguage);
	_format_usage_string(strUsage);
	return _L("Script Usage Examples") + ":\n" + strUsage + "\n";
}

string		XFunction::getHelpVariablesInfo(int nLanguage, BOOL bComplete, int nHelpList)
{
	string	strVarInfo = GetVarsHelpInfo(nLanguage, bComplete, nHelpList);
	return _L("Variables") + ":\n" + strVarInfo;
}
string		XFunction::getHelpTreeNodeDetailsInfo()
{
	Tree	trRuntime;
	TreeNode trVarTreeNodes = trRuntime.AddNode("TreeNode_Details");
	vector<string>		vsVarNames;
	int nTrees = GetVariables(vsVarNames, NULL, NULL, false, NULL, trVarTreeNodes, XF_GET_SIMPLE_DEFAULT_VALUE);
	
	if ( nTrees > 0 )
	{
		string 	strOptions;
		vector<int> vnTableDisplayFormat = { DISPLAY_CENTER, DISPLAY_RIGHT, DISPLAY_RIGHT};
		
		//------ Folger 08/22/08 QA80-12075 SHOULD_NOT_HIDE_EMPTY_TREE_NODE_IN_DASH_H_HELP
		//tree_hide_empty_nodes(trVarTreeNodes, true, false);
		//------
		tree_to_str(trVarTreeNodes, strOptions, vnTableDisplayFormat, TREE2STR_SKIP_HIDDEN | TREE2STR_SIMPLE_TYPE_ONLY | TREE2STR_INCLUDE_COMBO_MAP_INFO);
		
		strOptions.Replace("TreeNode_Details", "\n" + _L("TreeNode Details:"));
	
		return strOptions;
	}
	
	return "";
}
//------ End BETTER_FORMATTING_FOR_XF_HELP_DUMPING

///------ Folger 03/10/09 QA80-11855 LT_XF_HELP_DUMPING_NEEDS_SUPPORT_DISPLAY_RELATED_XF
string		XFunction::getRelatedXFInfo(int nLanguage)
{
	return _L("Related X-Functions") + ": " + GetHelpText(IDV_HELP_RELATED_XF, nLanguage);
}
///------ End LT_XF_HELP_DUMPING_NEEDS_SUPPORT_DISPLAY_RELATED_XF

///------ Folger 03/19/10 QA81-15221 CNORMALIZE_FAILED_IF_SET_OUTPUT_AS_INPUT_FOR_MULTIPLE_DATA
static		void	_prepare_xyrange_data(vector*& pXTemp, vector* pY, XYRange& dr, XYRange& drReference)
{
	BOOL	bIntersectX = dr.IsIntersect(drReference, "X");
	BOOL	bIntersectY = dr.IsIntersect(drReference, "Y");
	if ( bIntersectX && !bIntersectY )
	{
		pXTemp = NULL;
	}
	/// pXTemp may still NULL since pX might be NULL
	else if ( bIntersectY )
	{
		if ( NULL != pY && NULL != pXTemp )
		{
			dr.ClearData(TRUE, FALSE);
		}
	}
}
///------ End CNORMALIZE_FAILED_IF_SET_OUTPUT_AS_INPUT_FOR_MULTIPLE_DATA

/// YuI 06/12/07 QA70-9913 XYRNAGE_EVEN_SAMPLING_PROPER_SUPPORT
/// ML 11/10/2008 QA70-12356 RANGE_GET_DATA_PROVIDE_MAP_OF_MISSING_VALUES
//BOOL	set_xyrange_data_ex(XYRange& dr, vector* pY, vector* pX, int nIndex, XYRange& drReference)
/// YuI 10/13/09 QA70-14023 OPTION_TO_FORCE_SAMPLING_INTERVAL_RECALCULATION
//	BOOL	set_xyrange_data_ex(XYRange& dr, vector* pY, vector* pX, int nIndex, XYRange& drReference, vector<int> *pvnMissingValsIndices)
BOOL	set_xyrange_data_ex(XYRange& dr, vector* pY, vector* pX, int nIndex, XYRange& drReference, vector<int> *pvnMissingValsIndices, DWORD dwCntrl)
/// end OPTION_TO_FORCE_SAMPLING_INTERVAL_RECALCULATION
/// end RANGE_GET_DATA_PROVIDE_MAP_OF_MISSING_VALUES
{
	vector* pXTemp = pX;
	///------ Folger 10/20/09 QA81-14500 XF_SHOULD_CLEAR_OUTPUT_DATA_BY_DEFAULT_WHEN_TOTALLY_INTERSECTED_WITH_INPUT
	/////Kyle 10/09/2009 QA80-14127-P6 UPDATE_THE_OUTPUT_X_IN_CASE_OF_INPUT_INPUT
	////if( NULL != drReference && dr.IsIntersect(drReference, "X") )
	//if( NULL != drReference && dr.IsIntersect(drReference, "X") && !dr.IsIntersect(drReference, "Y") )
	/////End UPDATE_THE_OUTPUT_X_IN_CASE_OF_INPUT_INPUT
	//{
		//pXTemp = NULL;
	//}
	if( NULL != drReference )
	{
		///------ Folger 03/19/10 QA81-15221 CNORMALIZE_FAILED_IF_SET_OUTPUT_AS_INPUT_FOR_MULTIPLE_DATA
		//if ( dr.IsIntersect(drReference, "X") && !dr.IsIntersect(drReference, "Y") )
			//pXTemp = NULL;
		///// pXTemp may still NULL since pX might be NULL
		//else if ( dr.IsIntersect(drReference, "Y") )
		//{
			//if ( NULL != pY && NULL != pXTemp )
			//{
				//dr.ClearData(TRUE, FALSE);
			//}
		//}
		DWORD	dwDataRules = DRR_NO_FACTORS | DRR_NO_WEIGHTS | DRR_GET_DEPENDENT;
		if ( dr.GetNumData(dwDataRules) > 1 )
		{
			DataRange	drSub;
			XYRange		drSubXY;
			if ( !dr.GetSubRange(drSub, dwDataRules, nIndex) )
			{
				ASSERT(FALSE);
				drSubXY = dr;
			}
			else
			{
				drSubXY = drSub;
			}

			_prepare_xyrange_data(pXTemp, pY, drSubXY, drReference);
		}
		else
		{
			_prepare_xyrange_data(pXTemp, pY, dr, drReference);
		}
		///------ End CNORMALIZE_FAILED_IF_SET_OUTPUT_AS_INPUT_FOR_MULTIPLE_DATA
	}
	///------ End XF_SHOULD_CLEAR_OUTPUT_DATA_BY_DEFAULT_WHEN_TOTALLY_INTERSECTED_WITH_INPUT
	
	/// ML 11/10/2008 QA70-12356 RANGE_GET_DATA_PROVIDE_MAP_OF_MISSING_VALUES
	//if( dr.SetData(pY, pXTemp, nIndex) )
	vector	*pXForEvenSamplignUpdate = pX;
	vector	vXForEvenSamplignUpdate;
	if ( pvnMissingValsIndices && pvnMissingValsIndices->GetSize() > 0 )
	{
		if ( pY )
			pY->InsertValue(*pvnMissingValsIndices, NANUM);
		if ( pXTemp )
		{
			vXForEvenSamplignUpdate = *pXTemp;		// must preserve the vector without the missing values
			pXForEvenSamplignUpdate = &vXForEvenSamplignUpdate;
			pXTemp->InsertValue(*pvnMissingValsIndices, NANUM);
		}
	}
	if( dr.SetData(pY, pXTemp, nIndex) )
	/// end RANGE_GET_DATA_PROVIDE_MAP_OF_MISSING_VALUES
	{
		//------ Folger 09/25/08 QA80-12276 SET_SAMPLING_INTERVAL_FOR_YXRANGE_OUTPUT
		/*
		Column colX; 
		Column colY; 
		if( dr.GetYColumn(colY, nIndex) && !dr.GetXColumn(colX, nIndex) )
		{
			// output XYrange may not have X column
			// it can be in case of
			// 1. (,<new>) 
			// 2. (<input>,<new>) - and input also not having XColumn
			// for now if dr has no X, we check if reference has sampling, if yes - use it, if not - try to figure out from pX
			Column colYRef;
			Column colXRef;
			int r1Ref;
		
			if( NULL != drReference && drReference.GetYColumn(colYRef, nIndex, &r1Ref) && !drReference.GetXColumn(colXRef, nIndex) )
			{
				double dX0 = NANUM;
				double dXInc = NANUM;
				string strUnits;
				string strLongName;
				
				/// YuI 07/31/08 QA70-11930 P3 SAMPLING_INTERVAL_CALCULATION_ISSUES
				// I am somehwt confused bout comment above, does not make sense to me - what I was thinking
				//	colYRef.IsEvenSampling(&dX0, &dXInc, &strUnits, &strLongName);
				//	if( dX0 != NANUM && dXInc != NANUM )
				if( colYRef.IsEvenSampling(&dX0, &dXInc, &strUnits, &strLongName) )
				/// end SAMPLING_INTERVAL_CALCULATION_ISSUES
				{
					dX0 = dX0 + dXInc * r1Ref; // need to advance dX0
					colY.SetEvenSampling(dX0, dXInc, strUnits);
				}
				/// RVD 8/11/2008 qa70-10944 REMOVE_EVEN_SAMPLING
				else
				{
					colY.SetEvenSampling(1.0, 1.0, "");
				}
				/// end REMOVE_EVEN_SAMPLING
			}
			else
			{
				// try to calculate sampling info
				if( NULL != pX && pX->GetSize() > 0 )
				{
					double dXInc;
					if( 0 == ocmath_sampling_resolution(pX->GetSize(), *pX, &dXInc) )
					{
						vector& vTemp = *pX;
						colY.SetEvenSampling(vTemp[0], dXInc);
					}
				}
			}
		}
		
		return TRUE;
		*/
		/// ML 9/25/2008 QA70-12276 MISSING_RETURN_VALUE
		/// ML 11/10/2008 QA70-12356 RANGE_GET_DATA_PROVIDE_MAP_OF_MISSING_VALUES
		//return update_output_xyrange_even_sampling(dr, pX, nIndex, drReference);
		/// YuI 10/13/09 QA70-14023 OPTION_TO_FORCE_SAMPLING_INTERVAL_RECALCULATION
		//	return update_output_xyrange_even_sampling(dr, pXForEvenSamplignUpdate, nIndex, drReference);
		return update_output_xyrange_even_sampling(dr, pXForEvenSamplignUpdate, nIndex, drReference, dwCntrl);
		/// end OPTION_TO_FORCE_SAMPLING_INTERVAL_RECALCULATION
		/// end RANGE_GET_DATA_PROVIDE_MAP_OF_MISSING_VALUES
		/// end MISSING_RETURN_VALUE
		//------ End SET_SAMPLING_INTERVAL_FOR_YXRANGE_OUTPUT
	}
	
	return FALSE;
}
/// end XYRNAGE_EVEN_SAMPLING_PROPER_SUPPORT

//------ Folger 09/25/08 QA80-12276 SET_SAMPLING_INTERVAL_FOR_YXRANGE_OUTPUT
/// YuI 10/13/09 QA70-14023 OPTION_TO_FORCE_SAMPLING_INTERVAL_RECALCULATION
//	BOOL	update_output_xyrange_even_sampling(XYRange& dr, vector* pX, int nIndex/* = 0*/, XYRange& drReference/* = NULL*/)
BOOL	update_output_xyrange_even_sampling(XYRange& dr, vector* pX, int nIndex, XYRange& drReference, DWORD dwCntrl)
/// end OPTION_TO_FORCE_SAMPLING_INTERVAL_RECALCULATION
{
	Column colX; 
	Column colY; 
	if( dr.GetYColumn(colY, nIndex) && !dr.GetXColumn(colX, nIndex) )
	{
		// output XYrange may not have X column
		// it can be in case of
		// 1. (,<new>) 
		// 2. (<input>,<new>) - and input also not having XColumn
		// for now if dr has no X, we check if reference has sampling, if yes - use it, if not - try to figure out from pX
		Column colYRef;
		Column colXRef;
		int r1Ref = 0;
	
		/// YuI 07/27/09 QA70-14023 EVEN_SAMPLING_LOOSE_DATASET_XYRANGE_ACCESS
		/*
		if( NULL != drReference && drReference.GetYColumn(colYRef, nIndex, &r1Ref) && !drReference.GetXColumn(colXRef, nIndex) )
		{
			double dX0 = NANUM;
			double dXInc = NANUM;
			string strUnits;
			string strLongName;
			
			/// YuI 07/31/08 QA70-11930 P3 SAMPLING_INTERVAL_CALCULATION_ISSUES
			// I am somehwt confused bout comment above, does not make sense to me - what I was thinking
			//	colYRef.IsEvenSampling(&dX0, &dXInc, &strUnits, &strLongName);
			//	if( dX0 != NANUM && dXInc != NANUM )
			///------ Folger 06/16/09 QA80-13787 XF_XYRANGE_OUTPUT_FAILS_TO_SET_EVEN_SAMPLING_WHEN_INPUT_X_USED_PARTIAL_ROW_NUMBER
			#ifdef		__XF_XYRANGE_OUTPUT_FAILS_TO_SET_EVEN_SAMPLING__
			if( colYRef.IsEvenSampling(&dX0, &dXInc, &strUnits, &strLongName) || 0 != r1Ref )
			{
				if ( NANUM == dXInc )
					dXInc = 1.0;
					
				dX0 = dX0 + dXInc * r1Ref;
				ASSERT(1.0 != dX0 || 1.0 != dXInc);
				colY.SetEvenSampling(dX0, dXInc, strUnits);
			}
			#else		/// !__XF_XYRANGE_OUTPUT_FAILS_TO_SET_EVEN_SAMPLING__
			///------ End XF_XYRANGE_OUTPUT_FAILS_TO_SET_EVEN_SAMPLING_WHEN_INPUT_X_USED_PARTIAL_ROW_NUMBER
			if( colYRef.IsEvenSampling(&dX0, &dXInc, &strUnits, &strLongName) )
			/// end SAMPLING_INTERVAL_CALCULATION_ISSUES
			{
				dX0 = dX0 + dXInc * r1Ref; // need to advance dX0
				colY.SetEvenSampling(dX0, dXInc, strUnits);
			}
			///------ Folger 06/16/09 QA80-13787 XF_XYRANGE_OUTPUT_FAILS_TO_SET_EVEN_SAMPLING_WHEN_INPUT_X_USED_PARTIAL_ROW_NUMBER
			#endif		/// !__XF_XYRANGE_OUTPUT_FAILS_TO_SET_EVEN_SAMPLING__
			///------ End XF_XYRANGE_OUTPUT_FAILS_TO_SET_EVEN_SAMPLING_WHEN_INPUT_X_USED_PARTIAL_ROW_NUMBER
			/// RVD 8/11/2008 qa70-10944 REMOVE_EVEN_SAMPLING
			else
			{
				colY.SetEvenSampling(1.0, 1.0, "");
			}
			/// end REMOVE_EVEN_SAMPLING
		}
		//------ Folger 11/24/08 QA80-12639 v8.0978 SHOULD_ONLY_UPDATE_OUTPUT_Y_COLUMN_SAMPLING_INTERVAL_WHEN_INPUT_RANGE_IS_EVEN_SAMPLING
		//else
		//{
			//// try to calculate sampling info
			//if( NULL != pX && pX->GetSize() > 0 )
			//{
				//double dXInc;
				//if( 0 == ocmath_sampling_resolution(pX->GetSize(), *pX, &dXInc) )
				//{
					//vector& vTemp = *pX;
					//colY.SetEvenSampling(vTemp[0], dXInc);
				//}
			//}
		//}
		//------ End SHOULD_ONLY_UPDATE_OUTPUT_Y_COLUMN_SAMPLING_INTERVAL_WHEN_INPUT_RANGE_IS_EVEN_SAMPLING
		*/
		/// YuI 09/30/09 QA70-14399 UNNECESARY_AUTOUPDATE_IN_CASE_OF_INPUT_NEW
		//	if( NULL != drReference && !drReference.GetXColumn(colXRef, nIndex) )
		
		// if reference Y intersects with dr Y, we can not rely on sampling interval and have to recalculate it
		/// YuI 10/13/09 QA70-14023 OPTION_TO_FORCE_SAMPLING_INTERVAL_RECALCULATION
		//	if( NULL != drReference && !drReference.GetXColumn(colXRef, nIndex) && !dr.IsIntersect(drReference, "Y"))
		if( !(dwCntrl & SXYDC_RECALCULATE_SAMPLING_INTERVAL) && NULL != drReference && !drReference.GetXColumn(colXRef, nIndex) && !dr.IsIntersect(drReference, "Y"))
		/// end OPTION_TO_FORCE_SAMPLING_INTERVAL_RECALCULATION
		/// end UNNECESARY_AUTOUPDATE_IN_CASE_OF_INPUT_NEW
		{
			///------ Folger 04/23/10 QA81-14023-P4 SMOOTH_OUTPUT_WRONG_SAMPLING_INTERVAL_ON_PARTIAL_RANGE_OF_LOOSE_DATASET
			//drReference.GetYColumn(colYRef, nIndex, &r1Ref);
			Datasheet	ds;
			int			r2, c1, c2;
			drReference.GetRange("Y", r1Ref, c1, r2, c2, ds);
			///------ End SMOOTH_OUTPUT_WRONG_SAMPLING_INTERVAL_ON_PARTIAL_RANGE_OF_LOOSE_DATASET
			
			double dX0 = NANUM;
			double dXInc = NANUM;
			string strUnits;
			string strLongName;
			#ifdef		__XF_XYRANGE_OUTPUT_FAILS_TO_SET_EVEN_SAMPLING__
			if( drReference.IsEvenSampling(nIndex, &dX0, &dXInc, &strUnits, &strLongName) || 0 != r1Ref )
			{
				if ( NANUM == dXInc )
					dXInc = 1.0;
					
				dX0 = dX0 + dXInc * r1Ref;
				ASSERT(1.0 != dX0 || 1.0 != dXInc);
				///Kyle 10/14/2009 SET_EVEN_SAMPLING_SUPPORT_UNDO
				//colY.SetEvenSampling(dX0, dXInc, strUnits);
				colY.SetEvenSampling(dX0, dXInc, strUnits, strLongName, NULL, true);
				///End SET_EVEN_SAMPLING_SUPPORT_UNDO
			}
			#else		/// __XF_XYRANGE_OUTPUT_FAILS_TO_SET_EVEN_SAMPLING__			
			if( drReference.IsEvenSampling(nIndex, &dX0, &dXInc, &strUnits, &strLongName) )
			{
				dX0 = dX0 + dXInc * r1Ref; // need to advance dX0
				colY.SetEvenSampling(dX0, dXInc, strUnits, strLongName);
			}
			#endif //__XF_XYRANGE_OUTPUT_FAILS_TO_SET_EVEN_SAMPLING__			
			else
			{
				///Kyle 10/14/2009 SET_EVEN_SAMPLING_SUPPORT_UNDO
				//colY.SetEvenSampling(1.0, 1.0, "");
				colY.SetEvenSampling(1.0, 1.0, "", NULL, NULL, true);
				///End SET_EVEN_SAMPLING_SUPPORT_UNDO
			}
		}
		///Kyle 09/22/2009 QA80-14023 FIX_SAMPLING_IS_NOT_RESET_IF_SET_INPUT_AS_OUTPUT
		else if( pX && pX->GetSize()>0)				// try to calculate sampling info
		{
			double dXInc;
			int nErr = ocmath_sampling_resolution(pX->GetSize(), *pX, &dXInc);
			if( nErr==OE_NOERROR || nErr==OE_NOT_SPACED_EQUALLY)
			{
				vector& vTemp = *pX;
				///Kyle 10/14/2009 SET_EVEN_SAMPLING_SUPPORT_UNDO
				//colY.SetEvenSampling(vTemp[0], dXInc);
				colY.SetEvenSampling(vTemp[0], dXInc, NULL, NULL, NULL, true);
				///End SET_EVEN_SAMPLING_SUPPORT_UNDO
			}
		}
		///End FIX_SAMPLING_IS_NOT_RESET_IF_SET_INPUT_AS_OUTPUT
		/// end EVEN_SAMPLING_LOOSE_DATASET_XYRANGE_ACCESS
		
		
	}
	
	return TRUE;
}
//------ End SET_SAMPLING_INTERVAL_FOR_YXRANGE_OUTPUT



/// YuI 04/06/06 BETTER_XFUNCTION_ERROR_HANDLING
// construct tree and create datarange for operation, this tree can be used in operation as InputData branch
bool make_input_data(TreeNode& trInputData, LPCSTR lpcszRange)
{
	XYRange rg;
	if( okxf_init_range_from_string(&rg, lpcszRange) )
		return rg.GetTree(trInputData, FALSE);
	
	return FALSE;
}

int xf_throw_exception(int nLineNumber, int nCode)
{
	okxf_add_runtime_exception_to_error_log(nCode, NULL, XFERR_NPARAM_UNUSED, NULL, nLineNumber);
	return nCode;
}

int xf_throw_exception(int nLineNumber, LPCSTR lpcszMessage)
{
	okxf_add_runtime_exception_to_error_log(-1, lpcszMessage, XFERR_NPARAM_UNUSED, NULL, nLineNumber);
	return XFERR_RUNTIME_EXCEPTION;
}

int xf_throw_exception_ex(int nLineNumber, LPCSTR lpcszMessage, int nAuxCode)
{
	okxf_add_runtime_exception_to_error_log(-1, lpcszMessage, nAuxCode, NULL, nLineNumber);
	return XFERR_RUNTIME_EXCEPTION;
}
///---Sim 11-15-2006 SUPPORT_MORE_ERROR_HANDLING
int xf_throw_exception_ex(int nLineNumber, LPCSTR lpcszMessage, LPCSTR lpcszParam)
{
	okxf_add_runtime_exception_to_error_log(-1, lpcszMessage, XFERR_NPARAM_UNUSED, lpcszParam, nLineNumber);
	return XFERR_RUNTIME_EXCEPTION;
}
///---END SUPPORT_MORE_ERROR_HANDLING
//---- CPY 7/6/06 QA70-8088 CENTRALIZED_ERR_MSG_DLL
int xf_throw_exception_ex(int nLineNumber, int nCode, int nParam)
{
	// it is the programmer's responsibility to make sure nCode is mapped to an err str with a %d for this call
	okxf_add_runtime_exception_to_error_log(nCode, NULL, nParam, NULL, nLineNumber);
	/// AW 04/18/07 QA80-9646 v8.0604 MORE_ON_ASCII_IMPORT_MESSAGE
	//return nCode;
	return XFERR_RUNTIME_EXCEPTION;	
	/// END MORE_ON_ASCII_IMPORT_MESSAGE
 
}

int xf_throw_exception_ex(int nLineNumber, int nCode, LPCSTR lpcszParam)
{
	// it is the programmer's responsibility to make sure nCode is mapped to an err str with a %s for this call
	okxf_add_runtime_exception_to_error_log(nCode, NULL, XFERR_NPARAM_UNUSED, lpcszParam, nLineNumber);
	/// AW 04/18/07 QA80-9646 v8.0604 MORE_ON_ASCII_IMPORT_MESSAGE
	//return nCode;
	return XFERR_RUNTIME_EXCEPTION;	
	/// END MORE_ON_ASCII_IMPORT_MESSAGE
}
//----

///---Sim 08-21-2006 SUPPORT_TOW_PARAM_ERROR_HANDLING
static bool _load_err_msg(int nErrCode, string &str)
{
	if ( !ocu_load_err_msg_str(nErrCode, &str) )
	{
		str.Format("ocu_load_err_msg_str failed to load %d, please report this to Originlab.", nErrCode);
		return false;
	}
	return true;
}
/*
static void _show_failed_load_err_msg(int nErrCode)
{
	string str;
	str.Format("ocu_load_err_msg_str failed to load %d, please report this to Originlab.", nErrCode);
	error_msg_box(str);
}
*/
int xf_throw_exception_ex(int nLineNumber, int nErrCode, LPCSTR lpcszParam, int nParam)
{
	// need code in VC level
	//okxf_add_runtime_exception_to_error_log(nErrCode, NULL, nParam, lpcszParam, nLineNumber);
	string str;
	//if(ocu_load_err_msg_str(nErrCode, &str))
	if ( _load_err_msg(nErrCode, str) )
	{
		string strTemp;
		strTemp.Format(str, lpcszParam, nParam);
		xf_throw_exception(nLineNumber, strTemp);
		
		return XFERR_RUNTIME_EXCEPTION;	/// AW 04/18/07 QA80-9646 v8.0604 MORE_ON_ASCII_IMPORT_MESSAGE
	}
	else
		//_show_failed_load_err_msg(nErrCode);
		error_msg_box(str);
		
	return nErrCode;
}

int xf_throw_exception_ex(int nLineNumber, int nErrCode, int nParam, LPCSTR lpcszParam)
{
	// need code in VC level
	//okxf_add_runtime_exception_to_error_log(nErrCode, NULL, nParam, lpcszParam, nLineNumber);
	string str;
	//if(ocu_load_err_msg_str(nErrCode, &str))
	if ( _load_err_msg(nErrCode, str) )
	{
		string strTemp;
		strTemp.Format(str, nParam, lpcszParam);
		xf_throw_exception(nLineNumber, strTemp);
		return XFERR_RUNTIME_EXCEPTION;	/// AW 04/18/07 QA80-9646 v8.0604 MORE_ON_ASCII_IMPORT_MESSAGE
	}
	else
		//_show_failed_load_err_msg(nErrCode);
		error_msg_box(str);
		
	return nErrCode;
}
///Arvin 04/04/07 v8.0596 SUPPORT_THROW_TWO_DOUBLE_VALUE
int xf_throw_exception_ex(int nLineNumber, int nErrCode, int nParam1, int nParam2)
{
	// need code in VC level
	//okxf_add_runtime_exception_to_error_log(nErrCode, NULL, nParam, lpcszParam, nLineNumber);
	string str;
	//if(ocu_load_err_msg_str(nErrCode, &str))
	if ( _load_err_msg(nErrCode, str) )
	{
		string strTemp;
		strTemp.Format(str, nParam1, nParam2);
		xf_throw_exception(nLineNumber, strTemp);
		return XFERR_RUNTIME_EXCEPTION;	/// AW 04/18/07 QA80-9646 v8.0604 MORE_ON_ASCII_IMPORT_MESSAGE
	}
	else
		//_show_failed_load_err_msg(nErrCode);
		error_msg_box(str);
		
	return nErrCode;
}
///END SUPPORT_THROW_TWO_DOUBLE_VALUE
///---END SUPPORT_TOW_PARAM_ERROR_HANDLING

///---Sim 08-22-2006 WARNING_MESSAGE_OUTPUT
/*
void xf_warning_exception(LPCSTR lpcszMessage)
{
	string str = lpcszMessage;
	okxf_notification_message(str);
}
void xf_warning_exception_ex(LPCSTR lpcszMessage, int nParam)
{
	string str = lpcszMessage;
	str.Format(str, nParam);
	okxf_notification_message(str);
}
void xf_warning_exception_ex(LPCSTR lpcszMessage, LPCSTR lpcszParam)
{
	string str = lpcszMessage;
	str.Format(str, lpcszParam);
	okxf_notification_message(str);
}
void xf_warning_exception(int nErrCode)
{
	string str;
	_load_err_msg(nErrCode, str);
	okxf_notification_message(str);
}
void xf_warning_exception_ex(int nErrCode, int nParam)
{
	string str;
	if ( _load_err_msg(nErrCode, str) )
	{
		string strTemp = str;
		str.Format(strTemp, nParam);
	}
	okxf_notification_message(str);
}
void xf_warning_exception_ex(int nErrCode, LPCSTR lpcszParam)
{
	string str;
	if ( _load_err_msg(nErrCode, str) )
	{
		string strTemp = str;
		str.Format(strTemp, lpcszParam);
	}
	okxf_notification_message(str);
}
void xf_warning_exception_ex(int nErrCode, LPCSTR lpcszParam, int nParam)
{
	string str;
	if ( _load_err_msg(nErrCode, str) )
	{
		string strTemp = str;
		str.Format(strTemp, lpcszParam, nParam);
	}
	okxf_notification_message(str);
}
void xf_warning_exception_ex(int nErrCode, int nParam, LPCSTR lpcszParam)
{
	string str;
	if ( _load_err_msg(nErrCode, str) )
	{
		string strTemp = str;
		str.Format(strTemp, nParam, lpcszParam);
	}
	okxf_notification_message(str);
}
*/
#define SETTING_WARN_STR_PARAM(_strErrMsg, _FORMAT_, _Param) \
		int _nIndex = _strErrMsg.Find(_FORMAT_); \
		if ( _nIndex >= 0 ) \
		{ \
			string _str; \
			_str.Format(_FORMAT_, _Param); \
			_strErrMsg.Delete(_nIndex, strlen(_FORMAT_)); \
			_strErrMsg.Insert(_nIndex, _str); \
		}
		
		
void xf_show_warning_msg(int nErrCode, LPCSTR lpcszErrMsg, int nParam, LPCSTR lpcszParam)
{
	//Load message
	string strErrMsg = "";
	if ( nErrCode < 0 )
	{
		if ( NULL != lpcszErrMsg )
			strErrMsg = lpcszErrMsg;
		//else
			//strErrMsg = "Warning message string is NULL.";
	}
	else
		_load_err_msg(nErrCode, strErrMsg);
	
	//Setting message parameter
	if ( XFERR_NPARAM_UNUSED != nParam )
	{
		SETTING_WARN_STR_PARAM(strErrMsg, "%d", nParam);
	}
	if ( NULL != lpcszParam )
	{
		SETTING_WARN_STR_PARAM(strErrMsg, "%s", lpcszParam);
	}
	//------ CPY 11/1/2007 QA70-10638 CMD_WND_OUTPUT_ERR_BY_DEFAULT
	/*strErrMsg.Insert(0, "Warning: ");
	
	// output message
	LT_execute("ty -aa");
	okxf_notification_message(strErrMsg);
	*/
	okoc_out_msg(_L("Warning:"), 'W');
	okoc_out_msg(strErrMsg, 'W');
	//------ end CMD_WND_OUTPUT_ERR_BY_DEFAULT
}

void xf_warning_exception(LPCSTR lpcszMessage)
{
	xf_show_warning_msg(-1, lpcszMessage, XFERR_NPARAM_UNUSED, NULL);
}
void xf_warning_exception_ex(LPCSTR lpcszMessage, int nParam)
{
	xf_show_warning_msg(-1, lpcszMessage, nParam, NULL);
}
void xf_warning_exception_ex(LPCSTR lpcszMessage, LPCSTR lpcszParam)
{
	xf_show_warning_msg(-1, lpcszMessage, XFERR_NPARAM_UNUSED, lpcszParam);
}
void xf_warning_exception(int nErrCode)
{
	xf_show_warning_msg(nErrCode, NULL, XFERR_NPARAM_UNUSED, NULL);
}
void xf_warning_exception_ex(int nErrCode, int nParam)
{
	xf_show_warning_msg(nErrCode, NULL, nParam, NULL);
}
void xf_warning_exception_ex(int nErrCode, LPCSTR lpcszParam)
{
	xf_show_warning_msg(nErrCode, NULL, XFERR_NPARAM_UNUSED, lpcszParam);
}
void xf_warning_exception_ex(int nErrCode, LPCSTR lpcszParam, int nParam)
{
	xf_show_warning_msg(nErrCode, NULL, nParam, lpcszParam);
}
void xf_warning_exception_ex(int nErrCode, int nParam, LPCSTR lpcszParam)
{
	xf_show_warning_msg(nErrCode, NULL, nParam, lpcszParam);
}
///---END WARNING_MESSAGE_OUTPUT

/// end BETTER_XFUNCTION_ERROR_HANDLING
///Jasmine QA70-9623 REPLACE_BY_OKOC_OUT_MSG
/*
///Jasmine 04/13/07 PRINT_XF_MSG_TO_SCRIPT_WINDOW
void xf_print_msg(LPCSTR lpcstr, bool bRestrict, int nDestination)//true, WRITE_SCRIPT_WINDOW
{
	double dPrintOff;
	if(bRestrict)
		LT_get_var("@PRINTOFF", &dPrintOff); 	
	if(!bRestrict || !dPrintOff)
	{
		string str(lpcstr);
		str.WriteLine(nDestination);
	} 
}
///End PRINT_XF_MSG_TO_SCRIPT_WINDOW
*/
///End REPLACE_BY_OKOC_OUT_MSG
/// ML 7/17/2006 GETTING_INPUT_DATA_DESCRIPTION_FROM_WITHIN_XFUNCTION_EXECUTION
XFPushPopGetNTree::XFPushPopGetNTree(TreeNode &trGetN)
{
	okxf_push_getntree(&trGetN);
}

XFPushPopGetNTree::~XFPushPopGetNTree()
{
	okxf_pop_getntree();
}
/// end GETTING_INPUT_DATA_DESCRIPTION_FROM_WITHIN_XFUNCTION_EXECUTION

/// EJP 2007-02-02 v8.0554 QA70-8966 PROMPT_WHEN_INSTALLING_DUPLICATE_XF
/// Hong 03/18/08 QA80-8966 FIX_DRAG_DROP_XF_FAIL_PUT_IN_CORRECT_CATEGORY
//static bool is_xfunction_installed(LPCSTR lpcszXFname)
static bool is_xfunction_installed(LPCSTR lpcszXFname, string* pXFPath = NULL)
/// end FIX_DRAG_DROP_XF_FAIL_PUT_IN_CORRECT_CATEGORY
{
	XFunction xf;
	TreeNode tnXF;
	/// Hong 03/18/08 QA80-8966 FIX_DRAG_DROP_XF_FAIL_PUT_IN_CORRECT_CATEGORY
	//return xf.Load(&tnXF, lpcszXFname, false, true);
	if ( !xf.Load(&tnXF, lpcszXFname, false, true) )
		return false;
	if ( pXFPath )
		*pXFPath = okutil_fo_GetFuncFileName(&tnXF, true);
	return true;
	/// end FIX_DRAG_DROP_XF_FAIL_PUT_IN_CORRECT_CATEGORY
}
/// end PROMPT_WHEN_INSTALLING_DUPLICATE_XF



//------- CPY 4/8/07 MOVE_COMMON_REPORT_TREE_PREP_CODE_TO_GLOBAL_FUNCTION
bool init_report_tree_common_tables(ReportTree& outTree, LPCSTR lpcszTitle, LPCSTR lpcszName, LPCSTR lpcszInputName, TreeNode& trTable)
{
	if(NULL == outTree || !outTree.IsValid())
		return false;
	
	//outTree.ID = 10000;// this should be removed, frame work should provide this
	// use current date-time in title	
	SYSTEMTIME st;
	get_current_time(st, true);
	double dDate;
	SystemTimeToJulianDate(&dDate, &st);
	string strLabel = lpcszTitle;	
	strLabel += " (" + get_date_str(dDate) + ")";
	outTree.SetAttribute(STR_LABEL_ATTRIB, strLabel);
	//////////////////////////////////////////////////////////////////
	// notes
	//////////////////////////////////////////////////////////////////
	ReportTable rtNotes = outTree.CreateTable("Notes", _L("Notes"), IDST_REPORT_NOTES);		
	rtNotes.AddRow("xf", _L("X-Function"), lpcszName, IDE_NOTES_DESCRIPTION);
	char szUserName[MAX_PATH];
	DWORD dwSize = MAX_PATH;
	if( GetUserName(szUserName, &dwSize) )
		rtNotes.AddRow("User", _L("User Name"), szUserName, IDE_NOTES_USERNAME);
	
	rtNotes.AddRow("Time", _L("Time"), get_date_str(dDate), IDE_NOTES_CREATION_TIME);
	
	//////////////////////////////////////////////////////////////////
	//Input data
	//////////////////////////////////////////////////////////////////
	if(lpcszInputName)
	{
		XFExeContext	*pxfexectxt = Project.GetCurrentXFExeCtxt();
		pxfexectxt->AddInputToTree(outTree, lpcszInputName, _L("Input Data"), trTable);
	}
	return true;
}
//-------


//////////////////////////////////////////////////////
// begin OC functions to be used from LabTalk via run -oc
//////////////////////////////////////////////////////
//---- CPY 12/6/06 QA70-12736 LT_NEED_MORE_CNTRL_ON_ALLOWING_OC_FUNCS
//#pragma labtalk(1)
#pragma labtalk(2)	// the following can be used from LT only inside the "run -oc cmd" syntax, or "run -oc {val=func(arg)}" syntax.
//----

/// EJP 2006-09-13 v8.0481 SAVE_XF_TO_MISC_WHEN_NO_CATEGORY_SPECIFIED
int install_xfunction(string lpcszFileName)
{
	/// Hong 03/18/08 QA80-8966 FIX_DRAG_DROP_XF_FAIL_PUT_IN_CORRECT_CATEGORY
	// if user drag a XF from user folder, should do nothing
	string strUserXFFolder = xf_get_function_folder(USER_FOLDER);
	strUserXFFolder.MakeLower();
	lpcszFileName.MakeLower();
	if ( 0 == lpcszFileName.Find(strUserXFFolder) )
		return 0;
	/// end FIX_DRAG_DROP_XF_FAIL_PUT_IN_CORRECT_CATEGORY
	Tree tr;
	if( tr.Load(lpcszFileName) )
	{
		/// EJP 2007-02-02 v8.0554 QA70-8966 PROMPT_WHEN_INSTALLING_DUPLICATE_XF
		string strXFname = tr.XFname.strVal;
		/// Hong 03/18/08 QA80-8966 FIX_DRAG_DROP_XF_FAIL_PUT_IN_CORRECT_CATEGORY
		//if( is_xfunction_installed(strXFname) )
		string strPath;
		if( is_xfunction_installed(strXFname, &strPath) )
		/// end FIX_DRAG_DROP_XF_FAIL_PUT_IN_CORRECT_CATEGORY
		{
			string strMsg;
			strMsg.Format(_L("An X-Function named %s is already installed.\nDo you want to replace the existing X-Function?"), strXFname);
			if( MessageBox(GetWindow(), strMsg, _L("Install X-Function"), MB_YESNO) == IDNO )
				return 1; // user chose to cancel, so treat as success
		}
		/// end PROMPT_WHEN_INSTALLING_DUPLICATE_XF		
		/// Hong 03/18/08 QA80-8966 FIX_DRAG_DROP_XF_FAIL_PUT_IN_CORRECT_CATEGORY
		strPath.MakeLower();
		// need delete the existing XF if it's in user folder, because it may in A, but drag in XF maybe put in B
		if ( 0 == strPath.Find(strUserXFFolder) )
			okutil_delete_file(strPath, TRUE);
		/// end FIX_DRAG_DROP_XF_FAIL_PUT_IN_CORRECT_CATEGORY
		if( xf_save_to_default_location(tr) )				
			return 0; // success
		return -2; // failed to save to default location
	}
	return -1; // failed to load x-function;
}
/// end SAVE_XF_TO_MISC_WHEN_NO_CATEGORY_SPECIFIED

/// YuI 04/09/09 QA70-13435 OPTION_TO_SUPPRESS_LT_ERROR_FOR_XF_INVOCATION
/// Max 7/31/09 v8.063c.988 QA70-13435 SUPPRESS_SHOWING_IN_SET_COLUMN_VALUES_DLG
// #pragma labtalk(1) // the following functions are callable from LT
//------------- CPY 9/24/09 QA70-13435 BRING_BACK_XF_ERR_CHKING_FUNC_FOR_LT
//#pragma labtalk(2)
#pragma labtalk(1, Miscellaneous)
//-------------
/// END SUPPRESS_SHOWING_IN_SET_COLUMN_VALUES_DLG
int		xf_get_last_error_code()
{
	XFBase xf;
	int nCode = 0;
	if( xf.GetLastError(nCode) )
		return nCode;
	
	return 0;
}

string	xf_get_last_error_message()
{
	XFBase xf;
	int nCode = 0;
	string strMessage;
	if( xf.GetLastError(nCode, strMessage) )
		return strMessage;
	
	return "";
}
/// end OPTION_TO_SUPPRESS_LT_ERROR_FOR_XF_INVOCATION
//////////////////////////////////////////////////////
// end OC functions to be used from LabTalk via run -oc
//////////////////////////////////////////////////////

///------ Folger 11/11/09 QA81-14630 SUPPORT_DUMPING_XF_SETTINGS_FROM_GETN_DIALOG
class	XFSettingsDumpingHelper
{
public:
	XFSettingsDumpingHelper(TreeNode& tr);
	
	string		GetStr();
	void		Dump();
	
private:
	TreeNode	GetFactoryDefaultSettings(LPCSTR lpcszXF);
	TreeNode	GetDifferentSettings(TreeNode& trTarget, TreeNode& trRef);
	//void		CheckUpdateBranchUseAttrib(TreeNode& tr, TreeNode& trTarget, TreeNode& trRef);	
	string		GetCheckAttrib();	
	void		CreateCmdLine(TreeNode& trSettings);	
	string		CheckResolveSpecialSetting(TreeNode& trNode);
	string		GetSetting(TreeNode& trNode);
	BOOL		CheckResolveSpeicalValue(string& str, TreeNode& trNode);
	string		GetSettingRecursively(TreeNode& trNode, const string& strPre);	
	string		GetTreeNodeValue(TreeNode& trNode, const string& strPre);	
	BOOL		IsSkip(TreeNode& trNode);	
	BOOL		IsBrachUncheck(TreeNode& trNode);	
	string		KeyAndAssign(const string& strKey);	
	string		GetValue(TreeNode& trNode);
	string		GetValueCheckAddQuotes(TreeNode& trNode);	
	int			GetXFVarType(TreeNode& trNode);	
	BOOL		IsXFVar(TreeNode& trNode);
	///------ Folger 06/25/10 ORG-122-P9 SUPPORT_ALWAYS_GENERATE_XF_LT_SCRIPT
	TreeNode	GetVar(LPCSTR lpcszName);
	///------ End SUPPORT_ALWAYS_GENERATE_XF_LT_SCRIPT
	
private:
	string		m_str;
	///------ Folger 06/25/10 ORG-122-P9 SUPPORT_ALWAYS_GENERATE_XF_LT_SCRIPT
	Tree		m_trVars;
	///------ End SUPPORT_ALWAYS_GENERATE_XF_LT_SCRIPT
};

#define		LT_STR_VAR_XFSettingsDumpingHelper		"__STR_XFSettingsDumpingHelper__$"
#define		LT_PRINT_XF_SETTINGS					"type -l -a;type -v " LT_STR_VAR_XFSettingsDumpingHelper ";"

XFSettingsDumpingHelper::XFSettingsDumpingHelper(TreeNode& tr)
{
	tr.GetAttribute(STR_XFUNCTION_NAME_ATTRIB, m_str);
	CreateCmdLine(GetDifferentSettings(tr, GetFactoryDefaultSettings(m_str)));
}

string		XFSettingsDumpingHelper::GetStr()
{
	return m_str;
}

void		XFSettingsDumpingHelper::Dump()
{
	LT_set_str(LT_STR_VAR_XFSettingsDumpingHelper, GetStr());
	LT_execute(LT_PRINT_XF_SETTINGS);
}

TreeNode	XFSettingsDumpingHelper::GetFactoryDefaultSettings(LPCSTR lpcszXF)
{
	XFunction	xf;
	TreeNode	trGetN;
	Tree		trXF;
	if ( xf.Load(&trXF, lpcszXF, 0, true, false, true) )
	{
		Tree		trGetNTempRoot;
		xf.GetGUI(trGetNTempRoot, trGetN);
		if ( trGetN.AutoUpdate )
		{
			trGetN.AutoUpdate.nVal = AU_NONE;		/// since call XF from LT, AutoUpdate will always be None
		}
		
		///------ Folger 06/25/10 ORG-122-P9 SUPPORT_ALWAYS_GENERATE_XF_LT_SCRIPT
		okutil_xft_GetVarsNode(&m_trVars, &trXF);
		///------ End SUPPORT_ALWAYS_GENERATE_XF_LT_SCRIPT
	}
	
	return trGetN;
}

TreeNode	XFSettingsDumpingHelper::GetDifferentSettings(TreeNode& trTarget, TreeNode& trRef)
{
	Tree		trDiff;
	TreeNode	trRet = trDiff;
	trRet.CreateDiff(trTarget, trRef, TRDIFF_CHK_ATTRIB | /*TRDIFF_KEEP_INDIVI_TARGET | */TRDIFF_KEEP_INDIVI_REF | TRDIFF_KEEP_REF_VALUES, 0, GetCheckAttrib());
	//CheckUpdateBranchUseAttrib(trRet, trTarget, trRef);
	return trRet;
}

//void		XFSettingsDumpingHelper::CheckUpdateBranchUseAttrib(TreeNode& tr, TreeNode& trTarget, TreeNode& trRef)
//{
	//foreach ( TreeNode trNode in tr.Children )
	//{
		//if ( trNode.FirstNode )
		//{
			//if ( -1 != trNode.Use && !IsBrachUncheck(trNode) )
			//{
				//TreeNode	trNode1, trNode2;
				//if ( octree_find_node_by_dataID(&trNode1, &trTarget, trNode.DataID) && octree_find_node_by_dataID(&trNode2, &trRef, trNode.DataID) )
				//{
					//if ( trNode1.Use == trNode2.Use )
						//trNode.RemoveAttribute(STR_USE_ATTRIB);
				//}
			//}
			//CheckUpdateBranchUseAttrib(trNode, trTarget, trRef);
		//}
	//}
//}

string		XFSettingsDumpingHelper::GetCheckAttrib()
{
	vector<string>		vsAttribs = { STR_ATTRIB_DYNACONTROL_USE_CHECK
		, STR_ATTRIB_AUTO
		, STR_USE_ATTRIB
	};
	
	string		str;
	str.SetTokens(vsAttribs, '|');
	return str;
}

void		XFSettingsDumpingHelper::CreateCmdLine(TreeNode& trSettings)
{
	foreach ( TreeNode trNode in trSettings.Children )
	{
		string		str = CheckResolveSpecialSetting(trNode);
		if ( !str.IsEmpty() )
		{
			m_str += str;
			continue;
		}
		
		if ( IsSkip(trNode) )
			continue;			
		m_str += GetSetting(trNode);
	}
	m_str += ";";
}

string		XFSettingsDumpingHelper::CheckResolveSpecialSetting(TreeNode& trNode)
{
	string		strTagName = trNode.tagName;
	string		str;
	
	if ( strTagName.Compare("OutResultsLog") == 0 )
	{
		if ( 0 == trNode.nVal )
			str = " -sl";
	}
	else if ( strTagName.Compare("AutoUpdate") == 0 )
	{
		str.Format(" -r %d", trNode.nVal);
	}
	
	return str;
}

string		XFSettingsDumpingHelper::GetSetting(TreeNode& trNode)
{
	BOOL		bTreeNodeType = GetXFVarType(trNode) == XVT_TREE;
	string		str;

	if ( !CheckResolveSpeicalValue(str, trNode) )
	{
		if ( trNode.FirstNode )
		{
			if ( bTreeNodeType )
				str = GetSettingRecursively(trNode, trNode.tagName);
			else
				trNode.GetAttribute(STR_DATA_ATTRIB, str);
		}
		else
		{
			string	strEnumList;
			if ( trNode.GetAttribute(STR_COMBO_ATTRIB_ENUM, strEnumList) && !strEnumList.IsEmpty() )
				str = strEnumList.GetToken(trNode.nVal, '|');
			else
				str = GetValue(trNode);
		}
	}
	else
	{
		if ( bTreeNodeType )
			str += GetSettingRecursively(trNode, trNode.tagName);
	}

	return str.IsEmpty() ? "" : (bTreeNodeType ? "" : KeyAndAssign(trNode.tagName)) + str;
}

BOOL		XFSettingsDumpingHelper::CheckResolveSpeicalValue(string& str, TreeNode& trNode)
{
	int		nVal = -1;
	if ( trNode.GetAttribute(STR_ATTRIB_DYNACONTROL_USE_CHECK, nVal) && 0 == nVal )
	{
		str = STR_OPTIONAL;
		return TRUE;
	}
	
	if ( 1 == octree_get_auto_support(&trNode) )
		return TRUE;

	if ( trNode.FirstNode && -1 != trNode.Use && !IsXFVar(trNode) )
	{
		str = trNode.Use;
		return TRUE;
	}
	
	return FALSE;
}

string		XFSettingsDumpingHelper::GetSettingRecursively(TreeNode& trNode, const string& strPre)
{
	string		str;
	foreach ( TreeNode trSub in trNode.Children )
	{
		if ( IsSkip(trSub) )
			continue;
		
		str += GetTreeNodeValue(trSub, strPre);
	}

	return str;
}

string		XFSettingsDumpingHelper::GetTreeNodeValue(TreeNode& trNode, const string& strPre)
{
	string		str = strPre + "." + trNode.tagName;
	string		strSpecial;
	if ( CheckResolveSpeicalValue(strSpecial, trNode) )
		return GetSettingRecursively(trNode, str) + (strSpecial.IsEmpty() ? "" : KeyAndAssign(str) + strSpecial);
	
	return trNode.FirstNode ? GetSettingRecursively(trNode, str) : KeyAndAssign(str) + GetValue(trNode);
}

BOOL		XFSettingsDumpingHelper::IsSkip(TreeNode& trNode)
{
	BOOL	bSkip = !(trNode.Show || trNode.Show < 0)
			|| !(ENABLE == trNode.Enable || trNode.Enable < 0)
			|| IsBrachUncheck(trNode)
			;

	///------ Folger 06/25/10 ORG-122-P9 SUPPORT_ALWAYS_GENERATE_XF_LT_SCRIPT
	if ( bSkip )
	{
		TreeNode	trVar = GetVar(trNode.tagName);
		if ( trVar )
		{
			XFVariable	var(trVar);
			if ( var.IsAlwaysGenerateLTScript() )
				return FALSE;
		}
	}
	///------ End SUPPORT_ALWAYS_GENERATE_XF_LT_SCRIPT

	return bSkip;
}

BOOL		XFSettingsDumpingHelper::IsBrachUncheck(TreeNode& trNode)
{
	string	str;
	int		nVarType;
	return trNode.FirstNode
		&& 0 == trNode.Use
		&& !trNode.GetAttribute(STR_ATTRIB_BRANCH_COMBO, str)
		&& !IsXFVar(trNode)
		;
}

string		XFSettingsDumpingHelper::KeyAndAssign(const string& strKey)
{
	return " " + strKey + ":=";
}

string		XFSettingsDumpingHelper::GetValue(TreeNode& trNode)
{
	switch ( trNode.ID )
	{
	case TRGP_DOUBLE:
		return ftoa(trNode.dVal);

	default:
		break;
	}

	switch ( GetXFVarType(trNode) )
	{
	case XVT_INT:
		return trNode.nVal;

	default:
		break;
	}

	return GetValueCheckAddQuotes(trNode);
}

#define		QUOTE_STR(_str)		"\"" + _str + "\""

string		XFSettingsDumpingHelper::GetValueCheckAddQuotes(TreeNode& trNode)
{		
	string	str = trNode.strVal;

	if ( !okutil_check_add_quotes(&str) )
	{
		int		nXFVarType = GetXFVarType(trNode);
		///------ Folger 10/08/2010 ORG-1207-P1 IMPORT_ASCII_NUMERIC_SEPARATOR_AUTO_SUPPORT
		//if ( nXFVarType < 0 || XVT_STRING == nXFVarType )
		if ( XVT_STRING == nXFVarType || (nXFVarType < 0 && !is_numeric(str)) )
		///------ End IMPORT_ASCII_NUMERIC_SEPARATOR_AUTO_SUPPORT
		{
			char		szChars[] = { ','
				, '-'
				, '%'
				, '\n'
				, '='
				///------ Folger 05/25/10 QA81-14630-P11 GENERATE_SCRIPT_FAILED_ON_IMPASC_IF_USE_SEMICOLON_AS_DELIMITER
				, ';'
				///------ End GENERATE_SCRIPT_FAILED_ON_IMPASC_IF_USE_SEMICOLON_AS_DELIMITER
				, '\0'
			};
			if ( str.FindOneOf(szChars) >= 0 )
			{
				return QUOTE_STR(str);
			}
			///------ Folger 09/03/2010 WEB2FILE_FAILED_WITH_GENERATED_SCRIPT
			if ( str.Find("//") >= 0 )
			{
				return QUOTE_STR(str);
			}
			///------ End WEB2FILE_FAILED_WITH_GENERATED_SCRIPT
		}
	}

	//int		nLenght = str.GetLength();
	///// at least "\", then turn it into "\\"
	//if ( nLenght >= 3 && '\\' == str[nLenght-2] && '\"' == str[nLenght-1] )
	//{
		//str.Insert(nLenght - 1, '\\');
	//}
		
	return str;
}

int			XFSettingsDumpingHelper::GetXFVarType(TreeNode& trNode)
{
	int		nVarType = -1;
	trNode.GetAttribute(STR_XF_VAR_TYPE, nVarType);
	return nVarType;
}

BOOL		XFSettingsDumpingHelper::IsXFVar(TreeNode& trNode)
{
	return GetXFVarType(trNode) >= 0;
}

///------ Folger 06/25/10 ORG-122-P9 SUPPORT_ALWAYS_GENERATE_XF_LT_SCRIPT
TreeNode	XFSettingsDumpingHelper::GetVar(LPCSTR lpcszName)
{
	foreach ( TreeNode trVar in m_trVars.Children )
	{
		if ( trVar.name.strVal.Compare(lpcszName) == 0 )
			return trVar;
	}
	
	TreeNode	trJunk;
	return trJunk;
}
///------ End SUPPORT_ALWAYS_GENERATE_XF_LT_SCRIPT

void		xf_settings_dumping(TreeNode& trGetN)
{
	XFSettingsDumpingHelper		clHelper(trGetN);
	clHelper.Dump();
}
///------ End SUPPORT_DUMPING_XF_SETTINGS_FROM_GETN_DIALOG

///------ Folger 03/31/10 QA81-15258 XF_GETPTS_NEEDED
BOOL		is_treenode_optional(TreeNode& tr)
{
	if ( okutil_cvt_str_to_predefined_type(tr.strVal) == PDS_OPTIONAL )
		return TRUE;

	int		nDynaUseCheck = 1;
	return tr.GetAttribute(STR_ATTRIB_DYNACONTROL_USE_CHECK, nDynaUseCheck) && 0 == nDynaUseCheck;
}

BOOL		is_xf_before_execute_body(int nGetNDialog, int dwCntrl)
{
	return nGetNDialog < 0 || 0 == nGetNDialog && !(XFEVT_PROCEED_WITH_DLG & dwCntrl);
}
///------ End XF_GETPTS_NEEDED

///------ Folger 08/02/10 ORG-672 INTEG1_SUPPORT_MULTIPLE_XYRANGES
BOOL		prepare_multixy_output_tree(TreeNode& trInput, TreeNode& trOutput)
{
	if( 1 == trOutput.GetNodeCount() )
		return okutil_prepare_multiXY_output_tree(&trOutput, &trInput, 0);
	return FALSE;
}
///------ End INTEG1_SUPPORT_MULTIPLE_XYRANGES

///------ Folger 08/26/2010 ORG-920-P1 ONE_SAMPLE_TTEST_BETTER_HANDLING_OF_OUTPUT_PLOT_AND_REPORT_DATA
BOOL	xf_event_is_change_param(TreeNode& trGetN)
{
	TreeNode	trAutoUpdate = trGetN.AutoUpdate;
	if ( !trAutoUpdate )
		return FALSE;
	
	int		nEnabled = ENABLE;
	return trAutoUpdate.GetAttribute(STR_ENABLE_ATTRIB, nEnabled) && nEnabled == DISABLE;
}
///------ End ONE_SAMPLE_TTEST_BETTER_HANDLING_OF_OUTPUT_PLOT_AND_REPORT_DATA

///------ Folger 10/20/2010 ORG-1286-P1 MORE_TOOLS_FAILED_TO_COPY_SAMPLING_INTERVAL_FROM_INPUT
BOOL	xf_copy_vector_sampling_interval(vector& vDest, vector& vSrouce, LPCSTR lpcszOutput)
{
	if ( !vDest || !vSrouce || NULL == lpcszOutput )
		return FALSE;

	XFExeContext*	pXFExeCtxt = Project.GetCurrentXFExeCtxt();
	if ( NULL == pXFExeCtxt )
		return FALSE;

	if ( !pXFExeCtxt->IsOrgObjNewCreated(lpcszOutput) )
		return FALSE;

	DataRange	drSrouce, drDest;
	drSrouce = vSrouce.GetSourceDataRange();
	drDest = vDest.GetSourceDataRange();

	Column		colSource, colDest;
	if ( !range_get_col(drSrouce, 0, colSource) || !colSource || !range_get_col(drDest, 0, colDest) || !colDest )
		return FALSE;

	double		x0, xInc;
	string		strLongName, strUnits;
	if ( !colSource.IsEvenSampling(&x0, &xInc, &strUnits, &strLongName) )
		return FALSE;

	return colDest.SetEvenSampling(x0, xInc, strUnits, strLongName, NULL, TRUE);
}
///------ End MORE_TOOLS_FAILED_TO_COPY_SAMPLING_INTERVAL_FROM_INPUT