/*------------------------------------------------------------------------------*
 * File Name: ImportWiz.c				 										*
 * Creation: 																	*
 * Purpose: OriginC Source C file for Origin Import Wizard						*
 * Copyright (c) OriginLab Corp.	2003, 2004, 2005, 2006, 2007				*
 * All Rights Reserved															*
 * 																				*
 * Modification Log:															*
 *	CPY 12/25/02 v7.0474 ASCII_IMPORT_FIX_BEFORE_ALPHA2							*
 *	CPY 1/2/03 v7.0478 QA70-3604 RICH_EDIT_SCROLL_SYNCHRONIZED					*
 *	YuI 1/21/03 v7.0493 IMPORT_WIZARD_SETTINGS_SAVING							*
 * EJP 04-23-2003 QA70-4321 PREVENT_CRASH_ON_REMOVAL_OF_LAST_PARAM				*
 * JCG 05/28/03 v7.0540 HOOK_COMBO_BOX											*
 * EJP 06-09-2003 v7.0599 QA70-3746 DISABLE_FINISH_WHEN_NO_FILENAME_ENTERED		*
 * JCG 06/09/03 v7.0599 LABEL_LINE_COMBOS_INIT_TO_NONE_IF_NO_HEADERLINES 		*
 * EJP 06-10-2003 v7.0600 QA70-4520 SUPPORT_HUGE_HEADER_SIZES					*
 * EJP 06-18-2003 QA70-4682 DATA_SELECTION_UI_CHANGES							*
 * EJP 07-07-2003 v7.0619 QA70-4783 POST_IMPORT_EXECUTE							*
 * EJP 07-08-2003 v7.0620 QA70-4792 MAKE_IMPWIZ_UI_MORE_CLEAR					*
 * EJP 07-14-2003 v7.0624 SCAN_FOR_NUM_COLS_ON_CHANGE_HEADER_LINES				*
 * EJP 07-16-2003 v7.0627 QA70-4818 SAVE_FILTER_IN_WKS							*
 * EJP 07-21-2003 v7.0630 QA70-4073 ADD_APPLY_BUTTON_TO_UPDATE_PREVIEW			*
 * EJP 07-23-2003 v7.0631 QA70-4575 ADD_SKIPROWS_TO_BINIMP						*
 * EJP 07-28-2003 v7.0637 QA70-4911 IMPROVE_HDR_VAR_SCAN						*
 * EJP 07-29-2002 v7.0637 QA70-4575 PROBLEM_50									*
 * EJP 08-01-2003 v7.0642 DETECT_IMPORT_SETTINGS_CHANGED						*
 * EJP 08-04-2003 v7.0644 QA70-4896 ADD_REFRESH_BTN_TO_HDRVAR_PAGE				*
 * EJP 08-15-2003 v7.5661 QA70-4073.58 CLEAN_IMPORT_FROM_CLIPBOARD				*
 * EJP 08-19-2003 v7.5667 REIMPORT_AFTER_USER_CHANGE_COL_FORMAT					*
 * EJP 08-22-2003 SET_OFFSET_WITHOUT_SEL_BUT_JUST_CARROT_POS					*
 * EJP 08-27-2003 v7.5677 QA70-5073 ADD_READROWS								*
 * EJP 08-29-2003 v7.5680 TRUNC_LONG_LINES_IN_HEADER_PREVIEW					*
 * EJP 08-29-2003 v7.5680 AUTO_SELECT_ONLY_DATA_FOLDER_FILTERS					*
 * EJP 09-04-2003 v7.5684 QA70-5106 INSERT_BIN_PATTERN_BEFORE_FIRST_ROW			*
 * EJP 09-08-2003 v7.5687 QA70-5118 FIX_COMPARE_BINIMP_STRUCTS					*
 * EJP 09-10-2003 v7.5890 QA70-5135.11 REMOVE_PLOTPAGE_OPTION_FROM_DRAGDROP_PAGE*
 * EJP 09-10-2003 v7.5690 NOTIFY_USER_WHEN_SAVE_FILTER_FAILS					*
 * EJP 09-12-2003 v7.5692 QA70-5135.15 COL_DESIGNATION_REPEAT_NOT_REMEMBERED	*
 * EJP 09-12-2003 v7.5693 QA70-5073 ADD_READROWS_TO_BINIMP						*
 * EJP 09-16-2003 v7.5696 QA70-4575 UPDATE_PLOT_LEGEND							*
 * EJP 09-23-2003 v7.5702 QA70-5135.27 UPDATE_NUMCOLS_ON_APPLY_FIXEDWIDTH		*
 * EJP 09-24-2003 v7.5706 QA70-4073.55 ADD_FILTER_DESCRIPTION					*
 * EJP 09-29-2003 v7.5709 QA70-5211.5 UPDATE_HDRVAR_ON_CHANGE_ENDIAN			*
 * EJP 10-08-2003 v7.5715 QA70-5289.3 UPDATE_COL_WIDTH							*
 * EJP 10-13-2003 v7.5717 QA70-5318 CUSTOM_DATE_FORMAT							*
 * EJP 10-16-2003 v7.5722 QA70-5289.7 UPDATE_SOURCE_FILE_ON_EDIT_CHANGE			*
 * EJP 10-20-2003 v7.5726 QA70-5374 ALLOW_CHANGING_PREVIEW_FONT					*
 * EJP 10-22-2003 v7.5728 QA70-5211.2 FIX_DESIG_AND_FMT_ON_PARTIAL_IMPORT		*
 * EJP 10-24-03 v7.5730 QA70-5412 SKIP_CHARS_FOR_COL_NAME_LABEL					*
 * EJP 10-27-2003 v7.5733 QA70-5238 DO_NOT_RESET_TARGET_WINDOW_TEMPLATE			*
 * EJP 10-30-2003 v7.5736 QA70-5448 NOTIFY_USER_OF_IMPORT_ERROR					*
 * EJP 11-11-2003 v7.5751 QA70-5211.7 FIX_USED_BYTES_COLORING					*
 * EJP 11-24-2003 v7.5769 QA70-5417.18 FIX_DESIG_AND_FMT						*
 *	ML 11/25/2003 BITWISE_OR_SEPARATED_TRANSLATION								*
 * EJP 11-26-2003 v7.5773 CHECK_PARTIAL_IMPORT_FROM_SETTINGS					*
 *------------------------------------------------------------------------------*/
 
////////////////////////////////////////////////////////////////////////////////////

//--- CPY 7/2/03 we will ship with OP, cannot include origin.h as OP might be in conflict with origin.PCH
#include <origin.h> 
//#include <Project.h> // The Project and Application class 
//#include <wksheet.h> // worksheet matrixlayer and column classes
//#include <graph.h> // graph, plot and graphic objects
//#include <utilities.h>
//#include <mswin.h>
//#include <file.h>
//#include <sys_utils.h>
//----
#include <dialog.h>
//#include <control.h>
#include <vsFlexGrid.h>
//#include <Tree.h>
#include <tree_utils.h>

#include "HelpID.h"
#include "Dlg_Utils.h"
#include "App_Utils.h"
#include "importwiz.h" // resource header
#include "binimp.h"    // resource header
#include "Filter_Utils.h"
#include "fileimport.h"
// Include definitions of all localized strings. $ causes CodeBuilder to look for 
// correct version of Local.h depending on Windows Regional settings.
#include "$Local.h"

//--------------------------------------------------------------------------
enum {
	NONNUMERIC_WIZ_TERMINATE = 0,
	NONNUMERIC_WIZ_READ_AS_TEXT,
	NONNUMERIC_WIZ_NEW_WKS,
	NONNUMERIC_WIZ_NEW_COL
};	

enum {
	NONNUMERIC_TERMINATE = 0,
	NONNUMERIC_READ_AS_MISSING,
	NONNUMERIC_START_NEW_WKSCOL,
	NONNUMERIC_APPEND_TO_LABEL
};

//--------------------------------------------------------------------------
// general definitions
//--------------------------------------------------------------------------
///#define IW_DEBUG
#define DISABLE_FILE_TYPES_PAGE

#define IDC_NEXT			0x3024
#define IDC_FINISH			0x3025

#define BIN_HDR_PREVIEW_BYTES_PER_ROW 	16
#define BIN_HDR_PREVIEW_NUM_ROWS		100
#define BIN_DATA_PREVIEW_NUM_BYTES		800
#define BIN_DATA_PREVIEW_BYTES_PER_ROW	20

#define IW_NUM_DATA_PREVIEW_ROWS			50
#define IW_NUM_DATA_PREVIEW_COLS			100
#define IW_NUM_HEADER_PREVIEW_LINES			s_iAscHdrPreviewLines
#define AIW_HDR_PREVIEW_LINES_DEFAULT		50

#define AIW_COLOR_DATA_LINES			RGB(0,0,0)
#define AIW_COLOR_COL_NAME				RGB(255,0,0)
#define AIW_COLOR_HEADER_LINES			RGB(0,0,255)
#define AIW_COLOR_COL_LABEL				RGB(0,128,0)
#define AIW_COLOR_SKIP_LINES			RGB(192,192,192)

#define IW_PREVIEW_LINE_MAX_LEN 1024 /// EJP 08-29-2003 v7.5680 TRUNC_LONG_LINES_IN_HEADER_PREVIEW

// These need to be localized
/// ML 11/25/2003 BITWISE_OR_SEPARATED_TRANSLATION
//#define BINIMP_DATA_TYPE_TOKENS		"Integer|Unsigned Integer|Real|String"
#define BINIMP_DATA_TYPE_TOKENS		_LB("Integer|Unsigned Integer|Real|String")
/// end BITWISE_OR_SEPARATED_TRANSLATION
#define SZ_IW_PAGE_FILTER			_L("<Use filter in active window>")

#define IW_PLOTTING_GRID_NUM_COLS		4
#define IW_PLOT_LINE					0
#define IW_PLOT_SCATTER					1
#define IW_PLOT_LINESYMB				2
#define IW_PLOT_COLUMN					3
#define IW_PLOT_BAR						4

#define FILTER_LOCATION_DATA			0
#define FILTER_LOCATION_ORIGIN			1
#define FILTER_LOCATION_USERFILES		2

#define IS_FILTER_TYPE_ASCII			(s_trFilter.Type.nVal == FILTER_TYPE_ASCII)
#define IS_FILTER_TYPE_BINARY			(s_trFilter.Type.nVal == FILTER_TYPE_BINARY)
#define IS_FILTER_TYPE_USERDEFINED		(s_trFilter.Type.nVal == FILTER_TYPE_USERDEFINED)

#define IW_HDRLINE_NONE		-1
#define IW_HDRLINE_LAST		-1

//--------------------------------------------------------------------------
// flags
//--------------------------------------------------------------------------
#define FLAG_DEFINE_HDR_VAR				0x00000001
#define FLAG_CLICKED_FINISH				0x00000002
#define FLAG_DATAFROM_CLIPBOARD			0x00000004
#define FLAG_FIXED_WIDTHS_CHANGED		0x00000008
#define FLAG_SAVE_FILTER				0x00000010
#define FLAG_RESCAN_FOR_NUM_COLS		0x00000020 /// EJP 07-14-2003 v7.0624 SCAN_FOR_NUM_COLS_ON_CHANGE_HEADER_LINES
#define FLAG_ADVOPTIONS_CHECKED			0x00000040
#define FLAG_UPDATE_PREVIEW_NEEDED		0x00000080
#define FLAG_BINPATTERN_BINVIEW			0x00000100
#define FLAG_GET_FILTER_ONLY			0x00000200 /// EJP 08-08-2003 v7.0650 QA70-4073.53 USE_SAME_FILTER_FOR_MULTI_FILES_ON_FILEOPEN_AND_DRAGDROP
#define FLAG_ON_BROWSE_SOURCE			0x00000400 /// EJP 10-16-2003 v7.5722 QA70-5289.7 UPDATE_SOURCE_FILE_ON_EDIT_CHANGE

#define IS_DEFINE_HDR_VAR			(s_flags & FLAG_DEFINE_HDR_VAR)
#define ENABLE_DEFINE_HDR_VAR		s_flags |= FLAG_DEFINE_HDR_VAR
#define DISABLE_DEFINE_HDR_VAR		s_flags &= ~FLAG_DEFINE_HDR_VAR

#define IS_CLICKED_FINISH			(s_flags & FLAG_CLICKED_FINISH)
#define ENABLE_CLICKED_FINISH		s_flags |= FLAG_CLICKED_FINISH
#define DISABLE_CLICKED_FINISH		s_flags &= ~FLAG_CLICKED_FINISH

#define IS_FIXED_WIDTHS_CHANGED			(s_flags & FLAG_FIXED_WIDTHS_CHANGED)
#define SET_FIXED_WIDTHS_CHANGED		s_flags |= FLAG_FIXED_WIDTHS_CHANGED
#define SET_FIXED_WIDTHS_UNCHANGED		s_flags &= ~FLAG_FIXED_WIDTHS_CHANGED

#define IS_DATAFROM_CLIPBOARD			(s_flags & FLAG_DATAFROM_CLIPBOARD)
#define IS_DATAFROM_FILE				!IS_DATAFROM_CLIPBOARD
#define SET_DATAFROM_CLIPBOARD			s_flags |= FLAG_DATAFROM_CLIPBOARD
#define SET_DATAFROM_FILE				s_flags &= ~FLAG_DATAFROM_CLIPBOARD

#define IS_SAVE_FILTER						(s_flags & FLAG_SAVE_FILTER)
#define ENABLE_SAVE_FILTER					s_flags |= FLAG_SAVE_FILTER
#define DISABLE_SAVE_FILTER					s_flags &= ~FLAG_SAVE_FILTER

/// EJP 07-14-2003 v7.0624 SCAN_FOR_NUM_COLS_ON_CHANGE_HEADER_LINES
#define IS_RESCAN_FOR_NUM_COLS				(s_flags & FLAG_RESCAN_FOR_NUM_COLS)
#define ENABLE_RESCAN_FOR_NUM_COLS			s_flags |= FLAG_RESCAN_FOR_NUM_COLS
#define DISABLE_RESCAN_FOR_NUM_COLS			s_flags &= ~FLAG_RESCAN_FOR_NUM_COLS
/// end SCAN_FOR_NUM_COLS_ON_CHANGE_HEADER_LINES

#define IS_ADVOPTIONS_ISCHECKED				(s_flags & FLAG_ADVOPTIONS_CHECKED)
#define ENABLE_ADVOPTIONS_ISCHECKED			s_flags |= FLAG_ADVOPTIONS_CHECKED
#define DISABLE_ADVOPTIONS_ISCHECKED		s_flags &= ~FLAG_ADVOPTIONS_CHECKED
#define IS_SHOW_ADVANCED					(IS_SAVE_FILTER && IS_ADVOPTIONS_ISCHECKED)

#define IS_UPDATE_PREVIEW_NEEDED		(s_flags & FLAG_UPDATE_PREVIEW_NEEDED)
#define ENABLE_UPDATE_PREVIEW_NEEDED	s_flags |= FLAG_UPDATE_PREVIEW_NEEDED
#define DISABLE_UPDATE_PREVIEW_NEEDED	s_flags &= ~FLAG_UPDATE_PREVIEW_NEEDED

#define IS_BINPATTERN_BINVIEW		(s_flags & FLAG_BINPATTERN_BINVIEW)
#define SET_BINPATTERN_BINVIEW		s_flags |= FLAG_BINPATTERN_BINVIEW
#define SET_BINPATTERN_ASCVIEW		s_flags &= ~FLAG_BINPATTERN_BINVIEW

/// EJP 08-08-2003 v7.0650 QA70-4073.53 USE_SAME_FILTER_FOR_MULTI_FILES_ON_FILEOPEN_AND_DRAGDROP
#define IS_GET_FILTER_ONLY			(s_flags & FLAG_GET_FILTER_ONLY)
#define ENABLE_GET_FILTER_ONLY		s_flags |= FLAG_GET_FILTER_ONLY
#define DISABLE_GET_FILTER_ONLY		s_flags &= ~FLAG_GET_FILTER_ONLY
/// end USE_SAME_FILTER_FOR_MULTI_FILES_ON_FILEOPEN_AND_DRAGDROP

/// EJP 10-16-2003 v7.5722 QA70-5289.7 UPDATE_SOURCE_FILE_ON_EDIT_CHANGE
#define IS_ON_BROWSE_SOURCE			(s_flags & FLAG_ON_BROWSE_SOURCE)
#define ENABLE_ON_BROWSE_SOURCE		s_flags |= FLAG_ON_BROWSE_SOURCE
#define DISABLE_ON_BROWSE_SOURCE		s_flags &= ~FLAG_ON_BROWSE_SOURCE
/// end UPDATE_SOURCE_FILE_ON_EDIT_CHANGE

//--------------------------------------------------------------------------
// static variables
//--------------------------------------------------------------------------
static Dialog ImportWizDlg(IDD_IW, "ImportWiz");

static Tree s_trFilter;
static ASCIMP s_ascimp;
static BINIMP s_binimp;

static StringArray s_saDataFiles;
///static string s_strDataFile;
#define s_strDataFile s_saDataFiles[0]
#define NUM_DATA_FILES (IS_DATAFROM_FILE ? s_saDataFiles.GetSize() : 1)

static string s_strFilterLoaded; /// EJP 08-01-2003 v7.0642 DETECT_IMPORT_SETTINGS_CHANGED
static string s_strFilter;
static int s_iSaveFilter;
///#define IS_SAVE_FILTER (s_iSaveFilter == IDC_SAVE_FILTER_GLOBAL_RADIO || s_iSaveFilter == IDC_SAVE_FILTER_DATA_FOLDER_RADIO)

static string s_strFilterFileSaved; /// EJP 08-08-2003 v7.0650 QA70-4073.53 USE_SAME_FILTER_FOR_MULTI_FILES_ON_FILEOPEN_AND_DRAGDROP

static DWORD s_flags;
static string s_strWks;
static vector<short> s_vColWidths;
static SIZE s_sizeGridFixWidthFont;

static bool 	s_bBusy;
static int		s_iActivePageType;           // Page type of active window when wiz is launched
static string	s_strActivePageName;         // Page name of active window when wiz is launched
static BOOL		s_bPlotInitFirstTime;        // Only initialize Plotting page once
///static int		s_nNumFiles;                 // Number of files imported/opened
static vector<short> s_vPlottingLayers;     // Layer numbers for plotting each file 
///static int 		s_nNumParameters;	    	 // Number of Parameter for Binary Import
static int		s_iFixedWidthGridFontWidth;
static int		s_iNumColsEstimated; // currently used for ASCII only
static int s_iStartingNumHdrLines; /// EJP 07-14-2003 v7.0624 SCAN_FOR_NUM_COLS_ON_CHANGE_HEADER_LINES

// Storage for file header parameters
static StringArray s_saHdrParamName;
static vector<int> s_vHdrParamType;
static vector<int> s_vHdrParamOffset;
static vector<int> s_vHdrParamSize;

#define HDRPARAM_COUNT s_saHdrParamName.GetSize()

enum {PARAM_TYPE_INT=0,PARAM_TYPE_UINT,PARAM_TYPE_REAL,PARAM_TYPE_STR};

enum {CHANGE_NONE, CHANGE_HEX, CHANGE_ASC, CHANGE_BYTEOFFSET, CHANGE_FONT};
static int s_iOnUserChange = CHANGE_NONE;

#define ASCIMP_TOTAL_HEADER_LINES(_ascimp) ((_ascimp).iHeaderLines + (_ascimp).iSubHeaderLines)

static int s_iBinHdrPreviewLines;
static int s_iAscHdrPreviewLines;

/// EJP 10-20-2003 v7.5726 QA70-5374 ALLOW_CHANGING_PREVIEW_FONT
static int s_iPreviewFont;
#define IW_PREVIEW_FONT s_iPreviewFont
/// end ALLOW_CHANGING_PREVIEW_FONT

//--------------------------------------------------------------------------
#define IS_SHOW_ASC_HEADER_PAGE				IS_FILTER_TYPE_ASCII
#define IS_SHOW_ASC_HEADER_PARAM_PAGE		(IS_FILTER_TYPE_ASCII && IS_DEFINE_HDR_VAR && ASCIMP_TOTAL_HEADER_LINES(s_ascimp))
#define IS_SHOW_ASC_COLUMNS_PAGE			IS_FILTER_TYPE_ASCII
#define IS_SHOW_PARTIAL_IMPORT_PAGE			(IS_FILTER_TYPE_ASCII || IS_FILTER_TYPE_BINARY)
#define IS_SHOW_BIN_HEADER_PAGE				IS_FILTER_TYPE_BINARY
#define IS_SHOW_BIN_PATTERN_PAGE			IS_FILTER_TYPE_BINARY
#define IS_SHOW_PLOTTING_PAGE				(s_iActivePageType == EXIST_PLOT)
#define IS_SHOW_SAVE_FILTER_PAGE			TRUE
#define IS_SHOW_FILE_TYPES_PAGE				IS_SHOW_ADVANCED
#define IS_SHOW_DRAG_DROP_PAGE				IS_SHOW_ADVANCED
#define IS_SHOW_USER_DEFINED_PAGE			IS_FILTER_TYPE_USERDEFINED

#define ON_PAGE_CHECK_SOURCE
#define ON_PAGE_CHECK_ASC_HEADER			if(!IS_SHOW_ASC_HEADER_PAGE) return FALSE;
#define ON_PAGE_CHECK_ASC_HEADER_PARAM		if(!IS_SHOW_ASC_HEADER_PARAM_PAGE) return FALSE;
#define ON_PAGE_CHECK_ASC_COLUMNS			if(!IS_SHOW_ASC_COLUMNS_PAGE) return FALSE;
#define ON_PAGE_CHECK_PARTIAL_IMPORT		if(!IS_SHOW_PARTIAL_IMPORT_PAGE) return FALSE;
#define ON_PAGE_CHECK_BIN_HEADER			if(!IS_SHOW_BIN_HEADER_PAGE) return FALSE;
#define ON_PAGE_CHECK_BIN_PATTERN			if(!IS_SHOW_BIN_PATTERN_PAGE) return FALSE;
#define ON_PAGE_CHECK_PLOTTING				if(!IS_SHOW_PLOTTING_PAGE) return FALSE;
#define ON_PAGE_CHECK_SAVE_FILTER
#define ON_PAGE_CHECK_FILE_TYPES			if(!IS_SHOW_FILE_TYPES_PAGE) return FALSE;
#define ON_PAGE_CHECK_DRAG_DROP				if(!IS_SHOW_DRAG_DROP_PAGE) return FALSE;
#define ON_PAGE_CHECK_USER_DEFINED			if(!IS_SHOW_USER_DEFINED_PAGE) return FALSE;


#define SZ_IW_NONE		_L("<None>")
#define SZ_IW_ALL		_L("<All>")
#define SZ_IW_END		_L("<End>")

//--------------------------------------------------------------------------
// ImportWizard
//
// The main function to call to start the Import Wizard.
//--------------------------------------------------------------------------
int ImportWizard(string strFileName)
{
	IW_Init(strFileName);
	return ImportWizDlg.DoModal(GetWindow());
}

/// EJP 08-08-2003 v7.0650 QA70-4073.53 USE_SAME_FILTER_FOR_MULTI_FILES_ON_FILEOPEN_AND_DRAGDROP
bool iwGetFilter(LPCSTR lpcszDataFile, string &strFilterFile, TreeNode &trFilter)
{
	IW_Init(lpcszDataFile);
	ENABLE_GET_FILTER_ONLY;
	int iRet = ImportWizDlg.DoModal(GetWindow());
	DISABLE_GET_FILTER_ONLY;
	if( IS_CLICKED_FINISH )
	{
		trFilter = s_trFilter;
		strFilterFile = s_strFilterFileSaved;
		return true;
	}
	return false;
}
/// end USE_SAME_FILTER_FOR_MULTI_FILES_ON_FILEOPEN_AND_DRAGDROP

//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
BEGIN_EVENT_MAP
	ON_INIT(OnInitDialog) 
	ON_FINISH(OnClickFinish)
	ON_CANCEL(OnClickCancel)
	ON_DESTROY(OnDestroyDialog)

	ON_WKSCTRL_EVENT(WKSCTRL_EVENT_TYPE_CHANGE, OnWksCtrlChangeColTypeOrDesignation)
	/// JCG 06/17/03 QA70-4575 v7.0602 FIX_ITEM32 
	ON_WKSCTRL_CHANGE_COL_DESIG(OnWksCtrlChangeColTypeOrDesignation)
	/// end FIX_ITEM32 

	////////////////////////////////////////////////////////////////////////
	// Source Page
	////////////////////////////////////////////////////////////////////////
	ON_PAGE_INIT(IDD_IW_SOURCE, Source_OnInit)
	ON_PAGE_ACTIVE(IDD_IW_SOURCE, Source_OnActive)
	ON_PAGE_KILLACTIVE(IDD_IW_SOURCE, Source_OnKillActive)

	ON_BN_CLICKED(IDC_DATATYPE_ASCII, Source_OnClickDataType)
	
	ON_BN_CLICKED(IDC_SOURCE_FILE, Source_OnClickDataFrom)
	ON_BN_CLICKED(IDC_SOURCE_BROWSE, Source_OnClickBrowse)
	ON_BN_CLICKED(IDC_IW_SOURCE_RENAMEWKS, Source_OnClickRenameWks)
	ON_BN_CLICKED(IDC_IW_FILENAME_TO_WKSLABEL, Source_OnClickFileNameToWksLabel)
	ON_EN_CHANGE(IDC_SOURCE_FILENAME, Source_OnChangeFileName)
	
	ON_BN_CLICKED(IDC_TARGET_WKS, Source_OnClickTargetWindow)
	ON_BN_CLICKED(IDC_TARGET_MATRIX, Source_OnClickTargetWindow)
	ON_BN_CLICKED(IDC_TARGET_WND_NONE, Source_OnClickTargetWindow)

	/// EJP 10-27-2003 v7.5733 QA70-5238 DO_NOT_RESET_TARGET_WINDOW_TEMPLATE
	///ON_CBN_SELCHANGE(IDC_TARGET_WKS_TEMPLATE, Source_OnSelChangeWksTemplate)
	ON_CBN_SELCHANGE(IDC_TARGET_WKS_TEMPLATE, Source_OnSelChangeTargetWindowTemplate)
	/// end DO_NOT_RESET_TARGET_WINDOW_TEMPLATE

	ON_BN_CLICKED(IDC_DISPLAY_ONLY_COMPATIBLE_CHK, Source_OnClickDisplayCompatibleFilters)
	ON_CBN_SELCHANGE(IDC_SOURCE_FILTER, Source_OnSelChangeFilter)
	
	////////////////////////////////////////////////////////////////////////
	// ASCII Header Page
	////////////////////////////////////////////////////////////////////////
	ON_PAGE_IS_SHOW(IDD_AIW_HEADER, OnIsShowASCII)
	ON_PAGE_INIT(IDD_AIW_HEADER, AscHeader_OnInit)
	ON_PAGE_ACTIVE(IDD_AIW_HEADER, AscHeader_OnActive)
	ON_PAGE_KILLACTIVE(IDD_AIW_HEADER, AscHeader_OnKillActive)

	// Number of header lines
	ON_CBN_EDITCHANGE(IDC_IW_HEADER_LINES, AscHeader_OnChangeHeaderLines)
	ON_CBN_SELCHANGE(IDC_IW_HEADER_LINES, AscHeader_OnSelChangeHeaderLines)
	ON_TOOLBAR_BN_CLICKED(IDB_IW_HEADER_LINES_REFRESH, AscHeader_OnRefreshHeaderLines)

	// Column names
	ON_CBN_EDITCHANGE(IDC_IW_COL_NAME_FROM, AscHdr_OnEditChangeColNameFrom)
	ON_CBN_SELCHANGE(IDC_IW_COL_NAME_FROM, AscHdr_OnSelChangeColNameFrom)
	ON_TOOLBAR_BN_CLICKED(IDB_IW_COL_NAME_REFRESH, AscHeader_OnTBClickRefreshColNameFrom)
	
	// Column labels
	/// EJP 08-15-2003 v7.5662 CLEAN_HEADER_LINES_INPUT
	///ON_CBN_EDITCHANGE(IDC_IW_COL_LABEL_FROM, AscHeader_OnChangeColNameFromLabelRange)
	///ON_CBN_SELCHANGE(IDC_IW_COL_LABEL_FROM, AscHeader_OnSelChangeColNameLabel)
	///ON_CBN_EDITCHANGE(IDC_HDR_LABEL_TO, AscHeader_OnChangeColNameFromLabelRange)
	///ON_CBN_SELCHANGE(IDC_HDR_LABEL_TO, AscHeader_OnSelChangeColNameLabel)
	ON_CBN_EDITCHANGE(IDC_IW_COL_LABEL_FROM, AscHdr_OnEditChangeColLabelFrom)
	ON_CBN_SELCHANGE(IDC_IW_COL_LABEL_FROM, AscHdr_OnSelChangeColLabelFrom)
	ON_CBN_EDITCHANGE(IDC_HDR_LABEL_TO, AscHdr_OnEditChangeColLabelFrom)
	ON_CBN_SELCHANGE(IDC_HDR_LABEL_TO, AscHdr_OnSelChangeColLabelFrom)
	/// end CLEAN_HEADER_LINES_INPUT
	ON_TOOLBAR_BN_CLICKED(IDB_IW_COL_LABEL_REFRESH, AscHeader_OnRefreshColLabelFrom)
	
	ON_CBN_EDITCHANGE(IDC_HDR_SAVE_FROM, AscHdr_OnEditChangeSaveFirstLine)
	ON_CBN_SELCHANGE(IDC_HDR_SAVE_FROM, AscHdr_OnSelChangeSaveFirstLine)

	/// JCG 05/28/03 v7.0540 HOOK_COMBO_BOX	
	ON_CBN_EDITCHANGE(IDC_HDR_SAVE_TO, AscHdr_OnEditChangeSaveFirstLine)
	ON_CBN_SELCHANGE(IDC_HDR_SAVE_TO, AscHdr_OnSelChangeSaveFirstLine)
	/// end HOOK_COMBO_BOX	

	ON_CBN_SELCHANGE(IDC_ASC_PREVIEW_FONT, AscHdr_OnSelChangeFont) /// EJP 10-20-2003 v7.5726 QA70-5374 ALLOW_CHANGING_PREVIEW_FONT
	ON_BN_CLICKED(IDC_HDRPARAM_DEFINEVAR, AscHeader_OnClickDefineVar)
	
	/// EJP 10-27-03 v7.5733 QA70-5412 SKIP_CHARS_FOR_COL_NAME_LABEL
	ON_CBN_EDITCHANGE(IDC_NAME_LABEL_CHAR_OFFSET, AscHdr_OnEditChangeNameOffset)
	ON_CBN_SELCHANGE(IDC_NAME_LABEL_CHAR_OFFSET, AscHdr_OnSelChangeNameOffset)
	/// end SKIP_CHARS_FOR_COL_NAME_LABEL

	////////////////////////////////////////////////////////////////////////
	// ASCII Header Variables Page
	////////////////////////////////////////////////////////////////////////
	ON_PAGE_IS_SHOW(IDD_AIW_HDRVAR, AscHdrVar_OnIsShow)
	ON_PAGE_INIT(IDD_AIW_HDRVAR, AscHdrVar_OnInit)
	ON_PAGE_ACTIVE(IDD_AIW_HDRVAR, AscHdrVar_OnActive)
	ON_PAGE_KILLACTIVE(IDD_AIW_HDRVAR, AscHdrVar_OnKillActive)

	ON_CBN_SELCHANGE(IDC_HDRVAR_FIRSTLINE, AscHdrVar_OnSelChangeFirstLine)
	ON_TOOLBAR_BN_CLICKED(IDB_ASCHDRVAR_LINESREFRESH, AscHdrVar_OnClickRefresh) /// EJP 08-04-2003 v7.0644 QA70-4896 ADD_REFRESH_BTN_TO_HDRVAR_PAGE
	ON_CBN_SELCHANGE(IDC_HDRVAR_SEPARATOR, AscHdrVar_OnSelChangeSeparator)
	ON_BN_CLICKED(IDC_HDRVAR_SCAN, AscHdrVar_OnClickScan)
	
	////////////////////////////////////////////////////////////////////////
	// ASCII Columns Page
	////////////////////////////////////////////////////////////////////////
	ON_PAGE_IS_SHOW(IDD_AIW_COLUMNS, OnIsShowASCII)
	ON_PAGE_INIT(IDD_AIW_COLUMNS, AscColumns_OnInit)
	ON_PAGE_ACTIVE(IDD_AIW_COLUMNS, AscColumns_OnActive)

	ON_BN_CLICKED(IDC_COLS_DELIMITED, AscColumns_OnClickDelimited)
	ON_CBN_SELCHANGE(IDC_COLS_DELIMITER, AscColumns_OnSelChangeDelimiter)
	ON_EN_CHANGE(IDC_COLS_CHAR, AscColumns_OnEditChangeCharacter)
	ON_EN_CHANGE(IDC_COLS_WIDTHS, AscColumns_OnEditChangeColumnWidths)

	/// EJP 07-21-2003 v7.0630 QA70-4073 ADD_APPLY_BUTTON_TO_UPDATE_PREVIEW
	///ON_EN_CHANGE(IDC_NUMBER_OF_COLS, AscCols_OnChangeNumCols)
	ON_BN_CLICKED(IDC_APPLY_NUM_COLS, AscCols_OnClickApplyNumCols)
	/// end ADD_APPLY_BUTTON_TO_UPDATE_PREVIEW

	ON_BN_CLICKED(IDC_COLS_REFRESH, AscColumns_OnClickRefresh)
	ON_BN_CLICKED(IDC_IW_COL_SET_PLOT_DESIG, AscColumns_OnClickSetDesignations)
///	ON_ORIGIN_CHANGE(SN_COL_CHANGE_PLOT_DESIGNATION, AscColumns_OnOriginChangeWks)
///	ON_ORIGIN_CHANGE(SN_COL_CHANGE_FORMAT, AscColumns_OnOriginChangeWks)
///	ON_WKSCTRL_EVENT(WKSCTRL_EVENT_TYPE_CHANGE, AscColumns_OnChangeColTypeOrDesignation)
	ON_BN_CLICKED(IDC_COL_PREV_SWITCH, AscColumns_OnClickFixedWidthPreview)
	ON_GRID_AFTER_USER_RESIZE(IDC_COL_WIDTH_PREVIEW_GRID, AscColumns_OnAfterResizeGridCol)
	ON_GRID_DRAW_CELL(IDC_COL_WIDTH_PREVIEW_GRID, AscColumns_OnDrawCell)
	ON_BN_CLICKED(IDC_ADD_COL, AscColumns_OnClickAddCol)
	ON_BN_CLICKED(IDC_DEL_COL, AscColumns_OnClickDelCol)
	ON_BN_CLICKED(IDC_IW_LEADING_ZERO, AscColumns_OnClickLeadingZeroes)

	ON_BN_CLICKED(IDC_APPLY_DATE_FORMAT, AscCols_ApplyDateFormat) /// EJP 10-13-2003 v7.5717 QA70-5318 CUSTOM_DATE_FORMAT

	////////////////////////////////////////////////////////////////////////
	// Data Selection Page
	////////////////////////////////////////////////////////////////////////
	ON_PAGE_IS_SHOW(IDD_IW_RANGE, Range_OnIsShow)
	ON_PAGE_INIT(IDD_IW_RANGE, Range_OnInit)
	ON_PAGE_ACTIVE(IDD_IW_RANGE, Range_OnActive)

	ON_CBN_SELCHANGE(IDC_RANGE_MODE, Range_OnSelChangeMode)
	ON_BN_CLICKED(IDC_RANGE_PARTIAL, Range_OnClickPartial)

	/// EJP 07-21-2003 v7.0630 QA70-4073 ADD_APPLY_BUTTON_TO_UPDATE_PREVIEW
	/*
	ON_EN_CHANGE(IDC_RANGE_FIRSTCOL, Range_OnEditChangeFirstCol)
	ON_EN_CHANGE(IDC_RANGE_LASTCOL, Range_OnEditChangeLastCol)
	ON_EN_CHANGE(IDC_RANGE_FIRSTROW, Range_OnEditChangeFirstRow)
	ON_EN_CHANGE(IDC_RANGE_LASTROW, Range_OnEditChangeLastRow)
	*/
	ON_BN_CLICKED(IDC_APPLY_PARTIAL, Range_OnClickApplyPartial)
	/// end ADD_APPLY_BUTTON_TO_UPDATE_PREVIEW

	ON_EN_CHANGE(IDC_IW_SKIP_ROWS, OnEditChangeSkipDataRows)
	/// EJP 08-27-2003 v7.5677 QA70-5073 ADD_READROWS
	ON_EN_CHANGE(IDC_IW_READ_ROWS, OnEditChangeReadRows)
	/// end ADD_READROWS

	ON_CBN_SELCHANGE(IDC_IW_HEADER_NONNUMERIC, OnSelChangeNonNumeric)

	////////////////////////////////////////////////////////////////////////
	// Binary Header Page
	////////////////////////////////////////////////////////////////////////
	ON_PAGE_IS_SHOW(IDD_BIW_HEADER, OnIsShowBinary)
	ON_PAGE_INIT(IDD_BIW_HEADER, BinHeader_OnInit)
	ON_PAGE_ACTIVE(IDD_BIW_HEADER, BinHeader_OnActivate)
	ON_PAGE_KILLACTIVE(IDD_BIW_HEADER, BinHeader_OnKillActive)

	ON_EN_CHANGE(IDC_BIW_HEADER_SKIPHEADER_EDIT, BinHeader_OnChangeHeaderSize)
	ON_TOOLBAR_BN_CLICKED(IDB_IW_BIN_HEADER_REFRESH, BinHeader_OnClickRefresh)
	ON_BN_CLICKED(IDC_BIW_HEADER_BIGENDIAN_CHECK, BinHeader_OnClickBigEndian)
	ON_EN_SELCHANGE(IDC_BIW_HEADER_ASCII_RICHEDIT, OnSelChangeAscPreview)
	ON_EN_SELCHANGE(IDC_BIW_HEADER_HEX_RICHEDIT, OnSelChangeHexPreview)
	ON_WM_VSCROLL(IDC_BIW_HEADER_ASCII_RICHEDIT, OnVScrollAscPreview)
	ON_WM_VSCROLL(IDC_BIW_HEADER_HEX_RICHEDIT, OnVScrollHexPreview)
	ON_BN_CLICKED(IDC_BIW_USE_PARAMETER_DEFINITIONS, BinHeader_OnClickDefineParam)
	ON_BN_CLICKED(IDC_BIW_HEADER_ADD_BUTTON, BinHeader_OnClickAddParam)
	ON_BN_CLICKED(IDC_BIW_HEADER_REMOVE_BUTTON, BinHeader_OnClickRemoveParam)
	ON_CBN_SELCHANGE(IDC_BIW_HEADER_CANDINTERP_COMBO, BinHeader_OnSelChangeParamType)
	ON_EN_CHANGE(IDC_BYTE_OFFSET, BinHeader_OnChangeByteOffset)

	ON_CBN_SELCHANGE(IDC_BIN_PREVIEW_FONT, BinHdr_OnSelChangeFont) /// EJP 10-24-2003 v7.5730 QA70-5374 ALLOW_CHANGING_PREVIEW_FONT

	////////////////////////////////////////////////////////////////////////
	// Binary Pattern Page
	////////////////////////////////////////////////////////////////////////
	ON_PAGE_IS_SHOW(IDD_BIW_DATAPATERN, OnIsShowBinary)
	ON_PAGE_INIT(IDD_BIW_DATAPATERN, BinPattern_OnInit)
	ON_PAGE_ACTIVE(IDD_BIW_DATAPATERN, BinPattern_OnActivate)
	ON_PAGE_KILLACTIVE(IDD_BIW_DATAPATERN, BinPattern_OnKillActive)

	ON_BN_CLICKED(IDC_BIW_DATAPATERN_HEX, BinPattern_OnClickDataView)
	ON_CBN_SELCHANGE(IDC_BIW_DATAPATERN_PARAMS, BinPattern_OnSelChangeHeaderVariable)
	ON_BN_CLICKED(IDC_DATAPATTERN_INSERT, BinPattern_OnClickInsertRow)
	ON_BN_CLICKED(IDC_DATAPATTERN_DELETE, BinPattern_OnClickDeleteRow)
	ON_GRID_BEFORE_EDIT(IDC_BIW_DATAPATERN_PATERN_GRID, BinPattern_OnBeforeEditGrid)
	ON_GRID_CHANGE_EDIT(IDC_BIW_DATAPATERN_PATERN_GRID, BinPattern_OnChangeEditGrid)
	ON_GRID_COMBO_CLOSEUP(IDC_BIW_DATAPATERN_PATERN_GRID, BinPattern_OnGridComboCloseUp)
	
	////////////////////////////////////////////////////////////////////////
	// Plotting Page
	////////////////////////////////////////////////////////////////////////
	ON_PAGE_IS_SHOW(IDD_IW_PLOTTING, Plotting_OnIsShow)
	ON_PAGE_INIT(IDD_IW_PLOTTING, Plotting_OnInit)
	ON_PAGE_ACTIVE(IDD_IW_PLOTTING, Plotting_OnActivate)
	ON_PAGE_KILLACTIVE(IDD_IW_PLOTTING, Plotting_OnKillActive)

	ON_CBN_SELCHANGE(IDC_IW_PLOT_TYPE, Plotting_OnPlotTypeChange)
	ON_GRID_COMBO_CLOSEUP(IDC_IW_PLOT_GRID_HLDR, Plotting_OnGridComboCloseUpGrid)
	ON_GRID_BEFORE_EDIT(IDC_IW_PLOT_GRID_HLDR, Plotting_OnBeforeEditCell)
	
	////////////////////////////////////////////////////////////////////////
	// Save Filters Page
	////////////////////////////////////////////////////////////////////////
	ON_PAGE_INIT(IDD_IW_SAVE_FILTERS, SaveFilters_OnInit)
	ON_PAGE_ACTIVE(IDD_IW_SAVE_FILTERS, SaveFilters_OnActive)
	ON_PAGE_KILLACTIVE(IDD_IW_SAVE_FILTERS, SaveFilters_OnKillActive)

	ON_BN_CLICKED(IDC_SAVE_FILTER, SaveFilters_OnClickSaveFilter)
	ON_BN_CLICKED(IDC_SAVE_FILTER_DATA_FOLDER_RADIO, SaveFilters_OnClickDestination)
	ON_BN_CLICKED(IDC_SAVE_FILTER_GLOBAL_RADIO, SaveFilters_OnClickDestination)
	ON_BN_CLICKED(IDC_SAVE_FILTER_IN_WKS, SaveFilters_OnClickDestination)
	ON_CBN_SELCHANGE(IDC_SAVE_FILTERS_NAME_COMBO, SaveFilter_OnSelChangeFilterName)
	ON_CBN_EDITCHANGE(IDC_SAVE_FILTERS_NAME_COMBO, SaveFilter_OnEditChangeFilterName)
	ON_BN_CLICKED(IDC_SAVE_FILTERS_ADVANCED, SaveFilters_OnClickAdvanced)

	////////////////////////////////////////////////////////////////////////
	// File Types Page
	////////////////////////////////////////////////////////////////////////
	ON_PAGE_IS_SHOW(IDD_IW_FILETYPES, FileTypes_OnIsShow)
	ON_PAGE_INIT(IDD_IW_FILETYPES, FileTypes_OnInit)
	ON_PAGE_ACTIVE(IDD_IW_FILETYPES, FileTypes_OnActive)
	ON_PAGE_KILLACTIVE(IDD_IW_FILETYPES, FileTypes_OnKillActive)

	ON_GRID_BEFORE_EDIT(IDC_FILE_TYPES_WILDCARDS_GRID, FileTypes_OnBeforeEditTypes)
	///ON_GRID_CHANGE_EDIT(IDC_FILE_TYPES_WILDCARDS_GRID, FileTypes_OnChangeTypes)
	
	////////////////////////////////////////////////////////////////////////
	// Drag and Drop Page
	////////////////////////////////////////////////////////////////////////
	ON_PAGE_IS_SHOW(IDD_IW_DRAP_AND_DROP, OnIsShowAdvanced)
	ON_PAGE_INIT(IDD_IW_DRAP_AND_DROP, DragDrop_OnInit)
	ON_PAGE_ACTIVE(IDD_IW_DRAP_AND_DROP, DragDrop_OnActive)
	ON_PAGE_KILLACTIVE(IDD_IW_DRAP_AND_DROP, DragDrop_OnKillActive)

	////////////////////////////////////////////////////////////////////////
	// User Defined Page
	////////////////////////////////////////////////////////////////////////
	ON_PAGE_IS_SHOW(IDD_IW_USER_DEFINED, OnIsShowUserDefined)
	ON_PAGE_INIT(IDD_IW_USER_DEFINED, UserDefined_OnInit)
	ON_PAGE_ACTIVE(IDD_IW_USER_DEFINED, UserDefined_OnActive)
	ON_PAGE_KILLACTIVE(IDD_IW_USER_DEFINED, UserDefined_OnKillActive)

	ON_BN_CLICKED(IDC_USER_DEFINED_BROWSE, UserDefined_OnClickBrowse)
	
END_EVENT_MAP

//--------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
//--------------------------------------------------------------------------

static BOOL OnInitDialog()
{
	return TRUE;
}

static BOOL OnClickFinish()
{
	ENABLE_CLICKED_FINISH;
	
	if( FILTER_TYPE_ASCII == s_trFilter.Type.nVal )
	{
		s_trFilter.Common.OCFile.strVal = FILTER_ASCII_OCFILE;
		s_trFilter.Common.OCFunction.strVal = FILTER_ASCII_OCFUNCTION;
	}
	else if( FILTER_TYPE_BINARY == s_trFilter.Type.nVal )
	{
		s_trFilter.Common.OCFile.strVal = FILTER_BINARY_OCFILE;
		s_trFilter.Common.OCFunction.strVal = FILTER_BINARY_OCFUNCTION;
	}

	if( IS_SAVE_FILTER )
	{
		/// EJP 09-10-2003 v7.5690 NOTIFY_USER_WHEN_SAVE_FILTER_FAILS
		///iwSaveFilter();
		if( !iwSaveFilter() )
		{
			Window winImpWiz = ImportWizDlg.GetWindow();
			MessageBox(winImpWiz.GetSafeHwnd(), _L("Failed to save import filter."), _L("Import Wizard"), MB_OK);
		}
		/// end NOTIFY_USER_WHEN_SAVE_FILTER_FAILS
	}
	/// EJP 09-03-2003 v7.5682 DETECT_IMPORT_SETTINGS_CHANGED
	else if( !iwIsLoadedFilterSettingsChanged() )
		s_strFilterFileSaved = s_strFilterLoaded;
	/// end DETECT_IMPORT_SETTINGS_CHANGED

	#ifndef IW_DEBUG
	Worksheet wks;
	wks.Attach(s_strWks);
	if( wks )
		wks.Destroy();
	#endif // !IW_DEBUG

	/// EJP 08-08-2003 v7.0650 QA70-4073.53 USE_SAME_FILTER_FOR_MULTI_FILES_ON_FILEOPEN_AND_DRAGDROP
	if( IS_GET_FILTER_ONLY )
		return TRUE;
	/// end USE_SAME_FILTER_FOR_MULTI_FILES_ON_FILEOPEN_AND_DRAGDROP
	
	///Page pgTarget(s_strActivePageName);
	Page pgActive(s_strActivePageName);
	Page pgTarget;

	int iErr; /// EJP 10-30-2003 v7.75736 QA70-5448 NOTIFY_USER_OF_IMPORT_ERROR
	
	for( int nFile = 0; nFile < s_saDataFiles.GetSize(); nFile++ )
	{
		pgTarget = pgActive;
		s_strDataFile = s_saDataFiles[nFile];
		
		/// EJP 10-30-2003 v7.5736 QA70-5448 NOTIFY_USER_OF_IMPORT_ERROR
		///ImportFile(pgTarget, s_trFilter, s_saDataFiles[nFile], nFile);
		iErr = ImportFile(pgTarget, s_trFilter, s_saDataFiles[nFile], nFile);
		if( IMPERR_NONE != iErr )
		{
			ImportErrorMsgBox(iErr);
			break; // do not continue
		}
		/// end NOTIFY_USER_OF_IMPORT_ERROR
		
		/// EJP 08-08-2003 v7.0650 QA70-4073.53 USE_SAME_FILTER_FOR_MULTI_FILES_ON_FILEOPEN_AND_DRAGDROP
		/*
		if( IS_SAVE_FILTER )
			pgTarget.Info.System.Import.Filter$ = s_strFilter;
		else
			pgTarget.Info.System.Import.Filter$ = "";
		*/
		if( pgTarget )
			pgTarget.Info.System.Import.Filter$ = s_strFilterFileSaved;
		/// end USE_SAME_FILTER_FOR_MULTI_FILES_ON_FILEOPEN_AND_DRAGDROP
		
		if( s_iActivePageType == EXIST_PLOT )
			IW_PlotToActiveGraph(pgTarget, nFile); // Argument is 0 based index of file number until multiple files is implemented
	}

	/// EJP 09-16-2003 v7.5696 QA70-4575 UPDATE_PLOT_LEGEND
	if( s_iActivePageType == EXIST_PLOT )
		pgActive.LT_execute("Label -p 75 5 -B 0; Legend -s;");
	/// end UPDATE_PLOT_LEGEND

	if( IS_DATAFROM_CLIPBOARD )
		DeleteFile(s_strDataFile); // delete temporary file

	return TRUE;
}

static BOOL OnClickCancel()
{
	DISABLE_CLICKED_FINISH;
	
	if( !s_strWks.IsEmpty() )
	{
#ifndef IW_DEBUG
		Worksheet wks(s_strWks);
		wks.Destroy();
#endif // !IW_DEBUG
		s_strWks.Empty();
	}

	if( IS_DATAFROM_CLIPBOARD )
		DeleteFile(s_strDataFile); // delete temporary file

	return TRUE;
}

static BOOL OnDestroyDialog()
{
	return TRUE;
}

static BOOL OnWksCtrlChangeColTypeOrDesignation(DWORD iCtrlID, LONG iColIndex)
{
	int iPageID;
	if( IDC_COL_WKS_PREVIEW == iCtrlID )
		iPageID = IDD_AIW_COLUMNS;
	else if( IDC_RANGE_PREVIEW == iCtrlID )
		iPageID = IDD_IW_RANGE;
	else
	/// JCG 06/11/03 QA70-4575 v7.0600 FIX_ITEM32 
	///	return FALSE; // unknown wks ctrl
	if( IDC_BIW_DATAPATERN_PREVIEW_LC == iCtrlID )
		iPageID = IDD_BIW_DATAPATERN;	
	else
	{
		ASSERT(FALSE);
		return FALSE;
	}
	/// end FIX_ITEM32 
	
	
	Worksheet wks(s_strWks);
	if( !wks )
		return FALSE;

	fuSetDesignations(s_trFilter, wks.GetColDesignations());
	fuSetFormats(s_trFilter, wks.GetColFormats());
	/// EJP 08-19-2003 v7.5667 REIMPORT_AFTER_USER_CHANGE_COL_FORMAT
	///UpdateWksCtrl(iPageID); // do not re-import, just update wks ctrl
	UpdatePreview(iPageID);
	/// end REIMPORT_AFTER_USER_CHANGE_COL_FORMAT
	return TRUE;
}

//--------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
//		Data Source Page
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
//--------------------------------------------------------------------------

static BOOL Source_OnInit()
{
	LPCSTR lpcszDataFile;

	Control pgSource = ImportWizDlg.GetItem(IDD_IW_SOURCE);
	Edit editFileName = ImportWizDlg.GetItem(IDC_SOURCE_FILENAME, IDD_IW_SOURCE);
	if( IS_DATAFROM_CLIPBOARD )
	{
		pgSource.CheckRadioButton(IDC_SOURCE_FILE, IDC_SOURCE_CLIPBOARD, IDC_SOURCE_CLIPBOARD);
		editFileName.Text = "";
		lpcszDataFile = NULL;
	}
	else
	{
		pgSource.CheckRadioButton(IDC_SOURCE_FILE, IDC_SOURCE_CLIPBOARD, IDC_SOURCE_FILE);
		editFileName.Text = s_strDataFile;
		lpcszDataFile = s_strDataFile;
	}

	ComboBox cbWksTemplate = ImportWizDlg.GetItem(IDC_TARGET_WKS_TEMPLATE, IDD_IW_SOURCE);
	InitComboBoxWithTemplateNames(cbWksTemplate, EXIST_WKS);

	///ComboBox cbMatrixTemplate = ImportWizDlg.GetItem(IDC_TARGET_MATRIX_TEMPLATE, IDD_IW_SOURCE);
	///InitComboBoxWithTemplateNames(cbMatrixTemplate, EXIST_MATRIX);

	Source_UpdateFilter(FALSE);
	Source_EnableDataSourceCtrls();
	Source_EnableTargetWindowCtrls();
	Source_UpdateButtons();

	Button chkCompatibleFilters = ImportWizDlg.GetItem(IDC_DISPLAY_ONLY_COMPATIBLE_CHK, IDD_IW_SOURCE);
	chkCompatibleFilters.Check = 1;

	Source_UpdateFilterComboBox();
	Source_LoadCurSelFilter();

	return TRUE;
}

static BOOL Source_OnActive()
{
	Source_UpdateButtons();
	return TRUE;
}

static BOOL Source_OnKillActive()
{
	Source_UpdateFilter();

	/// EJP 08-15-2003 v7.5661 QA70-4073.58 CLEAN_IMPORT_FROM_CLIPBOARD
	/*
	if( IS_DATAFROM_CLIPBOARD )
	{
		// Copy clipboard text into local string
		string strClipboardText;
		GetClipboardText(strClipboardText);

		// Get a temporary file name
		AIW_GetTempFileName(s_strDataFile);
		
		// Write clipboard text to temporary file
		stdioFile filTemp(s_strDataFile, file::modeCreate | file::modeWrite | file::shareExclusive | file::typeText );
		filTemp.WriteString(strClipboardText);
		filTemp.Close();
	}
	else // Data is from a file
	{
		Edit editFileName = ImportWizDlg.GetItem(IDC_SOURCE_FILENAME, IDD_IW_SOURCE);
		s_strDataFile = editFileName.Text;
	}
	*/
	/// end CLEAN_IMPORT_FROM_CLIPBOARD

	////////////////////////////////////////////////////////////////////////
	// Create a worksheet
	////////////////////////////////////////////////////////////////////////
	Worksheet wks;
	if( !s_strWks.IsEmpty() )
	{
		// If we already created a wks then delete it
		wks.Attach(s_strWks);
		wks.Destroy();
		s_strWks.Empty();
	}

#ifdef IW_DEBUG
	int nOption = CREATE_VISIBLE;
#else // !IW_DEBUG
	int nOption = CREATE_HIDDEN;
#endif // !IW_DEBUG
	ComboBox comboTemplate = ImportWizDlg.GetItem(IDC_TARGET_WKS_TEMPLATE);

	if( comboTemplate.GetCurSel() == 0 )
		wks.Create(NULL, nOption);
	else
	{
		string strTemplate = comboTemplate.Text + ".otw";
		wks.Create(strTemplate, nOption);
	}

	wks.GetPage().GetName(s_strWks);
	
	BOOL bFilterRepetitive = fuGetRepetitive(s_trFilter);
	wks.SetColDesignations(fuGetDesignations(s_trFilter), bFilterRepetitive);
	wks.SetColFormats(fuGetFormats(s_trFilter), bFilterRepetitive);

	if( EXIST_PLOT == s_iActivePageType )
	{
		s_vPlottingLayers.SetSize(0);
		for( int i = 0; i < s_saDataFiles.GetSize(); i++ )
			s_vPlottingLayers.Add(0); // 0=first layer
	}	

	return TRUE;
}

///////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////// Data Type functions
///////////////////////////////////////////////////////////

static BOOL Source_OnClickDataType(Control Cntrl)
{
	Control pgSource = ImportWizDlg.GetItem(IDD_IW_SOURCE);
	int iType = pgSource.GetCheckedRadioButton(IDC_DATATYPE_ASCII, IDC_DATATYPE_USERDEF) - IDC_DATATYPE_ASCII;
	
	s_trFilter.Type.nVal = iType;

	Source_EnableDataSourceCtrls();
	Source_EnableTargetWindowCtrls();
	Source_UpdateFilterComboBox();
	Source_LoadCurSelFilter();
	Source_UpdateTargetWindowTemplateList();
	Source_UpdateButtons();
	return TRUE;
}

///////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////// Data Source functions
///////////////////////////////////////////////////////////

static BOOL Source_OnClickDataFrom(Control ctrl)
{
	/// EJP 08-15-2003 v7.5661 QA70-4073.58 CLEAN_IMPORT_FROM_CLIPBOARD
	if( IS_DATAFROM_CLIPBOARD )
		DeleteFile(s_strDataFile); // delete temporary file
	/// end CLEAN_IMPORT_FROM_CLIPBOARD

	Button radioClipboard = ImportWizDlg.GetItem(IDC_SOURCE_CLIPBOARD, IDD_IW_SOURCE);
	if( radioClipboard.Check )
	{
		SET_DATAFROM_CLIPBOARD;

		/// EJP 08-15-2003 v7.5661 QA70-4073.58 CLEAN_IMPORT_FROM_CLIPBOARD
		// Copy clipboard text into local string
		string strClipboardText;
		GetClipboardText(strClipboardText);

		// Get a temporary file name
		AIW_GetTempFileName(s_strDataFile);
		
		// Write clipboard text to temporary file
		stdioFile filTemp(s_strDataFile, file::modeCreate | file::modeWrite | file::shareExclusive | file::typeText );
		filTemp.WriteString(strClipboardText);
		filTemp.Close();
		/// end CLEAN_IMPORT_FROM_CLIPBOARD
	}
	else
	{
		SET_DATAFROM_FILE;

		/// EJP 08-15-2003 v7.5661 QA70-4073.58 CLEAN_IMPORT_FROM_CLIPBOARD
		Edit editFileName = ImportWizDlg.GetItem(IDC_SOURCE_FILENAME, IDD_IW_SOURCE);
		s_strDataFile = editFileName.Text;
		/// end CLEAN_IMPORT_FROM_CLIPBOARD
	}

	Source_EnableFileCtrls(IS_DATAFROM_FILE);
	Source_UpdateFilterComboBox();
	Source_LoadCurSelFilter();
	Source_UpdateButtons();
	return TRUE;
}

static void Source_EnableFileCtrls(BOOL bEnable=true)
{
	Edit ebFileName = ImportWizDlg.GetItem(IDC_SOURCE_FILENAME, IDD_IW_SOURCE);
	ebFileName.Enable = bEnable;

	Button btnBrowse = ImportWizDlg.GetItem(IDC_SOURCE_BROWSE, IDD_IW_SOURCE);
	btnBrowse.Enable = bEnable;

	Button chkRenameWks = ImportWizDlg.GetItem(IDC_IW_SOURCE_RENAMEWKS, IDD_IW_SOURCE);
	chkRenameWks.Enable = bEnable;
	
	Button chkFileNameToWksLabel = ImportWizDlg.GetItem(IDC_IW_FILENAME_TO_WKSLABEL, IDD_IW_SOURCE);
	chkFileNameToWksLabel.Enable = bEnable;
}

static void Source_EnableDataSourceCtrls()
{
	Control pgSource = ImportWizDlg.GetItem(IDD_IW_SOURCE);

	Button radClipboard = ImportWizDlg.GetItem(IDC_SOURCE_CLIPBOARD, IDD_IW_SOURCE);

	int iDataType = pgSource.GetCheckedRadioButton(IDC_DATATYPE_ASCII, IDC_DATATYPE_USERDEF);
	if( IDC_DATATYPE_BINARY == iDataType )
	{
		pgSource.CheckRadioButton(IDC_SOURCE_FILE, IDC_SOURCE_CLIPBOARD, IDC_SOURCE_FILE);
		SET_DATAFROM_FILE;
		radClipboard.Enable = false;
	}
	else
		radClipboard.Enable = true;

	int iDataSource = pgSource.GetCheckedRadioButton(IDC_SOURCE_FILE, IDC_SOURCE_CLIPBOARD);
	Source_EnableFileCtrls(IDC_SOURCE_FILE == iDataSource);
}

static BOOL Source_OnClickBrowse(Control ctrl)
{
	ENABLE_ON_BROWSE_SOURCE; /// EJP 10-16-2003 v7.5722 QA70-5289.7 UPDATE_SOURCE_FILE_ON_EDIT_CHANGE

	Control pgSource = ImportWizDlg.GetItem(IDD_IW_SOURCE);
	int nDataType = pgSource.GetCheckedRadioButton(IDC_DATATYPE_ASCII, IDC_DATATYPE_USERDEF);
	nDataType -= IDC_DATATYPE_ASCII;

	StringArray saDataFiles;
	if( GetMultiOpenBox(saDataFiles, nDataType + FDLOG_FILTER_ASCII) )
	{
		s_saDataFiles = saDataFiles;
		Edit editFileName = ImportWizDlg.GetItem(IDC_SOURCE_FILENAME, IDD_IW_SOURCE);
		editFileName.Text = s_saDataFiles[0];
		/// EJP 06-26-2003: setting editFileName.Text will trigger a call to Source_OnChangeFileName
		///Source_UpdateButtons();
		///Source_SelectFilterOnChangeFileName();
	}
	
	DISABLE_ON_BROWSE_SOURCE; /// EJP 10-16-2003 v7.5722 QA70-5289.7 UPDATE_SOURCE_FILE_ON_EDIT_CHANGE
	return TRUE;
}

static BOOL Source_OnChangeFileName(Control ctrl)
{
	/// EJP 10-16-2003 v7.5722 QA70-5289.7 UPDATE_SOURCE_FILE_ON_EDIT_CHANGE
	if( !IS_ON_BROWSE_SOURCE )
	{
		Edit editFileName = ImportWizDlg.GetItem(IDC_SOURCE_FILENAME, IDD_IW_SOURCE);
		s_saDataFiles[0] = editFileName.Text;
	}
	/// end UPDATE_SOURCE_FILE_ON_EDIT_CHANGE

	Source_UpdateButtons();
	Source_UpdateFilterComboBox();
	Source_LoadCurSelFilter();
	return TRUE;
}

static BOOL Source_OnClickRenameWks(Control ctrl)
{
	Button chkRenameWks = ImportWizDlg.GetItem(IDC_IW_SOURCE_RENAMEWKS, IDD_IW_SOURCE);
	s_trFilter.Common.RenameWks.nVal = chkRenameWks.Check;
	return TRUE;
}

static BOOL Source_OnClickFileNameToWksLabel(Control ctrl)
{
	Button chkFileNameToWksLabel = ImportWizDlg.GetItem(IDC_IW_FILENAME_TO_WKSLABEL, IDD_IW_SOURCE);
	s_trFilter.Common.FileNameToWksLabel.nVal = chkFileNameToWksLabel.Check;
	return TRUE;
}

///////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////// Target Window functions
///////////////////////////////////////////////////////////

static BOOL Source_OnClickTargetWindow(Control ctrl)
{
	Source_UpdateTargetWindowTemplateList();
	Source_EnableTargetWindowCtrls();
	return TRUE;
}

/// EJP 10-27-2003 v7.5733 QA70-5238 DO_NOT_RESET_TARGET_WINDOW_TEMPLATE
/*
static BOOL	Source_OnSelChangeWksTemplate(Control ctrl)
{
	string strTemplate;
	ComboBox cbTemplate(ctrl);
	if( cbTemplate.GetCurSel() > 0 )
	{
		/// JCG 05/28/03 v7.0540 HOOK_COMBO_BOX	
		/// strTemplate = cbTemplate.Text + ".otw";
		// Ext name will be appended at nex call AIW_FileNameToFullPath
		strTemplate = cbTemplate.Text;
		/// end HOOK_COMBO_BOX	
		if( !AIW_FileNameToFullPath(strTemplate, strTemplate, FALSE) )
			strTemplate.Empty();
	}
	fuSetTargetWindow(s_trFilter, EXIST_WKS, strTemplate);
	return TRUE;
}

static void Source_UpdateTargetWindowTemplateList()
{
	Control pgSource = ImportWizDlg.GetItem(IDD_IW_SOURCE);
	int iTargetWindow = pgSource.GetCheckedRadioButton(IDC_TARGET_WKS, IDC_TARGET_WND_NONE);
	if( IDC_TARGET_WKS == iTargetWindow || IDC_TARGET_MATRIX == iTargetWindow )
	{
		if( IDC_TARGET_WKS == iTargetWindow )
			iTargetWindow = EXIST_WKS;
		else
			iTargetWindow = EXIST_MATRIX;
		ComboBox cbTemplate = ImportWizDlg.GetItem(IDC_TARGET_WKS_TEMPLATE, IDD_IW_SOURCE);
		InitComboBoxWithTemplateNames(cbTemplate, iTargetWindow);
	}
}
*/
static int Source_GetTargetWindowType()
{
	Control pgSource = ImportWizDlg.GetItem(IDD_IW_SOURCE);
	int iTargetWindow = pgSource.GetCheckedRadioButton(IDC_TARGET_WKS, IDC_TARGET_WND_NONE);
	switch( iTargetWindow )
	{
	case IDC_TARGET_WKS:
		iTargetWindow = EXIST_WKS;
		break;
	case IDC_TARGET_MATRIX:
		iTargetWindow = EXIST_MATRIX;
		break;
	default:
		iTargetWindow = EXIST_NONE;
		break;
	}
	return iTargetWindow;
}

static void Source_UpdateTargetWindowTemplateList()
{
	int iTargetWindowType = Source_GetTargetWindowType();
	if( iTargetWindowType == EXIST_NONE )
		return;
	ComboBox cbTemplate = ImportWizDlg.GetItem(IDC_TARGET_WKS_TEMPLATE, IDD_IW_SOURCE);
	InitComboBoxWithTemplateNames(cbTemplate, iTargetWindowType);
}

static BOOL Source_OnSelChangeTargetWindowTemplate(Control ctrl)
{
	ComboBox cbTemplate(ctrl);
	if( !cbTemplate )
		return FALSE;
	string strTemplate;
	int iWindowType = Source_GetTargetWindowType();
	if( iWindowType != EXIST_NONE && cbTemplate.GetCurSel() > 0 )
		strTemplate = cbTemplate.Text;
	fuSetTargetWindow(s_trFilter, iWindowType, strTemplate);
	return TRUE;
}
/// end DO_NOT_RESET_TARGET_WINDOW_TEMPLATE


static void Source_EnableTargetWindowCtrls()
{
	Control pgSource = ImportWizDlg.GetItem(IDD_IW_SOURCE);
	int iDataType = pgSource.GetCheckedRadioButton(IDC_DATATYPE_ASCII, IDC_DATATYPE_USERDEF);
	
	Button radMatrix = ImportWizDlg.GetItem(IDC_TARGET_MATRIX, IDD_IW_SOURCE);
	radMatrix.Enable = (IDC_DATATYPE_USERDEF == iDataType);
	
	Button radWndNone = ImportWizDlg.GetItem(IDC_TARGET_WND_NONE, IDD_IW_SOURCE);
	radWndNone.Enable = (IDC_DATATYPE_USERDEF == iDataType);
	
	int iTargetWindow = pgSource.GetCheckedRadioButton(IDC_TARGET_WKS, IDC_TARGET_WND_NONE);
	ComboBox cbWksTemplate = ImportWizDlg.GetItem(IDC_TARGET_WKS_TEMPLATE, IDD_IW_SOURCE);
	cbWksTemplate.Enable = (IDC_TARGET_WKS == iTargetWindow || IDC_TARGET_MATRIX == iTargetWindow);
}

///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////

static void	Source_UpdateFilter(BOOL bDlgToFilter=TRUE)
{
	int i;
	string str;
	
	Control pgSource = ImportWizDlg.GetItem(IDD_IW_SOURCE);

	Button chkRenameWks = ImportWizDlg.GetItem(IDC_IW_SOURCE_RENAMEWKS, IDD_IW_SOURCE);
	Button chkFileNameToWksLabel = ImportWizDlg.GetItem(IDC_IW_FILENAME_TO_WKSLABEL, IDD_IW_SOURCE);
	
	Button chkWks = ImportWizDlg.GetItem(IDC_TARGET_WKS, IDD_IW_SOURCE);
	ComboBox cbWksTemplate = ImportWizDlg.GetItem(IDC_TARGET_WKS_TEMPLATE, IDD_IW_SOURCE);
	Button chkMat = ImportWizDlg.GetItem(IDC_TARGET_MATRIX, IDD_IW_SOURCE);
	
	if( bDlgToFilter )
	{
		s_trFilter.Type.nVal = pgSource.GetCheckedRadioButton(IDC_DATATYPE_ASCII, IDC_DATATYPE_USERDEF) - IDC_DATATYPE_ASCII;
		s_trFilter.Common.RenameWks.nVal = (chkRenameWks.Check ? 1 : 0);
		s_trFilter.Common.FileNameToWksLabel.nVal = (chkFileNameToWksLabel.Check ? 1 : 0);

		int iType = pgSource.GetCheckedRadioButton(IDC_TARGET_WKS, IDC_TARGET_WND_NONE);
		switch( iType )
		{
		case IDC_TARGET_WKS:
			str = cbWksTemplate.Text;
			iType = EXIST_WKS;
			break;
		case IDC_TARGET_MATRIX:
			str = cbWksTemplate.Text;
			iType = EXIST_MATRIX;
			break;
		case IDC_TARGET_WND_NONE:
			str.Empty();
			iType = EXIST_NONE;
			break;
		}
		if( 0 == str.CompareNoCase(AIW_DEFAULT_FILTER) )
			str.Empty(); // store empty string to indicate default
		fuSetTargetWindow(s_trFilter, iType, str);
	}
	else // update dialog from filter
	{
		i = tree_node_get_int(s_trFilter.Type, FILTER_TYPE_ASCII);
		pgSource.CheckRadioButton(IDC_DATATYPE_ASCII, IDC_DATATYPE_USERDEF, IDC_DATATYPE_ASCII + i);
		
		chkRenameWks.Check = tree_node_get_int(s_trFilter.Common.RenameWks, 0);
		chkFileNameToWksLabel.Check = tree_node_get_int(s_trFilter.Common.FileNameToWksLabel, 1);

		fuGetTargetWindow(s_trFilter, i, str);
		switch( i )
		{
		case EXIST_MATRIX:
			i = IDC_TARGET_MATRIX;
			break;
		case EXIST_WKS:
			i = IDC_TARGET_WKS;
			break;
		case EXIST_NONE:
			i = IDC_TARGET_WND_NONE;
			break;
		}
		pgSource.CheckRadioButton(IDC_TARGET_WKS, IDC_TARGET_WND_NONE, i);
		cbWksTemplate.SetCurSel(0);
		cbWksTemplate.SelectString(-1, str);

		Source_EnableTargetWindowCtrls();
		
		/// EJP 09-24-2003 v7.5706 QA70-4073.55 ADD_FILTER_DESCRIPTION
		str.Empty();
		fuGetDescription(s_trFilter, str);
		Edit ebDescrip = ImportWizDlg.GetItem(IDC_FILTER_DESCRIP, IDD_IW_SOURCE);
		ebDescrip.Text = str;
		/// end ADD_FILTER_DESCRIPTION
	}
}

//--------------------------------------------------------------------------
// Source_OnSelChangeFilter
//
// DialogBuilder calls this function when the selection in the filter
// combobox is changed.
//--------------------------------------------------------------------------
static BOOL	Source_OnSelChangeFilter(Control ctrl)
{
	Source_LoadCurSelFilter();
	return TRUE;
}

static void Source_UpdateButtons()
{
	int iDisable = 1; // Disable Next & Finish buttons
	
	if( IS_DATAFROM_CLIPBOARD )
	{
		string strClipboardText;
		if( GetClipboardText(strClipboardText) )
			iDisable = 0; // Enable Next & Finish buttons
	}
	else // Data is from a file
	{
		Edit editFileName = ImportWizDlg.GetItem(IDC_SOURCE_FILENAME, IDD_IW_SOURCE);
		string strPath = editFileName.Text;
		if( strPath.IsFile() ) // If not valid file name
		{
			iDisable = 0; // Enable Next & Finish buttons
		}
	}
	
	ImportWizDlg.Page.Pal = iDisable; 
}

static BOOL	Source_OnClickDisplayCompatibleFilters(Control ctrl)
{
	Source_UpdateFilterComboBox();
	return TRUE;
}

static int Source_FindFirstCompatibleFilter(int iFilterType, LPCSTR lpcszDataFile)
{
	string str, strFilter;
	string strDataPath;
	if( lpcszDataFile )
		strDataPath = GetFilePath(lpcszDataFile);
	ComboBox cbFilters = ImportWizDlg.GetItem(IDC_SOURCE_FILTER, IDD_IW_SOURCE);

	/// EJP 07-17-2003 v7.0627 QA70-4818 SAVE_FILTER_IN_WKS
	if( cbFilters.GetCount() <= 1 )
		return 0; // no filter
	cbFilters.GetLBText(1, str);
	if( 0 == str.CompareNoCase(SZ_IW_PAGE_FILTER) )
	{
		Page pgTarget(s_strActivePageName);
		if( fuIsFilterInPage(pgTarget, iFilterType, lpcszDataFile) )
			return 1; // use filter in page
	}
	/// end SAVE_FILTER_IN_WKS

	/// EJP 08-29-2003 v7.5680 AUTO_SELECT_ONLY_DATA_FOLDER_FILTERS
	/// This change will also cause Clipboard to auto select no filter.
	if( strDataPath.IsEmpty() )
		return 0; // no filter in data folder
	/// end AUTO_SELECT_ONLY_DATA_FOLDER_FILTERS

	for( int i = 1; i < cbFilters.GetCount(); i++ )
	{
		cbFilters.GetLBText(i, str);
		if( fuGetFilterFileNameFromListItem(str, strFilter, strDataPath) )
			/// EJP 09-02-2003 v7.5681 AUTO_SELECT_ONLY_DATA_FOLDER_FILTERS
			///if( fuIsApplicable(strFilter, lpcszDataFile, iFilterType) )
			if( 0 == strDataPath.CompareNoCase(GetFilePath(strFilter)) && fuIsApplicable(strFilter, lpcszDataFile, iFilterType) )
			/// end AUTO_SELECT_ONLY_DATA_FOLDER_FILTERS
				return i;
	}
	return 0; // Default
}

static void Source_UpdateFilterComboBoxSel(int iFilterType, LPCSTR lpcszDataFile)
{
	/// EJP 07-17-2003 v7.0627 QA70-4818 SAVE_FILTER_IN_WKS
	///int iSel = 0;
	///if( lpcszDataFile && *lpcszDataFile )
	///	iSel = Source_FindFirstCompatibleFilter(iFilterType, lpcszDataFile);
	int iSel = Source_FindFirstCompatibleFilter(iFilterType, lpcszDataFile);
	/// end SAVE_FILTER_IN_WKS
	ComboBox cbFilters = ImportWizDlg.GetItem(IDC_SOURCE_FILTER, IDD_IW_SOURCE);
	cbFilters.SetCurSel(iSel);
}

static void Source_UpdateFilterComboBoxList(int iFilterType, LPCSTR lpcszDataFile)
{
	StringArray saFilterFiles;
	fuGetFilterFiles(saFilterFiles, iFilterType, lpcszDataFile);
	
	StringArray saFilterList;
	fuGetFilterList(saFilterList, saFilterFiles);
	
	ComboBox cbFilters = ImportWizDlg.GetItem(IDC_SOURCE_FILTER, IDD_IW_SOURCE);
	cbFilters.ResetContent();
	cbFilters.AddString(IW_FILTER_NONE);

	/// EJP 07-17-2003 v7.0627 QA70-4818 SAVE_FILTER_IN_WKS
	Page pgTarget(s_strActivePageName);
	if( fuIsFilterInPage(pgTarget, iFilterType) )
		cbFilters.AddString(SZ_IW_PAGE_FILTER);
	/// end SAVE_FILTER_IN_WKS

	for( int i = 0; i < saFilterList.GetSize(); i++ )
		cbFilters.AddString(saFilterList[i]);
}

static void Source_UpdateFilterComboBox()
{
	// Get data type setting
	Control pgSource = ImportWizDlg.GetItem(IDD_IW_SOURCE);
	int iFilterType = pgSource.GetCheckedRadioButton(IDC_DATATYPE_ASCII, IDC_DATATYPE_USERDEF);
	iFilterType -= IDC_DATATYPE_ASCII;

	// Get data file name
	/*
	LPCSTR lpcszDataFile = NULL;
	Button chkCompatibleFilters = ImportWizDlg.GetItem(IDC_DISPLAY_ONLY_COMPATIBLE_CHK, IDD_IW_SOURCE);
	if( chkCompatibleFilters.Check )
	{
		if( IS_DATAFROM_FILE )
			lpcszDataFile = s_strDataFile;
	}
	*/
	string strDataFile;
	if( IS_DATAFROM_FILE )
	{
		Button chkCompatibleFilters = ImportWizDlg.GetItem(IDC_DISPLAY_ONLY_COMPATIBLE_CHK, IDD_IW_SOURCE);
		if( chkCompatibleFilters.Check )
			strDataFile = s_strDataFile;
		else
			strDataFile = GetFilePath(s_strDataFile);
	}

	// Save current filter selection
	/*
	string strFilter;
	ComboBox cbFilters = ImportWizDlg.GetItem(IDC_SOURCE_FILTER, IDD_IW_SOURCE);
	int iCurSel = cbFilters.GetCurSel();
	if( iCurSel < 0 )
		iCurSel = 0;
	cbFilters.GetLBText(iCurSel, strFilter);
	*/

	// Update list
	///Source_UpdateFilterComboBoxList(iFilterType, lpcszDataFile);
	Source_UpdateFilterComboBoxList(iFilterType, strDataFile);
	
	// Update selection
	///Source_UpdateFilterComboBoxSel(iFilterType, lpcszDataFile);
	Source_UpdateFilterComboBoxSel(iFilterType, strDataFile);
}

static void Source_LoadCurSelFilter()
{
	s_strFilter.Empty();
	
	Control pgSource = ImportWizDlg.GetItem(IDD_IW_SOURCE);
	int iDataType = pgSource.GetCheckedRadioButton(IDC_DATATYPE_ASCII, IDC_DATATYPE_USERDEF) - IDC_DATATYPE_ASCII;

	ComboBox cbFilter = ImportWizDlg.GetItem(IDC_SOURCE_FILTER, IDD_IW_SOURCE);
	/// EJP 07-17-2003 v7.0627 QA70-4818 SAVE_FILTER_IN_WKS
	if( 0 == cbFilter.Text.CompareNoCase(SZ_IW_PAGE_FILTER) )
	{
		Page pg(s_strActivePageName);
		fuLoadFilterFromPage(s_trFilter, pg, iDataType);
		UpdateImpStructFromTree();
		s_iSaveFilter = IDC_SAVE_FILTER_IN_WKS;
	}
	else
	{
		s_iSaveFilter = IDC_SAVE_FILTER_GLOBAL_RADIO;
	/// end SAVE_FILTER_IN_WKS
		if( cbFilter.Text.CompareNoCase(IW_FILTER_NONE) )
			fuGetFilterFileNameFromListItem(cbFilter.Text, s_strFilter, GetFilePath(s_strDataFile));
		iwLoadFilter(s_strFilter);
	
		if( s_strFilter.IsEmpty() ) // If no filter selected keep current Data Type setting
			/// EJP 10-27-2003 v7.5733 QA70-5238 DO_NOT_RESET_TARGET_WINDOW_TEMPLATE
			///s_trFilter.Type.nVal = iDataType;
			Source_UpdateFilter();
			/// end DO_NOT_RESET_TARGET_WINDOW_TEMPLATE
		
	/// EJP 07-18-2003 v7.0627 QA70-4818 SAVE_FILTER_IN_WKS
		else
		{
			string strDataPath = GetFilePath(s_strDataFile);
			if( 0 == strDataPath.CompareNoCase(GetFilePath(s_strFilter)) )
				s_iSaveFilter = IDC_SAVE_FILTER_DATA_FOLDER_RADIO;
		}
	}
	/// end SAVE_FILTER_IN_WKS

	Source_UpdateFilter(FALSE); // FALSE = filter to dialog
}

////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// ASCII Header Page
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////

static BOOL AscHeader_OnInit()
{
	ON_PAGE_CHECK_ASC_HEADER

	/// EJP 10-20-2003 v7.5726 QA70-5374 ALLOW_CHANGING_PREVIEW_FONT
	///RichEdit reAscPreview = ImportWizDlg.GetItem(IDC_HEADER_PREVIEW, IDD_AIW_HEADER);
	///reAscPreview.SetFont(SYSTEM_FIXED_FONT);
	///AscHdr_UpdatePreviewText();
	///reAscPreview.SetSel(0, 0); // Position cursor at top left of preview window
	iw_InitFontComboBox(IDC_ASC_PREVIEW_FONT, IDD_AIW_HEADER);
	AscHdr_UpdatePreviewText();
	/// end ALLOW_CHANGING_PREVIEW_FONT

	int nCheck;
	// If filter has Defined attribute (indicating it has been here before)
	if( fuGetHeaderParamDefined(s_trFilter, nCheck) )
		// Use parameter count to determine default check box state
		nCheck = (fuGetHeaderParamCount(s_trFilter) ? 1 : 0);
	else // no Defined attribute
		// Use header line count to determine default check box state
		nCheck = (ASCIMP_TOTAL_HEADER_LINES(s_ascimp) ? 1 : 0);
	if( nCheck )
		ENABLE_DEFINE_HDR_VAR;
	else
		DISABLE_DEFINE_HDR_VAR;
		
	return TRUE;
}

static BOOL AscHeader_OnActive()
{
	ON_PAGE_CHECK_ASC_HEADER

	/// EJP 10-20-2003 v7.5726 QA70-5374 ALLOW_CHANGING_PREVIEW_FONT
	RichEdit reHdr = ImportWizDlg.GetItem(IDC_HEADER_PREVIEW, IDD_AIW_HEADER);
	if( reHdr )
		reHdr.SetFont(IW_PREVIEW_FONT);
	/// end ALLOW_CHANGING_PREVIEW_FONT

	/// EJP 07-14-2003 v7.0624 SCAN_FOR_NUM_COLS_ON_CHANGE_HEADER_LINES
	s_iStartingNumHdrLines = ASCIMP_TOTAL_HEADER_LINES(s_ascimp);
	/// end SCAN_FOR_NUM_COLS_ON_CHANGE_HEADER_LINES
	
	AscHeader_Update();
	return TRUE;
}

static BOOL AscHeader_OnKillActive()
{
	ON_PAGE_CHECK_ASC_HEADER
	AscHeader_Update(FALSE); // FALSE = dlg to data

	/// EJP 07-14-2003 v7.0624 SCAN_FOR_NUM_COLS_ON_CHANGE_HEADER_LINES
	if( s_iStartingNumHdrLines != ASCIMP_TOTAL_HEADER_LINES(s_ascimp) )
		ENABLE_RESCAN_FOR_NUM_COLS;
	/// end SCAN_FOR_NUM_COLS_ON_CHANGE_HEADER_LINES
	return TRUE;
}

/// EJP 10-20-2003 v7.5726 QA70-5374 ALLOW_CHANGING_PREVIEW_FONT
static BOOL AscHdr_OnSelChangeFont(Control ctrl)
{
	ComboBox cbFonts(ctrl);
	if( !cbFonts )
		return FALSE;
	int i = cbFonts.GetCurSel();
	if( -1 == i )
		return FALSE;
	s_iPreviewFont = cbFonts.GetItemData(i);
	iw_SetRichEditFont(IDC_HEADER_PREVIEW, IDD_AIW_HEADER, s_iPreviewFont);
	AscHdr_UpdatePreviewColor();
	return TRUE;
}
/// end ALLOW_CHANGING_PREVIEW_FONT

//--------------------------------------------------------------------------
// Functions for handling number of header lines
//--------------------------------------------------------------------------
static BOOL AscHeader_OnChangeHeaderLines(Control ctrl)
{
	/// EJP 08-15-2003 v7.5662 CLEAN_HEADER_LINES_INPUT
	/*
	int iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo, iSkipRows;
	AscHeader_GetDialogSettings(iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo, iSkipRows);
	if( iHeaderLines < iColNameFrom )
		iColNameFrom = 0;
	if( iHeaderLines < iColLabelFrom )
		iColNameFrom = 0;

	/// EJP 06-11-2003 v7.0600 QA70-4520 SUPPORT_HUGE_HEADER_SIZES
	if( iHeaderLines >= IW_NUM_HEADER_PREVIEW_LINES )
	{
		IW_NUM_HEADER_PREVIEW_LINES = iHeaderLines + 5; // 5=to show some data lines
		AscHdr_UpdatePreviewText();
	}
	/// end SUPPORT_HUGE_HEADER_SIZES
		
	AscHeader_SetDialogSettings(iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo, iSkipRows);
	AscHeader_UpdatePreview(iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo, iSkipRows);
	AscHeader_SetAscImpStruct(iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo);
	*/
	int iHeaderLines = AscHdr_GetHeaderLines();
	if( iHeaderLines >= IW_NUM_HEADER_PREVIEW_LINES )
	{
		IW_NUM_HEADER_PREVIEW_LINES = iHeaderLines + 5; // 5=to show some data lines
		AscHdr_UpdatePreviewText();
	}
	AscHdr_DialogToASCIMP();
	AscHdr_EnableCtrls();
	AscHdr_UpdatePreviewColor();
	/// end CLEAN_HEADER_LINES_INPUT
	return TRUE;
}

static BOOL AscHeader_OnSelChangeHeaderLines(Control ctrl)
{
	ComboBox cmbHeaderLines(ctrl);
	int nCurSel = cmbHeaderLines.GetCurSel();
	string str;
	cmbHeaderLines.GetLBText(nCurSel, str);
	cmbHeaderLines.Text = str;
	return AscHeader_OnChangeHeaderLines(ctrl);
}

static BOOL AscHeader_OnRefreshHeaderLines()
{
	RichEdit reAscPreview = ImportWizDlg.GetItem(IDC_HEADER_PREVIEW, IDD_AIW_HEADER);
	long nStartChar, nEndChar;
	reAscPreview.GetSel(nStartChar, nEndChar);
	int nLineNumber = reAscPreview.LineFromChar(nEndChar) + 1;
	
	string str;
	str.Format("%d", nLineNumber);
	ComboBox cmbxHeaderLines = ImportWizDlg.GetItem(IDC_IW_HEADER_LINES, IDD_AIW_HEADER);
	cmbxHeaderLines.Text = str;

	Control ctrl = cmbxHeaderLines;
	AscHeader_OnChangeHeaderLines(ctrl);
	reAscPreview.SetSel(nEndChar, nEndChar);

	return TRUE;
}

static int AscHdr_GetHeaderLines()
{
	ComboBox cbHeaderLines = ImportWizDlg.GetItem(IDC_IW_HEADER_LINES, IDD_AIW_HEADER);
	int iHeaderLines = atoi(cbHeaderLines.Text);
	if( iHeaderLines < 0 )
		iHeaderLines = 0;
	return iHeaderLines;
}

//--------------------------------------------------------------------------
// Functions for handling column names
//--------------------------------------------------------------------------
static BOOL AscHdr_OnEditChangeColNameFrom(Control ctrl)
{
	AscHdr_UpdatePreviewColor();
	AscHdr_EnableCtrls(); /// EJP 11-06-03 v7.5745 QA70-5412 SKIP_CHARS_FOR_COL_NAME_LABEL
	return TRUE;
}

static BOOL AscHdr_OnSelChangeColNameFrom(Control ctrl)
{
	ComboBox cb(ctrl);
	int nCurSel = cb.GetCurSel();
	string str;
	cb.GetLBText(nCurSel, str);
	cb.Text = str;
	AscHdr_UpdatePreviewColor();
	AscHdr_EnableCtrls(); /// EJP 11-06-03 v7.5745 QA70-5412 SKIP_CHARS_FOR_COL_NAME_LABEL
	return TRUE;
}

static BOOL AscHeader_OnTBClickRefreshColNameFrom()
{
	RichEdit reAscPreview = ImportWizDlg.GetItem(IDC_HEADER_PREVIEW, IDD_AIW_HEADER);
	long nStartChar, nEndChar;
	reAscPreview.GetSel(nStartChar, nEndChar);
	int nLineNumber = reAscPreview.LineFromChar(nStartChar) + 1;

	string str;
	str.Format("%d", nLineNumber);
	ComboBox cmbxColNameFrom = ImportWizDlg.GetItem(IDC_IW_COL_NAME_FROM, IDD_AIW_HEADER);
	cmbxColNameFrom.Text = str;

	/// EJP 08-15-2003 v7.5662 CLEAN_HEADER_LINES_INPUT
	/*
	/// JCG 06/15/03 QA70-4575 v7.0610 SUB_ITEM_62
	/// AscHeader_OnChangeColNameFromLabelRange(cmbxColNameFrom);
	// Here, can not call an event handler from another one 
	AscHeader_OnUpdataColNameFromLabelSettings();
	// end SUB_ITEM_62
	
	reAscPreview.SetSel(nEndChar, nEndChar);
	*/
	AscHdr_UpdatePreviewColor();
	/// end CLEAN_HEADER_LINES_INPUT
	return TRUE;
}

static int AscHdr_GetColNameFrom()
{
	ComboBox cbColNameFrom = ImportWizDlg.GetItem(IDC_IW_COL_NAME_FROM, IDD_AIW_HEADER);
	int iColNameFrom = atoi(cbColNameFrom.Text);
	if( iColNameFrom < 0 ) // if user setting less than zero
		iColNameFrom = 0; // change user setting to zero (none)
	return iColNameFrom - 1; // minus 1 for zero based line index, or (-1) for none
}

//--------------------------------------------------------------------------
// Functions for handling column labels
//--------------------------------------------------------------------------
static BOOL AscHdr_OnEditChangeColLabelFrom(Control ctrl)
{
	AscHdr_EnableCtrls();
	AscHdr_UpdatePreviewColor();
	return TRUE;
}

static BOOL AscHdr_OnSelChangeColLabelFrom(Control ctrl)
{
	ComboBox cb(ctrl);
	int nCurSel = cb.GetCurSel();
	string str;
	cb.GetLBText(nCurSel, str);
	cb.Text = str;
	AscHdr_EnableCtrls();
	AscHdr_UpdatePreviewColor();
	return TRUE;
}

static BOOL AscHeader_OnRefreshColLabelFrom()
{
	RichEdit reAscPreview = ImportWizDlg.GetItem(IDC_HEADER_PREVIEW, IDD_AIW_HEADER);
	long nStartChar, nEndChar;
	reAscPreview.GetSel(nStartChar, nEndChar);
	int nLineNumber = reAscPreview.LineFromChar(nEndChar) + 1;

	/// EJP 08-15-2003 v7.5662 CLEAN_HEADER_LINES_INPUT
	/*	
	/// JCG 05/28/03 v7.0540 HOOK_COMBO_BOX	
	///	string str;
	///	str.Format("%d", nLineNumber);
	///	ComboBox cmbxColLabelFrom = ImportWizDlg.GetItem(IDC_IW_COL_LABEL_FROM, IDD_AIW_HEADER);
	///	cmbxColLabelFrom.Text = str;
	///
	///	Control ctrl = cmbxColLabelFrom;
	///	AscHeader_OnChangeColNameFromLabelRange(ctrl);
	///	reAscPreview.SetSel(nEndChar, nEndChar);
	//
#define UI_LINEFROMCHAR(_re,_char) (_re.LineFromChar(_char) + 1)
	string str;
	str.Format("%d", UI_LINEFROMCHAR(reAscPreview, nStartChar)); // UI Index is 1 based, plus 1
	ComboBox cmbxColLabelFrom = ImportWizDlg.GetItem(IDC_IW_COL_LABEL_FROM, IDD_AIW_HEADER);
	cmbxColLabelFrom.Text = str;
	
	ComboBox cmbxColLabelTo = ImportWizDlg.GetItem(IDC_HDR_LABEL_TO, IDD_AIW_HEADER);
	str.Format("%d", UI_LINEFROMCHAR(reAscPreview, nEndChar)); // UI Index is 1 based, plus 1
	cmbxColLabelTo.Text = str;
	
///	AscHeader_OnChangeColNameFromLabelRange(cmbxColLabelFrom);
	AscHeader_OnUpdataColNameFromLabelSettings();
	
	reAscPreview.SetSel(nEndChar, nEndChar);
	/// end HOOK_COMBO_BOX	
	*/
	if( nStartChar != nEndChar && nEndChar == reAscPreview.LineIndex(nLineNumber - 1) )
		nLineNumber--;
	string str;
	str.Format("%d", nLineNumber);
	ComboBox cmbxColLabelTo = ImportWizDlg.GetItem(IDC_HDR_LABEL_TO, IDD_AIW_HEADER);
	cmbxColLabelTo.Text = str;
	
	nLineNumber = reAscPreview.LineFromChar(nStartChar) + 1;
	str.Format("%d", nLineNumber);
	ComboBox cmbxColLabelFrom = ImportWizDlg.GetItem(IDC_IW_COL_LABEL_FROM, IDD_AIW_HEADER);
	cmbxColLabelFrom.Text = str;
	AscHdr_EnableCtrls();
	AscHdr_UpdatePreviewColor();
	/// end CLEAN_HEADER_LINES_INPUT

	return TRUE;
}

static bool AscHdr_GetColLabelLines(int &iColLabelFrom, int &iColLabelTo)
{
	ComboBox cbColLabelFrom = ImportWizDlg.GetItem(IDC_IW_COL_LABEL_FROM, IDD_AIW_HEADER);
	ComboBox cbColLabelTo = ImportWizDlg.GetItem(IDC_HDR_LABEL_TO, IDD_AIW_HEADER);

	if( !cbColLabelFrom || !cbColLabelTo )
		return false;
	
	iColLabelFrom = atoi(cbColLabelFrom.Text);
	if( iColLabelFrom < 0 ) // if user setting less than zero
		iColLabelFrom = 0; // change user setting to zero (none)

	iColLabelTo = atoi(cbColLabelTo.Text);
	if( iColLabelTo < 0 ) // if user setting less than zero
		iColLabelTo = 0; // change user setting to zero (none)

	iColLabelFrom--; // minus 1 for zero based line index, or (-1) for none
	iColLabelTo--; // minus 1 for zero based line index, or (-1) for none
	return true;
}

//--------------------------------------------------------------------------
// Functions for handling lines to save
//--------------------------------------------------------------------------
static BOOL AscHdr_OnSelChangeSaveFirstLine(Control ctrl)
{
	ComboBox cbFirstLine(ctrl);
	ComboBox cbLastLine = ImportWizDlg.GetItem(IDC_HDR_SAVE_TO, IDD_AIW_HEADER);
	int iSel = cbFirstLine.GetCurSel();
	string str;
	cbFirstLine.GetLBText(iSel, str);
	int iFirstLine, iNumLines;
	AscHdr_GetSaveLines(iFirstLine, iNumLines);
	if( 0 == str.CompareNoCase(SZ_IW_NONE) )
	{
		iFirstLine = 0;
		iNumLines = 0;
		cbLastLine.Enable = 0;
	}
	else if( 0 == str.CompareNoCase(SZ_IW_ALL) )
	{
		iFirstLine = 0;
		iNumLines = AscHdr_GetHeaderLines();
		cbLastLine.Enable = 0;
	}
	else
	{
		iFirstLine = atoi(str);
		cbLastLine.Enable = 1;
	}
	
	/// JCG 05/28/03 v7.0540 HOOK_COMBO_BOX	
	/// AscHdr_SetSaveLines(iFirstLine, iNumLines);
	// shouldn't update the combobox value.
	/// end HOOK_COMBO_BOX	
	
	AscHdr_SetSaveLines(iFirstLine, iNumLines, false);
	return TRUE;
}

static BOOL AscHdr_OnEditChangeSaveFirstLine(Control ctrl)
{
	AscHdr_UpdateSaveLines(); // update filter
	return TRUE;
}

static void AscHdr_UpdateSaveLines(bool bUpdateData=true)
{
	int iFirstLine, iNumLines;
	if( bUpdateData )
	{
		AscHdr_GetSaveLines(iFirstLine, iNumLines); // from dialog
		AscHdr_SetSaveLines(iFirstLine, iNumLines, false); // to filter
	}
	else
	{
		AscHdr_GetSaveLines(iFirstLine, iNumLines, false); // from filter
		AscHdr_SetSaveLines(iFirstLine, iNumLines); // to dialog
	}
}

static void AscHdr_GetSaveLines(int &iFirstLine, int &iNumLines, bool bFromDlg=true)
{
	int iLastLine;
	string str;
	
	if( bFromDlg )
	{
		ComboBox cbFirstLine = ImportWizDlg.GetItem(IDC_HDR_SAVE_FROM, IDD_AIW_HEADER);
		ComboBox cbLastLine = ImportWizDlg.GetItem(IDC_HDR_SAVE_TO, IDD_AIW_HEADER);

		str = cbFirstLine.Text;
		if( 0 == str.CompareNoCase(SZ_IW_ALL) )
		{
			iFirstLine = 0;
			iNumLines = ASCIMP_TOTAL_HEADER_LINES(s_ascimp);
			return;
		}
		if( 0 == str.CompareNoCase(SZ_IW_NONE) )
		{
			iFirstLine = 0;
			iNumLines = 0; // none
			return;
		}
		iFirstLine = atoi(str);
		if( iFirstLine < 1 )
			iFirstLine = 1;

		str = cbLastLine.Text;
		if( 0 == str.CompareNoCase(SZ_IW_END) )
		{
			iNumLines = ASCIMP_TOTAL_HEADER_LINES(s_ascimp) - iFirstLine;
			return;
		}
		iLastLine = atoi(str);
		if( iLastLine < 1 || iLastLine < iFirstLine )
			iLastLine = iFirstLine;

		iFirstLine--;
		iNumLines = iLastLine - iFirstLine;
	}
	else // from filter
	{
		if( !fuGetHdrSave(s_trFilter, iFirstLine, iNumLines) )
		{
			iFirstLine = 0;
			iNumLines = ASCIMP_TOTAL_HEADER_LINES(s_ascimp);
			fuSetHdrSave(s_trFilter, iFirstLine, iNumLines);
		}
	}
}

static void AscHdr_SetSaveLines(int iFirstLine, int iNumLines, bool bToDlg=true)
{
	if( bToDlg )
	{
		string str;
		ComboBox cbFirstLine = ImportWizDlg.GetItem(IDC_HDR_SAVE_FROM, IDD_AIW_HEADER);
		ComboBox cbLastLine = ImportWizDlg.GetItem(IDC_HDR_SAVE_TO, IDD_AIW_HEADER);
		
		if( iNumLines < 1 )
		{
			cbLastLine.Text = SZ_IW_END;
			cbLastLine.Enable = 0;
			str = SZ_IW_NONE;
		}
		else
		{
			str.Format("%d", iFirstLine + iNumLines);
			cbLastLine.Text = str;
			cbLastLine.Enable = 1;
			str.Format("%d", iFirstLine + 1);
		}
		cbFirstLine.Text = str;
	}
	else // to filter
	{
		fuSetHdrSave(s_trFilter, iFirstLine, iNumLines);
	}
}

//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
static BOOL	AscHeader_OnClickDefineVar(Control ctrl)
{
	Button chkDefineVar(ctrl);
	if( chkDefineVar.Check )
		ENABLE_DEFINE_HDR_VAR;
	else
		DISABLE_DEFINE_HDR_VAR;
	return TRUE;
}

/// EJP 10-27-03 v7.5733 QA70-5412 SKIP_CHARS_FOR_COL_NAME_LABEL
static BOOL AscHdr_OnEditChangeNameOffset(Control ctrl)
{
	ComboBox cbOffset(ctrl);
	if( !cbOffset )
		return FALSE;
	s_ascimp.iLabelSkipChars = atoi(cbOffset.Text);
	if( s_ascimp.iLabelSkipChars < 0 )
		s_ascimp.iLabelSkipChars = 0;
	AscHdr_UpdatePreviewColor();
	return TRUE;
}

static BOOL AscHdr_OnSelChangeNameOffset(Control ctrl)
{
	ComboBox cbOffset(ctrl);
	if( !cbOffset )
		return FALSE;
	int iCurSel = cbOffset.GetCurSel();
	if( iCurSel == -1 )
		return FALSE;
	string strCurSel;
	cbOffset.GetLBText(iCurSel, strCurSel);
	s_ascimp.iLabelSkipChars = atoi(strCurSel);
	if( s_ascimp.iLabelSkipChars < 0 )
		s_ascimp.iLabelSkipChars = 0;
	AscHdr_UpdatePreviewColor();
	return TRUE;
}
/// end SKIP_CHARS_FOR_COL_NAME_LABEL

static void AscHeader_Update(BOOL bDataToDlg=TRUE)
{
	int iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo;
	int iFirstLine, iNumLines;

	/// EJP 10-24-03 v7.5730 QA70-5412 SKIP_CHARS_FOR_COL_NAME_LABEL
	string str;
	ComboBox cbColNameLabelOffset = ImportWizDlg.GetItem(IDC_NAME_LABEL_CHAR_OFFSET, IDD_AIW_HEADER);
	/// end SKIP_CHARS_FOR_COL_NAME_LABEL

	if( bDataToDlg )
	{
		AscHdr_GetFromASCIMP(iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo);
		AscHdr_SetToDialog(iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo);
		AscHdr_EnableCtrls();
		AscHdr_UpdatePreviewColor();

		AscHdr_GetSaveLines(iFirstLine, iNumLines, false); // false = get data
		AscHdr_SetSaveLines(iFirstLine, iNumLines, true); // true = set dialog
		
		Button chkDefineVar = ImportWizDlg.GetItem(IDC_HDRPARAM_DEFINEVAR, IDD_AIW_HEADER);
		chkDefineVar.Check = IS_DEFINE_HDR_VAR;
		
		/// EJP 10-24-03 v7.5730 QA70-5412 SKIP_CHARS_FOR_COL_NAME_LABEL
		str.Format("%d", s_ascimp.iLabelSkipChars);
		cbColNameLabelOffset.Text = str;
		/// end SKIP_CHARS_FOR_COL_NAME_LABEL
	}
	else
	{
		///AscHdr_GetFromDialog(iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo);
		///AscHdr_Check(iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo);
		///AscHdr_SetToASCIMP(iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo);
		AscHdr_DialogToASCIMP();
		AscHdr_GetFromASCIMP(iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo);

		AscHdr_GetSaveLines(iFirstLine, iNumLines); // get from dlg
		if( iFirstLine >= iHeaderLines )
		{
			iFirstLine = 0;
			iNumLines = 0;
		}
		if( (iFirstLine + iNumLines - 1) >= iHeaderLines )
			iNumLines = iHeaderLines - iFirstLine;
		AscHdr_SetSaveLines(iFirstLine, iNumLines, false); // set tree
	}
}

static void AscHdr_GetFromDialog(int& iHeaderLines, int& iColNameFrom, int& iColLabelFrom, int& iColLabelTo)
{
	iHeaderLines = AscHdr_GetHeaderLines();
	AscHdr_GetColLabelLines(iColLabelFrom, iColLabelTo);
	iColNameFrom = AscHdr_GetColNameFrom();
}

static void AscHdr_SetToDialog(int iHeaderLines, int iColNameFrom, int iColLabelFrom, int iColLabelTo)
{
	string str, str2;

	////////// Header Lines

	str.Format("%d", iHeaderLines);
	ComboBox cbHeaderLines = ImportWizDlg.GetItem(IDC_IW_HEADER_LINES, IDD_AIW_HEADER);
	cbHeaderLines.Text = str;
	
	////////// Column Names
	
	ComboBox cbColNameFrom = ImportWizDlg.GetItem(IDC_IW_COL_NAME_FROM, IDD_AIW_HEADER);
	if( iColNameFrom >= 0 )
		str.Format("%d", iColNameFrom + 1);
	else
		str = SZ_IW_NONE;
	cbColNameFrom.Text = str;
	
	////////// Column Labels
	
	ComboBox cbColLabelFrom = ImportWizDlg.GetItem(IDC_IW_COL_LABEL_FROM, IDD_AIW_HEADER);
	ComboBox cbColLabelTo = ImportWizDlg.GetItem(IDC_HDR_LABEL_TO, IDD_AIW_HEADER);

	if( iColLabelFrom >= 0 )
	{
		str.Format("%d", iColLabelFrom + 1);
		if( iColLabelFrom >= 0 )
			str2.Format("%d", iColLabelTo + 1);
		else
			str2 = SZ_IW_END;
	}
	else
	{
		str = SZ_IW_NONE;
		str2 = SZ_IW_END;
	}
	cbColLabelFrom.Text = str;
	cbColLabelTo.Text = str2;
}

static void AscHdr_GetFromASCIMP(int& iHeaderLines, int& iColNameFrom, int& iColLabelFrom, int& iColLabelTo)
{
	iHeaderLines = s_ascimp.iHeaderLines + s_ascimp.iSubHeaderLines;
	
	if( s_ascimp.iRenameCols )
		iColNameFrom = iHeaderLines - s_ascimp.iRenameCols;
	else
		iColNameFrom = -1;

	if( s_ascimp.iLabels )
	{
		iColLabelFrom = iHeaderLines - s_ascimp.iSubHeaderLines;
		iColLabelTo = s_ascimp.iMaxLabels + (iColLabelFrom - 1);
	}
	else
	{
		iColLabelFrom = -1;
		iColLabelTo = -1;
	}
}

static void AscHdr_SetToASCIMP(int iHeaderLines, int iColNameFrom, int iColLabelFrom, int iColLabelTo)
{
	s_ascimp.iAutoSubHeaderLines = 0;
	
	if( iColNameFrom >= 0 )
		s_ascimp.iRenameCols = iHeaderLines - iColNameFrom;
	else
		s_ascimp.iRenameCols = 0;
	
	if( iColLabelFrom >= 0 )
	{
		s_ascimp.iSubHeaderLines = iHeaderLines - iColLabelFrom;
		s_ascimp.iMaxLabels = iColLabelTo - iColLabelFrom + 1;
		s_ascimp.iLabels = 1;
	}
	else
	{
		s_ascimp.iSubHeaderLines = 0;
		s_ascimp.iMaxLabels = 0;
		s_ascimp.iLabels = 0;
	}
	
	s_ascimp.iHeaderLines = iHeaderLines - s_ascimp.iSubHeaderLines;
}

static void AscHdr_DialogToASCIMP()
{
	int iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo;
	AscHdr_GetFromDialog(iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo);
	AscHdr_Check(iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo);
	AscHdr_SetToASCIMP(iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo);
}

static void AscHdr_Check(int& iHeaderLines, int& iColNameFrom, int& iColLabelFrom, int& iColLabelTo)
{
	if( iHeaderLines )
	{
		if( iColLabelFrom > iColLabelTo )
		{
			int i = iColLabelFrom;
			iColLabelFrom = iColLabelTo;
			iColLabelTo = i;
		}
		if( iColLabelFrom >= iHeaderLines )
		{
			iColLabelFrom = -1;
			iColLabelTo = -1;
		}
		else if( iColLabelTo < 0 || iColLabelTo >= iHeaderLines )
		{
			iColLabelTo = iHeaderLines - 1;
		}
		
		if( iColNameFrom >= iHeaderLines )
			iColNameFrom = -1;
	}
	else // no header lines means no column names and no labels
	{
		iColNameFrom = -1;
		iColLabelFrom = -1;
		iColLabelTo = -1;
	}
}

static void AscHdr_EnableCtrls()
{
	int iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo;
	AscHdr_GetFromDialog(iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo);
	bool bHeaderLines = (iHeaderLines > 0);

	ComboBox cbColNameFrom = ImportWizDlg.GetItem(IDC_IW_COL_NAME_FROM, IDD_AIW_HEADER);
	Control btnColNameRefresh = ImportWizDlg.GetItem(IDC_IW_COL_NAME_TB, IDD_AIW_HEADER);
	ComboBox cbColLabelFrom = ImportWizDlg.GetItem(IDC_IW_COL_LABEL_FROM, IDD_AIW_HEADER);
	ComboBox cbColLabelTo = ImportWizDlg.GetItem(IDC_HDR_LABEL_TO, IDD_AIW_HEADER);
	Control btnColLabelRefresh = ImportWizDlg.GetItem(IDC_IW_COL_LABEL_TB, IDD_AIW_HEADER);

	cbColNameFrom.Enable = bHeaderLines;
	btnColNameRefresh.Enable = cbColNameFrom.Enable;
	cbColLabelFrom.Enable = bHeaderLines;
	cbColLabelTo.Enable = (cbColLabelFrom.Enable && iColLabelFrom >= 0);
	btnColLabelRefresh.Enable = cbColLabelFrom.Enable;

	int iFirstSaveLine, iNumSaveLines;
	AscHdr_GetSaveLines(iFirstSaveLine, iNumSaveLines);
	
	ComboBox cbFirstLine = ImportWizDlg.GetItem(IDC_HDR_SAVE_FROM, IDD_AIW_HEADER);
	ComboBox cbLastLine = ImportWizDlg.GetItem(IDC_HDR_SAVE_TO, IDD_AIW_HEADER);
	
	cbFirstLine.Enable = bHeaderLines;
	cbLastLine.Enable = (cbFirstLine.Enable && iNumSaveLines);
	
	/// EJP 11-06-03 v7.5745 QA70-5412 SKIP_CHARS_FOR_COL_NAME_LABEL
	ComboBox cbColNameLabelOffset = ImportWizDlg.GetItem(IDC_NAME_LABEL_CHAR_OFFSET, IDD_AIW_HEADER);
	if( cbColNameLabelOffset )
		cbColNameLabelOffset.Enable = (bHeaderLines && (iColNameFrom >= 0 || iColLabelFrom >= 0));
	/// end SKIP_CHARS_FOR_COL_NAME_LABEL
}

static void AscHdr_UpdatePreviewColor()
{
	RichEdit rePreview = ImportWizDlg.GetItem(IDC_HEADER_PREVIEW, IDD_AIW_HEADER);
	if( !rePreview )
		return;

	// Save selection
	long nSelStartChar, nSelEndChar;
	rePreview.GetSel(nSelStartChar, nSelEndChar);
	
	long nStartChar, nEndChar;

	int iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo;
	AscHdr_GetFromDialog(iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo);
	AscHdr_Check(iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo);

	// If there are header lines then color them
	if( iHeaderLines )
	{
		nEndChar = rePreview.LineIndex(iHeaderLines);
		rePreview.SetTextColor(0, nEndChar, AIW_COLOR_HEADER_LINES);
	
		// If there are label lines then color them
		if( iColLabelFrom >= 0 )
		{
			if( iColLabelTo < 0 )
				iColLabelTo = iHeaderLines;
	
			/// EJP 10-27-03 v7.5733 QA70-5412 SKIP_CHARS_FOR_COL_NAME_LABEL
			///nStartChar = rePreview.LineIndex(iColLabelFrom);
			///nEndChar = rePreview.LineIndex(iColLabelTo + 1);
			///rePreview.SetTextColor(nStartChar, nEndChar, AIW_COLOR_COL_LABEL);
			for( int iLine = iColLabelFrom; iLine <= iColLabelTo; iLine++ )
			{
				nStartChar = rePreview.LineIndex(iLine) + s_ascimp.iLabelSkipChars;
				nEndChar = rePreview.LineIndex(iLine + 1);
				if( nStartChar <= nEndChar )
					rePreview.SetTextColor(nStartChar, nEndChar, AIW_COLOR_COL_LABEL);
			}
			/// end SKIP_CHARS_FOR_COL_NAME_LABEL

		}
	
		// If there is a line for column names then color it
		if( iColNameFrom >= 0 )
		{
			/// EJP 10-27-03 v7.5733 QA70-5412 SKIP_CHARS_FOR_COL_NAME_LABEL
			///nStartChar = rePreview.LineIndex(iColNameFrom);
			///nEndChar = rePreview.LineIndex(iColNameFrom + 1);
			///rePreview.SetTextColor(nStartChar, nEndChar, AIW_COLOR_COL_NAME);
			nStartChar = rePreview.LineIndex(iColNameFrom) + s_ascimp.iLabelSkipChars;
			nEndChar = rePreview.LineIndex(iColNameFrom + 1);
			if( nStartChar <= nEndChar )
				rePreview.SetTextColor(nStartChar, nEndChar, AIW_COLOR_COL_NAME);
			/// end SKIP_CHARS_FOR_COL_NAME_LABEL
		}

		// Get char index of first data line
		nStartChar = rePreview.LineIndex(iHeaderLines);
	}
	else
		nStartChar = 0; // first char is first data line
	nEndChar = rePreview.LineIndex(IW_NUM_HEADER_PREVIEW_LINES);
	
	// Color data lines
	rePreview.SetTextColor(nStartChar, nEndChar, AIW_COLOR_DATA_LINES);

	// Restore selection
	rePreview.SetSel(nSelStartChar, nSelEndChar);
}

static void AscHdr_UpdatePreviewText()
{
	string str;

	/// EJP 08-29-2003 v7.5680 TRUNC_LONG_LINES_IN_HEADER_PREVIEW
	/// This code may change again if we get the RichEdit control to stop wordwrapping.
	///if( LoadTextFile(str, s_strDataFile, IW_NUM_HEADER_PREVIEW_LINES) )
	///	iwDataFileErrorMsgBox();
	StringArray saLines;
	ReadFileLines(saLines, s_strDataFile, IW_NUM_HEADER_PREVIEW_LINES);
	for( int iLine = 0; iLine < saLines.GetSize(); iLine++ )
	{
		int iLineLen = saLines[iLine].GetLength();
		if( iLineLen > IW_PREVIEW_LINE_MAX_LEN )
			saLines[iLine].Delete(IW_PREVIEW_LINE_MAX_LEN, iLineLen - IW_PREVIEW_LINE_MAX_LEN);
///		printf("line %d trunc from %d to %d\n", iLine, iLineLen, saLines[iLine].GetLength());
		str += saLines[iLine];
		str += "\n";
	}
	str.Replace('\t', ' '); // Replace tabs with spaces
	/// end TRUNC_LONG_LINES_IN_HEADER_PREVIEW

	RichEdit reHdrPreview = ImportWizDlg.GetItem(IDC_HEADER_PREVIEW, IDD_AIW_HEADER);
	reHdrPreview.Text = str;
}

/// EJP 08-15-2003 v7.5662 CLEAN_HEADER_LINES_INPUT
#ifdef JUNK_CLEAN_HEADER_LINES_INPUT

//--------------------------------------------------------------------------
// AscHeader_UpdatePreview
//
// Support function to update the preview window.
//--------------------------------------------------------------------------
static BOOL AscHeader_UpdatePreview(int iHeaderLines, int iColNameFrom, int iColLabelFrom, int iColLabelTo, int iSkipRows)
{
	long nStartChar, nEndChar;
	COLORREF cr;
	RichEdit reAscPreview = ImportWizDlg.GetItem(IDC_HEADER_PREVIEW, IDD_AIW_HEADER);

	nStartChar = 0;
	nEndChar = reAscPreview.LineIndex(iHeaderLines);
	cr = AIW_COLOR_HEADER_LINES;
	reAscPreview.SetTextColor(nStartChar, nEndChar, cr);

	if( iColLabelFrom && iColLabelTo)
	{
		nStartChar = reAscPreview.LineIndex(iColLabelFrom - 1);
		/// JCG 05/28/03 v7.0540 HOOK_COMBO_BOX	
		//nEndChar = reAscPreview.LineIndex(iHeaderLines);
		nEndChar = reAscPreview.LineIndex(iColLabelTo);
		/// end HOOK_COMBO_BOX	
		cr = AIW_COLOR_COL_LABEL;
		reAscPreview.SetTextColor(nStartChar, nEndChar, cr);
	}

	if( iColNameFrom )
	{
		nStartChar = reAscPreview.LineIndex(iColNameFrom - 1);
		nEndChar = reAscPreview.LineIndex(iColNameFrom);
		cr = AIW_COLOR_COL_NAME;
		reAscPreview.SetTextColor(nStartChar, nEndChar, cr);
	}

	/// EJP 06-18-2003 QA70-4682 DATA_SELECTION_UI_CHANGES
	/*
	if( iSkipRows )
	{
		for( int ii = iHeaderLines; ii < IW_NUM_HEADER_PREVIEW_LINES; ii++ )
		{
			nStartChar = reAscPreview.LineIndex(ii);
			nEndChar = reAscPreview.LineIndex(ii + 1);
			cr = AIW_COLOR_DATA_LINES;
			reAscPreview.SetTextColor(nStartChar, nEndChar, cr);
			nStartChar = nEndChar;
			ii += iSkipRows;
			ii = ii > IW_NUM_HEADER_PREVIEW_LINES ? IW_NUM_HEADER_PREVIEW_LINES : ii;
			nEndChar = reAscPreview.LineIndex(ii + 1);
			cr = AIW_COLOR_SKIP_LINES;
			reAscPreview.SetTextColor(nStartChar, nEndChar, cr);
		}
	}
	else
	{
		nStartChar = reAscPreview.LineIndex(iHeaderLines);
		nEndChar = reAscPreview.LineIndex(IW_NUM_HEADER_PREVIEW_LINES);
		cr = AIW_COLOR_DATA_LINES;
		reAscPreview.SetTextColor(nStartChar, nEndChar, cr);
	}
	*/
	nStartChar = reAscPreview.LineIndex(iHeaderLines);
	nEndChar = reAscPreview.LineIndex(IW_NUM_HEADER_PREVIEW_LINES);
	cr = AIW_COLOR_DATA_LINES;
	reAscPreview.SetTextColor(nStartChar, nEndChar, cr);
	/// end DATA_SELECTION_UI_CHANGES

	return TRUE;
}

static BOOL AscHdr_SetAscImpStruct(int iHeaderLines, int iColNameFrom, int iColLabelFrom, int iColLabelTo)
{
	s_ascimp.iAutoSubHeaderLines = 0;
	
	/// EJP 08-20-2003 v7.5668 CLEAN_HEADER_LINES_INPUT
	///if( iColNameFrom )
	///	s_ascimp.iRenameCols = iHeaderLines - iColNameFrom + 1;
	if( iColNameFrom >= 0 )
		s_ascimp.iRenameCols = iHeaderLines - iColNameFrom;
	/// end CLEAN_HEADER_LINES_INPUT
	else
		s_ascimp.iRenameCols = 0;
	
	/// EJP 08-20-2003 v7.5668 CLEAN_HEADER_LINES_INPUT
	/*
	if( iColLabelFrom )
	{
		s_ascimp.iSubHeaderLines = iHeaderLines - iColLabelFrom + 1;

		/// JCG 05/28/03 v7.0540 HOOK_COMBO_BOX			
		///s_ascimp.iMaxLabels = s_ascimp.iSubHeaderLines;
		s_ascimp.iMaxLabels = iColLabelTo - iColLabelFrom + 1;
		/// end HOOK_COMBO_BOX			
	*/
	if( iColLabelFrom >= 0 )
	{
		s_ascimp.iSubHeaderLines = iHeaderLines - iColLabelFrom;
		s_ascimp.iMaxLabels = iColLabelTo - iColLabelFrom + 1;
	/// end CLEAN_HEADER_LINES_INPUT

		s_ascimp.iLabels = 1;
	}
	else
	{
		s_ascimp.iSubHeaderLines = 0;
		s_ascimp.iMaxLabels = 0;
		s_ascimp.iLabels = 0;
	}
	
	s_ascimp.iHeaderLines = iHeaderLines - s_ascimp.iSubHeaderLines;
	return TRUE;
}

static void AscHeader_SetDialogSettings(int iHeaderLines, int iColNameFrom, int iColLabelFrom, int iColLabelTo, int iSkipRows)
{
	string str;
	
//	str.Format("%d", iHeaderLines);
//	ComboBox cbHeaderLines = ImportWizDlg.GetItem(IDC_IW_HEADER_LINES, IDD_AIW_HEADER);
//	cbHeaderLines.Text = str;

	// JCG 06/09/03 v7.0599 LABEL_LINE_COMBOS_INIT_TO_NONE_IF_NO_HEADERLINES
	// EParent says: the Labels From and To boxes are not initialized very well.  
	// when there are no header lines then they should be init to <none>.  
	// see "Save header lines" comboboxes.
	// end LABEL_LINE_COMBOS_INIT_TO_NONE_IF_NO_HEADERLINES

	ComboBox cbColNameFrom = ImportWizDlg.GetItem(IDC_IW_COL_NAME_FROM, IDD_AIW_HEADER);
	if( iColNameFrom > 0 )
	{
		str.Format("%d", iColNameFrom);
		cbColNameFrom.Text = str;
	}
	else
		cbColNameFrom.SetCurSel(0);

	ComboBox cbColLabelFrom = ImportWizDlg.GetItem(IDC_IW_COL_LABEL_FROM, IDD_AIW_HEADER);

	// JCG 06/09/03 v7.0599 LABEL_LINE_COMBOS_INIT_TO_NONE_IF_NO_HEADERLINES
	/// if( iColLabelFrom > 0 )
	if( iColLabelFrom > 0 && 0 != iHeaderLines )  
	// end LABEL_LINE_COMBOS_INIT_TO_NONE_IF_NO_HEADERLINES
	{
		str.Format("%d", iColLabelFrom);
		cbColLabelFrom.Text = str;
	}
	else
		cbColLabelFrom.SetCurSel(0);
	// end LABEL_LINE_COMBOS_INIT_TO_NONE_IF_NO_HEADERLINES

	/// JCG 05/28/03 v7.0540 HOOK_COMBO_BOX			
	ComboBox cbColLabelTo = ImportWizDlg.GetItem(IDC_HDR_LABEL_TO, IDD_AIW_HEADER);

	// JCG 06/09/03 v7.0599 LABEL_LINE_COMBOS_INIT_TO_NONE_IF_NO_HEADERLINES
	/// if( iColLabelTo > 0 )
	if( iColLabelTo > 0 && 0 != iHeaderLines)
	// end LABEL_LINE_COMBOS_INIT_TO_NONE_IF_NO_HEADERLINES
	{
		str.Format("%d", iColLabelTo);
		cbColLabelTo.Text = str;
	}
	else
	{
		cbColLabelTo.SetCurSel(0);
		// JCG 06/09/03 v7.0599 LABEL_LINE_COMBOS_INIT_TO_NONE_IF_NO_HEADERLINES
		cbColLabelTo.Enable = 0; 
		// end LABEL_LINE_COMBOS_INIT_TO_NONE_IF_NO_HEADERLINES
	}
	/// end HOOK_COMBO_BOX	
	
	/// EJP 06-18-2003 QA70-4682 DATA_SELECTION_UI_CHANGES
	/*
	str.Format("%d", iSkipRows);
	Edit ebSkipRows = ImportWizDlg.GetItem(IDC_IW_SKIP_ROWS, IDD_AIW_HEADER);
	ebSkipRows.Text = str;
	*/
	/// end DATA_SELECTION_UI_CHANGES
}

//--------------------------------------------------------------------------
// AscHeader_GetDialogSettings
//
// Support function to get the HeaderLines, ColNameFrom, and ColLabelFrom
// values from the ImportWizDlg dialog.
//--------------------------------------------------------------------------
static BOOL AscHeader_GetDialogSettings(int& iHeaderLines, int& iColNameFrom, int& iColLabelFrom, int& iColLabelTo, int& iSkipRows)
{
	///ComboBox cmbxHeaderLines = ImportWizDlg.GetItem(IDC_IW_HEADER_LINES, IDD_AIW_HEADER);
	///iHeaderLines = atoi(cmbxHeaderLines.Text);
	///if( iHeaderLines < 0 )
	///	iHeaderLines = 0;
	iHeaderLines = AscHdr_GetHeaderLines();

	/*
	ComboBox cmbxColNameFrom = ImportWizDlg.GetItem(IDC_IW_COL_NAME_FROM, IDD_AIW_HEADER);
	iColNameFrom = atoi(cmbxColNameFrom.Text);
	if( iColNameFrom < 0 )
		iColNameFrom = 0;

	ComboBox cmbxColLabelFrom = ImportWizDlg.GetItem(IDC_IW_COL_LABEL_FROM, IDD_AIW_HEADER);
	iColLabelFrom = atoi(cmbxColLabelFrom.Text);
	if( iColLabelFrom < 0 )
		iColLabelFrom = 0;

	/// JCG 05/28/03 v7.0540 HOOK_COMBO_BOX	
	ComboBox cmbxColLabelTo = ImportWizDlg.GetItem(IDC_HDR_LABEL_TO, IDD_AIW_HEADER);
	iColLabelTo = atoi(cmbxColLabelTo.Text);
	if( iColLabelTo < 0 )
		iColLabelTo = 0;
	/// end HOOK_COMBO_BOX	
	*/
	iColNameFrom = AscHdr_GetColNameFrom();
	AscHdr_GetColLabelLines(iColLabelFrom, iColLabelTo);
	
	/// EJP 06-18-2003 QA70-4682 DATA_SELECTION_UI_CHANGES
	/*
	Edit ebxSkipRows = ImportWizDlg.GetItem(IDC_IW_SKIP_ROWS, IDD_AIW_HEADER);
	iSkipRows = atoi(ebxSkipRows.Text);
	if( iSkipRows < 0 )
		iSkipRows = 0;
	*/
	/// end DATA_SELECTION_UI_CHANGES

	return TRUE;
}

//--------------------------------------------------------------------------
// AscHeader_CheckHeaderLines
//
// Support function to check HeaderLines value when ColNameFrom and ColLabelFrom
// values are changed.
//--------------------------------------------------------------------------
static BOOL AscHeader_CheckHeaderLines(int& iHeaderLines, int iColNameFrom, int iColLabelFrom, int iColLabelTo )
{
	if( iHeaderLines < iColNameFrom || iHeaderLines < iColLabelTo )
	{
		iHeaderLines = (iColNameFrom > iColLabelTo ? iColNameFrom : iColLabelTo);
		string str;
		str.Format("%d", iHeaderLines);
		ComboBox cmbxHeaderLines = ImportWizDlg.GetItem(IDC_IW_HEADER_LINES, IDD_AIW_HEADER);
		cmbxHeaderLines.Text = str;
	}
	
	if(iColLabelFrom > iColLabelTo)
		iColLabelTo = iColLabelFrom;
	
	return TRUE;
}

/// JCG 06/15/03 QA70-4575 v7.0610 SUB_ITEM_62
static BOOL AscHeader_OnUpdataColNameFromLabelSettings()
{
	/*
	ComboBox cbLabelFrom= ImportWizDlg.GetItem(IDC_IW_COL_LABEL_FROM, IDD_AIW_HEADER);
	string str = cbLabelFrom.Text;

	ComboBox cbLabelTo= ImportWizDlg.GetItem(IDC_HDR_LABEL_TO, IDD_AIW_HEADER);

	if( 0 == str.CompareNoCase(SZ_IW_NONE) )
		cbLabelTo.Enable = 0;
	else
		cbLabelTo.Enable = 1;
	*/

	int iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo, iSkipRows;
	AscHeader_GetDialogSettings(iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo, iSkipRows);
	AscHeader_CheckHeaderLines(iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo);
	AscHdr_EnableLabelCtrls();
	AscHeader_UpdatePreview(iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo, iSkipRows);
	AscHeader_SetAscImpStruct(iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo);
	return TRUE;
}
/// end SUB_ITEM_62

//--------------------------------------------------------------------------
// AscHeader_OnChangeColNameFromLabelRange
//
// Dialog Builder calls this function when the user enters or selects a value
// in the ColNameFrom or ColLabelFrom combobox.
//--------------------------------------------------------------------------
static BOOL AscHeader_OnChangeColNameFromLabelRange(Control ctrl)
{
	/// JCG 06/15/03 QA70-4575 v7.0610 SUB_ITEM_62
	/*
	/// JCG 05/28/03 v7.0540 HOOK_COMBO_BOX	
	ComboBox cbLabelFrom= ImportWizDlg.GetItem(IDC_IW_COL_LABEL_FROM, IDD_AIW_HEADER);
	
	// Should use the window text.
	//int iSel = cbLabelFrom.GetCurSel();
	//string str;
	//cbLabelFrom.GetLBText(iSel, str);
	string str = cbLabelFrom.Text;
	ComboBox cbLabelTo= ImportWizDlg.GetItem(IDC_HDR_LABEL_TO, IDD_AIW_HEADER);

	if( 0 == str.CompareNoCase(SZ_IW_NONE) )
	{
		cbLabelTo.Enable = 0;
	}
	else
	{
		cbLabelTo.Enable = 1;
	}
	/// end HOOK_COMBO_BOX	
	

	int iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo, iSkipRows;
	AscHeader_GetDialogSettings(iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo, iSkipRows);
	AscHeader_CheckHeaderLines(iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo);
	AscHeader_UpdatePreview(iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo, iSkipRows);
	AscHeader_SetAscImpStruct(iHeaderLines, iColNameFrom, iColLabelFrom, iColLabelTo);
	return TRUE;
	*/
	return AscHeader_OnUpdataColNameFromLabelSettings();
	/// end SUB_ITEM_62
}

static BOOL AscHeader_OnSelChangeColNameLabel(Control ctrl)
{
	ComboBox cmbHeaderLines(ctrl);
	int nCurSel = cmbHeaderLines.GetCurSel();
	string str;
	cmbHeaderLines.GetLBText(nCurSel, str);
	cmbHeaderLines.Text = str;
	return AscHeader_OnChangeColNameFromLabelRange(ctrl);
}
#endif // JUNK_CLEAN_HEADER_LINES_INPUT
/// end CLEAN_HEADER_LINES_INPUT

////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// ASCII Header Variables Page
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////

enum {
	ASCHDR_VARCOL_NAME=0,
	ASCHDR_VARCOL_VALUE,
};

enum {
	DELIMITER_EQUAL=0,
	DELIMITER_COMMA,
	DELIMITER_TAB,
	DELIMITER_SPACE,
	DELIMITER_COLON,
	DELIMITER_OTHER
};

#define IS_ASCHDRVAR_SEPARATOR_SEL(_i) (DELIMITER_EQUAL <= _i && _i <= DELIMITER_COLON)
static string s_strAscHdrVarSeparators = "=,\t :";


static BOOL AscHdrVar_OnIsShow(DWORD dwPageID, DWORD lParam)
{
	return IS_SHOW_ASC_HEADER_PARAM_PAGE;
}

static BOOL AscHdrVar_OnInit()
{
	// No check, because we always want to setup the grid in case
	// user clicks Back and turns on "Define User Variables".
	///ON_PAGE_CHECK_ASC_HEADER_PARAM
	
	Control ctrlVar = ImportWizDlg.GetItem(IDC_HDRVAR_VARIABLES, IDD_AIW_HDRVAR);
	if( ctrlVar )
	{
		Object gridVar = ctrlVar.GetActiveXControl();
		if( gridVar )
		{
			gridVar.Editable = flexEDNone;
			gridVar.FixedCols = 0;
			gridVar.FixedRows = 1;
			gridVar.ExtendLastCol = TRUE;
			gridVar.AllowUserResizing = 1;
			gridVar.ColWidthMin = 4;
			gridVar.ColWidthMax = 0;
			
			gridVar.Rows = 1;
			gridVar.Cols = 2;
	
			gridVar.Row = 0; // 0=Column headers
			gridVar.Col = ASCHDR_VARCOL_NAME;
			gridVar.ColWidth(ASCHDR_VARCOL_NAME) = gridVar.ClientWidth * 0.5;
			gridVar.Text = IW_COLHDR_NAME;
			gridVar.Col = ASCHDR_VARCOL_VALUE;
			gridVar.Text = IW_COLHDR_VALUE;
			
			gridVar.AutoSizeMode = flexAutoSizeColWidth; /// EJP 10-08-2003 v7.5715 QA70-5289.3 UPDATE_COL_WIDTH
		}
	}

	return true;
}

static BOOL AscHdrVar_OnActive()
{
	ON_PAGE_CHECK_ASC_HEADER_PARAM

	string str;
	if( LoadTextFile(str, s_strDataFile, ASCIMP_TOTAL_HEADER_LINES(s_ascimp)) )
		iwDataFileErrorMsgBox();
	RichEdit reHdr = ImportWizDlg.GetItem(IDC_HDRVAR_HEADER, IDD_AIW_HDRVAR);
	if( reHdr )
	{
		reHdr.Text = str;
		/// EJP 10-20-2003 v7.5726 QA70-5374 ALLOW_CHANGING_PREVIEW_FONT
		///reHdr.SetFont(SYSTEM_FIXED_FONT);
		reHdr.SetFont(IW_PREVIEW_FONT);
		/// end ALLOW_CHANGING_PREVIEW_FONT
		reHdr.SetSel(0, 0);
	}

	/// EJP 10-23-2003 v7.5726 QA70-5374 ALLOW_CHANGING_PREVIEW_FONT
	iw_SetGridFont(IDC_HDRVAR_VARIABLES, IDD_AIW_HDRVAR, IW_PREVIEW_FONT);
	/// end ALLOW_CHANGING_PREVIEW_FONT
	
	AscHdrVar_Update(); // update dialog from filter
	return TRUE;
}

static BOOL	AscHdrVar_OnKillActive()
{
	ON_PAGE_CHECK_ASC_HEADER_PARAM
	AscHdrVar_Update(false); // false = update filter from dialog
	return true;
}

//--------------------------------------------------------------------------
static BOOL	AscHdrVar_OnSelChangeFirstLine(Control ctrl)
{
	ComboBox cbFirstLine(ctrl);
	int iSel = cbFirstLine.GetCurSel();
	ComboBox cbLastLine = ImportWizDlg.GetItem(IDC_HDRVAR_LASTLINE, IDD_AIW_HDRVAR);
	if( 0 == iSel || 1 == iSel )
		cbLastLine.Enable = 0;
	else
		cbLastLine.Enable = 1;
	return TRUE;
}

static int AscHdrVar_GetFirstLine()
{
	ComboBox cbFirstLine = ImportWizDlg.GetItem(IDC_HDRVAR_FIRSTLINE, IDD_AIW_HDRVAR);
	return atoi(cbFirstLine.Text);
}

/// EJP 08-04-2003 v7.0644 QA70-4896 ADD_REFRESH_BTN_TO_HDRVAR_PAGE
static BOOL AscHdrVar_OnClickRefresh()
{
	int iFrom, iTo, iSeparator;
	AscHdrVar_GetScanSettings(iFrom, iTo, iSeparator);
	
	RichEdit reHdrLines = ImportWizDlg.GetItem(IDC_HDRVAR_HEADER, IDD_AIW_HDRVAR);
	long nStartChar, nEndChar;
	reHdrLines.GetSel(nStartChar, nEndChar);
	
	iFrom = reHdrLines.LineFromChar(nStartChar);
	iTo = reHdrLines.LineFromChar(nEndChar);
	AscHdrVar_SetScanSettings(iFrom, iTo, iSeparator);

	return TRUE;
}
/// end ADD_REFRESH_BTN_TO_HDRVAR_PAGE

//--------------------------------------------------------------------------
static BOOL	AscHdrVar_OnSelChangeSeparator(Control ctrl)
{
	ComboBox cbSeparator(ctrl);
	int iSel = cbSeparator.GetCurSel();
	Edit ebOther = ImportWizDlg.GetItem(IDC_HDRVAR_OTHERSEPARATOR, IDD_AIW_HDRVAR);
	if( DELIMITER_OTHER == iSel )
		ebOther.Enable = 1;
	else
		ebOther.Enable = 0;
	return TRUE;
}

static BOOL	AscHdrVar_OnClickScan(Control ctrl)
{
	/// EJP 07-28-2003 v7.0637 QA70-4911 IMPROVE_HDR_VAR_SCAN
	///int iFrom, iTo, iSeparator;
	///AscHdrVar_GetScanSettings(iFrom, iTo, iSeparator);
	///AscHdrVar_UpdateGrid(iFrom, iTo, iSeparator);
	AscHdrVar_Update(false); // false = update filter
	AscHdrVar_UpdateGrid();
	/// end IMPROVE_HDR_VAR_SCAN
	return TRUE;
}

static void AscHdrVar_Update(bool bTreeToDlg=true)
{
	int iFirstLine, iLastLine, iSeparator;

	if( bTreeToDlg )
	{
		if( !fuGetHdrVarScan(s_trFilter, iFirstLine, iLastLine, iSeparator) )
		{
			iFirstLine = 0;
			iLastLine = ASCIMP_TOTAL_HEADER_LINES(s_ascimp) - 1;
			iSeparator = '\t';
			fuSetHdrVarScan(s_trFilter, iFirstLine, iLastLine, iSeparator); /// EJP 07-28-2003 v7.0637 QA70-4911 IMPROVE_HDR_VAR_SCAN
		}
		AscHdrVar_SetScanSettings(iFirstLine, iLastLine, iSeparator);
		/// EJP 07-28-2003 v7.0637 QA70-4911 IMPROVE_HDR_VAR_SCAN
		///AscHdrVar_UpdateGrid(iFirstLine, iLastLine, iSeparator);
		AscHdrVar_UpdateGrid();
		/// end IMPROVE_HDR_VAR_SCAN
	}
	else // update tree from dlg
	{
		AscHdrVar_GetScanSettings(iFirstLine, iLastLine, iSeparator);
		fuSetHdrVarScan(s_trFilter, iFirstLine, iLastLine, iSeparator);
	}
}

static void AscHdrVar_GetScanSettings(int &iFrom, int &iTo, int &iSeparator)
{
	ComboBox cbFrom = ImportWizDlg.GetItem(IDC_HDRVAR_FIRSTLINE, IDD_AIW_HDRVAR);
	ComboBox cbTo = ImportWizDlg.GetItem(IDC_HDRVAR_LASTLINE, IDD_AIW_HDRVAR);
	ComboBox cbSeparator = ImportWizDlg.GetItem(IDC_HDRVAR_SEPARATOR, IDD_AIW_HDRVAR);
	Edit ebOther = ImportWizDlg.GetItem(IDC_HDRVAR_OTHERSEPARATOR, IDD_AIW_HDRVAR);
	string str;
	
	iTo = atoi(cbTo.Text) - 1;
	if( iTo < 0 )
	{
		if( 0 == cbTo.Text.CompareNoCase(SZ_IW_END) )
			iTo = ASCIMP_TOTAL_HEADER_LINES(s_ascimp) - 1;
	}

	iFrom = atoi(cbFrom.Text) - 1;
	if( iFrom < 0 )
	{
		if( 0 == cbFrom.Text.CompareNoCase(SZ_IW_NONE) )
		{
			iFrom = -1;
			iTo = -1;
		}
		else if( 0 == cbFrom.Text.CompareNoCase(SZ_IW_ALL) )
		{
			iFrom = 0;
			iTo = ASCIMP_TOTAL_HEADER_LINES(s_ascimp) - 1;
		}
	}
	
	if( iFrom > iTo )
	{
		int iSwap = iFrom;
		iFrom = iTo;
		iTo = iSwap;
	}

	if( iFrom >= ASCIMP_TOTAL_HEADER_LINES(s_ascimp) )
		iFrom = ASCIMP_TOTAL_HEADER_LINES(s_ascimp) - 1;
	if( iTo >=  ASCIMP_TOTAL_HEADER_LINES(s_ascimp) )
		iTo = ASCIMP_TOTAL_HEADER_LINES(s_ascimp) - 1;
	
	iSeparator = cbSeparator.GetCurSel();
	if( -1 == iSeparator )
		iSeparator = '\t';
	else if( DELIMITER_OTHER == iSeparator )
	{
		if( ebOther.Text.IsEmpty() )
			iSeparator = '\t';
		else
			iSeparator = ebOther.Text.GetAt(0);
	}
	else
	{
		iSeparator = s_strAscHdrVarSeparators[iSeparator];
	}
}

static void AscHdrVar_SetScanSettings(int iFrom, int iTo, int iSeparator)
{
	ComboBox cbFrom = ImportWizDlg.GetItem(IDC_HDRVAR_FIRSTLINE, IDD_AIW_HDRVAR);
	ComboBox cbTo = ImportWizDlg.GetItem(IDC_HDRVAR_LASTLINE, IDD_AIW_HDRVAR);
	ComboBox cbSeparator = ImportWizDlg.GetItem(IDC_HDRVAR_SEPARATOR, IDD_AIW_HDRVAR);
	Edit ebOther = ImportWizDlg.GetItem(IDC_HDRVAR_OTHERSEPARATOR, IDD_AIW_HDRVAR);
	string str;

	if( iTo < iFrom || iTo == ASCIMP_TOTAL_HEADER_LINES(s_ascimp) - 1 )
		str = SZ_IW_END;
	else
		str.Format("%d", iTo + 1);
	cbTo.Text = str;
	cbTo.Enable = 1;

	if( iFrom == -1 )
		str = SZ_IW_NONE;
	else
	{
		if( iFrom == 0 && iTo == ASCIMP_TOTAL_HEADER_LINES(s_ascimp) - 1 )
		{
			str = SZ_IW_ALL;
			cbTo.Enable = 0;
		}
		else
			str.Format("%d", iFrom + 1);
	}
	cbFrom.Text = str;

	int i = s_strAscHdrVarSeparators.Find((char)iSeparator);
	if( i >= 0 )
	{
		cbSeparator.SetCurSel(i);
		ebOther.Enable = 0;
	}
	else // other
	{
		cbSeparator.SetCurSel(DELIMITER_OTHER);
		ebOther.Text.Format("%c", iSeparator);
		ebOther.Enable = 1;
	}
}

/// EJP 07-28-2003 v7.0637 QA70-4911 IMPROVE_HDR_VAR_SCAN
///static void AscHdrVar_UpdateGrid(int iFrom, int iTo, int iSeparator)
static void AscHdrVar_UpdateGrid()
/// end IMPROVE_HDR_VAR_SCAN
{
	/// EJP 07-28-2003 v7.0637 QA70-4911 IMPROVE_HDR_VAR_SCAN
	///StringArray saLines;
	///ReadFileLines(saLines, s_strDataFile, iTo - iFrom + 1, iFrom);
	/// end IMPROVE_HDR_VAR_SCAN
	
	Control ctrlVar = ImportWizDlg.GetItem(IDC_HDRVAR_VARIABLES, IDD_AIW_HDRVAR);
	if( !ctrlVar )
		return;
	Object gridVar = ctrlVar.GetActiveXControl();
	if( gridVar )
	{
		gridVar.Rows = 1; // only column headings
		
		int i;
		/// EJP 07-28-2003 v7.0637 QA70-4911 IMPROVE_HDR_VAR_SCAN
		/*
		string strName, strVal;
		
		for( int iLine = 0; iLine < saLines.GetSize(); iLine++ )
		{
			i = saLines[iLine].Find(iSeparator);
			if( i > 0 )
			{
				strName = saLines[iLine].Left(i);
				strName.TrimLeft();
				strName.TrimRight();
				strName.MakeValidCName('_');
				if( !strName.IsEmpty() )
				{
					strVal = saLines[iLine].Mid(i + 1);
					strVal.TrimLeft();
					strVal.TrimRight();
					
					i = gridVar.Rows;
					gridVar.Rows = i + 1;
					gridVar.Cell(flexcpText, i, ASCHDR_VARCOL_NAME) = strName;
					gridVar.Cell(flexcpText, i, ASCHDR_VARCOL_VALUE) = strVal;
				}
			}
		}
		*/
		StringArray saNames, saValues;
		get_ascii_file_header_variables(saNames, saValues, s_strDataFile, s_trFilter);
		for( int iVar = 0; iVar < saNames.GetSize(); iVar++ )
		{
			i = gridVar.Rows;
			gridVar.Rows = i + 1;
			gridVar.Cell(flexcpText, i, ASCHDR_VARCOL_NAME) = saNames[iVar];
			gridVar.Cell(flexcpText, i, ASCHDR_VARCOL_VALUE) = saValues[iVar];
		}
		/// end IMPROVE_HDR_VAR_SCAN
		
		gridVar.AutoSize(ASCHDR_VARCOL_VALUE); /// EJP 10-08-2003 v7.5715 QA70-5289.3 UPDATE_COL_WIDTH
	}
}

////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// ASCII Columns Page
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////

static BOOL AscColumns_OnInit()
{
	ON_PAGE_CHECK_ASC_COLUMNS
	convert_string_to_shorts(s_vColWidths, s_ascimp.szFixedWidth);

	////////////////////////////////
	Control ctrlGrid = ImportWizDlg.GetItem(IDC_COL_WIDTH_PREVIEW_GRID, IDD_AIW_COLUMNS);
	if( ctrlGrid )
	{
		Object objGrid = ctrlGrid.GetActiveXControl();
		if( objGrid )
		{
			objGrid.AllowUserResizing = flexResizeColumns;
			objGrid.FixedCols = 0;
			objGrid.FixedRows = (s_ascimp.iRenameCols > 0 ? 2 : 1);
			objGrid.Editable = flexEDNone;
			objGrid.MergeCells = flexMergeSpill;
			objGrid.OwnerDraw = flexODOver;
			objGrid.Rows = objGrid.FixedRows;
		}
	}
	////////////////////////////////

	return TRUE;
}

static BOOL AscColumns_OnActive()
{
	ON_PAGE_CHECK_ASC_COLUMNS

	/// EJP 10-20-2003 v7.5726 QA70-5374 ALLOW_CHANGING_PREVIEW_FONT
	WorksheetControl wc = ImportWizDlg.GetItem(IDC_COL_WKS_PREVIEW, IDD_AIW_COLUMNS);
	wc.SetFont(IW_PREVIEW_FONT);
	/// end ALLOW_CHANGING_PREVIEW_FONT
	
	/// EJP 07-14-2003 v7.0624 SCAN_FOR_NUM_COLS_ON_CHANGE_HEADER_LINES
	if( IS_RESCAN_FOR_NUM_COLS )
	{
		s_ascimp.iNumColumns = iwScanForNumColumns(s_strDataFile, s_ascimp);
		DISABLE_RESCAN_FOR_NUM_COLS;
	}
	/// end SCAN_FOR_NUM_COLS_ON_CHANGE_HEADER_LINES

	/// EJP 10-23-2003 v7.5726 QA70-5374 ALLOW_CHANGING_PREVIEW_FONT
	iw_SetGridFont(IDC_COL_WIDTH_PREVIEW_GRID, IDD_AIW_COLUMNS, IW_PREVIEW_FONT);
	Control ctrlGrid = ImportWizDlg.GetItem(IDC_COL_WIDTH_PREVIEW_GRID, IDD_AIW_COLUMNS);
	if( ctrlGrid )
		AscColumns_SetGridColWidthInChars(ctrlGrid, s_vColWidths);
	/// end ALLOW_CHANGING_PREVIEW_FONT

	AscColumns_UpdateData(FALSE);
	AscColumns_EnableDelimiterCtrls();
	UpdatePreview(IDD_AIW_COLUMNS);
	return TRUE;
}

static BOOL AscColumns_OnClickLeadingZeroes(Control ctrl)
{
	Button btnLeadingZeroes(ctrl);
	s_ascimp.iLeadingZeroes = btnLeadingZeroes.Check;
	UpdatePreview(IDD_AIW_COLUMNS);
	return TRUE;
}

static BOOL AscColumns_OnClickDelimited(Control ctrl)
{
	Button radioDelimited(ctrl);
	if( radioDelimited.Check )
	{
		s_ascimp.iDelimited = 1; // Delimiter separated columns
		s_ascimp.iNumColumns = s_iNumColsEstimated;
	}
	else
	{
		s_ascimp.iDelimited = 0; // Fixed width columns
		s_ascimp.iNumColumns = s_vColWidths.GetSize();
	}
	AscColumns_EnableDelimiterCtrls();
	UpdatePreview(IDD_AIW_COLUMNS);
	return TRUE;
}

static BOOL	AscColumns_OnSelChangeDelimiter(Control ctrl)
{
	ComboBox comboDelimiter(ctrl);
	s_ascimp.iDelimiter = comboDelimiter.GetCurSel();
	AscColumns_EnableDelimiterCtrls();
	UpdatePreview(IDD_AIW_COLUMNS);
	return TRUE;
}

static BOOL	AscColumns_OnEditChangeCharacter(Control ctrl)
{
	Edit ebxDelimiter(ctrl);
	string str = ebxDelimiter.Text;
	s_ascimp.cChar = str[0];
	UpdatePreview(IDD_AIW_COLUMNS);
	return TRUE;
}

static BOOL	AscColumns_OnEditChangeColumnWidths(Control ctrl)
{
	static BOOL s_bBusy = FALSE;
	if( s_bBusy )
		return FALSE;
	s_bBusy = TRUE;
	
	Edit ebxFixedWidths(ctrl);
	string strWidths = ebxFixedWidths.Text;
	string str = strWidths.SpanIncluding("0123456789,");
	if( str.Compare(strWidths) ) // If strings are not same then not all legal characters
	{
		int nChar = str.GetLength();
		ebxFixedWidths.SetSel(nChar, nChar + 1);
		ebxFixedWidths.ReplaceSel(""); // Replace illegal character with ""
		MessageBeep(MB_OK);
	}
	else // all legal characters
	{
		SET_FIXED_WIDTHS_CHANGED;
	}

	//Button btnRefresh = ImportWizDlg.GetItem(IDC_COLS_REFRESH, IDD_AIW_COLUMNS);
	//btnRefresh.Enable = !ebxFixedWidths.Text.IsEmpty();
	
	s_bBusy = FALSE;

	return TRUE;
}

/// EJP 07-21-2003 v7.0630 QA70-4073 ADD_APPLY_BUTTON_TO_UPDATE_PREVIEW
///static BOOL AscCols_OnChangeNumCols(Control ctrl)
static BOOL AscCols_OnClickApplyNumCols(Control ctrl)
/// end ADD_APPLY_BUTTON_TO_UPDATE_PREVIEW
{
	/// EJP 07-21-2003 v7.0630 QA70-4073 ADD_APPLY_BUTTON_TO_UPDATE_PREVIEW
	///Edit ebNumCols(ctrl);
	Edit ebNumCols = ImportWizDlg.GetItem(IDC_NUMBER_OF_COLS, IDD_AIW_COLUMNS);
	/// end ADD_APPLY_BUTTON_TO_UPDATE_PREVIEW
	int i = atoi(ebNumCols.Text);
	if( i >= 0 )
	{
		s_ascimp.iNumColumns = i;
		UpdatePreview(IDD_AIW_COLUMNS);
	}
	return TRUE;
}

/// EJP 10-13-2003 v7.5717 QA70-5318 CUSTOM_DATE_FORMAT
static BOOL AscCols_ApplyDateFormat(Control ctrl)
{
	ComboBox cbDateFormat = ImportWizDlg.GetItem(IDC_CUSTOM_DATE_FORMAT, IDD_AIW_COLUMNS);
	if( cbDateFormat )
	{
		string str;
		cbDateFormat.GetLBText(0, str); // get text for <None>
		if( 0 == str.Compare(cbDateFormat.Text) )
			str.Empty();
		else
			str = cbDateFormat.Text;
		lstrcpyn(s_ascimp.szDateFormat, str, MAX_SIZE_CUSTOM_FORMAT);
		UpdatePreview(IDD_AIW_COLUMNS);
		return TRUE;
	}
	return FALSE;
}
/// end CUSTOM_DATE_FORMAT

static void AscColumns_UpdateFixedWidthColStr()
{
	string str;
	convert_shorts_to_string(str, s_vColWidths);
	lstrcpyn(s_ascimp.szFixedWidth, str, MAX_FIXED_COL_WIDTH);
	Edit editFixedWidths = ImportWizDlg.GetItem(IDC_COLS_WIDTHS, IDD_AIW_COLUMNS);
	editFixedWidths.Text = str;
}

static BOOL	AscColumns_OnClickRefresh(Control ctrl)
{
	Edit editFixedWidths = ImportWizDlg.GetItem(IDC_COLS_WIDTHS, IDD_AIW_COLUMNS);
	lstrcpyn(s_ascimp.szFixedWidth, editFixedWidths.Text, MAX_FIXED_COL_WIDTH);
	
	convert_string_to_shorts(s_vColWidths, s_ascimp.szFixedWidth);
	s_ascimp.iNumColumns = s_vColWidths.GetSize();
	
	Control ctrlGrid = ImportWizDlg.GetItem(IDC_COL_WIDTH_PREVIEW_GRID, IDD_AIW_COLUMNS);
	AscColumns_SetGridColWidthInChars(ctrlGrid, s_vColWidths);	

	UpdatePreview(IDD_AIW_COLUMNS);
	AscColumns_UpdateData(FALSE); /// EJP 09-23-2003 v7.5702 QA70-5135.27 UPDATE_NUMCOLS_ON_APPLY_FIXEDWIDTH
	return true;
}

static BOOL	AscColumns_OnClickSetDesignations(Control ctrl)
{
	ComboBox comboDesignations = ImportWizDlg.GetItem(IDC_IW_COL_PLOT_DESIG, IDD_AIW_COLUMNS);
	string strDesignations = comboDesignations.Text;
	AscColumns_SetColumnDesignations(strDesignations);
	UpdateWksCtrl(IDD_AIW_COLUMNS); // do not re-import, just update wks ctrl
	return true;
}

static void AscColumns_EnableDelimiterCtrls()
{
	Button rbDelimited = ImportWizDlg.GetItem(IDC_COLS_DELIMITED, IDD_AIW_COLUMNS);
	ComboBox cmbxDelimiter = ImportWizDlg.GetItem(IDC_COLS_DELIMITER, IDD_AIW_COLUMNS);
	Edit ebxDelimiter = ImportWizDlg.GetItem(IDC_COLS_CHAR, IDD_AIW_COLUMNS);	
	Edit ebxFixedWidths = ImportWizDlg.GetItem(IDC_COLS_WIDTHS, IDD_AIW_COLUMNS);	
	Button btnRefresh = ImportWizDlg.GetItem(IDC_COLS_REFRESH, IDD_AIW_COLUMNS);		
	Button chkFixedWidthGrid = ImportWizDlg.GetItem(IDC_COL_PREV_SWITCH, IDD_AIW_COLUMNS);
	WorksheetControl wc = ImportWizDlg.GetItem(IDC_COL_WKS_PREVIEW, IDD_AIW_COLUMNS);
	Control ctrlGrid = ImportWizDlg.GetItem(IDC_COL_WIDTH_PREVIEW_GRID, IDD_AIW_COLUMNS);
	if( !ctrlGrid )
		return;

	if( rbDelimited.Check == 1 ) // Delimiter separated columns
	{
		cmbxDelimiter.Enable = 1;
		if( cmbxDelimiter.GetCurSel() == ASCIMP_DELIM_OTHER )
			ebxDelimiter.Enable = 1;
		else
			ebxDelimiter.Enable = 0;
		ebxFixedWidths.Enable = 0;
		btnRefresh.Enable = 0;
		chkFixedWidthGrid.Enable = 0;
		ctrlGrid.Visible = 0;
		wc.Visible = 1;
	}
	else // Fixed width columns
	{
		cmbxDelimiter.Enable = 0;
		ebxDelimiter.Enable = 0;
		ebxFixedWidths.Enable = 1;
		btnRefresh.Enable = 1;
		chkFixedWidthGrid.Enable = 1;
		if( chkFixedWidthGrid.Check )
		{
			ctrlGrid.Visible = 1;
			wc.Visible = 0;
		}
		else
		{
			ctrlGrid.Visible = 0;
			wc.Visible = 1;
		}
	}
	
	Button btnAddCol = ImportWizDlg.GetItem(IDC_ADD_COL, IDD_AIW_COLUMNS);
	btnAddCol.Enable = (chkFixedWidthGrid.Check && chkFixedWidthGrid.Enable);
	Button btnDelCol = ImportWizDlg.GetItem(IDC_DEL_COL, IDD_AIW_COLUMNS);
	btnDelCol.Enable = (chkFixedWidthGrid.Check && chkFixedWidthGrid.Enable);
}

static bool AscColumns_SetColumnDesignations(LPCSTR lpcszDesignations)
{
	string strDesignations(lpcszDesignations);
	
	BOOL bRepeat = FALSE;
	int i = strDesignations.Find(' ');
	if( i != -1 )
	{
		bRepeat = TRUE;
		strDesignations.Delete(0, i + 1);
	}
	strDesignations.Replace("YErr", "E");

	fuSetDesignations(s_trFilter, strDesignations);
	fuSetRepetitive(s_trFilter, bRepeat);
	
	Worksheet wks(s_strWks);
	wks.SetColDesignations(strDesignations, bRepeat);

	return true;
}

static BOOL AscColumns_OnClickFixedWidthPreview(Control ctrl)
{
	AscColumns_EnableDelimiterCtrls();
	Button chkFixedWidthPreview(ctrl);
	if( !chkFixedWidthPreview.Check && IS_UPDATE_PREVIEW_NEEDED )
	{
		UpdatePreview(IDD_AIW_COLUMNS);
		DISABLE_UPDATE_PREVIEW_NEEDED;
	}
	/// JCG 06/12/03 QA50-4575 v7.0601 FIX_ITEM43_FIXWIDTH_BUG
	else
	if(chkFixedWidthPreview.Check)
		 AscColumns_ReadFileIntoFixedWidthGrid();
	/// end FIX_ITEM43_FIXWIDTH_BUG
	return true;
}

static BOOL AscColumns_OnClickAddCol(Control ctrl)
{
	Control ctrlGrid = ImportWizDlg.GetItem(IDC_COL_WIDTH_PREVIEW_GRID, IDD_AIW_COLUMNS);
	Object objGrid = ctrlGrid.GetActiveXControl();
	if( objGrid )
		AscColumns_AddColToFixedWidthGrid(ctrlGrid);
	ENABLE_UPDATE_PREVIEW_NEEDED;
	return TRUE;
}

static BOOL AscColumns_OnClickDelCol(Control ctrl)
{
	Control ctrlGrid = ImportWizDlg.GetItem(IDC_COL_WIDTH_PREVIEW_GRID, IDD_AIW_COLUMNS);
	Object objGrid = ctrlGrid.GetActiveXControl();
	if( objGrid )
		AscColumns_DeleteColFromFixedWidthGrid(ctrlGrid);
	ENABLE_UPDATE_PREVIEW_NEEDED;
	return TRUE;
}

static BOOL AscColumns_OnAfterResizeGridCol(Control ctrl, int nRow, int nCol)
{
	s_vColWidths[nCol] = AscColumns_GetGridColWidthInChars(ctrl, nCol);
	AscColumns_UpdateGridColTitle(ctrl, nCol);
	AscColumns_UpdateFixedWidthColStr();
	ENABLE_UPDATE_PREVIEW_NEEDED;
	return TRUE;
}

static void AscColumns_OnDrawCell(Control ctrl, UINT dwDC, int nRow, int nCol, int nLeft, int nTop, int nRight, int nBottom, BOOL* pDone)
{
	HDC hDC = (HDC)dwDC;
	DeviceContext	dc;
	dc.Attach(hDC);
	SIZE sz;
	sz = dc.GetTextExtent("A", 1);
	dc.Detach();
	s_iFixedWidthGridFontWidth = sz.cx;
	*pDone = FALSE; // let VSFlex grid to finish drawing cell
	
	Object objGrid = ctrl.GetActiveXControl();
	objGrid.OwnerDraw = flexODNone;

	// First time showing the grid, let update the column widths.
	AscColumns_SetGridColWidthInChars(ctrl, s_vColWidths);	
	AscColumns_ReadFileIntoFixedWidthGrid();
}

static int AscColumns_GetGridColWidthInChars(Control ctrlGrid, int nCol)
{
	Object objGrid = ctrlGrid.GetActiveXControl();
	int iPixels = TwipsToPixels(ctrlGrid, objGrid.ColWidth(nCol));
	return (iPixels / s_iFixedWidthGridFontWidth);//sizeChar.cx);
}

static void AscColumns_UpdateGridColTitle(Control ctrlGrid, int nCol)
{
	string str;
	str.Format("%d\naaa", s_vColWidths[nCol]);

	Object objGrid = ctrlGrid.GetActiveXControl();
	objGrid.Row = 0;
	objGrid.Col = nCol;
	objGrid.Text = str;
}

static void AscColumns_SetGridColWidthInChars(Control ctrlGrid, int nCol, int nChars)
{
	Object objGrid = ctrlGrid.GetActiveXControl();
	if( nCol >= objGrid.Cols )
		return;
	int iTwips = PixelsToTwips(ctrlGrid, s_iFixedWidthGridFontWidth * nChars);
	objGrid.ColWidth(nCol) = iTwips;
}

static void AscColumns_SetGridColWidthInChars(Control ctrlGrid, vector<short> vColWidths)
{
	Object objGrid = ctrlGrid.GetActiveXControl();
	objGrid.Cols = vColWidths.GetSize();
	if( objGrid.Cols == 0 )
	{
		AscColumns_AddColToFixedWidthGrid(ctrlGrid);
		AscColumns_ReadFileIntoFixedWidthGrid();
	}
	else
	{
		for( int iCol = 0; iCol < vColWidths.GetSize(); iCol++ )
		{
			AscColumns_SetGridColWidthInChars(ctrlGrid, iCol, vColWidths[iCol]);
			AscColumns_UpdateGridColTitle(ctrlGrid, iCol);
		}
	}
}

static void AscColumns_ReadFileIntoFixedWidthGrid()
{
	Control ctrlGrid = ImportWizDlg.GetItem(IDC_COL_WIDTH_PREVIEW_GRID, IDD_AIW_COLUMNS);
	Object objGrid = ctrlGrid.GetActiveXControl();
	
	if( objGrid.Cols == 0 )
		AscColumns_AddColToFixedWidthGrid(ctrlGrid);
	objGrid.Col = 0; // read into first column

	StringArray saLines;

	int nFixedRows = objGrid.FixedRows;
	if( nFixedRows > 1 ) // if show column names
	{
		///ReadFileLines(saLines, s_strDataFile, 1, s_ascimp.iHeaderLines - s_ascimp.iRenameCols);
		ReadFileLines(saLines, s_strDataFile, 1, ASCIMP_TOTAL_HEADER_LINES(s_ascimp) - s_ascimp.iRenameCols);
		objGrid.Row = 1;
		objGrid.Text = saLines[0];
		saLines.SetSize(0);
	}

	ReadFileLines(saLines, s_strDataFile, 50, ASCIMP_TOTAL_HEADER_LINES(s_ascimp));
	objGrid.Rows = nFixedRows + saLines.GetSize();

	for( int n = 0; n < saLines.GetSize(); n++ )
	{
		objGrid.Row = nFixedRows + n;
		objGrid.Text = saLines[n];
	}
}

static void AscColumns_AddColToFixedWidthGrid(Control ctrlGrid)
{
	Object objGrid = ctrlGrid.GetActiveXControl();
	int iCol = objGrid.Cols;
	objGrid.Cols = objGrid.Cols + 1;
	s_vColWidths.Add(AscColumns_GetGridColWidthInChars(ctrlGrid, iCol));
	AscColumns_UpdateGridColTitle(ctrlGrid, iCol);
	AscColumns_UpdateFixedWidthColStr();
}

static void AscColumns_DeleteColFromFixedWidthGrid(Control ctrlGrid)
{
	Object objGrid = ctrlGrid.GetActiveXControl();
	int nCol = objGrid.Cols - 1;
	if( nCol )
	{
		objGrid.Cols = nCol;
		s_vColWidths.RemoveAt(nCol);
		AscColumns_UpdateFixedWidthColStr();
	}
}

static void AscColumns_UpdateData(BOOL bRetrieveFromDlg=TRUE)
{
	Control wizpage = ImportWizDlg.GetItem(IDD_AIW_COLUMNS);
	ComboBox cmbDelimiter = ImportWizDlg.GetItem(IDC_COLS_DELIMITER, IDD_AIW_COLUMNS);
	Edit ebDelimiter = ImportWizDlg.GetItem(IDC_COLS_CHAR, IDD_AIW_COLUMNS);
	Edit ebFixedWidths = ImportWizDlg.GetItem(IDC_COLS_WIDTHS, IDD_AIW_COLUMNS);
	ComboBox cmbDesig = ImportWizDlg.GetItem(IDC_IW_COL_PLOT_DESIG, IDD_AIW_COLUMNS);
	Button btnLeadingZeroes = ImportWizDlg.GetItem(IDC_IW_LEADING_ZERO, IDD_AIW_COLUMNS);
	Edit ebNumCols = ImportWizDlg.GetItem(IDC_NUMBER_OF_COLS, IDD_AIW_COLUMNS);
	ComboBox cbDateFormat = ImportWizDlg.GetItem(IDC_CUSTOM_DATE_FORMAT, IDD_AIW_COLUMNS); /// EJP 10-13-2003 v7.5717 QA70-5318 CUSTOM_DATE_FORMAT

	string str;
	
	if( bRetrieveFromDlg )
	{
		s_ascimp.iDelimited = (wizpage.GetCheckedRadioButton(IDC_COLS_DELIMITED, IDC_COLS_FIXED) == IDC_COLS_DELIMITED);
		
		s_ascimp.iDelimiter = cmbDelimiter.GetCurSel();
		
		s_ascimp.cChar = ebDelimiter.Text[0];
		
		lstrcpyn(s_ascimp.szFixedWidth, ebFixedWidths.Text, MAX_FIXED_COL_WIDTH);

		s_ascimp.iLeadingZeroes = btnLeadingZeroes.Check;
	}
	else // update dialog controls
	{
		if( s_ascimp.iDelimited )
			wizpage.CheckRadioButton(IDC_COLS_DELIMITED, IDC_COLS_FIXED, IDC_COLS_DELIMITED);
		else
			wizpage.CheckRadioButton(IDC_COLS_DELIMITED, IDC_COLS_FIXED, IDC_COLS_FIXED);

		cmbDelimiter.SetCurSel(s_ascimp.iDelimiter);

		str.Format("%c", s_ascimp.cChar);
		ebDelimiter.Text = str;

		str.Format("%s", s_ascimp.szFixedWidth);
		ebFixedWidths.Text = str;

		cmbDesig.SetCurSel(0);

		btnLeadingZeroes.Check = s_ascimp.iLeadingZeroes;
		
		ebNumCols.Text.Format("%d", s_ascimp.iNumColumns);

		/// EJP 10-13-2003 v7.5717 QA70-5318 CUSTOM_DATE_FORMAT
		if( s_ascimp.szDateFormat[0] )
			cbDateFormat.Text = s_ascimp.szDateFormat;
		else
			cbDateFormat.SetCurSel(0); // select <None> text
		/// end CUSTOM_DATE_FORMAT
	}
}

////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
//	Data Selection Page
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////

static BOOL Range_OnIsShow(DWORD dwPageID, DWORD lParam)
{
	return IS_SHOW_PARTIAL_IMPORT_PAGE;
}

static BOOL Range_OnInit()
{
	ON_PAGE_CHECK_PARTIAL_IMPORT
	Range_UpdateData(FALSE); // FALSE=update dialog
	Range_EnablePartialCtrls(s_trFilter.Common.Partial.nVal);
	return TRUE;
}

static BOOL Range_OnActive()
{
	/// EJP 10-20-2003 v7.5726 QA70-5374 ALLOW_CHANGING_PREVIEW_FONT
	WorksheetControl wc = ImportWizDlg.GetItem(IDC_RANGE_PREVIEW, IDD_IW_RANGE);
	wc.SetFont(IW_PREVIEW_FONT);
	/// end ALLOW_CHANGING_PREVIEW_FONT

	UpdatePreview(IDD_IW_RANGE);
	return TRUE;
}

static BOOL OnSelChangeNonNumeric(Control ctrl)
{
	ComboBox cbNonNumeric(ctrl);
	int iNonNumeric = cbNonNumeric.GetCurSel();

	bool bEnable = true;
	switch( iNonNumeric )
	{
	case NONNUMERIC_WIZ_TERMINATE:
		s_ascimp.iNonnumeric = NONNUMERIC_TERMINATE;
		break;
	case NONNUMERIC_WIZ_READ_AS_TEXT:
		s_ascimp.iNonnumeric = NONNUMERIC_READ_AS_MISSING;
		break;
	case NONNUMERIC_WIZ_NEW_WKS:
		s_ascimp.iNonnumeric = NONNUMERIC_START_NEW_WKSCOL;
		fuSetImportMode(s_trFilter, ASCIMP_MODE_REPLACE_DATA);
		bEnable = false;
		break;
	case NONNUMERIC_WIZ_NEW_COL:
		s_ascimp.iNonnumeric = NONNUMERIC_START_NEW_WKSCOL;
		fuSetImportMode(s_trFilter, ASCIMP_MODE_APPEND_COLS);
		bEnable = false;
		break;
	}

	ComboBox cbImportMode = ImportWizDlg.GetItem(IDC_RANGE_MODE, IDD_IW_RANGE);
	cbImportMode.SetCurSel(fuGetImportMode(s_trFilter));
	cbImportMode.Enable = bEnable;
	UpdatePreview(IDD_IW_RANGE);
	return TRUE;
}

static BOOL Range_OnSelChangeMode(Control ctrl)
{
	ComboBox cbMode(ctrl);
	fuSetImportMode(s_trFilter, cbMode.GetCurSel());
	UpdatePreview(IDD_IW_RANGE);
	return TRUE;
}

static BOOL Range_OnClickPartial(Control ctrl)
{
	Range_UpdateData();
	Range_EnablePartialCtrls(s_trFilter.Common.Partial.nVal);
	UpdatePreview(IDD_IW_RANGE);
	return TRUE;
}

/// EJP 07-21-2003 v7.0630 QA70-4073 ADD_APPLY_BUTTON_TO_UPDATE_PREVIEW
/*
static BOOL Range_OnEditChangeFirstCol(Control ctrl)
{
	Range_UpdateData();
	UpdatePreview(IDD_IW_RANGE);
	return TRUE;
}

static BOOL Range_OnEditChangeLastCol(Control ctrl)
{
	Range_UpdateData();
	UpdatePreview(IDD_IW_RANGE);
	return TRUE;
}

static BOOL Range_OnEditChangeFirstRow(Control ctrl)
{
	Range_UpdateData();
	UpdatePreview(IDD_IW_RANGE);
	return TRUE;
}

static BOOL Range_OnEditChangeLastRow(Control ctrl)
{
	Range_UpdateData();
	UpdatePreview(IDD_IW_RANGE);
	return TRUE;
}
*/
static BOOL Range_OnClickApplyPartial(Control ctrl)
{
	Range_UpdateData();
	/// EJP 11-26-2003 v7.5773 CHECK_PARTIAL_IMPORT_FROM_SETTINGS
	Range_UpdateData(false); // update user's settings
	/// end CHECK_PARTIAL_IMPORT_FROM_SETTINGS
	UpdatePreview(IDD_IW_RANGE);
	return TRUE;
}
/// end ADD_APPLY_BUTTON_TO_UPDATE_PREVIEW

static BOOL OnEditChangeSkipDataRows(Control ctrl)
{
	Edit ebSkipDataRows(ctrl);
	int iSkipRows = atoi(ebSkipDataRows.Text);
	if( iSkipRows < 0 )
		iSkipRows = 0;
	
	/// EJP 08-27-2003 v7.5677 QA70-5073 ADD_READROWS
	Edit ebReadRows = ImportWizDlg.GetItem(IDC_IW_READ_ROWS, IDD_IW_RANGE);
	ebReadRows.Enable = (iSkipRows > 0);
	/// end ADD_READROWS

	/// EJP 07-23-2003 v7.0631 QA70-4575 ADD_SKIPROWS_TO_BINIMP
	///s_ascimp.iSkipRows = iSkipRows;
	s_trFilter.Common.SkipRows.nVal = iSkipRows;
	/// end ADD_SKIPROWS_TO_BINIMP

	UpdatePreview(IDD_IW_RANGE);
	return TRUE;
}

/// EJP 08-27-2003 v7.5677 QA70-5073 ADD_READROWS
static BOOL OnEditChangeReadRows(Control ctrl)
{
	Edit ebReadRows(ctrl);
	int iReadRows = atoi(ebReadRows.Text);
	if( iReadRows < 1 )
		iReadRows = 1;
	s_trFilter.Common.ReadRows.nVal = iReadRows;
	UpdatePreview(IDD_IW_RANGE);
	return TRUE;
}
/// end ADD_READROWS

static void	Range_EnablePartialCtrls(BOOL bEnable=true)
{
	Edit editFirstCol = ImportWizDlg.GetItem(IDC_RANGE_FIRSTCOL, IDD_IW_RANGE);
	if( editFirstCol )
		editFirstCol.Enable = bEnable;
		
	Edit editLastCol = ImportWizDlg.GetItem(IDC_RANGE_LASTCOL, IDD_IW_RANGE);
	if( editLastCol )
		editLastCol.Enable = bEnable;
		
	Edit editFirstRow = ImportWizDlg.GetItem(IDC_RANGE_FIRSTROW, IDD_IW_RANGE);
	if( editFirstRow )
		editFirstRow.Enable = bEnable;
	
	Edit editLastRow = ImportWizDlg.GetItem(IDC_RANGE_LASTROW, IDD_IW_RANGE);
	if( editLastRow )
		editLastRow.Enable = bEnable;

	/// EJP 07-21-2003 v7.0630 QA70-4073 ADD_APPLY_BUTTON_TO_UPDATE_PREVIEW
	Button btnApply = ImportWizDlg.GetItem(IDC_APPLY_PARTIAL, IDD_IW_RANGE);
	if( btnApply )
		btnApply.Enable = bEnable;
	/// end ADD_APPLY_BUTTON_TO_UPDATE_PREVIEW
}

static void DataSel_UpdateNonNumericCtrls()
{
	bool bImportModeEnable = true, bNonNumericVisible = IS_FILTER_TYPE_ASCII;

	Control ctrlNonNumericLabel = ImportWizDlg.GetItem(IDC_NONNUMERIC_LABEL, IDD_IW_RANGE);
	ctrlNonNumericLabel.Visible = bNonNumericVisible;

	ComboBox cbNonNumeric = ImportWizDlg.GetItem(IDC_IW_HEADER_NONNUMERIC, IDD_IW_RANGE);
	cbNonNumeric.Visible = bNonNumericVisible;

	ComboBox cbImportMode = ImportWizDlg.GetItem(IDC_RANGE_MODE, IDD_IW_RANGE);
	if( bNonNumericVisible )
	{
		int iNonNumeric = cbNonNumeric.GetCurSel();
		if( NONNUMERIC_WIZ_NEW_WKS == iNonNumeric || NONNUMERIC_WIZ_NEW_COL == iNonNumeric )
			bImportModeEnable = false;
	}
	cbImportMode.Enable = bImportModeEnable;
}

static void DataSel_ConvertStructToDialog(int &iNonNumeric, int &iImportMode)
{
	switch( iNonNumeric )
	{
	case NONNUMERIC_TERMINATE:
		iNonNumeric = NONNUMERIC_WIZ_TERMINATE;
		// import mode does not change
		break;
	case NONNUMERIC_READ_AS_MISSING:
	case NONNUMERIC_APPEND_TO_LABEL:
		iNonNumeric = NONNUMERIC_WIZ_READ_AS_TEXT;
		// import mode does not change
		break;
	case NONNUMERIC_START_NEW_WKSCOL:
		if( ASCIMP_MODE_REPLACE_DATA == iImportMode )
			iNonNumeric = NONNUMERIC_WIZ_NEW_WKS;
		else
		{
			iNonNumeric = NONNUMERIC_WIZ_NEW_COL;
			iImportMode = ASCIMP_MODE_APPEND_COLS;
		}
		break;
	}
}

static void DataSel_ConvertDialogToStruct(int &iNonNumeric, int &iImportMode)
{
	switch( iNonNumeric )
	{
	case NONNUMERIC_WIZ_TERMINATE:
		iNonNumeric = NONNUMERIC_TERMINATE;
		// import mode does not change
		break;
	case NONNUMERIC_WIZ_READ_AS_TEXT:
		iNonNumeric = NONNUMERIC_READ_AS_MISSING;
		// import mode does not change
		break;
	case NONNUMERIC_WIZ_NEW_WKS:
	case NONNUMERIC_WIZ_NEW_COL:
		iNonNumeric = NONNUMERIC_START_NEW_WKSCOL;
		// import mode does not change
		break;
	}
}

static void Range_UpdateData(BOOL bDlgToData=true)
{
	Button chkPartial = ImportWizDlg.GetItem(IDC_RANGE_PARTIAL, IDD_IW_RANGE);
	Edit editFirstCol = ImportWizDlg.GetItem(IDC_RANGE_FIRSTCOL, IDD_IW_RANGE);
	Edit editLastCol = ImportWizDlg.GetItem(IDC_RANGE_LASTCOL, IDD_IW_RANGE);
	Edit editFirstRow = ImportWizDlg.GetItem(IDC_RANGE_FIRSTROW, IDD_IW_RANGE);
	Edit editLastRow = ImportWizDlg.GetItem(IDC_RANGE_LASTROW, IDD_IW_RANGE);
	ComboBox cbImportMode = ImportWizDlg.GetItem(IDC_RANGE_MODE, IDD_IW_RANGE);
	Edit ebSkipDataRows = ImportWizDlg.GetItem(IDC_IW_SKIP_ROWS, IDD_IW_RANGE);
	ComboBox cbNonNumeric = ImportWizDlg.GetItem(IDC_IW_HEADER_NONNUMERIC, IDD_IW_RANGE);

	/// EJP 08-27-2003 v7.5677 QA70-5073 ADD_READROWS
	Edit ebReadRows = ImportWizDlg.GetItem(IDC_IW_READ_ROWS, IDD_IW_RANGE);
	/// end ADD_READROWS
	
	if( bDlgToData )
	{
		if( chkPartial.Check )
		{
			int i;
			
			s_trFilter.Common.Partial.nVal = 1;

			/// EJP 11-26-2003 v7.5773 CHECK_PARTIAL_IMPORT_FROM_SETTINGS
			///s_trFilter.Common.PartialC1.nVal = atoi(editFirstCol.Text) - 1;
			i = atoi(editFirstCol.Text) - 1;
			if( i < 0 )
				i = 0;
			s_trFilter.Common.PartialC1.nVal = i;
			/// end CHECK_PARTIAL_IMPORT_FROM_SETTINGS

			i = atoi(editLastCol.Text);
			if( i < 1 )
				i = -1; // last column
			else
			{
				i--;
				if( i < s_trFilter.Common.PartialC1.nVal )
					i = s_trFilter.Common.PartialC1.nVal;
			}
			s_trFilter.Common.PartialC2.nVal = i;
			
			/// EJP 11-26-2003 v7.5773 CHECK_PARTIAL_IMPORT_FROM_SETTINGS
			///s_trFilter.Common.PartialR1.nVal = atoi(editFirstRow.Text) - 1;
			i = atoi(editFirstRow.Text) - 1;
			if( i < 0 )
				i = 0;
			s_trFilter.Common.PartialR1.nVal = i;
			/// end CHECK_PARTIAL_IMPORT_FROM_SETTINGS

			i = atoi(editLastRow.Text);
			if( i < 1 )
				i = -1; // last column
			else
			{
				i--;
				if( i < s_trFilter.Common.PartialR1.nVal )
					i = s_trFilter.Common.PartialR1.nVal;
			}
			s_trFilter.Common.PartialR2.nVal = i;
		}
		else
		{
			s_trFilter.Common.Partial.nVal = 0;
			s_trFilter.Common.PartialC1.nVal = 0; // first column
			s_trFilter.Common.PartialC2.nVal = -1; // last column
			s_trFilter.Common.PartialR1.nVal = 0; // first row
			s_trFilter.Common.PartialR2.nVal = -1; // last row
		}

		int iImportMode = cbImportMode.GetCurSel();
		int iNonNumeric = cbNonNumeric.GetCurSel();
		DataSel_ConvertDialogToStruct(iNonNumeric, iImportMode);
		fuSetImportMode(s_trFilter, iImportMode);
		s_ascimp.iNonnumeric = iNonNumeric;

		/// EJP 07-23-2003 v7.0631 QA70-4575 ADD_SKIPROWS_TO_BINIMP
		///s_ascimp.iSkipRows = atoi(ebSkipDataRows.Text);
		/// end ADD_SKIPROWS_TO_BINIMP
	}
	else // data to dialog
	{
		chkPartial.Check = s_trFilter.Common.Partial.nVal;
		editFirstCol.Text.Format("%d", s_trFilter.Common.PartialC1.nVal + 1);
		editLastCol.Text.Format("%d", s_trFilter.Common.PartialC2.nVal + 1);
		editFirstRow.Text.Format("%d", s_trFilter.Common.PartialR1.nVal + 1);
		editLastRow.Text.Format("%d", s_trFilter.Common.PartialR2.nVal + 1);

		int iImportMode = fuGetImportMode(s_trFilter);
		int iNonNumeric = s_ascimp.iNonnumeric;
		DataSel_ConvertStructToDialog(iNonNumeric, iImportMode);
		cbNonNumeric.SetCurSel(iNonNumeric);
		cbImportMode.SetCurSel(iImportMode);
		DataSel_UpdateNonNumericCtrls();

		/// EJP 08-27-2003 v7.5677 QA70-5073 ADD_READROWS
		///	/// EJP 07-23-2003 v7.0631 QA70-4575 ADD_SKIPROWS_TO_BINIMP
		///	///ebSkipDataRows.Text.Format("%d", s_ascimp.iSkipRows);
		///	ebSkipDataRows.Text.Format("%d", tree_node_get_int(s_trFilter.Common.SkipRows, 0));
		///	/// end ADD_SKIPROWS_TO_BINIMP
		int iSkipRows = tree_node_get_int(s_trFilter.Common.SkipRows, 0);
		ebSkipDataRows.Text.Format("%d", iSkipRows);
		ebReadRows.Text.Format("%d", tree_node_get_int(s_trFilter.Common.ReadRows, 1));
		ebReadRows.Enable = (iSkipRows > 0);
		/// end ADD_READROWS
	}
}

////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
//	Plotting page functions
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////

static BOOL Plotting_OnIsShow(DWORD dwPageID, DWORD lParam)
{
	ON_PAGE_CHECK_PLOTTING
	return TRUE;
}

static BOOL Plotting_OnActivate()
{
	ON_PAGE_CHECK_PLOTTING
	Edit editDesig = ImportWizDlg.GetItem(IDC_IW_PLOT_RO_PLOT_DESIG, IDD_IW_PLOTTING);
	editDesig.Text = fuGetDesignations(s_trFilter);
	Plotting_UpdateGrid();
	Plotting_UpdateData(false); // false = data to dialog
	return TRUE;
}

static BOOL Plotting_OnKillActive()
{
	ON_PAGE_CHECK_PLOTTING
	Plotting_UpdateData();
	return true;
}

static BOOL Plotting_OnBeforeEditCell(Control ctrl, int iRow, int iCol, BOOL *pCancel)
{
	if( iCol != 1 ) // if not Layer # column
		*pCancel = true; // do not allow editing
	return true;
}

static BOOL Plotting_OnInit()
{
	ON_PAGE_CHECK_PLOTTING

	Control ctrlGrid = ImportWizDlg.GetItem(IDC_IW_PLOT_GRID_HLDR, IDD_IW_PLOTTING);
	if( !ctrlGrid )
		return FALSE;
	Object objPlottingGrid = ctrlGrid.GetActiveXControl();
	if( !objPlottingGrid )
		return FALSE;
	objPlottingGrid.Cols = IW_PLOTTING_GRID_NUM_COLS;
	objPlottingGrid.Editable = 1;
	objPlottingGrid.FixedCols = 0;
	objPlottingGrid.FixedRows = 1;
	objPlottingGrid.ExtendLastCol = TRUE;
	objPlottingGrid.AllowUserResizing = 1;
	objPlottingGrid.ColWidthMin = 0;
	objPlottingGrid.ColWidthMax = 0;
	objPlottingGrid.ExplorerBar = flexExSortShow;
	
	objPlottingGrid.Row = 0;
	objPlottingGrid.Col = 0;
	objPlottingGrid.Text = IW_FILE_NAME;
	objPlottingGrid.Col = 1;
	objPlottingGrid.Text = IW_LAYER_NUM;
	objPlottingGrid.Col = 2;
	objPlottingGrid.Text = IW_FILE_SIZE;
	objPlottingGrid.Col = 3;
	objPlottingGrid.Text = IW_MODIFY_DATE;
	objPlottingGrid.ColDataType(3) = flexDTDate;

	string strLayers;
	int i, iActive = GetLayerNumbers(strLayers); // Get 1 based Layer numbers for display
	objPlottingGrid.ColComboList(1) = strLayers;
	objPlottingGrid.Cell(flexcpText, 1, 1, objPlottingGrid.Rows - 1, 1) = iActive;

	if( s_bPlotInitFirstTime )
	{
		ComboBox cmbxPlotType = ImportWizDlg.GetItem(IDC_IW_PLOT_TYPE, IDD_IW_PLOTTING);
		// Plot Type combox items
		cmbxPlotType.SetItemData(IW_PLOT_LINE, IDM_PLOT_LINE);
		cmbxPlotType.SetItemData(IW_PLOT_SCATTER, IDM_PLOT_SCATTER);
		cmbxPlotType.SetItemData(IW_PLOT_LINESYMB, IDM_PLOT_LINESYMB);
		cmbxPlotType.SetItemData(IW_PLOT_COLUMN, IDM_PLOT_COLUMN);
		cmbxPlotType.SetItemData(IW_PLOT_BAR, IDM_PLOT_BAR);

		// Grid column widths
		for( i = 0; i < IW_PLOTTING_GRID_NUM_COLS; i++ )
			objPlottingGrid.ColWidth(i) = objPlottingGrid.ClientWidth * 0.25;
		
		s_bPlotInitFirstTime = FALSE;
	}

	return TRUE;
}

static int Plotting_GetCurSelPlotID()
{
	ComboBox cbPlotType = ImportWizDlg.GetItem(IDC_IW_PLOT_TYPE, IDD_IW_PLOTTING);
	int i = cbPlotType.GetCurSel();
	if( i != -1 )
		return cbPlotType.GetItemData(i);
	return IDM_PLOT_LINE;
}

static int Plotting_SetCurSelPlotID(int iPlotID)
{
	int iIndex;
	switch( iPlotID )
	{
	case IDM_PLOT_SCATTER:
	case IDM_PLOT_LINESYMB:
	case IDM_PLOT_COLUMN:
		iIndex = iPlotID - IDM_PLOT_LINE;
		break;
	case IDM_PLOT_BAR:
		iIndex = IW_PLOT_BAR;
		break;
	default: // IDM_PLOT_LINE
		iIndex = IW_PLOT_LINE;
		break;
	}	 

	ComboBox cbPlotType = ImportWizDlg.GetItem(IDC_IW_PLOT_TYPE, IDD_IW_PLOTTING);
	return cbPlotType.SetCurSel(iIndex);
}

//--------------------------------------------------------------------------
// Plotting_OnPlotTypeChange
//
// Dialog Builder calls this function when the selection in the Plot Type
// combobox on the Plotting page changes.
//--------------------------------------------------------------------------
BOOL Plotting_OnPlotTypeChange(Control ctrl)
{
	ComboBox cmbxPlotType(ctrl);
	int iPlotTypeSel = cmbxPlotType.GetCurSel();
	if( iPlotTypeSel >= 0 )
		fuSetPlotID(s_trFilter, cmbxPlotType.GetItemData(iPlotTypeSel));
	else
		fuSetPlotID(s_trFilter, IDM_PLOT_UNKNOWN);
	return true;
}

static BOOL Plotting_OnGridComboCloseUpGrid(Control ctrl, int nRow, int nCol, BOOL* pFinishEdit)
{
	Object objPlottingGrid = ctrl.GetActiveXControl();
	string str = objPlottingGrid.EditText;
	s_vPlottingLayers[nRow - 1] = atoi(str) - 1;
	return true;
}

static void Plotting_UpdateGrid()
{
	int iNumFiles = NUM_DATA_FILES;
	string str;
	
	Control ctrlGrid = ImportWizDlg.GetItem(IDC_IW_PLOT_GRID_HLDR, IDD_IW_PLOTTING);
	if( !ctrlGrid )
		return;
	Object objPlottingGrid = ctrlGrid.GetActiveXControl();
	if( !objPlottingGrid )
		return;
	objPlottingGrid.Rows = iNumFiles + 1;

	for( int iFile = 0; iFile < iNumFiles; iFile++ )
	{
		objPlottingGrid.Row = iFile + 1;
	
		objPlottingGrid.Col = 0; // file name
		objPlottingGrid.Text = GetFilename(s_saDataFiles[iFile]);
	
		objPlottingGrid.Col = 1; // layer number
		str.Format("%d", s_vPlottingLayers[iFile]+1); // +1=user sees with 1
		objPlottingGrid.Text = str;

		objPlottingGrid.Col = 2; // file size
		objPlottingGrid.Text = GetFileSize(s_saDataFiles[iFile]);
		
		objPlottingGrid.Col = 3; // modify date
		objPlottingGrid.Text = GetFileModificationDate(s_saDataFiles[iFile], LDF_SHORT_AND_HHMM_SEPARCOLON);
	}
}

static void Plotting_UpdateData(BOOL bDlgToData=true)
{
	int i;
	string str;
	
	if( bDlgToData )
	{
		fuSetPlotID(s_trFilter, Plotting_GetCurSelPlotID());
	}
	else
	{
		Plotting_SetCurSelPlotID(fuGetPlotID(s_trFilter));
	}
}

////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Utility functions
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////

//--------------------------------------------------------------------------
// IW_Init
//
// This function is for initializing all the "global" variables. 
//--------------------------------------------------------------------------
static void IW_Init(LPCSTR lpcszFileName)
{
	fuPrepareDefault(s_trFilter);
	fuGetASCIMP(s_trFilter, s_ascimp, TRUE); // TRUE = get Common node too
	fuGetBINIMP(s_trFilter, s_binimp, TRUE); // TRUE = get Common node too
	
	s_flags = 0;

	s_strFilterFileSaved.Empty(); /// EJP 08-08-2003 v7.0650 QA70-4073.53 USE_SAME_FILTER_FOR_MULTI_FILES_ON_FILEOPEN_AND_DRAGDROP
	
	///s_strDataFile = lpcszFileName;
	s_saDataFiles.SetSize(0);
	if( lpcszFileName )
		s_saDataFiles.Add(lpcszFileName);
	else
		s_saDataFiles.Add("");

	s_strWks.Empty();
	s_bPlotInitFirstTime = TRUE;                        // Only Init parts of Plotting Page once per wizard session
	s_iSaveFilter = IDC_SAVE_FILTER_GLOBAL_RADIO;
	s_strFilter.Empty();
	s_vColWidths.SetSize(0);
	s_iFixedWidthGridFontWidth = 16;
	s_iOnUserChange = CHANGE_NONE;

	s_iBinHdrPreviewLines = BIN_HDR_PREVIEW_NUM_ROWS;
	s_iAscHdrPreviewLines = AIW_HDR_PREVIEW_LINES_DEFAULT;
	
	s_saHdrParamName.SetSize(0);
	s_vHdrParamType.SetSize(0);
	s_vHdrParamOffset.SetSize(0);
	s_vHdrParamSize.SetSize(0);

	s_iPreviewFont = SYSTEM_FIXED_FONT; /// EJP 10-20-2003 v7.5726 QA70-5374 ALLOW_CHANGING_PREVIEW_FONT

	PageBase pbActiveWindow;
	pbActiveWindow = Project.Pages();                   // Get active page base (window)
	if( pbActiveWindow.IsValid() )                      // If valid...
	{
		s_iActivePageType = pbActiveWindow.GetType();   //   Save active page type in static
		s_strActivePageName = pbActiveWindow.GetName(); //   Save active page name in static
	}
	else                                                // Else not valid...
	{
		s_iActivePageType = EXIST_NONE;                 //   Set active page type to none
		s_strActivePageName.Empty();                    //   Set active page name to ""
	}
	
	if( EXIST_WKS == s_iActivePageType )
	{
		Worksheet wks(s_strActivePageName);
		///Tree trFilter;
		///trFilter = IW_GetFilter();
		fuSetDesignations(s_trFilter, wks.GetColDesignations());
		fuSetFormats(s_trFilter, wks.GetColFormats());
		///IW_SetFilter(trFilter);
	}
}

//--------------------------------------------------------------------------
// convert_shorts_to_string
// convert_string_to_shorts
//
// These functions are for converting between a vector of shorts to a
// comma separated values string. 
//--------------------------------------------------------------------------
static void convert_shorts_to_string(string &strTarget, vector<short> &vSource)
{
	string str;
	StringArray sa;
	for( int n = 0; n < vSource.GetSize(); n++ )
	{
		if( vSource[n] > 0 )
		{
			str.Format("%d", vSource[n]);
			sa.Add(str);
		}
	}
	strTarget.SetTokens(sa, ',');
}

static void convert_string_to_shorts(vector<short> &vTarget, LPCSTR lpcstrSource)
{
	vTarget.SetSize(0);
	
	if( NULL == lpcstrSource )
		return;
	string str(lpcstrSource);

	StringArray sa;
	str.GetTokens(sa, ',');
	
	for( int n = 0; n < sa.GetSize(); n++ )
	{
		sa[n].TrimLeft();
		sa[n].TrimRight();
		if( !sa[n].IsEmpty() )
			vTarget.Add(atoi(sa[n]));
	}
}

//--------------------------------------------------------------------------
// AIW_GetTempFileName
//
// When importing from the clipboard we need to write the clipboard to
// a temporary file.  This function will return a unique file name.
//
// return:
//	TRUE = success
//	FALSE = failure
//--------------------------------------------------------------------------
static BOOL AIW_GetTempFileName(string &strFile)
{
	char sz[MAXFULLPATH];
	DWORD dw = GetTempPath(MAXFULLPATH, sz);
	if( dw )
	{
		strFile = sz;
		dw = GetTempFileName(strFile, "AIW", 0, sz);
		if( dw )
		{
			strFile = sz;
			return TRUE;
		}
	}
	return FALSE;
}


/// YuI 1/21/03 v7.0493 IMPORT_WIZARD_SETTINGS_SAVING
static BOOL	AIW_CheckFile(LPCSTR lpcszPath)
{
	file fil;
	if( fil.Open(lpcszPath, file::modeRead) )
	{
		fil.Close();
		return TRUE;
	}
	
	return FALSE;
}
/// end IMPORT_WIZARD_SETTINGS_SAVING

//--------------------------------------------------------------------------
// IW_PlotToActiveGraph
//
// Plot the data file, specified on the source page, into the active
// graph using the current settings on the Plotting page.
//
//--------------------------------------------------------------------------
static BOOL IW_PlotToActiveGraph(Page &pgData, int iFileNumber)
{
	GraphPage gpGraph(s_strActivePageName);
	if( gpGraph )
	{
		// Get Layer number and GraphLayer object
		int iLayerNumber; // 0 based layer number
		GraphLayer glLayer;
		iLayerNumber = s_vPlottingLayers[iFileNumber]; // Read 0 based layer number for current file from static 
		glLayer = gpGraph.Layers(iLayerNumber); // Get specified layer  

		if( !glLayer ) // If Layer is not valid...
			glLayer = gpGraph.Layers(); // Get active layer

		if( glLayer )
		{
			// Plot all datasets in Worksheet to specified Layer using specified Plot ID	
			///Tree trFilter; trFilter = IW_GetFilter();
			int iOriginPlotType = fuGetPlotID(s_trFilter);

//			// This function is called after a file is imported.
//			// It assumes the active window is the target worksheet.
			string strNewWks;
			strNewWks = pgData.GetName();
//			PageBase pbActiveWindow;
//			pbActiveWindow = Project.Pages();
//			if( pbActiveWindow.IsValid() )
//			{
//				strNewWks = pbActiveWindow.GetName();

				string strLTCommand;
				strLTCommand.Format("Win -a %%H;Layer -w %s 0 0 0 0 %d;", strNewWks, iOriginPlotType);
				glLayer.LT_execute(strLTCommand);
				glLayer.Rescale();
//			}			
		}
	}
	
	return TRUE;
}

//--------------------------------------------------------------------------
// AIW_FileNameToFullPath
//
// Get the full file name for a specified file.
// This function will work for the client-server version of Origin by
// checking the Filters sub-folder in the ini path and checking the
// Filters sub-folder in the exe path.
//
// return:
//	TRUE = success
//	FALSE = failure, filter file not found
//--------------------------------------------------------------------------
static BOOL AIW_FileNameToFullPath(string &strFullPath, LPCSTR lpcstrFile, BOOL bFilter)
{
	string strFormat;
	if( bFilter )
		strFormat = "%sFilters\\%s.%s";
	else
		strFormat = "%s%s.OTW";

	strFullPath.Format(strFormat, GetAppPath(), lpcstrFile, IMPORT_FILTER_EXTENSION);
	if( AIW_CheckFile(strFullPath) )
		return TRUE;
	
	strFullPath.Format(strFormat, GetAppPath(TRUE), lpcstrFile);
	if( AIW_CheckFile(strFullPath) )
		return TRUE;
	/// end IMPORT_WIZARD_SETTINGS_SAVING

	return FALSE;
}

static BOOL iwLoadFilter(LPCSTR lpcstrFilter)
{
	s_strFilterLoaded.Empty(); /// EJP 09-03-2003 v7.5682 DETECT_IMPORT_SETTINGS_CHANGED

	fuPrepareDefault(s_trFilter);
	if( lpcstrFilter && *lpcstrFilter )
	{
		if( !s_trFilter.Load(lpcstrFilter) )
			printf("Error loading %s filter.\n", lpcstrFilter);
		/// EJP 09-03-2003 v7.5682 DETECT_IMPORT_SETTINGS_CHANGED
		else
			s_strFilterLoaded = lpcstrFilter;
		/// end DETECT_IMPORT_SETTINGS_CHANGED

	}
	else // no filter, init as ASCII
	{
		ASCIMP ascimp;
		AscImpReadFileStruct(s_strDataFile, &ascimp);
		ascimp.iAutoSubHeaderLines = 0; /// EJP 07-29-2002 v7.0637 QA70-4575 PROBLEM_50
		s_iNumColsEstimated = ascimp.iNumColumns;

		/// EJP 06-06-2003 QA70-4592 ASCII_HEADER_SCAN_MAIN_SUB_SEPARATION
		/* CP made some internal changes to set these values.
		ascimp.iHeaderLines += ascimp.iSubHeaderLines;
		ascimp.iSubHeaderLines = 0;
		ascimp.iRenameCols = 0;
		ascimp.iMaxLabels = 0;
		ascimp.iLabels = 0;
		*/
		/// end ASCII_HEADER_SCAN_MAIN_SUB_SEPARATION
		fuSetASCIMP(s_trFilter, ascimp);
	}
	fuGetASCIMP(s_trFilter, s_ascimp, TRUE); // TRUE = get Common node too
	fuGetBINIMP(s_trFilter, s_binimp, TRUE); // TRUE = get Common node too
	return TRUE;
}

/// EJP 07-17-2003 v7.0627 QA70-4818 SAVE_FILTER_IN_WKS, funcs no longer used
/*
static BOOL iwSaveFilterInUserFilesFolder(LPCSTR lpcszFilterName)
{
	// Get target path
	string strPath;
	strPath.Format("%s%s", GetAppPath(), FILTERS_FOLDER_NAME);
	
	// Check target path
	if( !strPath.IsPath() )
		CreateDirectory(strPath, NULL);
	
	// Get target file
	string strFile;
	strFile.Format("%s%s.%s", strPath, lpcszFilterName, IMPORT_FILTER_EXTENSION);
	
	// Save filter
	return (s_trFilter.Save(strPath) ? 0 : 1);
}

static BOOL iwSaveFilterInDataFileFolder(LPCSTR lpcszFilterName, LPCSTR lpcszDataFileName)
{
	string strPath(lpcszDataFileName);
	if( !strPath.IsFile() )
		return 1;
	string strFileNameOnly = GetFilename(strPath);
	strPath.Delete(strPath.GetLength() - strFileNameOnly.GetLength(), strFileNameOnly.GetLength());
	string strFilterFileName;
	if( !strPath.IsPath() )
		CreateDirectory(strPath, NULL);
	strFilterFileName.Format("%s%s.%s", strPath, lpcszFilterName, IMPORT_FILTER_EXTENSION);
	return (s_trFilter.Save(strFilterFileName) ? 0 : 1);
}
*/
/// end SAVE_FILTER_IN_WKS

static BOOL iwSaveFilter()
{
	switch( s_trFilter.Type.nVal )
	{
	case FILTER_TYPE_ASCII:
		s_trFilter.RemoveChild("BINIMP");
		s_trFilter.RemoveChild("UserDefined");
		break;
	case FILTER_TYPE_BINARY:
		s_trFilter.RemoveChild("ASCIMP");
		s_trFilter.RemoveChild("UserDefined");
		break;
	case FILTER_TYPE_USERDEFINED:
		s_trFilter.RemoveChild("ASCIMP");
		s_trFilter.RemoveChild("BINIMP");
		break;
	default:
		return FALSE;
	}
	
	/// EJP 07-17-2003 v7.0627 QA70-4818 SAVE_FILTER_IN_WKS, move check to later
	///if( s_strFilter.IsEmpty() )
	///	return FALSE;
	/// end SAVE_FILTER_IN_WKS

	fuSetHeaderParamDefined(s_trFilter, 1);
	
	/// EJP 07-17-2003 v7.0627 QA70-4818 SAVE_FILTER_IN_WKS
	/*
	switch( s_iSaveFilter )
	{
	case IDC_SAVE_FILTER_GLOBAL_RADIO:
		return iwSaveFilterInUserFilesFolder(s_strFilter);
	case IDC_SAVE_FILTER_DATA_FOLDER_RADIO:
		return iwSaveFilterInDataFileFolder(s_strFilter, s_strDataFile);
	}
	return FALSE;
	*/
	if( IDC_SAVE_FILTER_IN_WKS == s_iSaveFilter )
	{
		Page pgTarget(s_strActivePageName);
		return fuSaveFilterToPage(s_trFilter, pgTarget);
	}
	
	if( s_strFilter.IsEmpty() )
		return FALSE;

	string strPath;
	if( IDC_SAVE_FILTER_GLOBAL_RADIO == s_iSaveFilter )
		strPath.Format("%s%s", GetAppPath(), FILTERS_FOLDER_NAME);
	else // IDC_SAVE_FILTER_DATA_FOLDER_RADIO
		strPath = GetFilePath(s_strDataFile);
	if( !strPath.IsPath() )
		CreateDirectory(strPath, NULL);

	/// EJP 08-08-2003 v7.0650 QA70-4073.53 USE_SAME_FILTER_FOR_MULTI_FILES_ON_FILEOPEN_AND_DRAGDROP
	/*
	string strFile;
	strFile.Format("%s%s.%s", strPath, s_strFilter, IMPORT_FILTER_EXTENSION);
	s_strFilter = strFile;
	
	return s_trFilter.Save(strFile);
	*/
	s_strFilterFileSaved.Format("%s%s.%s", strPath, s_strFilter, IMPORT_FILTER_EXTENSION);
	return fuSave(s_trFilter, s_strFilterFileSaved);
	/// end SAVE_FILTER_IN_WKS
}

/// EJP 08-01-2003 v7.0642 DETECT_IMPORT_SETTINGS_CHANGED
static bool iwIsLoadedFilterSettingsChanged()
{
	if( s_strFilterLoaded.IsEmpty() )
		return false; // no filter was loaded

	// Load a copy of the filter we started with
	Tree trStartFilter;
	if( !trStartFilter.Load(s_strFilterLoaded) )
		return false; // can not compare so assume no change

	switch( s_trFilter.Type.nVal )
	{
	case FILTER_TYPE_ASCII:
		{
			ASCIMP aiStart, aiCurrent;
			if( fuGetASCIMP(trStartFilter, aiStart) &&
				fuGetASCIMP(s_trFilter, aiCurrent) )
			{
				return (memcmp(&aiStart, &aiCurrent, sizeof(ASCIMP)) != 0);
			}
		}
		return false; // can not compare so assume no change
	case FILTER_TYPE_BINARY:
		{
			BINIMP biStart, biCurrent;
			if( fuGetBINIMP(trStartFilter, biStart) &&
				fuGetBINIMP(s_trFilter, biCurrent) )
			{
				/// EJP 09-08-2003 v7.5687 QA70-5118 FIX_COMPARE_BINIMP_STRUCTS
				///return (memcmp(&biStart, &biCurrent, sizeof(BINIMP)) != 0);
				return !is_BINIMP_equal(biStart, biCurrent);
				/// end FIX_COMPARE_BINIMP_STRUCTS
			}
		}
		return false; // can not compare so assume no change
	case FILTER_TYPE_USERDEFINED:
		{
			string strOCFile1, strOCFunc1;
			fuGetUserDefinedFunction(s_trFilter, strOCFile1, strOCFunc1);

			string strOCFile2, strOCFunc2;
			fuGetUserDefinedFunction(trStartFilter, strOCFile2, strOCFunc2);
			
			if( strOCFile1.CompareNoCase(strOCFile2) || strOCFunc1.CompareNoCase(strOCFunc2) )
				return true;
		}
		break;
	}
	return false; // can not compare so assume no change
}
/// end DETECT_IMPORT_SETTINGS_CHANGED

////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Binary Header page functions
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////

static BOOL BinHeader_OnInit()
{
	ON_PAGE_CHECK_BIN_HEADER

	/// EJP 10-20-2003 v7.5726 QA70-5374 ALLOW_CHANGING_PREVIEW_FONT
	iw_InitFontComboBox(IDC_BIN_PREVIEW_FONT, IDD_BIW_HEADER);
	/// end ALLOW_CHANGING_PREVIEW_FONT

	RichEdit reAscPreview = ImportWizDlg.GetItem(IDC_BIW_HEADER_ASCII_RICHEDIT, IDD_BIW_HEADER);
	reAscPreview.SendMessage(EM_SETEVENTMASK, 0, ENM_CHANGE|ENM_SCROLL|ENM_SELCHANGE);
	/// EJP 10-20-2003 v7.5726 QA70-5374 ALLOW_CHANGING_PREVIEW_FONT
	///reAscPreview.SetFont(SYSTEM_FIXED_FONT);
	/// end ALLOW_CHANGING_PREVIEW_FONT
	
	RichEdit reBinPreview = ImportWizDlg.GetItem(IDC_BIW_HEADER_HEX_RICHEDIT, IDD_BIW_HEADER);
	reBinPreview.SendMessage(EM_SETEVENTMASK, 0, ENM_CHANGE|ENM_SCROLL|ENM_SELCHANGE);
	/// EJP 10-20-2003 v7.5726 QA70-5374 ALLOW_CHANGING_PREVIEW_FONT
	///reBinPreview.SetFont(SYSTEM_FIXED_FONT);
	/// end ALLOW_CHANGING_PREVIEW_FONT

	BinHdr_UpdatePreview();
	ImportWizDlg.Page.BinHeader.InterpType.v1$=_L("Integer (1, 2 or 4 bytes)");
	ImportWizDlg.Page.BinHeader.InterpType.v2$=_L("Unsigned Integer (1, 2 or 4 bytes)");
	ImportWizDlg.Page.BinHeader.InterpType.v3$=_L("Real (4 or 8 bytes)");
	ImportWizDlg.Page.BinHeader.InterpType.v4$=_L("String (variable length)");
	ImportWizDlg.Page.BinHeader.InterpType.choice = 0;
	Button paramChk = ImportWizDlg.GetItem(IDC_BIW_USE_PARAMETER_DEFINITIONS, IDD_BIW_HEADER);	
	paramChk.Check = 0;
	Button addBtn = ImportWizDlg.GetItem(IDC_BIW_HEADER_ADD_BUTTON, IDD_BIW_HEADER);	
	addBtn.Enable = 0;
	Button removeBtn = ImportWizDlg.GetItem(IDC_BIW_HEADER_REMOVE_BUTTON, IDD_BIW_HEADER);	
	removeBtn.Enable = 0;
	Control paramsList = ImportWizDlg.GetItem(IDC_BINHEADER_PARAMLIST, IDD_BIW_HEADER);
	paramsList.Enable = 0;
	Control valueEdit = ImportWizDlg.GetItem(IDC_BIW_HEADER_CANDINTERP_EDIT, IDD_BIW_HEADER);
	valueEdit.Enable = 0;
	Control typeList = ImportWizDlg.GetItem(IDC_BIW_HEADER_CANDINTERP_COMBO, IDD_BIW_HEADER);
	typeList.Enable = 0;
	
	BinHeader_ReadHeaderParamsFromTree(); // they are read into local static vectors
	BinHeader_UpdateParamListBox();
	
	return TRUE;
}

static BOOL	BinHeader_OnActivate()
{
	ON_PAGE_CHECK_BIN_HEADER
		
	Edit editHeader = ImportWizDlg.GetItem(IDC_BIW_HEADER_SKIPHEADER_EDIT, IDD_BIW_HEADER);
	editHeader.Text = s_binimp.iHeaderBytes;
	Button chkBigEndian = ImportWizDlg.GetItem(IDC_BIW_HEADER_BIGENDIAN_CHECK, IDD_BIW_HEADER);
	chkBigEndian.Check = s_binimp.iBigEndian;

	BinHdr_SetFont(IW_PREVIEW_FONT); /// EJP 10-20-2003 v7.5726 QA70-5374 ALLOW_CHANGING_PREVIEW_FONT

	return TRUE;
}

static BOOL BinHeader_OnKillActive()
{
	ON_PAGE_CHECK_BIN_HEADER
	BinHeader_WriteHeaderParamsToTree();
	return true;
}

/// EJP 10-20-2003 v7.5726 QA70-5374 ALLOW_CHANGING_PREVIEW_FONT
static void BinHdr_SetFont(int iFont)
{
	if( s_iOnUserChange != CHANGE_NONE )
		return;
	s_iOnUserChange = CHANGE_FONT;
	iw_SetRichEditFont(IDC_BIW_HEADER_ASCII_RICHEDIT, IDD_BIW_HEADER, iFont);
	iw_SetRichEditFont(IDC_BIW_HEADER_HEX_RICHEDIT, IDD_BIW_HEADER, iFont);
	s_iOnUserChange = CHANGE_NONE
}

static BOOL BinHdr_OnSelChangeFont(Control ctrl)
{
	ComboBox cbFonts(ctrl);
	if( cbFonts )
	{
		int iCurSel = cbFonts.GetCurSel();
		if( iCurSel >= 0 )
		{
			s_iPreviewFont = cbFonts.GetItemData(iCurSel);
			BinHdr_SetFont(s_iPreviewFont);
			return TRUE;
		}
	}
	return FALSE;
}
/// end ALLOW_CHANGING_PREVIEW_FONT

static BOOL BinHeader_OnSelChangeParamType(Control ctrl)
{
	BinHeader_UpdateParamValPreview();
	return true;
}

static BOOL BinHeader_WriteHeaderParamsToTree()
{
	fuRemoveHeaderParams(s_trFilter);
	for( int n = 0; n < s_saHdrParamName.GetSize(); n++ )
		fuAddBinHeaderParam(s_trFilter, s_saHdrParamName[n], s_vHdrParamType[n], s_vHdrParamOffset[n], s_vHdrParamSize[n]);
	return true;
}

static bool BinHeader_ReadHeaderParamsFromTree()
{
	/*
	s_saHdrParamName.SetSize(0);
	if( !fuGetHeaderParamNames(s_trFilter, s_saHdrParamName) )
		return false;

	int nCount = s_saHdrParamName.GetSize();	
	s_vHdrParamType.SetSize(nCount);
	s_vHdrParamOffset.SetSize(nCount);
	s_vHdrParamSize.SetSize(nCount);

	int iType, iOffset, iSize;
	for( int n = 0; n < nCount; n++ )
	{
		fuGetBinHeaderParam(s_trFilter, s_saHdrParamName[n], s_vHdrParamType[n], s_vHdrParamOffset[n], s_vHdrParamSize[n]);
	}
	*/
	s_saHdrParamName.SetSize(0);
	s_vHdrParamType.SetSize(0);
	s_vHdrParamOffset.SetSize(0);
	s_vHdrParamSize.SetSize(0);
	
	StringArray saNames;
	if( fuGetHeaderParamNames(s_trFilter, saNames) )
	{
		int iType, iOffset, iSize;
		for( int i = 0; i < saNames.GetSize(); i++ )
		{
			if( fuGetBinHeaderParam(s_trFilter, saNames[i], iType, iOffset, iSize) );
			{
				s_saHdrParamName.Add(saNames[i]);
				s_vHdrParamType.Add(iType);
				s_vHdrParamOffset.Add(iOffset);
				s_vHdrParamSize.Add(iSize);
			}
		}
	}
	return true;
}

//------ CPY 1/2/03 v7.0478 QA70-3604 RICH_EDIT_SCROLL_SYNCHRONIZED 
/*
//static BOOL OnVScrollAscPreview(EVENT_BEFORE_UPDATE_ARGS)
{
	RichEdit reAscPreview = ImportWizDlg.GetItem(IDC_BIW_HEADER_ASCII_RICHEDIT, IDD_BIW_HEADER);
	int iAscFirstVisible = reAscPreview.GetFirstVisibleLine();
	
	RichEdit reBinPreview = ImportWizDlg.GetItem(IDC_BIW_HEADER_HEXPREVIEW_RICHEDIT, IDD_BIW_HEADER);
	int iBinFirstVisible = reBinPreview.GetFirstVisibleLine();
	int iScroll = iAscFirstVisible - iBinFirstVisible;
	if( iScroll )
		reBinPreview.LineScroll(iScroll);
	//return TRUE;
}
*/
static void OnVScrollAscPreview(Control ctrl, uint nScrollCode, uint nScrollPos)
{
	RichEdit reAscPreview = ctrl;
	int iAscFirstVisible = reAscPreview.GetFirstVisibleLine();
	
	RichEdit reBinPreview = ImportWizDlg.GetItem(IDC_BIW_HEADER_HEX_RICHEDIT, IDD_BIW_HEADER);
	int iBinFirstVisible = reBinPreview.GetFirstVisibleLine();
	int iScroll = iAscFirstVisible - iBinFirstVisible;
	if( iScroll )
		reBinPreview.LineScroll(iScroll);
}

//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
static int get_bin_preview_char_index(int nAscPreviewCharIndex, RichEdit& reAscPreview, RichEdit& reBinPreview)
{
	int nLineNumber = reAscPreview.LineFromChar(nAscPreviewCharIndex);
	int	nChar1 = reAscPreview.LineIndex(nLineNumber);
	int nCharOffset = nAscPreviewCharIndex - nChar1;
	
	nChar1 = reBinPreview.LineIndex(nLineNumber);
	//every char is shown as 3 in bin preview, but the last char is only 2, so we better compute from line index
	return nChar1 + nCharOffset * 3;
}

// we try to select same in hex dump as in ascii dump
static BOOL OnSelChangeAscPreview(Control ctrl)
{
	if( s_iOnUserChange != CHANGE_NONE )
		return true;
	s_iOnUserChange = CHANGE_ASC;

	RichEdit reAscPreview = ctrl;
	long nStartChar, nEndChar;
	reAscPreview.GetSel(nStartChar, nEndChar);

	Edit ebByteOffset = ImportWizDlg.GetItem(IDC_BYTE_OFFSET, IDD_BIW_HEADER);
	ebByteOffset.Text.Format("%d", GetByteOffsetFromAscPreviewCharIndex(nStartChar)); 

	RichEdit reBinPreview = ImportWizDlg.GetItem(IDC_BIW_HEADER_HEX_RICHEDIT, IDD_BIW_HEADER);
	
	nStartChar = get_bin_preview_char_index(nStartChar, reAscPreview, reBinPreview);
	nEndChar = get_bin_preview_char_index(nEndChar, reAscPreview, reBinPreview);

	reBinPreview.SetSel(nStartChar, nEndChar);
	if(s_bBusy)
   		return FALSE;

	BinHeader_UpdateParamValPreview();
	s_iOnUserChange = CHANGE_NONE;
	return true;
}
//------ end CPY 1/2/03 v7.0478 QA70-3604 RICH_EDIT_SCROLL_SYNCHRONIZED 

static void OnVScrollHexPreview(Control ctrl, uint nScrollCode, uint nScrollPos)
{
	RichEdit reHexPreview = ctrl;
	int iBinFirstVisible = reHexPreview.GetFirstVisibleLine();
	
	RichEdit reAscPreview = ImportWizDlg.GetItem(IDC_BIW_HEADER_ASCII_RICHEDIT, IDD_BIW_HEADER);
	int iAscFirstVisible = reAscPreview.GetFirstVisibleLine();
	int iScroll = iBinFirstVisible - iAscFirstVisible;
	if( iScroll )
		reAscPreview.LineScroll(iScroll);
}

// we try to select same in hex dump as in ascii dump
static BOOL OnSelChangeHexPreview(Control ctrl)
{
	if( s_iOnUserChange != CHANGE_NONE )
		return TRUE;
	s_iOnUserChange = CHANGE_HEX;
	
	long nStartChar, nEndChar;

	RichEdit reBinPreview = ctrl;
	reBinPreview.GetSel(nStartChar, nEndChar);

	Edit ebByteOffset = ImportWizDlg.GetItem(IDC_BYTE_OFFSET, IDD_BIW_HEADER);
	ebByteOffset.Text.Format("%d", GetByteOffsetFromHexPreviewCharIndex(nStartChar)); 

	ConvertHexPreviewSelToAscPreviewSel(nStartChar, nEndChar);
	
	RichEdit reAscPreview = ImportWizDlg.GetItem(IDC_BIW_HEADER_ASCII_RICHEDIT, IDD_BIW_HEADER);
	reAscPreview.SetSel(nStartChar, nEndChar);

	BinHeader_UpdateParamValPreview();
	s_iOnUserChange = CHANGE_NONE;
	return TRUE;
}

static void ConvertHexPreviewSelToAscPreviewSel(long &nStartChar, long &nEndChar)
{
	/// EJP 08-22-2003 SET_OFFSET_WITHOUT_SEL_BUT_JUST_CARROT_POS, old code is off by 1 byte
	/*
	long nFirstChar = nStartChar;
	nStartChar = get_ascii_preview_char_index(nStartChar);
	if( nFirstChar == nEndChar ) // if no selection
		nEndChar = nStartChar;
	else
		nEndChar = get_ascii_preview_char_index(nEndChar - 1) + 1;
	*/
	if( nStartChar == nEndChar )
		nStartChar = get_ascii_preview_char_index(nStartChar - 1) + 1;
	else
		nStartChar = get_ascii_preview_char_index(nStartChar);		
	nEndChar = get_ascii_preview_char_index(nEndChar - 1) + 1;
	/// end SET_OFFSET_WITHOUT_SEL_BUT_JUST_CARROT_POS
}

static int get_ascii_preview_char_index(int nBinPreviewCharIndex)
{
	int nCharIndex = GetByteOffsetFromHexPreviewCharIndex(nBinPreviewCharIndex);
	nCharIndex += ((nCharIndex / 16) * 2);
	return nCharIndex;
}

static BOOL BinHeader_OnChangeHeaderSize(Control ctrl)
{
	Edit eHeaderBytes(ctrl);
	s_binimp.iHeaderBytes = atoi(eHeaderBytes.Text);

	/// EJP 06-10-2003 v7.0600 QA70-4520 SUPPORT_HUGE_HEADER_SIZES
	int iRowsNeeded = (s_binimp.iHeaderBytes / BIN_HDR_PREVIEW_BYTES_PER_ROW) + 3; // 3=1(at least one line)+2(two extra lines)
	if( iRowsNeeded < BIN_HDR_PREVIEW_NUM_ROWS )
		iRowsNeeded = BIN_HDR_PREVIEW_NUM_ROWS;
	if( iRowsNeeded != s_iBinHdrPreviewLines )
	{
		s_iBinHdrPreviewLines = iRowsNeeded;
		BinHdr_UpdatePreview();
	}
	/// end SUPPORT_HUGE_HEADER_SIZES

	return TRUE;
}

static BOOL BinHeader_OnChangeByteOffset(Control ctrl)
{
	if( s_iOnUserChange != CHANGE_NONE )
		return true;
	s_iOnUserChange = CHANGE_BYTEOFFSET;

	Edit eByteOffset(ctrl);
	int iByteOffset = atoi(eByteOffset.Text);

	RichEdit reBinPreview = ImportWizDlg.GetItem(IDC_BIW_HEADER_HEX_RICHEDIT, IDD_BIW_HEADER);
	int i = GetHexPreviewCharIndexFromByteOffset(iByteOffset);
	reBinPreview.SetSel(i, i+3);

	RichEdit reAscPreview = ImportWizDlg.GetItem(IDC_BIW_HEADER_ASCII_RICHEDIT, IDD_BIW_HEADER);
	i = GetAscPreviewCharIndexFromByteOffset(iByteOffset);
	reAscPreview.SetSel(i, i+1);

	s_iOnUserChange = CHANGE_NONE;
	return true;
}

static BOOL BinHeader_OnClickBigEndian(Control ctrl)
{
	Button chkBigEndian(ctrl);
	s_binimp.iBigEndian = chkBigEndian.Check;
	BinHeader_UpdateParamValPreview();
	BinHeader_UpdateParamListBox(); /// EJP 09-29-2003 v7.5709 QA70-5211.5 UPDATE_HDRVAR_ON_CHANGE_ENDIAN
	return true;
}

static BOOL BinHeader_OnClickRefresh()
{
	RichEdit reAscPreview = ImportWizDlg.GetItem(IDC_BIW_HEADER_ASCII_RICHEDIT, IDD_BIW_HEADER);
	long nStartChar, nEndChar;
	reAscPreview.GetSel(nStartChar, nEndChar);
	int nLineNumber = reAscPreview.LineFromChar(nEndChar);
	int nLineIndex = reAscPreview.LineIndex(nLineNumber);
	int nCharOffset = nEndChar - nLineIndex;
	ImportWizDlg.Page.BinHeader.SkipBytes = 16 * nLineNumber + nCharOffset;
	reAscPreview.SetSel(0, nEndChar);
	return TRUE;
}

static BOOL BinHeader_OnClickDefineParam(Control ctrl)
{
	Button chkDefineParam(ctrl);

	Button btnAdd = ImportWizDlg.GetItem(IDC_BIW_HEADER_ADD_BUTTON, IDD_BIW_HEADER);
	btnAdd.Enable = chkDefineParam.Check;

	Button btnRemove = ImportWizDlg.GetItem(IDC_BIW_HEADER_REMOVE_BUTTON, IDD_BIW_HEADER);
	btnRemove.Enable = chkDefineParam.Check;

	ListBox lbParam = ImportWizDlg.GetItem(IDC_BINHEADER_PARAMLIST, IDD_BIW_HEADER);
	lbParam.Enable = chkDefineParam.Check;

	Edit edValue = ImportWizDlg.GetItem(IDC_BIW_HEADER_CANDINTERP_EDIT, IDD_BIW_HEADER);
	edValue.Enable = chkDefineParam.Check;

	ListBox typeList = ImportWizDlg.GetItem(IDC_BIW_HEADER_CANDINTERP_COMBO, IDD_BIW_HEADER);
	typeList.Enable = chkDefineParam.Check;

	return true;
}

static BOOL BinHeader_OnClickAddParam(Control ctrl)
{
	int nType, nOffset, nSize;
	if( !BinHeader_GetParamInfo(nType, nOffset, nSize) )
		return false;

	string str;
	str.Format("P%d", s_saHdrParamName.GetSize()+1);
	int n = AddBinHdrParam(str, nType, nSize, nOffset);
	BinHeader_AddParamToListBox(n-1);
	return true;
}

static BOOL BinHeader_OnClickRemoveParam(Control cntrl)
{
	ListBox lbParams = ImportWizDlg.GetItem(IDC_BINHEADER_PARAMLIST, IDD_BIW_HEADER);
	int nIndex = lbParams.GetCurSel();
	/// EJP 04-23-2003 QA70-4321 PREVENT_CRASH_ON_REMOVAL_OF_LAST_PARAM
	if( nIndex == -1 )
		return FALSE; // no selection
	/// end PREVENT_CRASH_ON_REMOVAL_OF_LAST_PARAM
	DelBinHdrParam(nIndex);
	BinHeader_UpdateParamListBox();
	if( nIndex == lbParams.GetCount() ) // if deleted last item
		nIndex--; // update index for new last item
	if( nIndex >= 0 )
		lbParams.SetCurSel(nIndex);
	return true;
}

static void BinHdr_UpdatePreview()
{
	char szTemp[BIN_HDR_PREVIEW_BYTES_PER_ROW];
	string strHexDumpTotal;
	string strHexDumpRow;
	string strAsciiDump;
	int nRead;
	
	file ff;
	ff.Open(s_strDataFile, file::modeRead | file::shareDenyRead | file::typeBinary);

	for( int iRow = 0; iRow < s_iBinHdrPreviewLines; iRow++ )
	{
		nRead = ff.Read(szTemp, sizeof(szTemp));
		if( 0 == nRead )
			break;
			
		strHexDumpRow = GetHexDump(szTemp, nRead);
		strHexDumpTotal += strHexDumpRow;
		strHexDumpTotal += "\r\n";
	
		for( int iChar = 0; iChar < nRead; iChar++ )
		{
			if( szTemp[iChar] < ' ' || '~' < szTemp[iChar] )
				szTemp[iChar] = '.';			
		}
				
		strAsciiDump += szTemp;
		strAsciiDump += "\r\n";
	}

	ff.Close();		

	RichEdit reBinPreview = ImportWizDlg.GetItem(IDC_BIW_HEADER_HEX_RICHEDIT, IDD_BIW_HEADER);
	reBinPreview.Text = strHexDumpTotal;

	RichEdit reAscPreview = ImportWizDlg.GetItem(IDC_BIW_HEADER_ASCII_RICHEDIT, IDD_BIW_HEADER);
	reAscPreview.Text = strAsciiDump;

	// Scroll hex wnd to top of file.  Why is this needed for hex wnd only?
	int iBinFirstVisible = 0 - reBinPreview.GetFirstVisibleLine();
	reBinPreview.LineScroll(iBinFirstVisible);
}

static void BinHeader_AddParamToListBox(int nIndex)
{
	string str;
	GetBinHdrParamListStr(str, nIndex);
	ListBox lbParams = ImportWizDlg.GetItem(IDC_BINHEADER_PARAMLIST, IDD_BIW_HEADER);
	lbParams.AddString(str);
}

static void BinHeader_UpdateParamListBox()
{
	/// EJP 04-23-2003 QA70-4321 PREVENT_CRASH_ON_REMOVAL_OF_LAST_PARAM
	ListBox lbParams = ImportWizDlg.GetItem(IDC_BINHEADER_PARAMLIST, IDD_BIW_HEADER);
	int iCurSel = lbParams.GetCurSel(); /// EJP 09-29-2003 v7.5709 QA70-5211.5 UPDATE_HDRVAR_ON_CHANGE_ENDIAN
	lbParams.ResetContent();
	/// end PREVENT_CRASH_ON_REMOVAL_OF_LAST_PARAM
	for( int n = 0; n < HDRPARAM_COUNT; n++ )
		BinHeader_AddParamToListBox(n);
	/// EJP 09-29-2003 v7.5709 QA70-5211.5 UPDATE_HDRVAR_ON_CHANGE_ENDIAN
	if( iCurSel >= 0 )
		lbParams.SetCurSel(iCurSel);
	/// end UPDATE_HDRVAR_ON_CHANGE_ENDIAN
}

static BOOL BinHeader_GetSelectedBytes(long &nFirst, long &nLast)
{
	long nStartChar, nEndChar;
	RichEdit reAscPreview = ImportWizDlg.GetItem(IDC_BIW_HEADER_ASCII_RICHEDIT, IDD_BIW_HEADER);
	reAscPreview.GetSel(nStartChar, nEndChar);
	if( nStartChar == nEndChar )
		return false;
	nFirst = GetByteOffsetFromAscPreviewCharIndex(nStartChar);
	nLast = GetByteOffsetFromAscPreviewCharIndex(nEndChar - 1);
	return true;
}

static BOOL BinHeader_GetParamInfo(int &nType, int &nOffset, int &nSize)
{
	long nFirst, nLast;
	if( !BinHeader_GetSelectedBytes(nFirst, nLast) )
		return false;

	nOffset = nFirst;

	ListBox lbParamType = ImportWizDlg.GetItem(IDC_BIW_HEADER_CANDINTERP_COMBO, IDD_BIW_HEADER);
	nType = lbParamType.GetCurSel();
	
	nSize = nLast - nFirst + 1;
	switch( nType )
	{
	case PARAM_TYPE_INT:
	case PARAM_TYPE_UINT:
		nType = (PARAM_TYPE_INT == nType ? BIP_TYPE_INT : BIP_TYPE_UINT);
		if( nSize > 4 )
			nSize = 4;
		else if( nSize == 3 )
			nSize = 2;
		break;
	case PARAM_TYPE_REAL:
		nType = BIP_TYPE_REAL;
		if( nSize >= 8 )
			nSize = 8;
		else
			nSize = 4;
		break;
	case PARAM_TYPE_STR:
		nType = BIP_TYPE_STRING;
		///nSize = nLast - nFirst;
		break;
	default:
		return false;
	}
	
	return true;
}

static int BinHeader_GetParamValAsStr(int nType, int nOffset, int nSize, string &strVal)
{
	file ff;
	if( ff.Open(s_strDataFile, file::modeRead|file::shareDenyRead|file::typeBinary) )
	{
		ReadBinaryHeaderParam(strVal, ff, nType, nOffset, nSize, !s_binimp.iBigEndian);
		ff.Close();
		return 0;
	}
	return 1; // failed to open
}

static void BinHeader_UpdateParamValPreview()
{
	string str;
	int nType, nOffset, nSize;
	if( BinHeader_GetParamInfo(nType, nOffset, nSize) )
		BinHeader_GetParamValAsStr(nType, nOffset, nSize, str);
	Edit edValue = ImportWizDlg.GetItem(IDC_BIW_HEADER_CANDINTERP_EDIT, IDD_BIW_HEADER);
	edValue.Text = str;
}

static int GetByteOffsetFromHexPreviewCharIndex(int iCharIndex)
{
	// Binary preview has 50 chars per line representing 16 bytes.
	// Each byte is represented by 3 chars (2 for value, 1 for space).
	// There are 2 additional chars for the CR/LF.
	int iLines = (iCharIndex / 50); // full lines
	iCharIndex %= 50;
	return ((iLines * 16) + (iCharIndex / 3));
}

static int GetHexPreviewCharIndexFromByteOffset(int iByteOffset)
{
	///iByteOffset--;
	int iLines = iByteOffset / 16;
	iByteOffset %= 16;
	return ((iLines * 50) + (iByteOffset * 3));
}

static int GetByteOffsetFromAscPreviewCharIndex(int iCharIndex)
{
	// ASC Preview has 18 chars per line representing 16 bytes.
	// Each byte is represented by 1 char.
	// There are 2 additional chars for the CR/LF.
	int iLines = (iCharIndex / 18); // full lines
	iCharIndex %= 18;
	return ((iLines * 16) + iCharIndex);
}

static int GetAscPreviewCharIndexFromByteOffset(int iByteOffset)
{
	///iByteOffset--;
	int iLines = iByteOffset / 16;
	iByteOffset %= 16;
	return ((iLines * 18) + iByteOffset);
}

////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Binary Pattern Page
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////

enum {
	GRIDCOL_BINPARAM_COLUMN = 0,
	GRIDCOL_BINPARAM_TYPE,
	GRIDCOL_BINPARAM_SIZE,
	GRIDCOL_BINPARAM_COUNT
};

static BOOL BinPattern_OnInit()
{
	ON_PAGE_CHECK_BIN_PATTERN

	// Setup the Data View controls
	Control pgSource = ImportWizDlg.GetItem(IDD_BIW_DATAPATERN);
	if( IS_BINPATTERN_BINVIEW )
		pgSource.CheckRadioButton(IDC_BIW_DATAPATERN_HEX, IDC_BIW_DATAPATERN_ASCII, IDC_BIW_DATAPATERN_HEX);
	else
		pgSource.CheckRadioButton(IDC_BIW_DATAPATERN_HEX, IDC_BIW_DATAPATERN_ASCII, IDC_BIW_DATAPATERN_ASCII);
	RichEdit reDataView = ImportWizDlg.GetItem(IDC_BIW_DATAPATERN_HEXDUMP_RICHEDIT, IDD_BIW_DATAPATERN);
	reDataView.SendMessage(EM_SETEVENTMASK, 0, ENM_CHANGE|ENM_SCROLL|ENM_SELCHANGE);
	/// EJP 10-20-2003 v7.5726 QA70-5374 ALLOW_CHANGING_PREVIEW_FONT
	///reDataView.SetFont(SYSTEM_FIXED_FONT);
	/// end ALLOW_CHANGING_PREVIEW_FONT
	BinPattern_UpdateDataView();
	
	// Setup the Pattern grid control
	Control ctrlGrid = ImportWizDlg.GetItem(IDC_BIW_DATAPATERN_PATERN_GRID, IDD_BIW_DATAPATERN);
	if( ctrlGrid )
	{
		Object objGrid = ctrlGrid.GetActiveXControl();
		if( objGrid )
		{
			objGrid.AllowUserResizing = flexResizeColumns;
			objGrid.Editable = flexEDKbdMouse;
			objGrid.Cols = 4;
			objGrid.FixedCols = 0;
			objGrid.Rows = 2; // column headers and 1 data row
			objGrid.Row = 0;
			objGrid.BackColorBkg = RGB(255, 255, 255);
			objGrid.Col = GRIDCOL_BINPARAM_COLUMN;
			objGrid.ColWidth(GRIDCOL_BINPARAM_COLUMN) = objGrid.ClientWidth * 0.15;
			objGrid.Text = _L("Column");
			objGrid.Col = GRIDCOL_BINPARAM_TYPE;
			objGrid.ColWidth(GRIDCOL_BINPARAM_TYPE) = objGrid.ClientWidth * 0.35;
			objGrid.Text = _L("Type");
			objGrid.Col = GRIDCOL_BINPARAM_SIZE;
			objGrid.ColWidth(GRIDCOL_BINPARAM_SIZE) = objGrid.ClientWidth * 0.25;
			objGrid.Text = _L("Size");
			objGrid.Col = GRIDCOL_BINPARAM_COUNT;
			objGrid.ColWidth(GRIDCOL_BINPARAM_COUNT) = objGrid.ClientWidth * 0.25;
			objGrid.Text = _L("Count");
			string str = BINIMP_DATA_TYPE_TOKENS;
			objGrid.ColComboList(GRIDCOL_BINPARAM_TYPE) = str;
			objGrid.Row = 1;
			objGrid.Col = 0;
			objGrid.Text = "1";
		}
	}

	BOOL bVisible = false;
	if( HDRPARAM_COUNT )
	{
		bVisible = true;
		
		string str;
		ComboBox comboParams = ImportWizDlg.GetItem(IDC_BIW_DATAPATERN_PARAMS, IDD_BIW_DATAPATERN);
		comboParams.ResetContent();
		for( int n = 0; n < HDRPARAM_COUNT; n++ )
		{
			GetBinHdrParamListStr(str, n);
			comboParams.AddString(str);
		}
	}

	Control ctrlParamText = ImportWizDlg.GetItem(IDC_PARAMETER_TEXT, IDD_BIW_DATAPATERN);
	ctrlParamText.Visible = bVisible;
	Control ctrlValueText = ImportWizDlg.GetItem(IDC_VALUE_TEXT, IDD_BIW_DATAPATERN);
	ctrlValueText.Visible = bVisible;
	ComboBox comboParams = ImportWizDlg.GetItem(IDC_BIW_DATAPATERN_PARAMS, IDD_BIW_DATAPATERN);
	comboParams.Visible = bVisible;
	Edit editValue = ImportWizDlg.GetItem(IDC_BIW_DATAPATERN_VALUE, IDD_BIW_DATAPATERN);
	editValue.Visible = bVisible;

	return true;
}

static BOOL BinPattern_OnActivate()
{
	ON_PAGE_CHECK_BIN_PATTERN

	/// EJP 10-20-2003 v7.5726 QA70-5374 ALLOW_CHANGING_PREVIEW_FONT
	iw_SetRichEditFont(IDC_BIW_DATAPATERN_HEXDUMP_RICHEDIT, IDD_BIW_DATAPATERN, IW_PREVIEW_FONT);
	WorksheetControl wc = ImportWizDlg.GetItem(IDC_BIW_DATAPATERN_PREVIEW_LC, IDD_BIW_DATAPATERN);
	if( wc )
		wc.SetFont(IW_PREVIEW_FONT);
	/// end ALLOW_CHANGING_PREVIEW_FONT

	BinPattern_UpdateGridFromParamVectors();
	BinCols_AddRowToGrid(); // a starting point for another param
	UpdatePreview(IDD_BIW_DATAPATERN);
	return TRUE;
}

static BOOL BinPattern_OnKillActive()
{
	ON_PAGE_CHECK_BIN_PATTERN
	return TRUE;
}

static BOOL BinPattern_OnClickDataView(Control ctrl)
{
	Control pgSource = ImportWizDlg.GetItem(IDD_BIW_DATAPATERN);
	int n = pgSource.GetCheckedRadioButton(IDC_BIW_DATAPATERN_HEX, IDC_BIW_DATAPATERN_ASCII);
	if( IDC_BIW_DATAPATERN_HEX == n )
		SET_BINPATTERN_BINVIEW;
	else
		SET_BINPATTERN_ASCVIEW;
	BinPattern_UpdateDataView();
	BinPattern_UpdateDataViewColoring();
	return TRUE;
}

static BOOL BinPattern_OnBeforeEditGrid(Control ctrl, int nRow, int nCol, BOOL *pCancel)
{
	Object objGrid = ctrl.GetActiveXControl();
	if( GRIDCOL_BINPARAM_COLUMN == nCol )
	{
		*pCancel = TRUE;
		return TRUE;
	}
	if( nRow == objGrid.Rows - 1 && GRIDCOL_BINPARAM_COUNT == nCol )
	{
		string str = objGrid.Cell(flexcpText, nRow, GRIDCOL_BINPARAM_COLUMN);
		if( !str.IsEmpty() && atoi(str) > 0 )
			objGrid.Rows += 1;
	}
	return TRUE;
}

static BOOL BinPattern_OnChangeEditGrid(Control ctrl)
{
	Object objGrid = ctrl.GetActiveXControl();
	if( GRIDCOL_BINPARAM_COUNT == objGrid.Col )
		BinPattern_UpdateDataColumnOffsetsInGrid(objGrid.Row);
	if( GRIDCOL_BINPARAM_COUNT == objGrid.Col || GRIDCOL_BINPARAM_SIZE == objGrid.Col )
	{
		BinPattern_UpdateParamVectorsFromGrid(objGrid.Row, objGrid.Col);
		UpdatePreview(IDD_BIW_DATAPATERN);
		BinPattern_UpdateDataViewColoring();
	}
	return TRUE;
}

static void BinPattern_OnGridComboCloseUp(Control ctrl, int nRow, int nCol, BOOL* pFinishEdit)
{
	Object objGrid = ctrl.GetActiveXControl();
	int iSel = objGrid.ComboIndex;
	objGrid.Col = GRIDCOL_BINPARAM_SIZE;
	if( PARAM_TYPE_INT == iSel || PARAM_TYPE_UINT == iSel )
		objGrid.Text = "4"; // default size of int/uint
	else if( PARAM_TYPE_REAL == iSel )
		objGrid.Text = "8"; // default size of Real
	if( PARAM_TYPE_STR != iSel ) // if param type is not string
		objGrid.Col = GRIDCOL_BINPARAM_COUNT; // set focus to the Count column
	BinPattern_UpdateParamVectorsFromGrid(objGrid.Row, GRIDCOL_BINPARAM_TYPE);
	UpdatePreview(IDD_BIW_DATAPATERN);
	BinPattern_UpdateDataViewColoring();
	objGrid.FinishEditing(FALSE);
}	

static void BinPattern_UpdateDataViewColoring()
{
	Control octrl = ImportWizDlg.GetItem(IDC_BIW_DATAPATERN_PATERN_GRID, IDD_BIW_DATAPATERN);
	Object grdPattern = octrl.GetActiveXControl();
	RichEdit rePreview = ImportWizDlg.GetItem(IDC_BIW_DATAPATERN_HEXDUMP_RICHEDIT, IDD_BIW_DATAPATERN);
	string strLength, strCount;
	int iLines;
	int iTotal;
	for(int iRows = 1; iRows < grdPattern.Rows; iRows++)
	{
		strLength = grdPattern.Cell(0, iRows, 2);
		strCount = grdPattern.Cell(0, iRows, 3);
		/// EJP 11-11-2003 v7.5751 QA70-5211.7 FIX_USED_BYTES_COLORING
		///if(iRows == grdPattern.Row && atoi(strCount) == 0)
		///	strCount = grdPattern.EditText;
		if( iRows == grdPattern.Row )
		{
			string str;
			str = grdPattern.EditText;
			if( !str.IsEmpty() )
			{
				if( 2 == grdPattern.Col )
					strLength = grdPattern.EditText;
				else
					strCount = grdPattern.EditText;
			}
		}
		/// end FIX_USED_BYTES_COLORING
		if(atoi(strLength) * atoi(strCount) == 0)
			break;
		iTotal = iTotal + (atoi(strLength) * atoi(strCount));
	}
 	if(ImportWizDlg.Page.DataPatern.Hex == 1)
	{		
		iTotal *= 3;
	}
	else
	{
		iLines = iTotal/20;
		iTotal += (iLines * 2);
	}
	int nTotal = 0;
	int nLineCount = rePreview.GetLineCount();
	for (int ii = 0; ii < nLineCount; ii++)
	{
		nTotal += rePreview.LineLength(ii) + 2;
	}
	rePreview.SetTextColor(0, nTotal, RGB(0, 0, 0));
	rePreview.SetTextColor(0, iTotal, RGB(0, 0, 255));
	rePreview.SetSel(0, 0); // put cursor at beginning of first line
}

static BOOL BinPattern_OnClickInsertRow(Control ctrl)
{
	Control ctrlGrid = ImportWizDlg.GetItem(IDC_BIW_DATAPATERN_PATERN_GRID, IDD_BIW_DATAPATERN);
	Object objGrid = ctrlGrid.GetActiveXControl();
	/// EJP 09-04-2003 v7.5684 QA70-5106 INSERT_BIN_PATTERN_BEFORE_FIRST_ROW
	///if( objGrid.Row <= 1 )
	if( objGrid.Row < 1 )
	/// end INSERT_BIN_PATTERN_BEFORE_FIRST_ROW
		objGrid.Rows += 1;
	else
		objGrid.AddItem("", objGrid.Row);
	BinPattern_UpdateDataColumnOffsetsInGrid(-1);
	BinPattern_UpdateParamVectorsFromGrid(-1,-1);
	UpdatePreview(IDD_BIW_DATAPATERN);
	BinPattern_UpdateDataViewColoring();
	return TRUE;
}

static BOOL BinPattern_OnClickDeleteRow(Control oCntrl)
{
	Control ctrlGrid = ImportWizDlg.GetItem(IDC_BIW_DATAPATERN_PATERN_GRID, IDD_BIW_DATAPATERN);
	Object objGrid = ctrlGrid.GetActiveXControl();
	if( objGrid.Row < 1 )
		return TRUE;
	objGrid.RemoveItem(objGrid.Row);
	BinPattern_UpdateDataColumnOffsetsInGrid(-1);
	BinPattern_UpdateParamVectorsFromGrid(-1,-1);
	UpdatePreview(IDD_BIW_DATAPATERN);
	BinPattern_UpdateDataViewColoring();
	return TRUE;
}

static BOOL BinPattern_UpdateDataView()
{
	int nRead;
	int nCurRows = BIN_HDR_PREVIEW_NUM_ROWS;//CPY 1/1/03
	string strDumpTotal;

	file ff;
	if( FALSE == ff.Open(s_strDataFile, file::modeRead | file::shareDenyRead | file::typeBinary) )
		return FALSE;
	
	ff.Seek(s_binimp.iHeaderBytes, file::begin);

	if( IS_BINPATTERN_BINVIEW )
	{
		BYTE by[BIN_DATA_PREVIEW_NUM_BYTES];
		nRead = ff.Read(by, BIN_DATA_PREVIEW_NUM_BYTES);
		if( nRead )
			strDumpTotal = GetHexDump(by, nRead);
	}
	else // Show as ASCII
	{
		char szTemp[BIN_DATA_PREVIEW_BYTES_PER_ROW + 1];
		for( int iRow = 0; iRow < nCurRows; iRow++ )
		{
			nRead = ff.Read(szTemp, BIN_DATA_PREVIEW_BYTES_PER_ROW);
			if( 0 == nRead )
				break;
			szTemp[nRead] = 0; // NULL terminate string
	
			for( int iChar = 0; iChar < nRead; iChar++ )
			{
				// Display all non-visible chars as periods.
				if( szTemp[iChar] < 32 || 127 < szTemp[iChar] )
					szTemp[iChar] = '.';			
			}
			strDumpTotal += szTemp;
			strDumpTotal += "\r\n";
		}
	}
	ff.Close();		
	ImportWizDlg.Page.DataPatern.HexDump$ = strDumpTotal;
	return TRUE;
}

static BOOL BinPattern_OnSelChangeHeaderVariable(Control ctrl)
{
	/* Will get to this after ver 8 beta1 is out
	string ltString = "%A=IW!Page.BinHeader.HeaderParams.v$(IW!Page.DataPatern.Parameters.Choice)$;"
					  "%A=%[%A,>'='];"
					  "IW!Page.DataPatern.value.v1$=%A;";
	LT_execute(ltString);
	*/
	return true;
}

static void BinPattern_UpdateDataColumnOffsetsInGrid(int iEditTextRow)
{
	Control ctrlGrid = ImportWizDlg.GetItem(IDC_BIW_DATAPATERN_PATERN_GRID, IDD_BIW_DATAPATERN);
	Object objGrid = ctrlGrid.GetActiveXControl();

	if( objGrid.Rows <= 1 )
		return; // nothing to do

	string str;
	int iCount, iDataCol = 1; // first data col is always 1
	for(int iRow = 1; iRow < objGrid.Rows; iRow++ )
	{
		objGrid.Cell(flexcpText, iRow, GRIDCOL_BINPARAM_COLUMN) = iDataCol;
		if( iRow == iEditTextRow )
			str = objGrid.EditText;
		else
			str = objGrid.Cell(flexcpText, iRow, GRIDCOL_BINPARAM_COUNT);
		iCount = atoi(str);
		iDataCol += iCount;
	}
}

static void BinPattern_UpdateGridFromParamVectors()
{
	Control ctrlGrid = ImportWizDlg.GetItem(IDC_BIW_DATAPATERN_PATERN_GRID, IDD_BIW_DATAPATERN);
	if( !ctrlGrid )
		return;
	Object objGrid = ctrlGrid.GetActiveXControl();
	if( !objGrid )
		return;
	
	objGrid.Rows = 1; // 1 for only the column headings

	if( s_binimp.vParamCount.GetSize() > 0 )
	{
		
		objGrid.Rows = s_binimp.vParamCount.GetSize() + 1;
		int iColumns = 1;

		string strBinImpDataTypes(BINIMP_DATA_TYPE_TOKENS); 

		for( int iParam = 0; iParam < s_binimp.vParamCount.GetSize(); iParam++ )
		{
			objGrid.Row = iParam + 1;

			objGrid.Col = GRIDCOL_BINPARAM_COLUMN;
			objGrid.Text = iColumns;
			
			iColumns += s_binimp.vParamCount[iParam];
			
			objGrid.Col = GRIDCOL_BINPARAM_TYPE;
			if( s_binimp.vParamType[iParam] == BIP_TYPE_INT )
				objGrid.Text = strBinImpDataTypes.GetToken(PARAM_TYPE_INT, '|');
			else if( s_binimp.vParamType[iParam] == BIP_TYPE_UINT )
				objGrid.Text = strBinImpDataTypes.GetToken(PARAM_TYPE_UINT, '|');
			else if( s_binimp.vParamType[iParam] == BIP_TYPE_REAL )
				objGrid.Text = strBinImpDataTypes.GetToken(PARAM_TYPE_REAL, '|');
			else if( s_binimp.vParamType[iParam] == BIP_TYPE_STRING )
				objGrid.Text = strBinImpDataTypes.GetToken(PARAM_TYPE_STR, '|');

			objGrid.Col = GRIDCOL_BINPARAM_SIZE;
			objGrid.Text = s_binimp.vParamSize[iParam];
			
			objGrid.Col = GRIDCOL_BINPARAM_COUNT;
			objGrid.Text = s_binimp.vParamCount[iParam];
		}
	}
}

static void BinPattern_UpdateParamVectorsFromGrid(int iEditTextRow, int iEditTextCol)
{
	s_binimp.vParamType.SetSize(0);
	s_binimp.vParamCount.SetSize(0);
	s_binimp.vParamSize.SetSize(0);

	int iBinImpDataTypes[] = {BIP_TYPE_INT, BIP_TYPE_UINT, BIP_TYPE_REAL, BIP_TYPE_STRING};
	
	string strBinImpDataTypes(BINIMP_DATA_TYPE_TOKENS);
	
	string strType, strCount, strSize;
	int iType, iCount, iSize;

	Control ctrlGrid = ImportWizDlg.GetItem(IDC_BIW_DATAPATERN_PATERN_GRID, IDD_BIW_DATAPATERN);
	Object objGrid = ctrlGrid.GetActiveXControl();

	for(int iRow = 1; iRow < objGrid.Rows; iRow++ )
	{
		strType = objGrid.Cell(flexcpText, iRow, GRIDCOL_BINPARAM_TYPE);
		if( strType.IsEmpty() )
			break;
		iType = strBinImpDataTypes.FindToken(strType, '|');
		if( iType < 0 || iType > 3 )
			break;
		
		if( iRow == iEditTextRow && GRIDCOL_BINPARAM_COUNT == iEditTextCol )
			strCount = objGrid.EditText;
		else
			strCount = objGrid.Cell(flexcpText, iRow, GRIDCOL_BINPARAM_COUNT);
		iCount = atoi(strCount);
///		if( iCount <= 0 )
///			break;
		
		if( iRow == iEditTextRow && GRIDCOL_BINPARAM_SIZE == iEditTextCol )
			strSize = objGrid.EditText;
		else
			strSize = objGrid.Cell(flexcpText, iRow, GRIDCOL_BINPARAM_SIZE);
		iSize = atoi(strSize);
///		if( iSize <= 0 )
///			break;
		
		s_binimp.vParamType.Add(iBinImpDataTypes[iType]);
		s_binimp.vParamCount.Add(iCount);
		s_binimp.vParamSize.Add(iSize);
	}
	
	s_binimp.iNumColumns = 0;
	for( int i = 0; i < s_binimp.vParamCount.GetSize(); i++ )
		s_binimp.iNumColumns += s_binimp.vParamCount[i];
}

static void BinCols_AddRowToGrid()
{
	Control ctrlGrid = ImportWizDlg.GetItem(IDC_BIW_DATAPATERN_PATERN_GRID, IDD_BIW_DATAPATERN);
	if( !ctrlGrid )
		return;
	Object objGrid = ctrlGrid.GetActiveXControl();
	if( !objGrid )
		return;
	objGrid.AddItem("", objGrid.Rows);
	BinPattern_UpdateDataColumnOffsetsInGrid(-1);
}

////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// User Defined Page
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////

static BOOL UserDefined_OnInit()
{
	ON_PAGE_CHECK_USER_DEFINED
	return TRUE;
}

static BOOL UserDefined_OnActive()
{
	ON_PAGE_CHECK_USER_DEFINED
	return UserDefined_Update();
}

static BOOL UserDefined_OnKillActive()
{
	ON_PAGE_CHECK_USER_DEFINED
	return UserDefined_Update(FALSE);
}

static BOOL UserDefined_OnClickBrowse(Control ctrl)
{
	string strPath = GetOpenBox("[Origin C (*.c;*.cpp)] *.c;*.cpp");
	if( !strPath.IsEmpty() )
	{
		Edit editPath = ImportWizDlg.GetItem(IDC_USER_DEF_FOLDER_PATH, IDD_IW_USER_DEFINED);
		editPath.Text = strPath;
	}
	return TRUE;
}

static BOOL UserDefined_Update(BOOL bTreeToDlg=TRUE)
{
	Edit editPath = ImportWizDlg.GetItem(IDC_USER_DEF_FOLDER_PATH, IDD_IW_USER_DEFINED);
	Edit editFunc = ImportWizDlg.GetItem(IDC_USER_DEFINED_FUNCTION, IDD_IW_USER_DEFINED);
	
	if( bTreeToDlg )
	{
		///editPath.Text = s_trFilter.Common.OCFile.strVal;
		///editFunc.Text = s_trFilter.Common.OCFunction.strVal;
		string strOCFile, strOCFunction;
		fuGetUserDefinedFunction(s_trFilter, strOCFile, strOCFunction);
		editPath.Text = strOCFile;
		editFunc.Text = strOCFunction;
	}
	else // dialog to tree
	{
		///s_trFilter.Common.OCFile.strVal = editPath.Text;
		///s_trFilter.Common.OCFunction.strVal = editFunc.Text;
		fuSetUserDefinedFunction(s_trFilter, editPath.Text, editFunc.Text);
	}

	return TRUE;	
}

////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// File Types Page
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////

static BOOL FileTypes_OnIsShow()
{
	// This page is not used in v7.5.  It will be used in v8 when Origin's
	// dynamic import menu is implemented.
	return FALSE;
}

static BOOL FileTypes_OnInit()
{
	ON_PAGE_CHECK_FILE_TYPES
	FileTypes_SetupGrid();
	return TRUE;
}

static BOOL FileTypes_OnActive()
{
	ON_PAGE_CHECK_FILE_TYPES
	return FileTypes_UpdateData();
}

static BOOL FileTypes_OnKillActive()
{
	ON_PAGE_CHECK_FILE_TYPES
	return FileTypes_UpdateData(FALSE);
}

static BOOL FileTypes_OnBeforeEditTypes(Control ctrl, int iRow, int iCol, BOOL *pCancel)
{
	if( iCol == 0 )
		*pCancel = true; // do not allow editing first column
	return true;
}

static BOOL FileTypes_UpdateData(BOOL bDataToDlg=TRUE)
{
	Edit editGroupName = ImportWizDlg.GetItem(IDC_FILE_TYPES_GROUP_NAME, IDD_IW_FILETYPES);
	
	if( bDataToDlg )
	{
		fuGetFilesOfTypeGroupName(s_trFilter, editGroupName.Text);
		FileTypes_UpdateGridFromTree();
	}
	else // dialog to data
	{
		fuSetFilesOfTypeGroupName(s_trFilter, editGroupName.Text);
		FileTypes_UpdateTreeFromGrid();
	}

	return TRUE;	
}

static void FileTypes_UpdateTreeFromGrid()
{
	string str;
	StringArray saFileSpecNames;

	Control ctrlGrid = ImportWizDlg.GetItem(IDC_FILE_TYPES_WILDCARDS_GRID, IDD_IW_FILETYPES);
	Object objGrid = ctrlGrid.GetActiveXControl();
	for( int i = 1; i < objGrid.Rows; i++ )
	{
		objGrid.Row = i;
		str = objGrid.Text;
		saFileSpecNames.Add(str);
	}
	fuSetFilesOfType(s_trFilter, saFileSpecNames);
}

static void FileTypes_UpdateGridFromTree()
{
	Control ctrlGrid = ImportWizDlg.GetItem(IDC_FILE_TYPES_WILDCARDS_GRID, IDD_IW_FILETYPES);
	if( !ctrlGrid )
		return;

	Object objGrid = ctrlGrid.GetActiveXControl();
	if( !objGrid )
		return;

	objGrid.Rows = 1;

	string str;
	fuGetFileSpec(s_trFilter, str);
	if( str.IsEmpty() )
		return;
	FileTypes_UpdateGridFromExtList(str);

	StringArray saFileSpecNames;
	fuGetFilesOfType(s_trFilter, saFileSpecNames);

	objGrid.Col = 1; // 2nd column holds file spec names
	objGrid.Row = 1; // start at row after column headings
	
	for( int i = 0; i < saFileSpecNames.GetSize(); i++ )
	{
		objGrid.Row = i + 1; // +1 to skip col headings
		objGrid.Text = saFileSpecNames[i];
	}
}

static void FileTypes_UpdateGridFromExtList(LPCSTR lpcstrFileSpecList)
{
	Control ctrlGrid = ImportWizDlg.GetItem(IDC_FILE_TYPES_WILDCARDS_GRID, IDD_IW_FILETYPES);
	if( !ctrlGrid )
		return;
	
	Object objGrid = ctrlGrid.GetActiveXControl();
	if( !objGrid )
		return;
	
	objGrid.Rows = 1; // only the column headings
	objGrid.Col = 0; // first column holds file spec

	StringArray saFileSpecs;
	string strFileSpecs(lpcstrFileSpecList);
	strFileSpecs.GetTokens(saFileSpecs, ';');

	for( int i = 0; i < saFileSpecs.GetSize(); i++ )
	{
		objGrid.Rows = i + 2; // +2 = 1(col headings)+1(1 based)
		objGrid.Row = i + 1; // +1 to skip col headings
		objGrid.Text = saFileSpecs[i];
	}
}

static void FileTypes_SetupGrid()
{
	Control ctrlGrid = ImportWizDlg.GetItem(IDC_FILE_TYPES_WILDCARDS_GRID, IDD_IW_FILETYPES);
	if( !ctrlGrid )
		return;
	
	Object objGrid = ctrlGrid.GetActiveXControl();
	if( !objGrid )
		return;

	objGrid.Cols = 2;
	objGrid.Rows = 1;
	objGrid.Editable = 1;
	objGrid.Fixedcols = 0;
	objGrid.ScrollBars = 3;

	objGrid.Row = 0; // first row is for column headings

	// File Spec
	objGrid.Col = 0;
	objGrid.ColWidth(0) = objGrid.ClientWidth / objGrid.Cols;
	objGrid.Text = "File Spec.";

	// File Spec Name
	objGrid.Col = 1;
	objGrid.ColWidth(1) = objGrid.ClientWidth / objGrid.Cols;
	objGrid.Text = "File Spec. Name";
}	

////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Drag and Drop Page
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////

static BOOL DragDrop_OnInit()
{
	ON_PAGE_CHECK_DRAG_DROP
	/// EJP 09-10-2003 v7.5890 QA70-5135.11 REMOVE_PLOTPAGE_OPTION_FROM_DRAGDROP_PAGE
	/*
	if( !(s_iActivePageType == EXIST_PLOT) )
	{
		ComboBox cbGraph = ImportWizDlg.GetItem(IDC_DROP_FILES_IN_GRAPH, IDD_IW_DRAP_AND_DROP);
		if( cbGraph.GetCount() > FILTER_DDGRAPH_PLOTSETTINGS )
			cbGraph.DeleteString(FILTER_DDGRAPH_PLOTSETTINGS);
	}
	*/
	/// end REMOVE_PLOTPAGE_OPTION_FROM_DRAGDROP_PAGE
	return TRUE;
}

static BOOL DragDrop_OnActive()
{
	ON_PAGE_CHECK_DRAG_DROP
	DragDrop_Update();

#ifdef DISABLE_FILE_TYPES_PAGE
	Button btnNext = ImportWizDlg.GetItem(IDC_NEXT);
	btnNext.Enable = FALSE;
#endif // ENABLE_FILE_TYPES_PAGE

	return TRUE;
}

static BOOL DragDrop_OnKillActive()
{
	ON_PAGE_CHECK_DRAG_DROP
	DragDrop_Update(FALSE);

#ifdef DISABLE_FILE_TYPES_PAGE
	Button btnNext = ImportWizDlg.GetItem(IDC_NEXT);
	btnNext.Enable = TRUE;
#endif // ENABLE_FILE_TYPES_PAGE

	return TRUE;
}

static void DragDrop_Update(BOOL bDataToDlg=TRUE)
{
	string str;
	
	ComboBox cbGraph = ImportWizDlg.GetItem(IDC_DROP_FILES_IN_GRAPH, IDD_IW_DRAP_AND_DROP);
	ComboBox cbWorkspace = ImportWizDlg.GetItem(IDC_DROP_FILES_IN_WKSP, IDD_IW_DRAP_AND_DROP);
	/// EJP 07-07-2003 v7.0619 QA70-4783 POST_IMPORT_EXECUTE
	Edit ebScript = ImportWizDlg.GetItem(IDC_POST_IMPORT_EXECUTE, IDD_IW_DRAP_AND_DROP);
	/// end POST_IMPORT_EXECUTE
	
	if( bDataToDlg )
	{
		cbGraph.SetCurSel(fuGetDragDropGraph(s_trFilter));
		cbWorkspace.SetCurSel(fuGetDragDropWorkspace(s_trFilter));
		
		Edit ebOpenIn = ImportWizDlg.GetItem(IDC_OPEN_FILES_IN, IDD_IW_DRAP_AND_DROP);
		int i = fuGetTargetPageType(s_trFilter);
		if( EXIST_MATRIX == i )
			ebOpenIn.Text = "Matrix";
		else
			ebOpenIn.Text = "Worksheet";
		
		/// EJP 07-07-2003 v7.0619 QA70-4783 POST_IMPORT_EXECUTE
		fuGetPostImportScript(s_trFilter, str);
		ebScript.Text = str;
		/// end POST_IMPORT_EXECUTE
	}
	else
	{
		fuSetDragDropGraph(s_trFilter, cbGraph.GetCurSel());
		fuSetDragDropWorkspace(s_trFilter, cbWorkspace.GetCurSel());

		/// EJP 07-07-2003 v7.0619 QA70-4783 POST_IMPORT_EXECUTE
		str = ebScript.Text;
		str.TrimLeft();
		str.TrimRight();
		fuSetPostImportScript(s_trFilter, str);
		/// end POST_IMPORT_EXECUTE
	}
}

////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// SaveFilters page functions
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////

static BOOL SaveFilters_OnInit()
{
	ON_PAGE_CHECK_SAVE_FILTER
	return TRUE;
}

static BOOL SaveFilters_OnActive()
{
	ON_PAGE_CHECK_SAVE_FILTER
	SaveFilters_UpdateData(); // tree to dlg
	SaveFilters_EnableControls();
	SaveFilter_UpdateFilterComboBox();
	SaveFilter_UpdateButtons();
	return TRUE;
}

static BOOL SaveFilters_OnKillActive()
{
	ON_PAGE_CHECK_SAVE_FILTER
	SaveFilters_UpdateData(FALSE); // FALSE = dlg to tree
	return TRUE;
}

static BOOL SaveFilters_OnClickSaveFilter(Control ctrl)
{
	Button chkSaveFilter(ctrl);
	if( chkSaveFilter.Check )
		ENABLE_SAVE_FILTER;
	else
		DISABLE_SAVE_FILTER;
	SaveFilters_EnableControls();
	SaveFilter_UpdateButtons();
	return TRUE;
}

static BOOL	SaveFilters_OnClickAdvanced(Control ctrl)
{
	Button chkAdvOptions(ctrl);
	if( chkAdvOptions.Check )
		ENABLE_ADVOPTIONS_ISCHECKED;
	else
		DISABLE_ADVOPTIONS_ISCHECKED;
	SaveFilter_UpdateButtons();
	return TRUE;
}

static BOOL	SaveFilters_OnClickDestination(Control ctrl)
{
	Control page = ImportWizDlg.GetItem(IDD_IW_SAVE_FILTERS);
	/// EJP 07-16-2003 v7.0627 QA70-4818 SAVE_FILTER_IN_WKS
	///s_iSaveFilter = page.GetCheckedRadioButton(IDC_SAVE_FILTER_DATA_FOLDER_RADIO, IDC_SAVE_FILTER_GLOBAL_RADIO);
	s_iSaveFilter = page.GetCheckedRadioButton(IDC_SAVE_FILTER_DATA_FOLDER_RADIO, IDC_SAVE_FILTER_IN_WKS);
	/// end SAVE_FILTER_IN_WKS
	
	SaveFilter_UpdateFilterComboBox();
	
	/// EJP 07-16-2003 v7.0627 QA70-4818 SAVE_FILTER_IN_WKS
	SaveFilters_EnableControls();
	SaveFilter_UpdateButtons();
	/// end SAVE_FILTER_IN_WKS
	return TRUE;
}

static BOOL	SaveFilter_OnSelChangeFilterName(Control ctrl)
{
	ComboBox comboName(ctrl);
	int n = comboName.GetCurSel();
	string str;
	comboName.GetLBText(n, str);
	comboName.Text = str;
	SaveFilter_UpdateButtons();
	return TRUE;
}

static BOOL	SaveFilter_OnEditChangeFilterName(Control ctrl)
{
	SaveFilter_UpdateButtons();
	return TRUE;
}

static void	SaveFilters_EnableControls()
{
	BOOL bEnable = IS_SAVE_FILTER;

	Button rbDataFolder = ImportWizDlg.GetItem(IDC_SAVE_FILTER_DATA_FOLDER_RADIO, IDD_IW_SAVE_FILTERS);
	rbDataFolder.Enable = bEnable;
	
	Button rbUserFolder = ImportWizDlg.GetItem(IDC_SAVE_FILTER_GLOBAL_RADIO, IDD_IW_SAVE_FILTERS);
	rbUserFolder.Enable = bEnable;

	/// EJP 07-16-2003 v7.0627 QA70-4818 SAVE_FILTER_IN_WKS
	Button rbWks = ImportWizDlg.GetItem(IDC_SAVE_FILTER_IN_WKS, IDD_IW_SAVE_FILTERS);
	rbWks.Enable = bEnable;
	
	BOOL bEnableName = bEnable;
	if( bEnable && IDC_SAVE_FILTER_IN_WKS == s_iSaveFilter )
		bEnableName = FALSE;
	/// end SAVE_FILTER_IN_WKS

	/// EJP 09-24-2003 v7.5706 QA70-4073.55 ADD_FILTER_DESCRIPTION
	Edit ebDescrip = ImportWizDlg.GetItem(IDC_FILTER_DESCRIP, IDD_IW_SAVE_FILTERS);
	ebDescrip.Enable = bEnableName;
	/// end ADD_FILTER_DESCRIPTION

	ComboBox cbName = ImportWizDlg.GetItem(IDC_SAVE_FILTERS_NAME_COMBO, IDD_IW_SAVE_FILTERS);
	/// EJP 07-16-2003 v7.0627 QA70-4818 SAVE_FILTER_IN_WKS
	///cbName.Enable = bEnable;
	cbName.Enable = bEnableName;
	/// end SAVE_FILTER_IN_WKS
	
	Edit editWildCard = ImportWizDlg.GetItem(IDC_SAVE_FILTERS_APPLICABILITY_EDIT, IDD_IW_SAVE_FILTERS);
	editWildCard.Enable = bEnable;
	
	Button chkAdvOptions = ImportWizDlg.GetItem(IDC_SAVE_FILTERS_ADVANCED, IDD_IW_SAVE_FILTERS);
	chkAdvOptions.Enable = bEnable;
}

static BOOL SaveFilters_UpdateData(BOOL bDataToDlg=TRUE)
{
	string str;

	Control page = ImportWizDlg.GetItem(IDD_IW_SAVE_FILTERS);
	Button chkSaveFilter = ImportWizDlg.GetItem(IDC_SAVE_FILTER, IDD_IW_SAVE_FILTERS);
	ComboBox comboName = ImportWizDlg.GetItem(IDC_SAVE_FILTERS_NAME_COMBO, IDD_IW_SAVE_FILTERS);
	Edit editFileSpec = ImportWizDlg.GetItem(IDC_SAVE_FILTERS_APPLICABILITY_EDIT, IDD_IW_SAVE_FILTERS);
	Button chkAdvOptions = ImportWizDlg.GetItem(IDC_SAVE_FILTERS_ADVANCED, IDD_IW_SAVE_FILTERS);

	/// EJP 09-24-2003 v7.5706 QA70-4073.55 ADD_FILTER_DESCRIPTION
	Edit ebDescrip = ImportWizDlg.GetItem(IDC_FILTER_DESCRIP, IDD_IW_SAVE_FILTERS);
	/// end ADD_FILTER_DESCRIPTION

	if( bDataToDlg )
	{
		/// EJP 07-08-2003 v7.0620 QA70-4792 MAKE_IMPWIZ_UI_MORE_CLEAR
		Edit ebDataFolder = ImportWizDlg.GetItem(IDC_SAVE_FILTER_DATA_PATH, IDD_IW_SAVE_FILTERS);
		ebDataFolder.Text = GetFilePath(s_strDataFile);
	
		str.Format("%s%s", GetAppPath(), FILTERS_FOLDER_NAME);
		Edit ebUserFilesFolder = ImportWizDlg.GetItem(IDC_SAVE_FILTER_USER_PATH, IDD_IW_SAVE_FILTERS);
		ebUserFilesFolder.Text = str;
		
		/// EJP 07-18-2003 v7.0627 QA70-4818 SAVE_FILTER_IN_WKS
		///// If filter file is from data file path
		///if( 0 == ebDataFolder.Text.CompareNoCase(GetFilePath(s_strFilter)) )
		///	s_iSaveFilter = IDC_SAVE_FILTER_DATA_FOLDER_RADIO;
		///else
		///	s_iSaveFilter = IDC_SAVE_FILTER_GLOBAL_RADIO;
		/// end SAVE_FILTER_IN_WKS
		/// end MAKE_IMPWIZ_UI_MORE_CLEAR

		chkSaveFilter.Check = (IS_SAVE_FILTER ? 1 : 0);

		/// EJP 07-16-2003 v7.0627 QA70-4818 SAVE_FILTER_IN_WKS
		///page.CheckRadioButton(IDC_SAVE_FILTER_DATA_FOLDER_RADIO, IDC_SAVE_FILTER_GLOBAL_RADIO, s_iSaveFilter);
		page.CheckRadioButton(IDC_SAVE_FILTER_DATA_FOLDER_RADIO, IDC_SAVE_FILTER_IN_WKS, s_iSaveFilter);
		/// end SAVE_FILTER_IN_WKS

		comboName.Text = GetFilename(s_strFilter, true); // true=strip file ext
		
		fuGetFileSpec(s_trFilter, str);
		if( str.IsEmpty() )
			str = AIW_GetExtensionFromPath(s_strDataFile);
		editFileSpec.Text = str;
		
		chkAdvOptions.Check = (IS_ADVOPTIONS_ISCHECKED ? 1 : 0);

		/// EJP 09-24-2003 v7.5706 QA70-4073.55 ADD_FILTER_DESCRIPTION
		if( !fuGetDescription(s_trFilter, str) )
			str.Empty();
		ebDescrip.Text = str;
		/// end ADD_FILTER_DESCRIPTION
	}
	else
	{
		/// EJP 07-16-2003 v7.0627 QA70-4818 SAVE_FILTER_IN_WKS
		///s_iSaveFilter = page.GetCheckedRadioButton(IDC_SAVE_FILTER_DATA_FOLDER_RADIO, IDC_SAVE_FILTER_GLOBAL_RADIO);
		/// end SAVE_FILTER_IN_WKS
		
		fuSetFileSpec(s_trFilter, editFileSpec.Text);
		s_strFilter = comboName.Text;
		
		if( chkAdvOptions.Check )
			ENABLE_ADVOPTIONS_ISCHECKED;
		else
			DISABLE_ADVOPTIONS_ISCHECKED;

		/// EJP 09-24-2003 v7.5706 QA70-4073.55 ADD_FILTER_DESCRIPTION
		fuSetDescription(s_trFilter, ebDescrip.Text);
		/// end ADD_FILTER_DESCRIPTION
	}
	return TRUE;
}

static void SaveFilter_UpdateButtons()
{
	bool bNext, bFinish;

	if( IS_SAVE_FILTER )
	{
		ComboBox cbName = ImportWizDlg.GetItem(IDC_SAVE_FILTERS_NAME_COMBO, IDD_IW_SAVE_FILTERS);
		/// EJP 07-17-2003 v7.0627 QA70-4818 SAVE_FILTER_IN_WKS
		if( IDC_SAVE_FILTER_IN_WKS == s_iSaveFilter )
			bFinish = TRUE;
		else
		{
		/// end SAVE_FILTER_IN_WKS
			string str = cbName.Text; // copy to string to avoid edit box from entering text backwards
			bFinish = !str.IsEmpty();
		} /// end SAVE_FILTER_IN_WKS
		bNext = (IS_ADVOPTIONS_ISCHECKED && bFinish);
	}
	else
	{
		bNext = false;
		bFinish = true;
	}

	Button btnNext = ImportWizDlg.GetItem(IDC_NEXT);
	btnNext.Enable = bNext;
	
	Button btnFinish = ImportWizDlg.GetItem(IDC_FINISH);
	btnFinish.Enable = bFinish;
}

static void SaveFilter_UpdateFilterComboBox()
{
	string strPath;
	if( IDC_SAVE_FILTER_GLOBAL_RADIO == s_iSaveFilter )
		strPath.Format("%s%s", GetAppPath(), FILTERS_FOLDER_NAME);
	else if( IDC_SAVE_FILTER_DATA_FOLDER_RADIO == s_iSaveFilter )
		strPath = GetFilePath(s_strDataFile);
	if( !strPath.IsEmpty() )
	{
		ComboBox cbFilters = ImportWizDlg.GetItem(IDC_SAVE_FILTERS_NAME_COMBO, IDD_IW_SAVE_FILTERS);
		string str = cbFilters.Text;
		iwFillFilterComboBox(cbFilters, strPath);
		cbFilters.Text = str;
	}
}

////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Common Functions
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////

static BOOL OnIsShowASCII(DWORD dwPageID, DWORD lParam)
{
	return IS_FILTER_TYPE_ASCII;
}

static BOOL OnIsShowBinary(DWORD dwPageID, DWORD lParam)
{
	return IS_FILTER_TYPE_BINARY;
}

//--------------------------------------------------------------------------
// OnIsShowUserDefined
//
// ON_PAGE_IS_SHOW handler function for all User Defined pages.
//--------------------------------------------------------------------------
static BOOL OnIsShowUserDefined(DWORD dwPageID, DWORD lParam)
{
	return IS_FILTER_TYPE_USERDEFINED;
}

//--------------------------------------------------------------------------
// OnIsShowAdvanced
//
// ON_PAGE_IS_SHOW handler function for all User Defined pages.
//--------------------------------------------------------------------------
static BOOL OnIsShowAdvanced(DWORD dwPageID, DWORD lParam)
{
	return IS_SHOW_ADVANCED;
}


static int AddBinHdrParam(LPCSTR lpcszName, int nType, int nSize, int nOffset)
{
	s_saHdrParamName.Add(lpcszName);
	s_vHdrParamType.Add(nType);
	s_vHdrParamSize.Add(nSize);
	s_vHdrParamOffset.Add(nOffset);
	return s_saHdrParamName.GetSize();
}

static BOOL DelBinHdrParam(int nIndex)
{
	s_saHdrParamName.RemoveAt(nIndex);
	s_vHdrParamType.RemoveAt(nIndex);
	s_vHdrParamSize.RemoveAt(nIndex);
	s_vHdrParamOffset.RemoveAt(nIndex);
	for( int i = nIndex; i < HDRPARAM_COUNT; i++ )
		s_saHdrParamName[i].Format("P%d", i+1);
	return true;
}

static BOOL GetBinHdrParamListStr(string &str, int nIndex, BOOL bWithValue=true)
{
	if( nIndex < 0 || nIndex >= HDRPARAM_COUNT )
		return FALSE;

	char cTypeCode;
	switch( s_vHdrParamType[nIndex] )
	{
	case BIP_TYPE_INT:
		cTypeCode = 'I';
		break;
	case BIP_TYPE_UINT:
		cTypeCode = 'U';
		break;
	case BIP_TYPE_REAL:
		cTypeCode = 'R';
		break;
	case BIP_TYPE_STRING:
		cTypeCode = 'S';
		break;
	default:
		return FALSE;
	}
	
	str.Format("%s(%c%d,%d)", s_saHdrParamName[nIndex], cTypeCode, s_vHdrParamSize[nIndex], s_vHdrParamOffset[nIndex]);

	if( bWithValue )
	{
		string strVal;
		BinHeader_GetParamValAsStr(s_vHdrParamType[nIndex], s_vHdrParamOffset[nIndex], s_vHdrParamSize[nIndex], strVal);
		str += "=";
		str += strVal;
	}
	return TRUE;
}

//--------------------------------------------------------------------------
// UpdateWksCtrl
//
// Call this function to update the worksheet control on the specified page.
//--------------------------------------------------------------------------
static void UpdateWksCtrl(int iWizPageID)
{
	int iCtrlID;
	switch( iWizPageID )
	{
	case IDD_AIW_COLUMNS:
		iCtrlID = IDC_COL_WKS_PREVIEW;
		break;
	case IDD_IW_RANGE:
		iCtrlID = IDC_RANGE_PREVIEW;
		break;
	case IDD_BIW_DATAPATERN:
		iCtrlID = IDC_BIW_DATAPATERN_PREVIEW_LC;
		break;
	default:
		return;
	}

	WorksheetControl wc = ImportWizDlg.GetItem(iCtrlID, iWizPageID);
	wc.Attach(s_strWks);
	wc.Update();
}

//--------------------------------------------------------------------------
// UpdateImpStructCommonFromTree
//
// The low level import functions for ASCII and Binary get their settings
// from a single struct argument (ASCIMP or BINIMP).
// Copies of these structs are stored in the tree.
// These structs have common settings.
// These common settings are also stored in the tree's Common branch.
// We assume the tree's Common branch is always up to date.
// This function will update the struct from the Common branch and then
// update the struct stored in the tree.
//--------------------------------------------------------------------------
static void UpdateImpStructCommonFromTree()
{
	if( s_trFilter.Type.nVal == FILTER_TYPE_ASCII )
	{
		s_ascimp.iRenameWks = s_trFilter.Common.RenameWks.nVal;
		s_ascimp.iPartial = s_trFilter.Common.Partial.nVal;
		s_ascimp.iPartialC1 = s_trFilter.Common.PartialC1.nVal;
		s_ascimp.iPartialC2 = s_trFilter.Common.PartialC2.nVal;
		s_ascimp.iPartialR1 = s_trFilter.Common.PartialR1.nVal;
		s_ascimp.iPartialR2 = s_trFilter.Common.PartialR2.nVal;
		s_ascimp.iMode = fuGetImportMode(s_trFilter);
		///s_ascimp.iApplyRange = fuGetApplyRangeToGraph(s_trFilter);
		s_ascimp.iSkipRows = tree_node_get_int(s_trFilter.Common.SkipRows, 0); /// EJP 07-23-2003 v7.0631 QA70-4575 ADD_SKIPROWS_TO_BINIMP
		s_ascimp.iReadRows = tree_node_get_int(s_trFilter.Common.ReadRows, 1); /// EJP 08-27-2003 v7.5677 QA70-5073 ADD_READROWS
		fuSetASCIMP(s_trFilter, s_ascimp);
	}
	else if( s_trFilter.Type.nVal == FILTER_TYPE_BINARY )
	{
		s_binimp.iRenameWks = s_trFilter.Common.RenameWks.nVal;
		s_binimp.iPartial = s_trFilter.Common.Partial.nVal;
		s_binimp.iPartialC1 = s_trFilter.Common.PartialC1.nVal;
		s_binimp.iPartialC2 = s_trFilter.Common.PartialC2.nVal;
		s_binimp.iPartialR1 = s_trFilter.Common.PartialR1.nVal;
		s_binimp.iPartialR2 = s_trFilter.Common.PartialR2.nVal;
		s_binimp.iMode = fuGetImportMode(s_trFilter);
		///s_binimp.iApplyRange = fuGetApplyRangeToGraph(s_trFilter);
		s_binimp.iSkipRows = tree_node_get_int(s_trFilter.Common.SkipRows, 0); /// EJP 07-23-2003 v7.0631 QA70-4575 ADD_SKIPROWS_TO_BINIMP
		s_binimp.iReadRows = tree_node_get_int(s_trFilter.Common.ReadRows, 1); /// EJP 09-12-2003 v7.5693 QA70-5073 ADD_READROWS_TO_BINIMP
		fuSetBINIMP(s_trFilter, s_binimp);
	}
}

static void UpdateImpStructFromTree()
{
	if( s_trFilter.Type.nVal == FILTER_TYPE_ASCII )
		fuGetASCIMP(s_trFilter, s_ascimp);
	else if( s_trFilter.Type.nVal == FILTER_TYPE_BINARY )
		fuGetBINIMP(s_trFilter, s_binimp);
}

static void ImportToWks(BOOL bTempWks=TRUE)
{
	waitCursor waitcursor;

	string strColDesig, strColFormat;
	
	int nErr = 0;
	if( bTempWks )
	{
		Worksheet wks(s_strWks);
		if( !wks )
			return;
		while( wks.DeleteCol(0) ); // Remove all columns in temp worksheet

		/// EJP 08-19-2003 v7.5667 REIMPORT_AFTER_USER_CHANGE_COL_FORMAT
		ASCIMP aiTemp;
		BINIMP biTemp;
		/// end REIMPORT_AFTER_USER_CHANGE_COL_FORMAT

		if( s_trFilter.Type.nVal == FILTER_TYPE_ASCII )
		{
			/// EJP 08-19-2003 v7.5667 REIMPORT_AFTER_USER_CHANGE_COL_FORMAT
			///ASCIMP aiTemp;
			/// end REIMPORT_AFTER_USER_CHANGE_COL_FORMAT
			
			aiTemp = s_ascimp;
			aiTemp.iRenameWks = 0;
			if( NONNUMERIC_START_NEW_WKSCOL == aiTemp.iNonnumeric )
			{
				if( ASCIMP_MODE_APPEND_COLS != aiTemp.iMode )
					aiTemp.iNonnumeric = NONNUMERIC_TERMINATE;
			}
			else
				aiTemp.iMode = ASCIMP_MODE_REPLACE_DATA;
			
			iwSetPartialImportForPreview(aiTemp.iPartial,
				aiTemp.iPartialR1, aiTemp.iPartialC1, aiTemp.iPartialR2, aiTemp.iPartialC2,
				aiTemp.iNumColumns);
				
			fuSetASCIMP(s_trFilter, aiTemp, TRUE);
			PrepareWksColsForImport(wks.GetPage(), s_trFilter, s_strDataFile);
			fuSetASCIMP(s_trFilter, s_ascimp, TRUE);

			/// EJP 08-19-2003 v7.5667 REIMPORT_AFTER_USER_CHANGE_COL_FORMAT
			/*
			strColDesig = wks.GetColDesignations();
			strColFormat = wks.GetColFormats();
			nErr = wks.ImportASCII(s_strDataFile, aiTemp);
			wks.SetColDesignations(strColDesig, false);
			wks.SetColFormats(strColFormat, false);
			*/
			/// end REIMPORT_AFTER_USER_CHANGE_COL_FORMAT
		}
		else if( s_trFilter.Type.nVal == FILTER_TYPE_BINARY )
		{
			/// EJP 08-19-2003 v7.5667 REIMPORT_AFTER_USER_CHANGE_COL_FORMAT
			///BINIMP biTemp;
			/// end REIMPORT_AFTER_USER_CHANGE_COL_FORMAT

/// EJP: temp workaround, see tracker #4335.
			biTemp = s_binimp;
/*
biTemp.iHeaderBytes = s_binimp.iHeaderBytes;
biTemp.iAutoColTypes = s_binimp.iAutoColTypes;
biTemp.iNumColumns = s_binimp.iNumColumns;
biTemp.iPartial = s_binimp.iPartial;
biTemp.iPartialC1 = s_binimp.iPartialC1;
biTemp.iPartialC2 = s_binimp.iPartialC2;
biTemp.iPartialR1 = s_binimp.iPartialR1;
biTemp.iPartialR2 = s_binimp.iPartialR2;
biTemp.iRenameWks = s_binimp.iRenameWks;
biTemp.iBigEndian = s_binimp.iBigEndian;
biTemp.iApplyRange = s_binimp.iApplyRange;
biTemp.iMode = s_binimp.iMode;
biTemp.vParamType = s_binimp.vParamType;
biTemp.vParamSize = s_binimp.vParamSize;
biTemp.vParamCount = s_binimp.vParamCount;
biTemp.iSkipRows = s_binimp.iSkipRows; /// EJP 07-23-2003 v7.0631 QA70-4575 ADD_SKIPROWS_TO_BINIMP
*/
			biTemp.iRenameWks = 0;
			biTemp.iMode = ASCIMP_MODE_REPLACE_DATA;

			iwSetPartialImportForPreview(biTemp.iPartial,
				biTemp.iPartialR1, biTemp.iPartialC1, biTemp.iPartialR2, biTemp.iPartialC2,
				biTemp.iNumColumns);

			fuSetBINIMP(s_trFilter, biTemp, TRUE);
			PrepareWksColsForImport(wks.GetPage(), s_trFilter, s_strDataFile);
			fuSetBINIMP(s_trFilter, s_binimp, TRUE);

			/// EJP 08-19-2003 v7.5667 REIMPORT_AFTER_USER_CHANGE_COL_FORMAT
			/*
			strColDesig = wks.GetColDesignations();
			strColFormat = wks.GetColFormats();
			nErr = wuImportBinary(wks, s_strDataFile, &biTemp);
			wks.SetColDesignations(strColDesig, false);
			wks.SetColFormats(strColFormat, false);
			*/
			/// end REIMPORT_AFTER_USER_CHANGE_COL_FORMAT
		}
		/// EJP 08-19-2003 v7.5667 REIMPORT_AFTER_USER_CHANGE_COL_FORMAT
		else
		{
			return; // Only ASCII and Binary supported here.
		}
		
		/// EJP 10-22-2003 v7.5728 QA70-5211.2 FIX_DESIG_AND_FMT_ON_PARTIAL_IMPORT
		strColDesig = wks.GetColDesignations();
		strColFormat = wks.GetColFormats();
		/// end FIX_DESIG_AND_FMT_ON_PARTIAL_IMPORT

		/// EJP 11-24-2003 v7.5769 QA70-5417.18 FIX_DESIG_AND_FMT
		///wks.SetColFormats("9", true); // temporary set all cols to Text&Numeric
		/// end FIX_DESIG_AND_FMT

		if( s_trFilter.Type.nVal == FILTER_TYPE_ASCII )
			nErr = wks.ImportASCII(s_strDataFile, aiTemp);
		else
			nErr = wuImportBinary(wks, s_strDataFile, &biTemp);
		/// EJP 10-22-2003 v7.5728 QA70-5211.2 FIX_DESIG_AND_FMT_ON_PARTIAL_IMPORT
		///strColDesig = fuGetDesignations(s_trFilter);
		///strColFormat = fuGetFormats(s_trFilter);
		/// end FIX_DESIG_AND_FMT_ON_PARTIAL_IMPORT
		
		/// EJP 09-12-2003 v7.5692 QA70-5135.15 COL_DESIGNATION_REPEAT_NOT_REMEMBERED
		///wks.SetColDesignations(strColDesig, false);
		///wks.SetColFormats(strColFormat, false);
		bool bRepeat = fuGetRepetitive(s_trFilter);
		wks.SetColDesignations(strColDesig, bRepeat);
		wks.SetColFormats(strColFormat, bRepeat);
		/// end COL_DESIGNATION_REPEAT_NOT_REMEMBERED
		/// end REIMPORT_AFTER_USER_CHANGE_COL_FORMAT
	}
	else
	{
		Worksheet wks;
		if( s_iActivePageType == EXIST_PLOT )
		{
			wks.Attach(s_strWks); // Re-use temp worksheet to import to and then keep
		}
		else
		{
			wks.Attach(s_strWks);
			if( wks )
				wks.Destroy();
			
			wks = (Worksheet) Project.ActiveLayer();
			if(!wks)
			{
				printf("No active worksheet to import.\n");
				return;
			}
		}
		s_strWks = wks.GetPage().GetName();
		/*
		SetupWksCols(s_strWks, s_trFilter);

		if( s_trFilter.Type.nVal == FILTER_TYPE_ASCII )
			nErr = wks.ImportASCII(s_strDataFile, s_ascimp);
		else if( s_trFilter.Type.nVal == FILTER_TYPE_BINARY )
			nErr = wuImportBinary(wks, s_strDataFile, &s_binimp);
		*/
	}
}

static void iwSetPartialImportForPreview(int& nPartial, int& nR1, int& nC1, int& nR2, int& nC2, int& nCols)
{
	if( nPartial )
	{
		if( nC2 < 0 )
			nC2 = nCols - 1;
		if( (nC2 - nC1 + 1) > IW_NUM_DATA_PREVIEW_COLS )
			nC2 = nC1 + IW_NUM_DATA_PREVIEW_COLS - 1;

		if( -1 == nR2 || (nR2 - nR1 + 1) > IW_NUM_DATA_PREVIEW_ROWS )
			nR2 = nR1 + IW_NUM_DATA_PREVIEW_ROWS - 1;
	}
	else
	{
		nPartial = 1;
		nC1 = 0;
		if( nCols > IW_NUM_DATA_PREVIEW_COLS )
			nC2 = IW_NUM_DATA_PREVIEW_COLS - 1;
		else
			nC2 = nCols - 1;
		nR1 = 0;
		nR2 = IW_NUM_DATA_PREVIEW_ROWS - 1;
	}
}

static void UpdatePreview(int iWizPageID)
{
	UpdateImpStructCommonFromTree();
	ImportToWks();
	UpdateWksCtrl(iWizPageID);
}

static string AIW_GetExtensionFromPath(LPCSTR lpcszPath) // return extension in "*.abc" format
{
	string strTemp(lpcszPath);
	string strFileExtension;
	int nDotPos = strTemp.ReverseFind('.');
	if( nDotPos >= 0 )
		strFileExtension.Format("*%s", strTemp.Right(strTemp.GetLength() - nDotPos));
	else
		strFileExtension.Empty();
	
	return strFileExtension;
}

static void iwFillFilterComboBox(ComboBox& comboFilters, BOOL bInsertDefault, LPCSTR lpcszDataPath, LPCSTR lpcszDataFile, int iFilterType)
{
	comboFilters.ResetContent();

	string strPath;
	StringArray saFilterFiles;
	
	if( lpcszDataPath )
	{
		fuGetFilterFiles(saFilterFiles, lpcszDataPath, lpcszDataFile, iFilterType);
		iwAddFiltersToComboBox(comboFilters, saFilterFiles, FILTER_LOCATION_DATA);
	}

	strPath.Format("%s%s", GetAppPath(), FILTERS_FOLDER_NAME);
	fuGetFilterFiles(saFilterFiles, strPath, lpcszDataFile, iFilterType);
	iwAddFiltersToComboBox(comboFilters, saFilterFiles, FILTER_LOCATION_USERFILES);
	
	strPath.Format("%s%s", GetAppPath(TRUE), FILTERS_FOLDER_NAME);
	fuGetFilterFiles(saFilterFiles, strPath, lpcszDataFile, iFilterType);
	iwAddFiltersToComboBox(comboFilters, saFilterFiles, FILTER_LOCATION_ORIGIN);

	if( bInsertDefault )
		comboFilters.InsertString(0, AIW_DEFAULT_FILTER);
}

static void iwFillFilterComboBox(ComboBox& comboFilters, LPCSTR lpcszPath)
{
	comboFilters.ResetContent();

	StringArray saFilterFiles;
	fuGetFilterFiles(saFilterFiles, lpcszPath);
	iwAddFiltersToComboBox(comboFilters, saFilterFiles, -1);
}

static void iwAddFiltersToComboBox(ComboBox& comboFilters, StringArray& saFilterFiles, int iFilterLocPrefix)
{
	string str;
	string strFilterLocPrefix;
	if( iFilterLocPrefix >= 0 )
	{
		str = FILTER_LOCATION_PREFIX;
		strFilterLocPrefix = str.GetToken(iFilterLocPrefix, '|');
	}

	for( int i = 0; i < saFilterFiles.GetSize(); i++ )
	{
		if( strFilterLocPrefix.IsEmpty() )
			str = GetFileName(saFilterFiles[i], TRUE);
		else
			str.Format("%s: %s", strFilterLocPrefix, GetFileName(saFilterFiles[i], TRUE));
		comboFilters.AddString(str);
		comboFilters.SetItemData(comboFilters.GetCount() - 1, iFilterLocPrefix);
	}
}
/*
static BOOL iwGetFilterFile(ComboBox& comboFilters, int iIndex, string &strFilterFile)
{
	string str;
	comboFilters.GetLBText(iIndex, str);
	if( !str.IsEmpty() )
	{
		strFilterFile.Format("%s.%s", str.GetToken(1, ':'), IMPORT_FILTER_EXTENSION);
		strFilterFile.Delete(0); // delete space between colon and file name
		
		string strPath;
		switch( comboFilters.GetItemData(iIndex) )
		{
		case FILTER_LOCATION_DATA:
			strPath = GetFilePath(s_strDataFile);
			break;
		case FILTER_LOCATION_USERFILES:
			strPath.Format("%s%s", GetAppPath(), FILTERS_FOLDER_NAME);
			break;
		case FILTER_LOCATION_ORIGIN:
			strPath.Format("%s%s", GetAppPath(TRUE), FILTERS_FOLDER_NAME);
			break;
		}
		strFilterFile.Insert(0, strPath);
		return TRUE;
	}
	return FALSE;
}
*/
static int iwDataFileErrorMsgBox()
{
	string strText;
	strText.Format("Error opening/reading data file:\n%s", GetFileName(s_strDataFile));
	return MessageBox(ImportWizDlg.GetWindow().GetSafeHwnd(), strText, "Import Wizard");
}

/// EJP 07-14-2003 v7.0624 SCAN_FOR_NUM_COLS_ON_CHANGE_HEADER_LINES
int iwScanForNumColumns(LPCSTR lpcszFile, ASCIMP &ascimp)
{
	ASCIMP aiTemp;
	aiTemp = ascimp;
	AscImpReadFileStruct(lpcszFile, &aiTemp, AIRF_USE_ASCIMP);
	return aiTemp.iNumColumns;
}
/// end SCAN_FOR_NUM_COLS_ON_CHANGE_HEADER_LINES

static int InitComboBoxWithTemplateNames(ComboBox &cbTarget, int iType)
{
	string strExt;
	switch( iType )
	{
	case EXIST_WKS:
		strExt = "otw";
		break;
	case EXIST_MATRIX:
		strExt = "otm";
		break;
	case EXIST_PLOT:
		strExt = "otp";
		break;
	default:
		return 1; // unsupported type
	}
	
	cbTarget.ResetContent();
	cbTarget.AddString(AIW_DEFAULT_FILTER);

	StringArray saTemplates;
	GetSystemFiles(saTemplates, strExt);

	string strFileName;
	for( int i = 0; i < saTemplates.GetSize(); i++ )
	{
		strFileName = GetFilenameWithoutExt(saTemplates[i]);
		cbTarget.AddString(strFileName);
	}

	cbTarget.SetCurSel(0);
	return 0;
}

static int TwipsToPixels(Control cntrl, int twips, bool bX=true)
{
	DeviceContext dc = cntrl.GetDC();
	double vv = 0.5 + dc.GetDeviceCaps(bX? LOGPIXELSX : LOGPIXELSY) * (double)twips / 1440.0;
	return vv;
}

static int PixelsToTwips(Control cntrl, int pixels, bool bX=true)
{
	DeviceContext dc = cntrl.GetDC();
	double vv = 0.5 + pixels * 1440.0 / dc.GetDeviceCaps(bX? LOGPIXELSX : LOGPIXELSY);
	return vv;
}

/// EJP 09-08-2003 v7.5687 QA70-5118 FIX_COMPARE_BINIMP_STRUCTS
static bool is_BINIMP_equal(BINIMP &bi1, BINIMP &bi2)
{
	if( bi1.iHeaderBytes != bi2.iHeaderBytes ||
		bi1.iAutoColTypes != bi2.iAutoColTypes ||
		bi1.iNumColumns != bi2.iNumColumns ||
		bi1.iRenameWks != bi2.iRenameWks ||
		bi1.iBigEndian != bi2.iBigEndian ||
		bi1.iApplyRange != bi2.iApplyRange ||
		bi1.iMode != bi2.iMode ||
		bi1.iSkipRows != bi2.iSkipRows ||
		bi1.iPartial != bi2.iPartial )
	{
		return false;
	}

	if( bi1.iPartial )
	{
		if( bi1.iPartialC1 != bi2.iPartialC1 ||
			bi1.iPartialC2 != bi2.iPartialC2 ||
			bi1.iPartialR1 != bi2.iPartialR1 ||
			bi1.iPartialR2 != bi2.iPartialR2 )
		{
			return false;
		}
	}

	if( bi1.vParamType.GetSize() != bi2.vParamType.GetSize() ||
		bi1.vParamSize.GetSize() != bi2.vParamSize.GetSize() ||
		bi1.vParamCount.GetSize() != bi2.vParamCount.GetSize() )
	{
		return false;
	}

	for( int i = 0; i < bi1.vParamType.GetSize(); i++ )
	{
		if( bi1.vParamType[i] != bi2.vParamType[i] ||
			bi1.vParamSize[i] != bi2.vParamSize[i] ||
			bi1.vParamCount[i] != bi2.vParamCount[i] )
		{
			return false;
		}
	}
	
	return true;
}
/// end FIX_COMPARE_BINIMP_STRUCTS

/// EJP 10-20-2003 v7.5726 QA70-5374 ALLOW_CHANGING_PREVIEW_FONT
static void iw_InitFontComboBox(int iCtrl, int iPage)
{
	ComboBox cbFonts = ImportWizDlg.GetItem(iCtrl, iPage);
	if( cbFonts )
	{
		int iFontIDs[] = {OEM_FIXED_FONT, ANSI_FIXED_FONT, SYSTEM_FIXED_FONT};
		iw_InitComboBox(cbFonts, _L("OEM|ANSI|System"), iFontIDs);
		iw_SelectFont(cbFonts, IW_PREVIEW_FONT);
	}
}

static void iw_InitComboBox(ComboBox &cb, LPCSTR lpcszStrings, int *lpiValues)
{
	string str = lpcszStrings;
	StringArray saItems;
	str.GetTokens(saItems, '|');
	
	cb.ResetContent();
	for( int iItem = 0; iItem < saItems.GetSize(); iItem++ )
	{
		cb.AddString(saItems[iItem]);
		if( lpiValues )
		{
			cb.SetItemData(iItem, *lpiValues);
			lpiValues++;
		}
	}
}

//--------------------------------------------------------------------------
// iw_SetRichEditFont
//
// This function will set the RichEdit control's font.
// It will maintain the control's current selection and first visible line.
//--------------------------------------------------------------------------
static void iw_SetRichEditFont(int iCtrl, int iPage, int iFont)
{
	RichEdit re = ImportWizDlg.GetItem(iCtrl, iPage);
	if( re )
		iw_SetRichEditFont(re, iFont);
}

static void iw_SetRichEditFont(RichEdit &re, int iFont)
{
	int iFirstVisibleLineBefore = re.GetFirstVisibleLine(); // get first visible line

	long nStartChar, nEndChar;
	re.GetSel(nStartChar, nEndChar); // save selection
	re.SetSel(0, -1); // select all
	re.SetFont(iFont);
	re.SetSel(nStartChar, nEndChar); // restore selection

	int iFirstVisibleLineAfter = re.GetFirstVisibleLine();
	if( iFirstVisibleLineAfter != iFirstVisibleLineBefore ) // check first visible line
		re.LineScroll(iFirstVisibleLineBefore - iFirstVisibleLineAfter, 0);
}

static void iw_SelectFont(ComboBox &cb, int iFont)
{
	int iData;
	for( int iItem = 0; iItem < cb.GetCount(); iItem++ )
	{
		if( cb.GetItemData(iItem) == iFont )
		{
			cb.SetCurSel(iItem);
			return;
		}
	}
}

static BOOL iw_SetGridFont(int iCtrl, int iPage, int iFont)
{
	Control ctrlGrid = ImportWizDlg.GetItem(iCtrl, iPage);
	if( ctrlGrid )
	{
		Object objGrid = ctrlGrid.GetActiveXControl();
		if( objGrid )
		{
			int iFontSize;
			objGrid.FontName = GetFontName(iFont, &iFontSize);
			return TRUE;
		}
	}
	return FALSE;
}
/// end ALLOW_CHANGING_PREVIEW_FONT
