/**************************************************************\
*	SPLAT Program                   Version 1.00		     *        *
*   For CompuScope 8500 boards and Microsoft Windows 95/98	 *
*	   												         *
*     09/09/1999							Jun				 *
\**************************************************************/

#include <iostream.h>
#include <fstream.h>
#include "whichdrv.h"
//#include <process.h>
#include <time.h>
#include <windows.h>
#include <windowsx.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>	/* for pow */
#include "gage_drv.h"
#include "gage_low.h"
#include "eeprom.h"
#include "structs.h"
#include "gsdlldem.h"
#include <direct.h>
#include "splatisa.h"
#include <sys/types.h>
#include <sys/timeb.h>
#include <commctrl.h>

// file subtraction
SYSTEMTIME initTime;

#include "resource.h"

#define USE_MEM_READ			0x0001
#define USE_TRIGGER_VIEW		0x0002
#define USE_TRIGGER_VIEW_2		0x0003
#define USE_TRIGGER_VIEW_3		0x0004
#define USE_TRANSFER_BUFFER		0x0005
#define USE_TRANSFER_BUFFER_2	0x0006
#define USE_TRANSFER_BUFFER_3	0x0007
#define USE_REAL_TIME			0x0008

#define blink   5   /*cont reset blink out time */

/****************************\
*                           *
*	GLOBAL DEFINITIONS.		*
*	===================		*
*                           *
\***************************/

void	Cap_Save_FILE(HWND hWnd);
int32	trigger_address[GAGE_B_L_MAX_CARDS];
int32	starting_address[GAGE_B_L_MAX_CARDS];
int32	ending_address[GAGE_B_L_MAX_CARDS];
int32	current_address[GAGE_B_L_MAX_CARDS];
int32	channel_ram_size = 0L;
uInt16	board_type = GAGE_ASSUME_NOTHING;
int32	board_memory = 0L;
double	sample_resolution = 128.0;    /*   12-bit = 2048.0 and 8-bit = 128.0.      */
int16	sample_offset = 0;            /*   12-bit = 1      and 8-bit = 0.          */
int16	CapturingData = FALSE;
void    check_stat();
int16	ContinuousMode = FALSE;
uInt16	wTimerInterval = 100;   	  /*   Number of milliseconds between timer events.  */
int16	number_of_timer_events = 0;
int16	multiple_record_avail = 0;
int cont_run = 1;
int running = 0;
int k=0;
int nxx=5;
int     j;
long		location;  
int32		trigger;	/* trigger address  */
FILE  *capstream;		/* used for cap save data */
int   save_file =0;		/* on or off */
FILE *stream;
//ostream ofile;
uInt8 *chan_a_8 = NULL;
int32		points;		/* number of points */
uInt32		offset_a;
char filename[40];
char filepath[50];
char line[100];
char linezip[100];
char lineunzip[100];
char directoryname[20];
char  buffer[200];
char tmpbuf1[128];
char tmpbuf2[128];


#define	TRIG_TIMEOUT   100000
#define	BUSY_TIMEOUT    10

HWND	hDisplayWnd;
UINT	wTimerID;
HPEN	hBlackPen;
HPEN    hTriggPen;
uInt8  hTriggPenStr[10];
HPEN	hZeroPen;
HPEN	hDotPen;
HBRUSH	hWhiteBrush;

uInt8 AdjustFlag=0;
int8    str[256];       /*  Miscellaneous uses.  */
uInt16	boards_in_system;

uInt8 *rt_packeddata=0;
uInt32 rt_packeddataLength=0;
uInt8 *rt_buffer;
uInt8 *rt_buffer_1M;

uInt32 trigger_trace=0;
uInt32 adjusted_depth=0;

int32	ptm_pre_samples=0, ptm_post_samples=0, ptm_start=0, ptm_max_group=0;
int32	ptm_max_pre = 0 , ptm_max_post = 0, view_start = 0, ptm_group;
int16	ptm_channel;
int16	buildup_signal = 0;

uInt32 acgtimes = 0;

// add new globals for time keeping to measure the speed of transfer
uInt32 time1, time2, time3, tmp1;


/*-------------------------------------------------------------------------*/

#define BLF    260

/*-------------------------------------------------------------------------*/

int8					board_loc_file[BLF];
uInt16					gage_board_location[GAGE_B_L_BUFFER_SIZE];
gage_driver_info_type   board_info;
uInt16					zoom_x = 1, zoom_x2 = 1;
uInt16					scrn_x;

uInt32	TVT3_offset[GAGE_B_L_MAX_CARDS]={0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L};
uInt32	TVT3_offsetB[GAGE_B_L_MAX_CARDS]={0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L};
int16	*TVT2_ptr[GAGE_B_L_MAX_CARDS];
int16	*TVT2_ptrB[GAGE_B_L_MAX_CARDS];

uInt8	far *TVTBufferPtr[GAGE_B_L_MAX_CARDS];

uInt8	far *a_buffer[GAGE_B_L_MAX_CARDS];
uInt8	far *b_buffer[GAGE_B_L_MAX_CARDS];
int16	far *a_buffer16[GAGE_B_L_MAX_CARDS];
int16	far *b_buffer16[GAGE_B_L_MAX_CARDS];

int32	bsize; // size of dedicated buffer for tvt2 and real-time mode

int16	transfer_type = USE_TRANSFER_BUFFER_3;
int16	xfer_time = 0;
int16	splat_isa_out = 0;
HWND 	SRateDlg = 0;
HWND	IRangeDlg = 0;
HWND	TriggerDlg = 0;
HWND	AboutDlg = 0;
HWND	PmtDlg   = 0;
HWND    CapDlg  = 0;
HWND    SetTimerDlg = 0;

// Timer declarations
#define BUFFERSIZE 50000

#define MY_TIMER 1
#define MY_TIMER2 2
int nTimer = 0, nTimer2 = 0;
int minutes = 10, seconds = 0;
char dpath[600] = "C:";
int zipFiles = 0;
int subtract = 0;
int nTar = 0;
char Filenames[50][200];

typedef struct huffnode {
  struct huffnode   *left;         /* Left child */
  struct huffnode   *right;        /* Right child */
  char              car;          /* Character stored in the node */
  int               freq;          /* Frequency that this char appeared in the file */
} Huffnode;

typedef struct {
  unsigned short  code;
  short           nbits;
} Codes;

char  Buffer[50][BUFFERSIZE];
char  *Bufferptr;
Huffnode  *    heap[40];
int            hash[128]; 
int   fnum = 0;


//end of timer declarations

int16	external_clock_in_use = 0;
float	external_clock_rate = 10000000.0F;
int16	use_multiple_record = 0;
int16	multiple_record_available;

int32	current_board_type;

void           encode(char ptr[50][200], int);
Huffnode **    getfreq(int *size, int numfiles);
void           buildheap(Huffnode **heap, int size);
Huffnode       *buildcodetree(Huffnode **heap, int size); 
Codes		   *assigncodes(Huffnode *root, int size);
void		   buildstream(HANDLE file, Codes *codes, int numfiles);
void           cleanup(Huffnode *root, Codes *codes);
void           heapify(int size, int posision);
Huffnode       *getmin(Huffnode ** heap, int *size);
void		   insert(Huffnode *newnode, int *size, Huffnode **heap);
void           getCodes(Huffnode *      root, 
			            Codes *         codes,
                        unsigned short  prefix, 
			            short *         index, 
			            short           nbits);
int			   left(int i);
int			   right(int i);
int			   parent(int i);
void           del(Huffnode * root);

// did not cpy this yet

LRESULT CALLBACK SRateDlgProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK IRangeDlgProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK TriggerDlgProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK AboutDlgProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK CapDlgProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK PmtDlgProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK SetTimerDlgProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
VOID CALLBACK MyTimerProc(HWND hWnd, UINT uTimerMsg, UINT uTimerID, DWORD DWTime);
VOID CALLBACK MyTimerProc2(HWND hWnd, UINT uTimerMsg, UINT uTimerID, DWORD DWTime);

void encode(char filename[50][200], int numfiles) {
  
  int k, l;
  Huffnode      *root;
  int           size = 1;
  Codes         *codes;
  char          space = '\b';
  HANDLE        file;
  DWORD         dwActBytes;
  char          newfilename[200];
  char          thefilename[200];
  char *        charptr;
  char *        Bufferptr = Buffer[0];
  int i, filenamelength;
  char car;

  // delete the following after debugging
  char str[100];

  //wsprintf(str, "in encode");
  //MessageBox(NULL, str, "debug", MB_OK);
	
  getfreq(&size, numfiles);

  //wsprintf(str, "after getfreq");
  //MessageBox(NULL, str, "debug", MB_OK);

  strcpy(newfilename, filename[0]);

  //wsprintf(str, "new file %s", newfilename);
  //MessageBox(NULL, str, "debug", MB_OK);

  //strcat(charptr, ".myzip");
  sprintf(thefilename, "%s\\dat\\%s.myzip", dpath, newfilename);

  //wsprintf(str, "new file %s", thefilename);
  //MessageBox(NULL, str, "debug", MB_OK);


  file = CreateFile(thefilename, GENERIC_WRITE, 0,
		NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

  if (!file) {
    wsprintf(str, "failed to open file");
	MessageBox(NULL, str, "error", MB_OK);
  }

  WriteFile(file, &numfiles, sizeof(int), &dwActBytes, NULL);
  for (i = 0; i < numfiles; i++) {
	filenamelength = strlen(Filenames[i]);
    WriteFile(file, &filenamelength, sizeof(int), &dwActBytes, NULL);
	WriteFile(file, Filenames[i], filenamelength * sizeof(char), &dwActBytes, NULL);
  }

  for (i = 1; i <= size; i++) {
    WriteFile(file, &heap[i]->car, sizeof(char), &dwActBytes, NULL);
	if (!dwActBytes) {
      wsprintf(str, "failed to write into the file");
	  MessageBox(NULL, str, "error", MB_OK);
	}
    WriteFile(file, &heap[i]->freq, sizeof(int), &dwActBytes, NULL);
	if (!dwActBytes) {
      wsprintf(str, "failed to write into the file");
	  MessageBox(NULL, str, "error", MB_OK);
	}
  }
  WriteFile(file, &space, sizeof(char), &dwActBytes, NULL);
  if (!dwActBytes) {
    wsprintf(str, "failed to write space into the file");
    MessageBox(NULL, str, "error", MB_OK);
  }
  //wsprintf(str, "here 1");
  //MessageBox(NULL, str, "debug", MB_OK);
  buildheap(heap, size);
  //wsprintf(str, "here 2");
  //MessageBox(NULL, str, "debug", MB_OK);
  root = buildcodetree(heap, size);
  //wsprintf(str, "here 3");
  //MessageBox(NULL, str, "debug", MB_OK);
  codes = assigncodes(root, size);
  //wsprintf(str, "here 4");
  //MessageBox(NULL, str, "debug", MB_OK);
  buildstream(file, codes, numfiles);
  CloseHandle(file);
  cleanup(root, codes);
}

Huffnode **    getfreq(int *size, int numfiles) {
  int          freq[128] = {0};
  int          i, j;
  int          length = strlen(Buffer[0]);

  // delete the following after debugging
  char str[100];

  for (j = 0; j < numfiles; j++) {
    for (i = 0; i < length; i++) {
	  freq[(int)Buffer[j][i]]++;
	}
	length = strlen(Buffer[j + 1]);
  }

  for (i = 0; i < 128; i++) {
    if (freq[i]) {
		heap[*size] = (Huffnode *)calloc(1, sizeof(Huffnode));
		if (!heap[*size]) {
			wsprintf (str, "did not allocate heap size is %i", (*size) - 1);
			MessageBox(NULL, str, "Error", MB_OK);
		}
      heap[*size]->freq = freq[i];
      heap[*size]->car = i;
      (*size)++;
    }
  }
  (*size)--;
  return heap;
}

void buildheap(Huffnode **heap, int size) {
  int i;
  for (i = (int) size/2; i >= 1; i--)
    heapify(size, i);
}

Huffnode *buildcodetree(Huffnode **heap, int size) {
  int          i,
               org_size = size;
  Huffnode     *left,
               *right,
               *newnode;
  
  for (i = 0; i < org_size - 1; i++) {
    newnode = (Huffnode *)calloc(1, sizeof(Huffnode));
    left = getmin(heap, &size);
    right = getmin(heap, &size);
    newnode->freq = left->freq + right->freq;
    newnode->left = left;
    newnode->right = right;
    insert(newnode, &size, heap);
  }
  return getmin(heap, &size);
}

Codes *assigncodes(Huffnode *root, int size) {
  Codes        *codes = (Codes *)calloc(size, sizeof(Codes));
  short        index = 0;

  getCodes(root, codes, 0, &index, 0);
  return codes;
}

void buildstream(HANDLE file, Codes *codes, int numfiles) {
  char str[100];
  short           stream[20000] = {0};
  int             i, j, k;
  short           posision = sizeof(unsigned short) * 8;
  int             masklength;
  short           *streamptr = stream;
  unsigned short  mask,
                  bits;
  DWORD           dwActBytes;
  int             length = strlen(Buffer[0]);
  int tmp1, tmp2;
  Codes *ptr;
  int gh;

  for (j = 0; j < numfiles; j++) {
	//length = strlen(Buffer[j]);
    for (i = 0; i < length; i++) {
		tmp1 = Buffer[j][i];
		tmp2 = hash[tmp1];
		ptr = &codes[hash[Buffer[j][i]]]; 
		mask = codes[hash[Buffer[j][i]]].code;    //.code;
		masklength = codes[hash[Buffer[j][i]]].nbits;
		posision = posision - masklength;
      if (posision < 0) {
        bits = mask >> abs(posision);
        (*streamptr) |= bits;
        streamptr++;
        posision = sizeof(unsigned short) * 8 + posision;
        bits = mask << posision;
        (*streamptr) |= bits;
	  }
      else {
        bits = mask << posision;
        (*streamptr) |= bits;
        if (!posision) {
	      posision = sizeof(unsigned short) * 8;
	      streamptr++;
		}
	  }
	}
  
  /* write out the rest of the file */
    i = streamptr - stream + 1;
	//wsprintf(str, "%i", i);
	//MessageBox(NULL, str, "debug", MB_OK);
    WriteFile(file, &i, sizeof(int), &dwActBytes, NULL);
    WriteFile(file, &posision, sizeof(short), &dwActBytes, NULL);
    WriteFile(file, stream, i * sizeof(short), &dwActBytes, NULL);
    streamptr = stream;
	posision = sizeof(unsigned short) * 8;
	for (k = 0; k < i + 10; k++)
		stream[k] = 0;
	if (j + 1 < numfiles)
		length = strlen(Buffer[j + 1]);
  }
}

void           cleanup(Huffnode *     root, 
						Codes *        codes) {


  /* deallocate the code tree */

  del(root);

  /* deallocate the code array */

  free(codes);
}

void           heapify(int            size,
		               int            posision) {
  int          l,
               r,
               smallest;
  Huffnode *   tmp;

  l = left(posision);
  r = right(posision);
  if (l <= size && heap[l]->freq < heap[posision]->freq)
    smallest = l;
  else
    smallest = posision;
  if (r <= size && heap[r]->freq < heap[smallest]->freq)
    smallest = r;
  if (smallest != posision) {
    tmp = heap[smallest];
    heap[smallest] = heap[posision];
    heap[posision] = tmp;
    heapify(size, smallest);
  }
}

Huffnode *getmin(Huffnode ** heap, int *size) {
  
  Huffnode *   min;

  if (*size < 1) {
    MessageBox(NULL, "Heap underflow", "Error", MB_OK);
    exit(0);
  }
  min = heap[1];
  heap[1] = heap[*size];
  (*size)--;
  heapify(*size, 1);
  return min;
}

void insert(Huffnode *newnode, int *size, Huffnode **heap) {
  int parent, child;
  Huffnode *tmp;

  (*size)++;
  heap[*size] = newnode;
  parent = (int)(*size)/2;
  child = *size;
  while (parent >= 1) {
    if (heap[parent]->freq > heap[child]->freq) {
      tmp = heap[parent];
      heap[parent] = heap[child];
      heap[child] = tmp;
      child = parent;
      parent /= 2;
    }
    else
      parent = 0;
  }
}

void           getCodes(Huffnode *      root, 
			            Codes *         codes,
                        unsigned short  prefix, 
			            short *         index, 
			            short           nbits) {
  if (root->left && root->right) {
    prefix = prefix << 1;
    getCodes(root->left, codes, prefix, index, (short)nbits + 1);
    prefix = prefix | 1;
    getCodes(root->right, codes, prefix, index, nbits + 1);
  }
  else {
    codes[*index].code = prefix;
    codes[*index].nbits = nbits;
    (*index)++;
    hash[root->car] = (*index) - 1;
  }
}

int left(int i) {
  return 2 * i;
}

int right(int i) {
  return 2 * i + 1;
}

int parent(int i) {
  return (int) i/2;
}

void del(Huffnode * root) {
  if (root->left != NULL)
    del(root->left);
  if (root->right != NULL)
    del(root->right);
  free(root);
}

BOOL CheckMessageQueue (void);
/*-------------------------------------------------------------------------*/
/*
 *  CheckMessageQueue retrieves and dispatches any messages waiting in
 *  the application's message queue. WM_QUIT messages are NOT removed from
 *  the queue.
 *
 *  Input parameters:
 *    None
 *
 *  Returns:
 *    TRUE = Message queue empty; okay to continue
 *    FALSE = WM_QUIT waiting in queue
 *-------------------------------------------------------------------------*/
 
BOOL CheckMessageQueue (void)
{
    MSG msg;

    while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)) {
        if (msg.message == WM_QUIT)
            return FALSE;
        else {
            GetMessage (&msg, NULL, 0, 0);
            TranslateMessage (&msg);
            DispatchMessage (&msg);
        }
    }
    return TRUE;
}

/*-------------------------------------------------------------------------*/

void	SetDefaultBoardLocation (uInt16 seg, uInt16 ind)
{
	int16             i;

	gage_set_records ((uInt16 far *)gage_board_location, 0, seg, ind, 0, 0);
	for (i = 1 ; i < GAGE_B_L_MAX_CARDS ; i++)
		gage_set_records ((uInt16 far *)gage_board_location, i, 0, 0, 0, 0);

}       /*      End of SetDefaultBoardLocation ().  */


/*-------------------------------------------------------------------------*/

int8	*BoardTypeSizeToText (unsigned short board_type, int32 max_memory)
{
	static char     str[13];
	
	if (board_type == 0)
		return ("ABSENT");
	if (board_type == GAGE_ASSUME_CS3200)
		lstrcpy (str, "3200");
	else if (board_type == 	GAGE_ASSUME_CS1610)
		lstrcpy (str, "1602");
	else if (board_type & (GAGE_ASSUME_CSLITE | GAGE_ASSUME_CSLITE15))
		lstrcpy (str, "LITE");
	else if (board_type & GAGE_ASSUME_CS250)
		lstrcpy (str, "250");
	else if (board_type & GAGE_ASSUME_CS25018)
		lstrcpy (str, "250v8");
	else if (board_type & GAGE_ASSUME_CS225)
		lstrcpy (str, "225");
	else if (board_type & GAGE_ASSUME_CS220)
		lstrcpy (str, "220");
	else if (board_type & GAGE_ASSUME_CS2125)
		lstrcpy (str, "2125");
	else if (board_type & GAGE_ASSUME_CS265)
		lstrcpy (str, "265");
	else if (board_type & GAGE_ASSUME_CS1016)
		lstrcpy (str, "1016");
	else if (board_type == GAGE_ASSUME_CS8500)
		lstrcpy (str, "8500");
	else if (board_type == GAGE_ASSUME_CS12100)
		if (board_info.ee_options & EEPROM_OPTIONS_ALTERNATE_CONFIG )
			lstrcpy (str, "1250");
		else if ((board_info.ee_options & EEPROM_OPTIONS_NORMAL_OSC) == 0)
			lstrcpy (str, "1210");
		else
			lstrcpy (str, "12100");
	else if (board_type & GAGE_ASSUME_CS512)
		if (board_type & GAGE_ASSUME_CSPCI)
			lstrcpy (str, "512PCI");
		else
			lstrcpy (str, "512");
	else if (board_type & GAGE_ASSUME_CS1012)
		if (board_type & GAGE_ASSUME_CSPCI)
			lstrcpy (str, "1012PCI");
		else
			lstrcpy (str, "1012");
	else if (board_type & GAGE_ASSUME_CS6012)
		if (board_type & GAGE_ASSUME_CSPCI)
			lstrcpy (str, "6012PCI");
		else
			lstrcpy (str, "6012");
	else if (board_type & GAGE_ASSUME_CS6012)
		if (board_type & GAGE_ASSUME_CSPCI)
			lstrcpy (str, "6012PCI");
		else
			lstrcpy (str, "6012");
	else if (board_type & GAGE_ASSUME_CS8012)
		if (board_type & GAGE_ASSUME_CSPCI)
			lstrcpy (str, "8012PCI");
		else
			lstrcpy (str, "8012");
	if (max_memory >= 1048576L)
		wsprintf (str + lstrlen (str), " %ldM", max_memory / 1048576L);
	else
		wsprintf (str + lstrlen (str), " %ldK", max_memory / 1024L);
	return (str);
	
}       /*  End of BoardTypeSizeToText ().  */

/*-------------------------------------------------------------------------*/

int	InitBoard (HWND hWnd)
{

	int16 				       	ret;
	uInt16						major_version, minor_version, board_support;
	int32						gdi_size, jj;
	gage_driver_info_type far 	*gdi;


	for (jj=0;jj<GAGE_B_L_MAX_CARDS; jj++)
	{
        a_buffer[jj] = NULL;
		b_buffer[jj] = NULL;
	}


	board_loc_file[0] = '\0';
	ret = gage_get_config_filename ((LPSTR)(board_loc_file));
	if ((ret = gage_read_config_file (board_loc_file, (uInt16 far *)(gage_board_location))) < 0)  {
#if 0
		wsprintf (str, "%s not found!", (LPSTR)board_loc_file);
		MessageBox(hWnd, str, "Error", MB_OK);
#endif
		SetDefaultBoardLocation (0xffff, 0xffff);
	}
	
	if (gage_driver_initialize((uInt16 far *)gage_board_location, GAGE_MEMORY_SIZE_TEST) <=0 ) 
	{
		if (gage_driver_initialize((uInt16 far *)gage_board_location, GAGE_MEMORY_SIZE_TEST) <=0 ) 
		{
			wsprintf (str, "No CompuScope boards found!  Error code = %02x", (int16)(gage_board_location[GAGE_B_L_STATUS_START + 1]));
			MessageBox(hWnd, str, "Error", MB_OK);
			return (1);
		}
	}

    gage_get_driver_info ((gage_driver_info_type far *)&board_info);
		
	boards_in_system = gage_get_boards_found();
	board_type = board_info.board_type;
	board_memory = board_info.max_memory;
	wsprintf (str, "CompuScope %s board found!", (LPSTR)(BoardTypeSizeToText (board_type, board_memory)));
	MessageBox(hWnd, str, "Success", MB_OK | MB_ICONINFORMATION);
	
	if (board_info.sample_bits == 12) {
		sample_resolution = 2048.0;
		sample_offset = 1;
	}else if (board_info.sample_bits == 16) {
		sample_resolution = 32768.0;
		sample_offset = 1;
	}else{
		sample_resolution = 128.0;
		sample_offset = 0;
	}

	board.srindex =	best_sample_rate (board_info.board_type, board.opmode, 0);


	for (jj=0; jj < boards_in_system; jj++)
	{
		if (a_buffer[jj] == NULL) {
			gage_select_board((int16)(jj+1));
			bsize = 0x00100000;
			a_buffer[jj] = VirtualAlloc(
                                NULL,	// address of region to reserve or commit  
                                (DWORD)(80+board.depth * ((board_info.sample_bits >= 12) + 1)),	// size of region 
                                MEM_COMMIT,	// type of allocation 
                                PAGE_READWRITE 	// type of access protection 
								);
			TVTBufferPtr[jj] = a_buffer[jj]; 
		}

	a_buffer16[jj] = (int16 far *)a_buffer[jj];

	if (b_buffer[jj] == NULL) {
		b_buffer[jj] = VirtualAlloc(
                                NULL,	// address of region to reserve or commit  
                                (DWORD)(80+board.depth * ((board_info.sample_bits >= 12) + 1)),	// size of region 
								MEM_COMMIT,	// type of allocation 
                                PAGE_READWRITE 	// type of access protection 
				        );
	}
	b_buffer16[jj] = (int16 far *)b_buffer[jj];

    if((a_buffer[jj] == NULL) || (b_buffer[jj] ==NULL))
       exit(1);
	
	}

	gage_get_driver_info_structure ((uInt16 far *)(&major_version), (uInt16 far *)(&minor_version), (uInt16 far *)(&board_support),
									(gage_driver_info_type far * far *)(&gdi), (int32 far *)(&gdi_size));

    gage_get_driver_info ((gage_driver_info_type far *)gdi);
	wsprintf (str, "CompuScope Driver Version %d.%02d%c.\n", major_version, minor_version & 0xff, (char)((minor_version >> 8) & 0xff));
    MessageBox (hWnd, str, "DLL version", MB_OK);

	current_board_type = B_T_DOUBLE_UP_BITS (board_info.board_type);
	update_sr_table_for_osc ((uInt16)0, (uInt16)current_board_type, (uInt32)board_info.ee_options);

	gage_initialize_start_capture (1);
	if (gage_select_board(1)!=1)  {
		MessageBox(hWnd, "Error while selecting board!", "Error", MB_OK);
		return (2);
	}

	multiple_record_avail = gage_detect_multiple_record();

    update_sr_table_for_osc (board_info.board_version, board_info.board_type, board_info.ee_options);
	update_range_table_for_version (board_info.board_version, board_info.board_type, board_info.ee_options); 
	
	/* Set opmode for the first time the window is drawn */
	if (board_info.board_type & GAGE_ASSUME_CS512)
		board.opmode = GAGE_DUAL_CHAN;
	else if ((board_info.board_type == GAGE_ASSUME_CS1016))
		board.opmode = GAGE_SINGLE_CHAN;
	else if ((board_info.board_type == GAGE_ASSUME_CS1610))
		board.opmode = GAGE_DUAL_CHAN;
	else if ((board_info.board_type == GAGE_ASSUME_CS8500) || (board_info.board_type == GAGE_ASSUME_CS3200))

	{
		board.opmode = GAGE_SINGLE_CHAN;
		if (board_info.board_type == GAGE_ASSUME_CS3200)
			board.source = GAGE_EXTERNAL;
	}
	else
		board.opmode = GAGE_DUAL_CHAN;

	return (0);


}       /*  End of InitBoard ().  */


/*-------------------------------------------------------------------------*/

void	prepare_for_capture (int16 boards_in_system, boarddef *board)
/*
	Preparing the CompuScope MASTER/SLAVE cards for data capture.
	Initialize the hardware with the new values.
*/
{

	int16	i, ret;
	int16	external_clock_in_use = 0;

	if (external_clock_in_use)  {
		board->srindex = SRTI_EXTERNAL;
		gage_set_ext_clock_variables (board->opmode, (uInt16)-1, (float)external_clock_rate);
		sample_rate_table[SRTI_EXTERNAL].sr_calc = 1000000000.0F / external_clock_rate;
		if (sample_rate_table[SRTI_EXTERNAL].sr_text != NULL)
			free (sample_rate_table[SRTI_EXTERNAL].sr_text);
		sample_rate_table[SRTI_EXTERNAL].sr_text = strdup (value_and_units_to_text ((double)(external_clock_rate), "Hz") + 1);	/*	Add 1 to skip the '+' sign.	*/
	}

	gage_get_driver_info (&board_info);

	if (board_info.board_type & GAGE_ASSUME_CS512)	
		/* If CS512, force opmode to dual channel, single is invalid for 512. */
    	board->opmode = GAGE_DUAL_CHAN;
	
	if (board_info.board_type == GAGE_ASSUME_CS1016) {
		/* If CS1016, force opmode to dual channel and range to +/- 1 volt.	*/
		board->opmode = GAGE_SINGLE_CHAN;
		board->range_a = board->range_b = GAGE_PM_1_V;
		board->source = GAGE_EXTERNAL;
		board->level = 192;
		board->range_e = GAGE_PM_5_V;
	}

	if (board_info.board_type == GAGE_ASSUME_CS8500)
	{
		board->opmode  = GAGE_SINGLE_CHAN;
	}

	if (board_info.board_type == GAGE_ASSUME_CS3200) {
		board->opmode = GAGE_SINGLE_CHAN;
		board->source = GAGE_EXTERNAL;
	}

//	board->srindex = best_sample_rate (board_info.board_type, board->opmode, external_clock_in_use);
	gage_select_board (1);	/* Select Master. */

	if (!gage_capture_mode (board->opmode, sample_rate_table[board->srindex].rate, sample_rate_table[board->srindex].mult))  {
		wsprintf (str, "Error while setting capture mode!  Error Code = %d", gage_get_error_code ());
		MessageBox(NULL, str, "Error", MB_OK);
	}
	
    if (!gage_input_control (GAGE_CHAN_A, GAGE_INPUT_ENABLE, board->couple_a, (int16)(board->range_a | board->imped_a)))  {
		wsprintf (str, "Error while setting channel A input control in master!  Error Code = %d", gage_get_error_code ());
		MessageBox(NULL, str, "Error", MB_OK);
	}
	if ( (board->opmode == GAGE_SINGLE_CHAN) && (board_info.board_type != GAGE_ASSUME_CS8500) && (board_info.board_type != GAGE_ASSUME_CS3200) )  {
		if (!gage_input_control (GAGE_CHAN_B, GAGE_INPUT_ENABLE, board->couple_a, (int16)(board->range_a | board->imped_a)))  {
			wsprintf (str, "Error while setting channel B input control in master!  Error Code = %d", gage_get_error_code ());
			MessageBox(NULL, str, "Error", MB_OK);
		}
	}else if ( (board_info.board_type != GAGE_ASSUME_CS8500) && (board_info.board_type != GAGE_ASSUME_CS3200) ){
	    if (!gage_input_control (GAGE_CHAN_B, GAGE_INPUT_ENABLE, board->couple_b, (int16)(board->range_b | board->imped_b)))  {
			wsprintf (str, "Error while setting channel B input control in master!  Error Code = %d", gage_get_error_code ());
			MessageBox(NULL, str, "Error", MB_OK);
		}
	}
	
	for (i = 2; i <= boards_in_system; i++) {
		gage_select_board (i);		/* Select slaves. */
		
		if ((board_info.board_type & (GAGE_ASSUME_CS1012 | GAGE_ASSUME_CS6012 | GAGE_ASSUME_CS512 | GAGE_ASSUME_CS8012)) && (board->srindex != SRTI_EXTERNAL)) {
			if (!gage_capture_mode (board->opmode, sample_rate_table[board->srindex].rate, sample_rate_table[board->srindex].mult)) {
				wsprintf (str, "Error setting capture mode on slave %d! Error code = %d", i, gage_get_error_code ());
				MessageBox (NULL, str, "Error", MB_OK);
			}	
		}else{
			if (!gage_capture_mode (board->opmode, 0, GAGE_EXT_CLK))  {
				wsprintf (str, "Error while setting EXT_CLK capture mode!  Error Code = %d", gage_get_error_code ());
				MessageBox(NULL, str, "Error", MB_OK);
			}
		}
		if (!gage_input_control (GAGE_CHAN_A, GAGE_INPUT_ENABLE, board->couple_a, (int16)(board->range_a | board->imped_a))) {
			wsprintf (str, "Error while setting Channel A input control in slave! Error Code = %d", gage_get_error_code ());
			MessageBox (NULL, str, "Error", MB_OK);
		}
		if ( (board->opmode == GAGE_SINGLE_CHAN) && (board_info.board_type != GAGE_ASSUME_CS8500))  {
			if (!gage_input_control (GAGE_CHAN_B, GAGE_INPUT_ENABLE, board->couple_a, (int16)(board->range_a | board->imped_a)))  {
				wsprintf (str, "Error while setting channel B input control in slave!  Error Code = %d", gage_get_error_code ());
				MessageBox(NULL, str, "Error", MB_OK);
			}
		}else if (board_info.board_type != GAGE_ASSUME_CS8500){
			if (!gage_input_control (GAGE_CHAN_B, GAGE_INPUT_ENABLE, board->couple_b, (int16)(board->range_b | board->imped_b)))  {
				wsprintf (str, "Error while setting channel B input control in slave!  Error Code = %d", gage_get_error_code ());
				MessageBox(NULL, str, "Error", MB_OK);
			}
		}
#define USE_TRIGGER_CONTROL_2
#ifdef	USE_TRIGGER_CONTROL_2

	if (board_info.board_type & (GAGE_ASSUME_CS1016 | GAGE_ASSUME_CS6012 | GAGE_ASSUME_CS1012 | GAGE_ASSUME_CS512 | GAGE_ASSUME_CS8012))	/*	12 bit boards have 12 bit trigger levels.	*/
		ret = gage_trigger_control_2 (board->source, board->source_2, board->couple_e, board->range_e, board->slope, board->slope_2, (int16)(board->level << 4), (int16)(board->level_2 << 4), board->depth, 1, 1);
	else
		ret = gage_trigger_control_2 (board->source, board->source_2, board->couple_e, board->range_e, board->slope, board->slope_2, board->level, board->level_2, board->depth, 1, 1);

#else	/*	USE_TRIGGER_CONTROL_2	*/

		ret = gage_trigger_control (GAGE_SOFTWARE, board->couple_e, board->range_e, board->slope, board->level, board->depth);

#endif	/*	USE_TRIGGER_CONTROL_2	*/

		if (!ret)  {
			wsprintf (str, "Error while setting trigger control in slave!  Error Code = %d", gage_get_error_code ());
			MessageBox(NULL, str, "Error", MB_OK);
		}

	}

	gage_select_board (1);	/* Select Master. */

#ifdef	USE_TRIGGER_CONTROL_2

	if (board_info.board_type & (GAGE_ASSUME_CS1016 | GAGE_ASSUME_CS6012 | GAGE_ASSUME_CS1012 | GAGE_ASSUME_CS512 | GAGE_ASSUME_CS8012))	/*	12 bit boards have 12 bit trigger levels.	*/
		ret = gage_trigger_control_2 (board->source, board->source_2, board->couple_e, board->range_e, board->slope, board->slope_2, (int16)(board->level << 4), (int16)(board->level_2 << 4), board->depth, 1, 1);
	else
		ret = gage_trigger_control_2 (board->source, board->source_2, board->couple_e, board->range_e, board->slope, board->slope_2, board->level, board->level_2, board->depth, 1, 1);

#else	/*	USE_TRIGGER_CONTROL_2	*/

		ret = gage_trigger_control (board->source, board->couple_e, board->range_e, board->slope, board->level, board->depth);

#endif	/*	USE_TRIGGER_CONTROL_2	*/

	if (!ret)  {
		wsprintf (str, "Error while setting trigger control in master!  Error Code = %d", gage_get_error_code ());
		MessageBox(NULL, str, "Error", MB_OK);
	}


	/* Get updated board_info in case max_available_memory has changed due to changing the mode */
	gage_get_driver_info (&board_info);
	Sleep(10);

//	channel_ram_size = board_info.max_available_memory;

}	/*	End of prepare_for_capture ().	*/

/*-------------------------------------------------------------------------*/

void	InitMemPtrs (void)
{
	int32			i;
	int16		channel;
	

	for (i = 0; i < (boards_in_system * 2); i += (1 + (board.opmode == GAGE_SINGLE_CHAN))) {
		gage_select_board ((int16)((i >> 1) + 1));
		channel = (int16)((i & 1) + GAGE_CHAN_A);

    /* When not using interpolated trigger, use this line. */
     	gage_calculate_addresses (channel, board.opmode,sample_rate_table[board.srindex].sr_calc,
     		&trigger_address[i], &starting_address[i], &ending_address[i]);
   }
}       /*  End of InitMemPtrs ().  */

/*-------------------------------------------------------------------------*/

void	AcquireStart (void)
{
	uInt32 rtn = 0;
	
    gage_select_board(1);

	gage_start_capture ((int16)(board.source == GAGE_SOFTWARE));
    CapturingData = TRUE;
	number_of_timer_events = 0;

}       /*      End of AcquireStart ().  */

/*------transfer_type == USE_TRANSFER_BUFFER_3-------------------------------------------------------------------*/


void	TransferTB3Data (HWND hWnd)
{
	int16	boards;
	int i;
	int32	offset = 0;
    uInt32	depth;
	LARGE_INTEGER count1, count2, counter;
	BOOL bool1;
	char str[40];
	SYSTEMTIME st;

	location = gage_trigger_address;   
	points = board.depth;
	depth = board.depth;

	for (boards = 0; boards < boards_in_system; boards++)
	{
		gage_select_board ((int16)(boards + 1));   	 	
		if (board.opmode == GAGE_SINGLE_CHAN)
		{
			if((board_type == GAGE_ASSUME_CS8500) || (board_type == GAGE_ASSUME_CS3200) )
			{	
				bool1 = QueryPerformanceFrequency(&counter);
				bool1 = QueryPerformanceCounter(&count1);
				TVT3_offset[boards]= gage_transfer_buffer_3(trigger_address[boards],(int16)(GAGE_CHAN_A+boards), (void *)TVTBufferPtr[boards], (int32)board.depth);
				bool1 = QueryPerformanceCounter(&count2);
				time3 = (count2.LowPart - count1.LowPart)/((counter.LowPart)/1000);
				/************my save data try*********
				/* 8 bits board */
				if(board_info.sample_bits == 8)
				{
					if((chan_a_8 = (uInt8 *) malloc(board.depth + 8)) == NULL)
					{
						wsprintf (str, "   Malloc Failed!   ");
						MessageBox(NULL, str, "Error", MB_OK);
						exit(1);
					}
					else
						/* Transfer Chan A 8 bits board single mode */
						offset_a = gage_transfer_buffer_3(location,GAGE_CHAN_A,chan_a_8, points);
				}
				if (!zipFiles) {
					for (i = 0; i < points+200; i++)  
						 fprintf(stream, "\t%d\n", (255 - a_buffer[0][i]));
					GetLocalTime(&st);

					if (subtract == 1) {
						SYSTEMTIME difference;
						FILETIME startFileTime, endFileTime, fileDiff;
						ULARGE_INTEGER start, end, diff;

						SystemTimeToFileTime(&initTime, &startFileTime);
						SystemTimeToFileTime(&st, &endFileTime);

						start.LowPart      =   startFileTime.dwLowDateTime; 
						start.HighPart     =   startFileTime.dwHighDateTime; 
						end.LowPart        =   endFileTime.dwLowDateTime; 
						end.HighPart       =   endFileTime.dwHighDateTime; 

						// Subtracts the lower and higher parts of the ULARGE_INTEGER structure 
						diff.HighPart  =   end.HighPart - start.HighPart; 
						diff.LowPart   =   end.LowPart  - start.LowPart; 

						if (end.LowPart < start.LowPart) {
							diff.HighPart -= 1;
							diff.LowPart = 4294967295 - (start.LowPart - end.LowPart - 1);
						}

						// Converts back to FILETIME structure from ULARGE_INTEGER structure 
						// Note:  Now this value has the difference, in milliseconds between the two time intervals 
						fileDiff.dwLowDateTime      =   diff.LowPart; 
						fileDiff.dwHighDateTime     =   diff.HighPart; 

						// Coverts back to SYSTEMTIME structure from FILETIME structure 
						// *IMPORTANT*:  This will add the number of milliseconds to the following base date: 1/1/1601 
						FileTimeToSystemTime( &fileDiff, &difference); 
					
						difference.wYear = 2002;
						difference.wMonth -= 1;
						difference.wDay -= 1;

						wsprintf(str, "%d/%d/%d-%d:%d:%d.%d", difference.wYear, difference.wMonth,
							difference.wDay, difference.wHour, difference.wMinute, difference.wSecond, difference.wMilliseconds);
					}
					else
						wsprintf(str, "%d/%d/%d-%d:%d:%d.%d", st.wYear, st.wMonth,
							st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);

					fprintf(stream, " %s ", str);
					fclose(stream);
				}
				else {
					//add code for zipping here

					int i;
					char filename[40] = {0};
					SYSTEMTIME	st;
					
					GetLocalTime(&st);
					wsprintf(filename, "%4d%2d%2d%2d%2d%2d%4d", st.wYear, st.wMonth,
						st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
					for (i = 0; i < 16; i++) {
						if (filename[i] == ' ')
							filename[i] = '0';
					}
					strcpy(Filenames[fnum], filename);

					Bufferptr = Buffer[fnum];

					regs.chn_enc  = INP(bio+CHNENC);    /* get channeltron output */
					regs.ptrvlt   = INP(bio+PTRVLT);    /*partical travel time from t1 to t2 */
					sprintf(Bufferptr, "%d\t%d\t%x\n",regs.ptrvlt*50,regs.chn_enc,regs.star);
					Bufferptr += strlen(Bufferptr);
					
					for (i = 0; i < points+200; i++)  {
						 sprintf(Bufferptr, " %d", (255 - a_buffer[0][i]));
						 Bufferptr += strlen(Bufferptr);
					}

					// change
					if (subtract == 1) {
						SYSTEMTIME difference;
						FILETIME startFileTime, endFileTime, fileDiff;
						ULARGE_INTEGER start, end, diff;

						SystemTimeToFileTime(&initTime, &startFileTime);
						SystemTimeToFileTime(&st, &endFileTime);

						start.LowPart      =   startFileTime.dwLowDateTime; 
						start.HighPart     =   startFileTime.dwHighDateTime; 
						end.LowPart        =   endFileTime.dwLowDateTime; 
						end.HighPart       =   endFileTime.dwHighDateTime; 

						// Subtracts the lower and higher parts of the ULARGE_INTEGER structure 
						diff.HighPart  =   end.HighPart - start.HighPart; 
						diff.LowPart   =   end.LowPart  - start.LowPart;

						if (end.LowPart < start.LowPart) {
							diff.HighPart -= 1;
							diff.LowPart = 4294967295 - (start.LowPart - end.LowPart - 1);
						}

						// Converts back to FILETIME structure from ULARGE_INTEGER structure 
						// Note:  Now this value has the difference, in milliseconds between the two time intervals 
						fileDiff.dwLowDateTime      =   diff.LowPart; 
						fileDiff.dwHighDateTime     =   diff.HighPart; 

						// Coverts back to SYSTEMTIME structure from FILETIME structure 
						// *IMPORTANT*:  This will add the number of milliseconds to the following base date: 1/1/1601 
						FileTimeToSystemTime( &fileDiff, &difference); 
					
						difference.wYear = 2002;
						difference.wMonth -= 1;
						difference.wDay -= 1;

						wsprintf(Bufferptr, "\n%d/%d/%d-%d:%d:%d.%d", difference.wYear, difference.wMonth,
							difference.wDay, difference.wHour, difference.wMinute, difference.wSecond, difference.wMilliseconds);
					}
					else
						wsprintf(Bufferptr, "\n%d/%d/%d-%d:%d:%d.%d", st.wYear, st.wMonth,
							st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);

					Bufferptr += strlen(Bufferptr);
					*Bufferptr = '\0';
					//fprintf(stream, "%s", Buffer[fnum]);
					fclose(stream);

					fnum++;
					if (fnum == nTar) {
						fnum = 0;
						encode(Filenames, nTar);
					}
				}

			  //  fprintf(stream, "\t%d\n", (255 - chan_a_8[offset_a + i])); 
				if(chan_a_8 != NULL)
					free(chan_a_8);	
				/********************/	
			}
			else
			{ 
				if ((board_info.sample_bits == 12) || (board_info.sample_bits == 16))
				{
					bool1 = QueryPerformanceFrequency(&counter);
					bool1 = QueryPerformanceCounter(&count1);
					TVT3_offset[boards]=gage_transfer_buffer_3(trigger_address[boards],(int16)GAGE_CHAN_A, (void *)(a_buffer16[boards]+ offset), (int32)board.depth);
					bool1 = QueryPerformanceCounter(&count2);
					time3 = (count2.LowPart - count1.LowPart)/((counter.LowPart)/1000);
				}
				else
				{
					TVT3_offset[boards]=gage_transfer_buffer_3(trigger_address[boards],(int16)GAGE_CHAN_A, (void *)(a_buffer16[boards]+ offset), (int32)board.depth);
				}
			}
		}
		else
		{
			if ((board_info.sample_bits == 12) || (board_info.sample_bits == 16))
			{
				bool1 = QueryPerformanceFrequency(&counter);
				bool1 = QueryPerformanceCounter(&count1);
				TVT3_offset[boards]=gage_transfer_buffer_3(trigger_address[boards],(int16)GAGE_CHAN_A, (void far *)(a_buffer16[boards]+offset), (int32)board.depth);
				TVT3_offsetB[boards]=gage_transfer_buffer_3(trigger_address[boards],(int16)GAGE_CHAN_B, (void far *)(b_buffer16[boards]+offset), (int32)board.depth);
				bool1 = QueryPerformanceCounter(&count2);
				time3 = (count2.LowPart - count1.LowPart)/((counter.LowPart)/1000);
			}
			else
			{
				gage_transfer_buffer_3 (trigger_address[boards],(int16)GAGE_CHAN_A, (void far *)(a_buffer16[boards]+ offset), (int32)board.depth>>1);
				gage_transfer_buffer_3 (trigger_address[boards],(int16)GAGE_CHAN_B, (void far *)(b_buffer16[boards]+ offset), (int32)board.depth>>1);
			}
		}
	}	
	Display (hWnd);
} /* TransferTB3Data()

/*-------------AcquireCheck------------------------------------------------------------*/


void	AcquireCheck (HWND hWnd)
{   
	int16			bd;
	int i;
	static int32	triggered = 0;
	SYSTEMTIME	st;
//	char tmpbuf1[128];
//	char tmpbuf2[128];
	
//  public boolean mkdir ();
  
//	char filename[20];
//	char filepath[30];

	if (!CapturingData)
		return;
    if (!gage_triggered ())  
		{
		if (number_of_timer_events > TRIG_TIMEOUT)  
			{
			gage_forced_trigger_capture (board.source);
			number_of_timer_events = 0;
			}
		
		return;
		}
		else if (!triggered)
			{
  //			wsprintf (str, "triggered = %d\n",triggered );
  //			MessageBox(NULL, str, "My Message", MB_OK);  
				triggered = 1;
				number_of_timer_events = 0;
			}
	for (bd = 1; bd <= boards_in_system; bd++)
		{
		gage_select_board (bd);
		while (gage_busy ()) 
			{
		   	number_of_timer_events++;
			}
		}

	number_of_timer_events = 0;
    triggered = 0;
	gage_multiple_record(use_multiple_record);
/********************
	    wsprintf (str, "%s not found!", (LPSTR)board_loc_file);
		wsprintf (str, "%s transfer_type", (LPSTR)(transfer_type));
				MessageBox(NULL, str, "My Message", MB_OK);   
/********************/
	if (use_multiple_record)
	{
		if (transfer_type == USE_TRANSFER_BUFFER_3)
		{
			MessageBox(hWnd, "Trigger_Transfer_Buffer_3 Method Not Available Yet,\nTrigger_Transfer_Buffer Will Be Used","Note", MB_OK);
//edit by jack		//	TransferMRTBData (hWnd);
		}
	}
	else
	{
		InitMemPtrs ();
		if (transfer_type == USE_TRANSFER_BUFFER_3)
		{
			if (ContinuousMode)
			{
				if ( k == 1 ) /* k=1 CONTINUOUS MODE*/
				{
					int i;
					char dir[200];
					filename[0]=0;

					wsprintf(dir, "%s\\dat", dpath);
					_mkdir(dir);
					
					GetLocalTime(&st);
					wsprintf(filepath, "%s\\dat\\%4d%2d%2d%2d%2d%2d%4d.dat", dpath, st.wYear, st.wMonth,
						st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
					for (i = 5 + strlen(dpath); i < strlen(dpath) + 24; i++) {
						if (filepath[i] == ' ')
							filepath[i] = '0';
					}
					//MessageBox(NULL, filepath, "debug", MB_OK);
					stream = fopen(filepath, "w+" );
					if (!zipFiles)
						save_data(stream);
					j++; 
					TransferTB3Data (hWnd);
					if (zipFiles)
						DeleteFile(filepath);
				}								
				else if ( j < nxx ) /* k=0 */
				{
					int i;
					char dir[200];
					filename[0]=0;
					wsprintf(dir, "%s\\dat", dpath);
					_mkdir(dir);
					GetLocalTime(&st);
					wsprintf(filepath, "%s\\dat\\%d%2d%2d%2d%2d%2d%4d.dat",dpath, st.wYear, st.wMonth,
						st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
					for (i = 5 + strlen(dpath); i < strlen(dpath) + 24; i++) {
						if (filepath[i] == ' ')
							filepath[i] = '0';
					}
					//MessageBox(NULL, filepath, "debug", MB_OK);
					stream = fopen(filepath, "w+" );
					j++;
					if (!zipFiles)
						save_data(stream);
					TransferTB3Data (hWnd);
					if (zipFiles)
						DeleteFile(filepath);
					if ( j == nxx ) {
						char dirname[200];
						char datname[200];
						GetLocalTime(&st);
						wsprintf(directoryname, "%4d%2d%2d%2d%2d%2d%4d", st.wYear, st.wMonth,
							st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
						for (i = 0; i < 17; i++) {
							if (directoryname[i] == ' ')
								directoryname[i] = '0';
						}
						wsprintf(dirname, "%s\\%s", dpath, directoryname);
						wsprintf(datname, "%s\\dat", dpath);
						rename(datname,dirname);
					}
				}
			}
		}
	}
    if (ContinuousMode)  {
		prepare_for_capture(boards_in_system, &board);
		AcquireStart ();
    }else
		CapturingData = FALSE;
}  /*      End of AcquireCheck ().  */

/*-------------------------------------------------------------------------*/

void	Abort (HWND hWnd)
{
	if (ContinuousMode)  
	{

		ContinuousMode = FALSE;

		if(stream != NULL)
			fclose( stream );
		else
			MessageBox(hWnd,"NO FILE OPEN CANT CLOSE","FUNCTION Abort",1);
	}
	else
	{
		if (!gage_triggered ())  
		{
			gage_forced_trigger_capture (board.source);
		}
		gage_abort_capture (board.source);
        if (!gage_triggered ())  
		{
			MessageBox(hWnd, "CompuScope hardware still reports it has not triggered!","Error", MB_OK);
	    }
	    if (gage_busy ())  
		{
			MessageBox(hWnd, "CompuScope hardware still reports it is busy!","Error", MB_OK);
	    }
	    if (!gage_triggered () || gage_busy ())  
		{
			CapturingData = FALSE;
			ContinuousMode = FALSE;
	    }
	}

}       /*      End of Abort ().  */

/*-------------------------------------------------------------------------*/





/*-------------------------------------------------------------------------*/

void	Display (HWND hWnd)

{
	InvalidateRect(hWnd, NULL, FALSE);
	UpdateWindow(hWnd);

}       /*  End of Display ().  */

/*-------------------------------------------------------------------------*/

int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow)

{
 /***********************************************************************/
 /* HANDLE hInstance;       handle for this instance                    */
 /* HANDLE hPrevInstance;   handle for possible previous instances      */
 /* LPSTR  lpszCmdLine;     long pointer to exec command line           */
 /* int32    nCmdShow;        Show code for main window display           */
 /***********************************************************************/

 	MSG        msg;             /* MSG structure to store your messages        */
 	int32        nRc;           /* return value from Register Classes          */
 	int32        ret;               /* return value from InitBoard.  */

    lpszCmdLine = lpszCmdLine;
 	strcpy(szAppName, "GSDLLDEM");
 	hInst = hInstance;

	//Compare the flag ...
	if(	!strcmp(lpszCmdLine,"mulrec_adjust_1012_16M"))
		AdjustFlag=1;
	
	if(!hPrevInstance) {
   	    /* register window classes if first instance of application         */
    	    if ((nRc = nCwRegisterClasses()) == -1) {
      	    /* registering one of the windows failed		*/
       		CwUnRegisterClasses();                         
       		LoadString(hInst, IDS_ERR_REGISTER_CLASS, szString, sizeof(szString));
       		MessageBox(NULL, szString, NULL, MB_ICONEXCLAMATION);
       		return nRc;
      	    }
   	}



 /* create application's Main window                                    */
 	hWndMain = CreateWindow(
		szAppName,               /* Window class name           */
		"SPLAT VER 0.1",         /* Window's title              */
		WS_CAPTION      |        /* Title and Min/Max           */
		WS_SYSMENU      |        /* Add system menu box         */
		WS_MINIMIZEBOX  |        /* Add minimize box            */
		WS_MAXIMIZEBOX  |        /* Add maximize box            */
		WS_THICKFRAME   |        /* thick sizeable frame        */
		WS_CLIPCHILDREN |        /* don't draw in child windows areas */
		WS_OVERLAPPED,
		CW_USEDEFAULT,           /* Use default X, Y            */
		CW_USEDEFAULT,           /* Use default X, Y            */
		600,                     /* Force the size of X         */
		400,                     /* Force the size of Y         */
		NULL,                    /* Parent window's handle      */
		NULL,                    /* Default to Class Menu       */
		hInst,                   /* Instance of window          */
		NULL);                   /* Create struct for WM_CREATE */

 	if(hWndMain == NULL) {
   	   	LoadString(hInst, IDS_ERR_CREATE_WINDOW, szString, sizeof(szString));
    	MessageBox(NULL, szString, NULL, MB_ICONEXCLAMATION);
    	return IDS_ERR_CREATE_WINDOW;
   	}
	
 	if ((ret = InitBoard (hWndMain)) != 0)
		return (FALSE);
	splatisa();
	if (bio == 0)
	{
		MessageBox(NULL, "SPLAT NOT FOUND", "ERROR", MB_OK);
		return (FALSE);
	}
	hAccel = LoadAccelerators(hInst, szAppName);

    SetPriorityClass(hInstance,REALTIME_PRIORITY_CLASS);

 	ShowWindow(hWndMain, nCmdShow);            /* display main window      */	
    while(GetMessage(&msg, NULL, 0, 0)) {       /* Until WM_QUIT message    */

		AcquireCheck (hDisplayWnd);
		if (save_file) Cap_Save_FILE(hDisplayWnd);
		if (running) check_stat();
    	if (!TranslateAccelerator(hWndMain, hAccel, &msg))
		if (!IsDialogMessage(SRateDlg, &msg))
		if (!IsDialogMessage(IRangeDlg, &msg))
		if (!IsDialogMessage(PmtDlg, &msg))
		if (!IsDialogMessage(CapDlg, &msg))
		if (!IsDialogMessage(TriggerDlg, &msg))
		if (!IsDialogMessage(SetTimerDlg, &msg))
		{
      		TranslateMessage(&msg);
    		DispatchMessage(&msg);
		}
   	    SendMessage(hWndMain,&msg, 0, 0);
	}
	
	gage_driver_remove();
 	/* Do clean up before exiting from the application                     */
 	return msg.wParam;
} /*  End of WinMain                                                    */

/*-------------------------------------------------------------------------*/

LRESULT CALLBACK SRateDlgProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	static	boarddef temp_board;
	int32		i, j;
	DWORD	nIndex;

	switch (msg) {

		case WM_INITDIALOG:

			memcpy (&temp_board, &board, sizeof(board));

			if (temp_board.opmode == GAGE_DUAL_CHAN)
			{
				SendDlgItemMessage (hWnd, IDC_DUAL, BM_SETCHECK, BST_CHECKED, 0);
				SendDlgItemMessage (hWnd, IDC_SINGLE, BM_SETCHECK, BST_UNCHECKED, 0);
			}
			else
			{
				SendDlgItemMessage (hWnd, IDC_SINGLE, BM_SETCHECK, BST_CHECKED, 0);
				if (board_type == GAGE_ASSUME_CS8500)
				{
					EnableWindow(GetDlgItem(hWnd, IDC_DUAL),FALSE);
				}
				else
				{
					SendDlgItemMessage (hWnd, IDC_DUAL, BM_SETCHECK, BST_UNCHECKED, 0);
				}
			}

			for (i = 0; i < SRTI_EXTERNAL; i++) {
				if (temp_board.opmode == GAGE_DUAL_CHAN) {	
					if ((sample_rate_table[i].sr_flag & B_T_DUAL) & current_board_type) {
						nIndex = SendDlgItemMessage (hWnd, IDC_SRATE, CB_ADDSTRING, 0, (LPARAM)((LPCTSTR)(sample_rate_table[i].sr_text)));
						SendDlgItemMessage (hWnd, IDC_SRATE, CB_SETITEMDATA, nIndex, (LPARAM)i);
						j = i; 
					}
				}
				else {
					if ((sample_rate_table[i].sr_flag & B_T_SINGLE) & current_board_type) {
						nIndex = SendDlgItemMessage (hWnd, IDC_SRATE, CB_ADDSTRING, 0, (LPARAM)((LPCTSTR)(sample_rate_table[i].sr_text)));
						SendDlgItemMessage (hWnd, IDC_SRATE, CB_SETITEMDATA, nIndex, (LPARAM)i);
						j = i;
					}
				}				
			}

			SendDlgItemMessage (hWnd, IDC_MULREC, BM_SETCHECK, (WPARAM)use_multiple_record, 0);
			SendDlgItemMessage (hWnd, IDC_EXTCLK, BM_SETCHECK, (WPARAM)external_clock_in_use, 0);
			
			if(external_clock_in_use){
				EnableWindow(GetDlgItem(hWnd, IDC_EXT_CLK_VALUE),TRUE);
				SetDlgItemInt(	hWnd,	// handle of dialog box
								IDC_EXT_CLK_VALUE,	// identifier of control
								(uInt32)external_clock_rate,	// value to set
								FALSE 	// signed or unsigned indicator
				);
		   	}else
			   EnableWindow(GetDlgItem(hWnd, IDC_EXT_CLK_VALUE),FALSE);
			
			if(external_clock_in_use)		
				nIndex = SRTI_EXTERNAL;
			else   
				nIndex = SendDlgItemMessage (hWnd, IDC_SRATE, CB_FINDSTRINGEXACT, (WPARAM)0, (LPARAM)((LPCTSTR)(sample_rate_table[board.srindex].sr_text)));

			SendDlgItemMessage (hWnd, IDC_SRATE, CB_SETCURSEL, (WPARAM)nIndex, 0);

			return (TRUE);

				
		case WM_COMMAND:

			switch (LOWORD(wParam)) {

				case IDC_SR_APPLY:
					{
					nIndex = SendDlgItemMessage (hWnd, IDC_SRATE, CB_GETCURSEL, 0, 0);
					temp_board.srindex =  (int16)(SendDlgItemMessage (hWnd, IDC_SRATE, CB_GETITEMDATA, (WPARAM)nIndex, 0));
					use_multiple_record = (int16)SendDlgItemMessage (hWnd, IDC_MULREC,BM_GETCHECK, 0, 0);
					external_clock_in_use = (int16)SendDlgItemMessage (hWnd, IDC_EXTCLK,BM_GETCHECK, 0, 0);
					if (!multiple_record_avail && use_multiple_record)
					{
						MessageBox(NULL, "MultipleRecord Is Not Available On Your Board", "Error", MB_OK);
						use_multiple_record = 0;
					}
					if(external_clock_in_use)
						external_clock_rate=(float)GetDlgItemInt (hWnd, IDC_EXT_CLK_VALUE, NULL, FALSE);
					else{
						EnableWindow(GetDlgItem(hWnd, IDC_EXT_CLK_VALUE),FALSE);
					    SetDlgItemInt(hWnd,	// handle of dialog box
                             IDC_EXT_CLK_VALUE,	// identifier of control
                             (uInt32)external_clock_rate,	// value to set
                             FALSE 	// signed or unsigned indicator
                        );
					}
					
					board.srindex = temp_board.srindex;
					board.opmode = temp_board.opmode;

					SetFocus (GetParent (hWnd));
					prepare_for_capture (boards_in_system, &temp_board);
					}
					break;

				case IDC_SR_CLOSE:
					DestroyWindow (SRateDlg);
					SRateDlg = 0;
					break;

				case IDC_SINGLE:
					for (i = 0; i < SRTI_EXTERNAL; i++) {
						if ((sample_rate_table[i].sr_flag & B_T_SINGLE) & current_board_type) {
							nIndex = SendDlgItemMessage (hWnd, IDC_SRATE, CB_ADDSTRING, 0, (LPARAM)((LPCTSTR)(sample_rate_table[i].sr_text)));
							SendDlgItemMessage (hWnd, IDC_SRATE, CB_SETITEMDATA, nIndex, (LPARAM)i);
							j = i;
						}
					}
					temp_board.opmode = GAGE_SINGLE_CHAN;
					temp_board.srindex = best_sample_rate (board_info.board_type, GAGE_SINGLE_CHAN, 0);
					break;
				
				case IDC_DUAL:

					for (i = 0; i < SRTI_EXTERNAL; i++) {
						if ((sample_rate_table[i].sr_flag & B_T_DUAL) & current_board_type) {
							nIndex = SendDlgItemMessage (hWnd, IDC_SRATE, CB_ADDSTRING, 0, (LPARAM)((LPCTSTR)(sample_rate_table[i].sr_text)));
							SendDlgItemMessage (hWnd, IDC_SRATE, CB_SETITEMDATA, nIndex, (LPARAM)i);
							j = i; 
						}
					}
					temp_board.opmode = GAGE_DUAL_CHAN;
					temp_board.srindex = best_sample_rate (board_info.board_type, GAGE_DUAL_CHAN, 0);
					break;

				case IDC_EXTCLK:
                    external_clock_in_use = (int16)SendDlgItemMessage (hWnd, IDC_EXTCLK,BM_GETCHECK, 0, 0);
				    if(external_clock_in_use){
					   EnableWindow(GetDlgItem(hWnd, IDC_EXT_CLK_VALUE),TRUE);
					   SetDlgItemInt(hWnd,	// handle of dialog box
                             IDC_EXT_CLK_VALUE,	// identifier of control
                            (uInt32) external_clock_rate,	// value to set
                             FALSE 	// signed or unsigned indicator
                       );
			        } 
					else{
                       EnableWindow(GetDlgItem(hWnd, IDC_EXT_CLK_VALUE),FALSE);
					  
					}
					break;
		}
			
		default:
			break;
	}

	return (FALSE);
}

LRESULT CALLBACK IRangeDlgProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	static	boarddef temp_board;
	int32	i;
	DWORD	nIndex;
	
	switch (msg) {
		
		case WM_INITDIALOG:

			memcpy (&temp_board, &board, sizeof(board));
			if (temp_board.couple_a == GAGE_AC)
				SendDlgItemMessage (hWnd, IDC_IRAC, BM_SETCHECK, 1, 0);
			else
				SendDlgItemMessage (hWnd, IDC_IRDC, BM_SETCHECK, 1, 0);
			
			
			for (i = 0; i < 7; i++) {
				if (ranges[i].ir_flag & current_board_type) {
					nIndex = SendDlgItemMessage (hWnd, IDC_IRANGE, CB_ADDSTRING, 0, (LPARAM)((LPCTSTR)(ranges[i].ir_text)));
					SendDlgItemMessage (hWnd, IDC_IRANGE, CB_SETITEMDATA, nIndex, (LPARAM)i);
				}	
			}
			nIndex = SendDlgItemMessage (hWnd, IDC_IRANGE, CB_FINDSTRINGEXACT, (WPARAM)0, (LPARAM)((LPCTSTR)(ranges[board.range_a].ir_text)));
			SendDlgItemMessage (hWnd, IDC_IRANGE, CB_SETCURSEL, (WPARAM)nIndex, 0);
			
			return (TRUE);

		case WM_COMMAND:

			switch (LOWORD(wParam)) {

				case IDC_IRAPPLY:
					
					nIndex = SendDlgItemMessage (hWnd, IDC_IRANGE, CB_GETCURSEL, 0, 0);
					temp_board.range_a = temp_board.range_b =  (int16)(SendDlgItemMessage (hWnd, IDC_IRANGE, CB_GETITEMDATA, (WPARAM)nIndex, 0));
					board.range_a = temp_board.range_a;
					board.range_b = temp_board.range_b;
					board.couple_a = temp_board.couple_a;
					board.couple_b = temp_board.couple_b;

					SetFocus (GetParent (hWnd));
					prepare_for_capture (boards_in_system, &board);
					break;

				case IDC_IRCLOSE:

					DestroyWindow (IRangeDlg);
					IRangeDlg = 0;
					break;

				case IDC_IRAC:

					temp_board.couple_a = temp_board.couple_b = GAGE_AC;
					break;

				case IDC_IRDC:

					temp_board.couple_a = temp_board.couple_b = GAGE_DC;
					break;
			}

		default:
			break;

	}
	return (FALSE);
}


LRESULT CALLBACK TriggerDlgProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	static	boarddef temp_board;
	uInt32 jj;

	switch (msg) {
		
		case WM_INITDIALOG:

			memcpy (&temp_board, &board, sizeof(board));
			if (temp_board.source == GAGE_CHAN_A)
				SendDlgItemMessage (hWnd, IDC_TRIGCHANA, BM_SETCHECK, 1, 0);
			else if (temp_board.source == GAGE_CHAN_B)
				SendDlgItemMessage (hWnd, IDC_TRIGCHANB, BM_SETCHECK, 1, 0);
			else if (temp_board.source == GAGE_SOFTWARE)
				SendDlgItemMessage (hWnd, IDC_TRIGSOFTWARE, BM_SETCHECK, 1, 0);
			else
				SendDlgItemMessage (hWnd, IDC_TRIGEXTERNAL, BM_SETCHECK, 1, 0);

			if (temp_board.imped_a == GAGE_1_MOHM_INPUT)
				SendDlgItemMessage (hWnd, IDC_IMPED1M, BM_SETCHECK, 1, 0);
			else
				SendDlgItemMessage (hWnd, IDC_IMPED50, BM_SETCHECK, 1, 0);

			if (temp_board.slope == GAGE_POSITIVE)
				SendDlgItemMessage (hWnd, IDC_TRIGPOS, BM_SETCHECK, 1, 0);
			else
				SendDlgItemMessage (hWnd, IDC_TRIGNEG, BM_SETCHECK, 1, 0);
			
			if ( temp_board.range_e == GAGE_PM_1_V )
				SendDlgItemMessage (hWnd, IDC_TRIG1V, BM_SETCHECK, 1, 0);
			if ( temp_board.range_e == GAGE_PM_5_V )
				SendDlgItemMessage (hWnd, IDC_TRIG5V, BM_SETCHECK, 1, 0);

			if ( temp_board.couple_e == GAGE_AC)
				SendDlgItemMessage (hWnd, IDC_TRIGAC, BM_SETCHECK, 1, 0);
			else
				SendDlgItemMessage (hWnd, IDC_TRIGDC, BM_SETCHECK, 1, 0);

			SetDlgItemInt (hWnd, IDC_TRIGGERLEVEL, board.level, FALSE);						
			SetDlgItemInt (hWnd, IDC_TRIGGERDEPTH, (int32)board.depth, FALSE);
			SetDlgItemInt (hWnd, IDC_TRIGGERTIMEOUT, TRIG_TIMEOUT, FALSE);	
			SetDlgItemInt (hWnd, IDC_BUSYIMEOUT, BUSY_TIMEOUT, FALSE);
			SetDlgItemInt (hWnd, IDC_NUMBEROFSAMPLES, nxx, FALSE);
			return (TRUE);
		case WM_COMMAND:
			switch (LOWORD(wParam)) {
				case IDC_TRIGAPPLY:
					temp_board.level = (int16)GetDlgItemInt (hWnd, IDC_TRIGGERLEVEL, NULL, FALSE);
					temp_board.depth = GetDlgItemInt (hWnd, IDC_TRIGGERDEPTH, NULL, FALSE);
					nxx = GetDlgItemInt (hWnd, IDC_NUMBEROFSAMPLES, NULL, FALSE);

					TRIG_TIMEOUT == GetDlgItemInt (hWnd, IDC_TRIGGERTIMEOUT, NULL, FALSE);
					BUSY_TIMEOUT == GetDlgItemInt (hWnd, IDC_BUSYIMEOUT, NULL, FALSE);

					if ((board_type & GAGE_ASSUME_CS8500) && (transfer_type == USE_TRIGGER_VIEW_2)) {
						if (temp_board.depth > bsize) {
							wsprintf (str, "Trigger depth exceeds allocated size of %d bytes", bsize);
							MessageBox(hWnd, str, "CS8500: Gage_Trigger_View_Transfer_2", MB_OK | MB_ICONINFORMATION);
							break;
						}
					}

					if (transfer_type == USE_TRIGGER_VIEW) {
						if (temp_board.depth >= 32*1024) {
							wsprintf (str, "Trigger depth exceeds allowed size of %d bytes", (32*1024)-1);
							MessageBox(hWnd, str, "Gage_Trigger_View_Transfer", MB_OK | MB_ICONINFORMATION);
							break;
						}
					}

					board.source = temp_board.source;
					board.slope = temp_board.slope;
					board.couple_e = temp_board.couple_a;
					board.range_e = temp_board.range_e;
					
					if((board.depth != temp_board.depth)&&(temp_board.depth>=8192)){
						for(jj=0;jj<boards_in_system;jj++){
							VirtualFree(
										a_buffer[jj],	// address of region of committed pages  
										0,	// size of region 
										MEM_RELEASE 	// type of free operation 
							);
							a_buffer[jj] = VirtualAlloc(
										NULL,	// address of region to reserve or commit  
										(DWORD)(80+temp_board.depth * ((board_info.sample_bits >= 12) + 1)),	// size of region 
										MEM_COMMIT,	// type of allocation 
										PAGE_READWRITE 	// type of access protection 
							);
							TVTBufferPtr[jj] = a_buffer[jj]; 
							a_buffer16[jj] = (int16  *)a_buffer[jj];
							VirtualFree(
										b_buffer[jj],	// address of region of committed pages  
										0,	// size of region 
										MEM_RELEASE 	// type of free operation 
							);
							b_buffer[jj] = VirtualAlloc(
										NULL,	// address of region to reserve or commit  
										(DWORD)(80+temp_board.depth * ((board_info.sample_bits >= 12) + 1)),	// size of region 
										MEM_COMMIT,	// type of allocation 
										PAGE_READWRITE 	// type of access protection 
							);					
							b_buffer16[jj] = (int16  *)b_buffer[jj];
						}
					}
					board.depth = temp_board.depth;
					board.level = temp_board.level;
					SetFocus (GetParent (hWnd));
					prepare_for_capture (boards_in_system, &board);
					break;

				case IDC_TRIGCLOSE:

					DestroyWindow (TriggerDlg);
					TriggerDlg = 0;
					break;

				case IDC_TRIGAC:

					temp_board.couple_e = GAGE_AC;
					break;

				case IDC_TRIGDC:

					temp_board.couple_e = GAGE_DC;
					break;

				case IDC_TRIGNEG:
					
					temp_board.slope = GAGE_NEGATIVE;
					break;

				case IDC_TRIGPOS:

					temp_board.slope = GAGE_POSITIVE;
					break;

				case IDC_TRIG5V:

					temp_board.range_e = GAGE_PM_5_V;
					break;

				case IDC_TRIG1V:

					temp_board.range_e = GAGE_PM_1_V;
					break;

				case IDC_TRIGCHANA:

					temp_board.source = GAGE_CHAN_A;
					break;

				case IDC_TRIGCHANB:

					temp_board.source = GAGE_CHAN_B;
					break;

				case IDC_TRIGSOFTWARE:

					temp_board.source = GAGE_SOFTWARE;
					break; 

				case IDC_TRIGEXTERNAL:

					temp_board.source = GAGE_EXTERNAL;
					break;
				case IDC_IMPED50:
					temp_board.imped_a = GAGE_50_OHM_INPUT;
					board.imped_a = GAGE_50_OHM_INPUT;
					break;
				case IDC_IMPED1M:
					temp_board.imped_a = GAGE_1_MOHM_INPUT;
					board.imped_a = GAGE_1_MOHM_INPUT;
					break;
			}

		default:
			break;

	}
	return (FALSE);
}


void check_stat()
{ static int cnt = 0;


	if(check_trigger())
	{
		cnt = 0;
	}
	else
	{
	  cnt++;
	  if (cnt == blink)
	  {	  reset_board();
		  cont_trigger();
	  }
	}

}


void Cap_Save_FILE(HWND hWnd)
{static int cnt=0;
    running = 0;
	if(check_trigger())
	{
		cnt = 0;
		save_data(capstream);
		Display(hWnd);
	}
	else
	{
	  cnt++;
	  if (cnt == blink)
	  {	  reset_board();
		  cont_trigger();
	  }
	}

}

/*-------------------------------------------------------------------------*/						
LRESULT CALLBACK CapDlgProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{ char temp[50];
  unsigned int  num;

	switch (msg) 
	{
		case WM_INITDIALOG:
		sprintf(temp,"tsplat.dat");
		SetDlgItemText(hWnd, IDC_CAP_FILE,temp);
		break;	
		case WM_COMMAND:
			switch (LOWORD(wParam)) 
			{
				case IDC_CAP_START:
					if (!save_file)
					{
					  char tempname[200];
					  GetDlgItemText(hWnd,IDC_CAP_FILE,temp,14);
					  
					  wsprintf(tempname, "%s\\%s", dpath, temp);

					  MessageBox(NULL, tempname, "debug", MB_OK);
					  capstream = fopen(tempname,"a");
					  
					  if (capstream != NULL)
					  {
						  cont_trigger();
						  fprintf(capstream,"start of FILE");
					      save_file = 1;
						  splat_isa_out = 1;
					  }
					  else
						MessageBox(NULL,"CANT CREATE FILE","ERROR",0);
					}
				break;
				case IDC_CAP_STOP:
					save_file = 0;
					reset_board();
					splat_isa_out = 0;
					fclose(capstream);
				break;
				case IDC_CANCEL:
					save_file = 0;
					fclose(capstream);
					DestroyWindow (CapDlg);
					CapDlg = 0;
				break;
			}
		break;
	}
	return (FALSE);
}

/*-------------------------------------------------------------------------*/						

LRESULT CALLBACK SetTimerDlgProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	char min[10];
	char sec[10];
	char nfiles[10];

	char str[60];

	switch (msg)
	{
	case WM_INITDIALOG:
		sprintf(str,"%i",minutes);
		SetDlgItemText(hWnd, IDT_MIN,str);
		sprintf(str,"%i",seconds);
		SetDlgItemText(hWnd, IDT_SEC,str);
		sprintf(str,"%i",nTar);
		SetDlgItemText(hWnd, IDT_NTAR,str);
		sprintf(str,"%s",dpath);
		SetDlgItemText(hWnd, IDT_DPATH,str);

		if (zipFiles == 1)
			SendDlgItemMessage (hWnd, IDT_ZIP, BM_SETCHECK, BST_CHECKED, 0);
		else
			SendDlgItemMessage (hWnd, IDT_ZIP, BM_SETCHECK, BST_UNCHECKED, 0);

		if (subtract == 1)
			SendDlgItemMessage (hWnd, IDC_SUB, BM_SETCHECK, BST_CHECKED, 0);
		else
			SendDlgItemMessage (hWnd, IDC_SUB, BM_SETCHECK, BST_UNCHECKED, 0);

		break;
	case WM_COMMAND:
		switch (LOWORD(wParam))
		{
			case IDT_OK:
				GetDlgItemText(hWnd,IDT_MIN,min,10);
				GetDlgItemText(hWnd,IDT_SEC,sec,10);
				minutes = atoi(min);
				seconds = atoi(sec);
				GetDlgItemText(hWnd, IDT_DPATH, dpath, 600);
				GetDlgItemText(hWnd, IDT_NTAR, nfiles, 10);
				//MessageBox(NULL, nfiles, "debug", MB_OK);
				nTar = atoi(nfiles);
				DestroyWindow (SetTimerDlg);
				SetTimerDlg = 0;
			break;
			case IDT_ZIP:
				if (zipFiles)
					zipFiles = 0;
				else 
					zipFiles = 1;
				break;
			case IDC_SUB:
				if (subtract == 1) 
					subtract = 0;
				else 
					subtract = 1;
				break;
			case IDT_CANCEL:
				if (!KillTimer(hWnd, MY_TIMER)) {
					if (nTimer) {
						wsprintf (str, "Timer not cancelled!");
						MessageBox(hWnd, str, "Error", MB_OK);
					}
					else
						nTimer = 0;
				}
				minutes = 10;
				seconds = 0;
				DestroyWindow (SetTimerDlg);
				SetTimerDlg = 0;
			break;
		}
	}
	return (FALSE);
}

VOID CALLBACK MyTimerProc2(HWND hWnd, UINT uTimerMsg, UINT uTimerID, DWORD DWTime)
{
	SendMessage(hWnd, WM_MOUSEMOVE, 0, 0L);
}

// My timer routine

VOID CALLBACK MyTimerProc(HWND hWnd, UINT uTimerMsg, UINT uTimerID, DWORD DWTime)
{
	char str[200];
	char datname[200];
	SYSTEMTIME	st;
	int i;
	wsprintf(datname, "%s\\dat", dpath);
	GetLocalTime(&st);
	wsprintf(directoryname, "%s\\%4d%2d%2d%2d%2d%2d%4d", dpath, st.wYear, st.wMonth,
		st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
	for (i = strlen(dpath); i < strlen(dpath) + 17; i++) {
		if (directoryname[i] == ' ')
			directoryname[i] = '0';
	}

	rename(datname,directoryname);

	_mkdir(datname);
	strcpy(filepath, ".\\dat\\");
	j = 0;
}

/*-------------------------------------------------------------------------*/						
LRESULT CALLBACK AboutDlgProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch (msg) 
	{
		case WM_COMMAND:
			switch (LOWORD(wParam)) 
			{
				case IDOK:
					DestroyWindow (AboutDlg);
					AboutDlg = 0;
				break;
			}
		break;
	}
	return (FALSE);
}



/*-------------------------------------------------------------------------*/						
LRESULT CALLBACK PmtDlgProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{ char temp[50];
  unsigned int  num;

	switch (msg) 
	{
		case WM_INITDIALOG:
		reg_read();
		sprintf(temp,"%#-5d",regs.pmt_trs);
		SetDlgItemText(hWnd, IDC_PTRS,temp);
		sprintf(temp,"%#-5d",regs.pmt_sat*25);
		SetDlgItemText(hWnd, IDC_PSAT,temp);
		sprintf(temp,"%#-5d",regs.pmt_wnd*25);
		SetDlgItemText(hWnd, IDC_PWND,temp);
		sprintf(temp,"%#-9f",(regs.errc/4096.0));
		SetDlgItemText(hWnd, IDC_ERRC,temp);
		sprintf(temp,"%#-5d",regs.chn_trs);
		SetDlgItemText(hWnd, IDC_CTRS,temp);
		sprintf(temp,"%#-5d",regs.chn_wnd*25);
		SetDlgItemText(hWnd, IDC_CWND,temp);
		sprintf(temp,"%#-5X",regs.star);
		SetDlgItemText(hWnd, IDC_STAR,temp);
		sprintf(temp,"%#-5d",regs.t1_wait*50);
		SetDlgItemText(hWnd, IDC_T1WAIT,temp);
		sprintf(temp,"%#-5d",regs.t2_wait*50);
		SetDlgItemText(hWnd, IDC_T2WAIT,temp);
		sprintf(temp,"%#-5d",regs.t3_wait*25);
		SetDlgItemText(hWnd, IDC_T3WAIT,temp);
		sprintf(temp,"%#-5d",regs.pmt_del*25);
		SetDlgItemText(hWnd, IDC_PMTDEL,temp);
		sprintf(temp,"%#-5f",regs.ltimeout*1.6);
		SetDlgItemText(hWnd, IDC_LTIMEOUT,temp);
		sprintf(temp,"%#-5d",regs.ptrvlt);
		SetDlgItemText(hWnd, IDC_PMT,temp);
		sprintf(temp,"%#-5d",regs.chn_enc);
		SetDlgItemText(hWnd, IDC_CHN,temp);
		if (cont_run == 1)
			SendDlgItemMessage (hWnd, IDC_C_CONT, BM_SETCHECK, BST_CHECKED, 0);
		else
			SendDlgItemMessage (hWnd, IDC_C_CONT, BM_SETCHECK, BST_UNCHECKED, 0);

	    if ((regs.star && 0x1) != 0)
		{
				SendDlgItemMessage (hWnd, IDC_START, BM_SETCHECK, BST_CHECKED, 0);
				SendDlgItemMessage (hWnd, IDC_STOP, BM_SETCHECK, BST_UNCHECKED, 0);
		}
		else
		{
				SendDlgItemMessage (hWnd, IDC_STOP, BM_SETCHECK, BST_CHECKED, 0);
				SendDlgItemMessage (hWnd, IDC_START, BM_SETCHECK,BST_UNCHECKED, 0);
		}


// set the spin range
		SendDlgItemMessage(hWnd,IDC_SPIN_PWND,UDM_SETRANGE32,1,0xff);
		SendDlgItemMessage(hWnd,IDC_SPIN_PSAT,UDM_SETRANGE32,1,0xff);
		SendDlgItemMessage(hWnd,IDC_SPIN_ERRC,UDM_SETRANGE32,1,0xffff);
		SendDlgItemMessage(hWnd,IDC_SPIN_CWND,UDM_SETRANGE32,1,0xff);
		SendDlgItemMessage(hWnd,IDC_SPIN_T1WAIT,UDM_SETRANGE32,1,0xffff);
		SendDlgItemMessage(hWnd,IDC_SPIN_T2WAIT,UDM_SETRANGE32,1,0xffff);
		SendDlgItemMessage(hWnd,IDC_SPIN_T3WAIT,UDM_SETRANGE32,0,0xffff);
		SendDlgItemMessage(hWnd,IDC_SPIN_PMTDEL,UDM_SETRANGE32,0,0xffff);
		SendDlgItemMessage(hWnd,IDC_SPIN_LTIMEOUT,UDM_SETRANGE32,0,0xffff);

// set the spin position
		SendDlgItemMessage(hWnd,IDC_SPIN_PWND,UDM_SETPOS,0,(LPARAM) MAKELONG((short) regs.pmt_wnd,0));
		SendDlgItemMessage(hWnd,IDC_SPIN_PSAT,UDM_SETPOS,0,(LPARAM) MAKELONG((short) regs.pmt_sat,0));
		SendDlgItemMessage(hWnd,IDC_SPIN_ERRC,UDM_SETPOS,0,(LPARAM) MAKELONG( regs.errc,0));
		SendDlgItemMessage(hWnd,IDC_SPIN_CWND,UDM_SETPOS,0,(LPARAM) MAKELONG((short) regs.chn_wnd,0));
		SendDlgItemMessage(hWnd,IDC_SPIN_T1WAIT,UDM_SETPOS,0,(LPARAM) MAKELONG(regs.t1_wait,0));
		SendDlgItemMessage(hWnd,IDC_SPIN_T2WAIT,UDM_SETPOS,0,(LPARAM) MAKELONG(regs.t2_wait,0));
		SendDlgItemMessage(hWnd,IDC_SPIN_T3WAIT,UDM_SETPOS,0,(LPARAM) MAKELONG(regs.t3_wait,0));
		SendDlgItemMessage(hWnd,IDC_SPIN_PMTDEL,UDM_SETPOS,0,(LPARAM) MAKELONG(regs.pmt_del,0));
		SendDlgItemMessage(hWnd,IDC_SPIN_LTIMEOUT,UDM_SETPOS,0,(LPARAM) MAKELONG(regs.ltimeout,0));

		return (TRUE);
		case WM_CLOSE:
				DestroyWindow (PmtDlg);
				PmtDlg = 0;
	 	break; 
		case WM_NOTIFY:
			switch (LOWORD(wParam)) 
			{

			case IDC_SPIN_PWND:
				regs.pmt_wnd = SendDlgItemMessage(hWnd,IDC_SPIN_PWND,UDM_GETPOS,0,0) & 0xff;
				sprintf(temp,"%#-5d",regs.pmt_wnd*25);
				SetDlgItemText(hWnd, IDC_PWND,temp);
				reg_bwrite();
			return(TRUE);
			case IDC_SPIN_PSAT:
				regs.pmt_sat = SendDlgItemMessage(hWnd,IDC_SPIN_PSAT,UDM_GETPOS,0,0) &0xff;
				sprintf(temp,"%#-5d",regs.pmt_sat*25);
				SetDlgItemText(hWnd, IDC_PSAT,temp);
				reg_bwrite();
			return(TRUE);
			case IDC_SPIN_ERRC:
				regs.errc = SendDlgItemMessage(hWnd,IDC_SPIN_ERRC,UDM_GETPOS,0,0) & 0xffff;
				sprintf(temp,"%#-5f",(regs.errc/4096.0));
				SetDlgItemText(hWnd, IDC_ERRC,temp);
				reg_bwrite();
			return(TRUE);
			case IDC_SPIN_CWND:
				regs.chn_wnd = SendDlgItemMessage(hWnd,IDC_SPIN_CWND,UDM_GETPOS,0,0) & 0xff;
				sprintf(temp,"%#-5d",regs.chn_wnd*25);
				SetDlgItemText(hWnd, IDC_CWND,temp);
				reg_bwrite();
			return(TRUE);
			case IDC_SPIN_T1WAIT:
				regs.t1_wait = SendDlgItemMessage(hWnd,IDC_SPIN_T1WAIT,UDM_GETPOS,0,0) &0xffff;
				sprintf(temp,"%#-5d",regs.t1_wait*50);
				SetDlgItemText(hWnd, IDC_T1WAIT,temp);
				reg_bwrite();
			return(TRUE);
			case IDC_SPIN_T2WAIT:
				regs.t2_wait = SendDlgItemMessage(hWnd,IDC_SPIN_T2WAIT,UDM_GETPOS,0,0) &0xffff;
				sprintf(temp,"%#-5d",regs.t2_wait*50);
				SetDlgItemText(hWnd, IDC_T2WAIT,temp);
				reg_bwrite();
			return(TRUE);

			case IDC_SPIN_T3WAIT:
				regs.t3_wait = SendDlgItemMessage(hWnd,IDC_SPIN_T3WAIT,UDM_GETPOS,0,0) &0xffff;
				sprintf(temp,"%#-5d",regs.t3_wait*25);
				SetDlgItemText(hWnd, IDC_T3WAIT,temp);
				reg_bwrite();
			return(TRUE);
			case IDC_SPIN_PMTDEL:
				regs.pmt_del = SendDlgItemMessage(hWnd,IDC_SPIN_PMTDEL,UDM_GETPOS,0,0) &0xffff;
				sprintf(temp,"%#-5d",regs.pmt_del*25);
				SetDlgItemText(hWnd, IDC_PMTDEL,temp);
				reg_bwrite();
			return(TRUE);
			case IDC_SPIN_LTIMEOUT:
				regs.ltimeout = SendDlgItemMessage(hWnd,IDC_SPIN_LTIMEOUT,UDM_GETPOS,0,0) &0xffff;
				sprintf(temp,"%#-5f",regs.ltimeout*1.6);
				SetDlgItemText(hWnd, IDC_LTIMEOUT,temp);
				reg_bwrite();
			return(TRUE);
			
			}
			return(TRUE);
			
		case WM_COMMAND:
			switch (LOWORD(wParam)) 
			{
				case IDC_PMTCLOSE:
					DestroyWindow (PmtDlg);
					PmtDlg = 0;
				break;
				case IDC_EVENT:
					single_trigger();
					reg_read();
					sprintf(temp,"%#-5d",regs.ptrvlt);
					SetDlgItemText(hWnd, IDC_PMT,temp);
					sprintf(temp,"%#-5d",regs.chn_enc);
					SetDlgItemText(hWnd, IDC_CHN,temp);
					GetDlgItemText(hWnd,IDC_STAR,temp,10);
					sscanf(temp,"%X",&num); regs.star = num;
					if (regs.star > 65536) regs.star = 65535;
				break;
				case IDC_START:
					reg_read();
					if ((cont_run) == 1)
						cont_trigger();
			    	else
						single_trigger();
					reg_read();
					running = 1;
			  		sprintf(temp,"%#-5X",regs.star);
					SetDlgItemText(hWnd, IDC_STAR,temp); 
				break;
				case IDC_STOP:
					reset_board();
					reg_read();
					running = 0;
					sprintf(temp,"%#-5X",regs.star);
					SetDlgItemText(hWnd, IDC_STAR,temp);
				break;
				case IDC_C_CONT:
					 if(cont_run == 1)
						cont_run = 0;
					 else
						cont_run = 1;


				break;
				case IDC_PMTAPPLY:
					GetDlgItemText(hWnd,IDC_PTRS,temp,10);
					regs.pmt_trs =  strtoul(temp,NULL,10);
					if (regs.pmt_trs > 65536) 
						regs.pmt_trs = 65535;
					GetDlgItemText(hWnd,IDC_PSAT,temp,10);
					regs.pmt_sat =  strtoul(temp,NULL,10)/25;
					if (regs.pmt_sat > 256) 
						regs.pmt_sat = 256;
					GetDlgItemText(hWnd,IDC_PWND,temp,10);
					regs.pmt_wnd =  strtoul(temp,NULL,10)/25;
					if (regs.pmt_wnd > 256) 
						regs.pmt_wnd = 256;
					GetDlgItemText(hWnd,IDC_ERRC,temp,10);
					regs.errc  = (int) ((atof(temp) + 0.00001)*4096.0);
					if (regs.errc > 65535) 
						regs.errc = 65535;
					GetDlgItemText(hWnd,IDC_CTRS,temp,10);
					regs.chn_trs =  strtoul(temp,NULL,10);
					if (regs.chn_trs > 65536) 
						regs.chn_trs = 65535;
					GetDlgItemText(hWnd,IDC_CWND,temp,10);
					regs.chn_wnd =  strtoul(temp,NULL,10)/25;
					if (regs.chn_wnd > 256) 
						regs.chn_wnd = 256;
					GetDlgItemText(hWnd,IDC_STAR,temp,10);
					sscanf(temp,"%X",&num); regs.star = num;
					if (regs.star > 65536) 
						regs.star = 65535;
					GetDlgItemText(hWnd,IDC_T1WAIT,temp,15);
					regs.t1_wait=  strtoul(temp,NULL,10)/50;
					if (regs.t1_wait > 65536) 
						regs.t1_wait = 65535;
					GetDlgItemText(hWnd,IDC_T2WAIT,temp,15);
					regs.t2_wait =  strtoul(temp,NULL,10)/50;
					if (regs.t2_wait > 65536) 
						regs.t2_wait = 65535;
					GetDlgItemText(hWnd,IDC_T3WAIT,temp,15);
					regs.t3_wait =  strtoul(temp,NULL,10)/25;
					if (regs.t3_wait > 65536) 
						regs.t3_wait = 65535;
					GetDlgItemText(hWnd,IDC_PMTDEL,temp,15);
					regs.pmt_del =  strtoul(temp,NULL,10)/25;
					if (regs.pmt_del > 65536) 
						regs.pmt_del = 65535;
					GetDlgItemText(hWnd,IDC_LTIMEOUT,temp,15);
					regs.ltimeout  =(int) (strtod(temp,NULL,30)/1.6);
					if (regs.ltimeout > 65536) 
						regs.ltimeout = 65535;
					reg_bwrite();
					reg_read();
					sprintf(temp,"%#-5d",regs.pmt_trs);
					SetDlgItemText(hWnd, IDC_PTRS,temp);
					sprintf(temp,"%#-5d",regs.pmt_sat*25);
					SetDlgItemText(hWnd, IDC_PSAT,temp);
					sprintf(temp,"%#-5d",regs.pmt_wnd*25);
					SetDlgItemText(hWnd, IDC_PWND,temp);
					sprintf(temp,"%#-5f",(regs.errc/4096.0));
					SetDlgItemText(hWnd, IDC_ERRC,temp);
					sprintf(temp,"%#-5d",regs.chn_trs);
					SetDlgItemText(hWnd, IDC_CTRS,temp);
					sprintf(temp,"%#-5d",regs.chn_wnd*25);
					SetDlgItemText(hWnd, IDC_CWND,temp);
					sprintf(temp,"%#-5X",regs.star);
					SetDlgItemText(hWnd, IDC_STAR,temp);
					sprintf(temp,"%#-5d",regs.t1_wait*50);
					SetDlgItemText(hWnd, IDC_T1WAIT,temp);
					sprintf(temp,"%#-5d",regs.t2_wait*50);
					SetDlgItemText(hWnd, IDC_T2WAIT,temp);
					sprintf(temp,"%#-5d",regs.t3_wait*25);
					SetDlgItemText(hWnd, IDC_T3WAIT,temp);
					sprintf(temp,"%#-5d",regs.pmt_del*25);
					SetDlgItemText(hWnd, IDC_PMTDEL,temp);
					sprintf(temp,"%#-5f",regs.ltimeout*1.6);
					SetDlgItemText(hWnd, IDC_LTIMEOUT,temp);
					sprintf(temp,"%#-5d",regs.ptrvlt);
					SetDlgItemText(hWnd, IDC_PMT,temp);
					sprintf(temp,"%#-5d",regs.chn_enc);
					SetDlgItemText(hWnd, IDC_CHN,temp);

					/* ? */

				if ((regs.star && 0x1) != 0)
				{		
					SendDlgItemMessage (hWnd, IDC_START, BM_SETCHECK, BST_CHECKED, 0);
					SendDlgItemMessage (hWnd, IDC_STOP, BM_SETCHECK, BST_UNCHECKED, 0);
				}
				else
				{		
					SendDlgItemMessage (hWnd, IDC_STOP, BM_SETCHECK, BST_CHECKED, 0);
					SendDlgItemMessage (hWnd, IDC_START, BM_SETCHECK,BST_UNCHECKED, 0);
				}
				if (cont_run == 1)
					SendDlgItemMessage (hWnd, IDC_C_CONT, BM_SETCHECK, BST_CHECKED, 0);
				else
					SendDlgItemMessage (hWnd, IDC_C_CONT, BM_SETCHECK, BST_UNCHECKED, 0);
					SendDlgItemMessage(hWnd,IDC_SPIN_PWND,UDM_SETPOS,0,(LPARAM) MAKELONG((short) regs.pmt_wnd,0));
					SendDlgItemMessage(hWnd,IDC_SPIN_PSAT,UDM_SETPOS,0,(LPARAM) MAKELONG((short) regs.pmt_sat,0));
					SendDlgItemMessage(hWnd,IDC_SPIN_ERRC,UDM_SETPOS,0,(LPARAM) MAKELONG( regs.errc,0));
					SendDlgItemMessage(hWnd,IDC_SPIN_CWND,UDM_SETPOS,0,(LPARAM) MAKELONG((short) regs.chn_wnd,0));
					SendDlgItemMessage(hWnd,IDC_SPIN_T1WAIT,UDM_SETPOS,0,(LPARAM) MAKELONG(regs.t1_wait,0));
					SendDlgItemMessage(hWnd,IDC_SPIN_T2WAIT,UDM_SETPOS,0,(LPARAM) MAKELONG(regs.t2_wait,0));
					SendDlgItemMessage(hWnd,IDC_SPIN_T3WAIT,UDM_SETPOS,0,(LPARAM) MAKELONG(regs.t3_wait,0));
					SendDlgItemMessage(hWnd,IDC_SPIN_PMTDEL,UDM_SETPOS,0,(LPARAM) MAKELONG(regs.pmt_del,0));
					SendDlgItemMessage(hWnd,IDC_SPIN_LTIMEOUT,UDM_SETPOS,0,(LPARAM) MAKELONG(regs.ltimeout,0));

				break;
			}

  
		break;
	}
	return (FALSE);
}


/*-------------------------------------------------------------------------*/			
			
void	CalcGr(double TimeBase, int32 ngrp,float *incell)
{ 
	double tbs;
	double srs;     
    
	gage_get_driver_info(&board_info); 
	tbs = TimeBase * 10;
	srs = (double)(ngrp) / (double)( board_info.rate * pow ( 1000, board_info.multiplier - 1));
	*incell = (float)(tbs/srs);
}    

/*-------------------------------------------------------------------------*/

void	CalcScale(int32 offset, int32 size_y, double vc, int32 range, double s_o, double s_r, double * coef, double * off) 
{
	double vcs;
    
	vcs = vc * 4;
	*coef = (double)(size_y * ranges[range].ir_calc  /(vcs * s_r));
	*off = (double)offset + (double)(size_y * ( 1 -  (ranges[range].ir_calc *  s_o/(s_r * vcs))));
}    

/*-----------user selects a command item from a menu--------------------------------------------------------------*/

void	Cls_OnCommand (HWND hWnd, int32 id, HWND hWndCtl, UINT codeNotify)

{

	int i;
	regs.star = INP(bio+STAR);
	if ((regs.star & 0x0001) != 0)
	{
		CheckMenuItem (GetMenu(hWnd), IDM_T_START, MF_CHECKED);	
		CheckMenuItem (GetMenu(hWnd), IDM_T_STP,  MF_UNCHECKED);
	}
	else
	{
		CheckMenuItem (GetMenu(hWnd), IDM_T_START, MF_UNCHECKED);	
		CheckMenuItem (GetMenu(hWnd), IDM_T_STP,  MF_CHECKED);
	}

	switch (id) {

/**NO1******************************************/

		case IDM_C_ACQUIRE:
			k=0;
			j=0;
//			prepare_for_capture(boards_in_system, &board);
			AcquireStart (); 
			ContinuousMode = TRUE;
			AcquireCheck(hWnd);
			break;
/********************************************/
	    case IDM_C_CONTINUOUS:
			
			if (subtract == 1) {
				// get the timestamp
				GetLocalTime(&initTime);
			}


			nTimer = SetTimer(hWnd, MY_TIMER, 
				(UINT) ((minutes * 60 + seconds) * 1000), (TIMERPROC) MyTimerProc);
			if (!nTimer) {
				wsprintf (str, "Error: timer not set");					MessageBox(hWnd, str, "Error", MB_OK);
			}

			k=1;
			j=0;
			prepare_for_capture(boards_in_system, &board);
			AcquireStart (); 
			ContinuousMode = TRUE;
			
			nTimer2 = SetTimer(hWnd, MY_TIMER2, 1, (TIMERPROC) MyTimerProc2);
			if (!nTimer2) {
				wsprintf (str, "Error: timer not set");
				MessageBox(hWnd, str, "Error", MB_OK);
			}

			//char dpath[600] = "C:\\";
			//int zipFiles = 0;
			//int nTar = 0;

			/*MessageBox(NULL, dpath, "debug", MB_OK);
			wsprintf(str, "zipFiles %i", zipFiles);
			MessageBox(NULL, str, "debug", MB_OK);
			wsprintf(str, "nTar %i", nTar);
			MessageBox(NULL, str, "debug", MB_OK);
			_exit(0);*/

			break;
/********************************************/
		
		
		case ID_FILE_ZIP_AS:
		    
			system( "zipfile.bat" );

			break;
/********************************************/
					
		
		case ID_FILE_UNZIP_AS:
		    
			system( "unzipfile.bat" );

			break;

/********************************************/		
		
		case IDM_C_ABORT:

//	MessageBox(NULL, "save data in CONTINUOUS ", "My Message", MB_OK);

			if (!KillTimer(hWnd, MY_TIMER)) {
				if (nTimer) {
					wsprintf (str, "Timer not cancelled!");
					MessageBox(hWnd, str, "Error", MB_OK);
				}
				else
					nTimer = 0;
			}
			KillTimer(hWnd, MY_TIMER2);
			KillTimer(hWnd, MY_TIMER);

			if (SetTimerDlg) {
				DestroyWindow (SetTimerDlg);
				SetTimerDlg = 0;
			}

			Abort (hWnd);
			{
				SYSTEMTIME	st;
				int i;
				char datname[200];
				wsprintf(datname, "%s\\dat", dpath);
				GetLocalTime(&st);
				wsprintf(directoryname, "%s\\%4d%2d%2d%2d%2d%2d%4d", dpath, st.wYear, st.wMonth,
					st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
				for (i = strlen(dpath); i < strlen(dpath) + 17; i++) {
					if (directoryname[i] == ' ')
						directoryname[i] = '0';
				}
				rename(datname,directoryname);
			}
			break;

/********************************************/
	    case IDM_C_ABOUT:
			{
			FARPROC lpfnDIALOGAMsgProc;
			int32 nRc = 0;
			lpfnDIALOGAMsgProc = MakeProcInstance((FARPROC)DIALOGAMsgProc, hInst);
			nRc = DialogBox(hInst, MAKEINTRESOURCE(100), hWnd, (DLGPROC)lpfnDIALOGAMsgProc);
			FreeProcInstance(lpfnDIALOGAMsgProc);
			}
			break;
/************************************************************/
	    case IDM_C_EXIT:
		    		 
			SendMessage (hWnd, WM_CLOSE, 0, 0L);
			break;
/************************************************************/
		case IDM_C_BUILD:			// Build up SIGNAL for Display

			buildup_signal = 1;
			break;
/************************************************************/
		case IDM_C_CLEAR:			// Clear Signal after build

			buildup_signal = 0;
			Display (hWnd);
			break;
/************************************************************/
		case IDM_C_HOME:

			view_start = 0L;
			Display (hWnd);
			break;
/************************************************************/
		case IDM_C_END:
			{
			long	temp = (((long)(scrn_x) * (long)(zoom_x2)) / (long)(zoom_x));
			view_start = adjusted_depth - temp + ptm_start;
			}
			Display (hWnd);
			break;
/************************************************************/
		case IDM_C_ALTLEFTKEY:

			view_start -= 1L;
			Display (hWnd);
			break;
/************************************************************/
		case IDM_C_CTLLEFTKEY:

			view_start -= 25L * zoom_x2;
			Display (hWnd);
			break;
/************************************************************/
		case IDM_C_ALTRIGHTKEY:

			view_start += 1L;
			Display (hWnd);
			break;
/************************************************************/
		case IDM_C_CTLRIGHTKEY:

			view_start += 25L * zoom_x2;
			Display (hWnd);

			break;
/************************************************************/
		case IDM_TB3_TRANSFER:

			if (transfer_type != USE_TRANSFER_BUFFER_3) {
				transfer_type = USE_TRANSFER_BUFFER_3;
				CheckMenuItem (GetMenu(hWnd), IDM_MEM_READ_TRANSFER, MF_UNCHECKED);	
				CheckMenuItem (GetMenu(hWnd), IDM_RT_TRANSFER,	MF_UNCHECKED);
				CheckMenuItem (GetMenu(hWnd), IDM_TV_TRANSFER,	MF_UNCHECKED);
				CheckMenuItem (GetMenu(hWnd), IDM_TV2_TRANSFER,	MF_UNCHECKED);
				CheckMenuItem (GetMenu(hWnd), IDM_TV3_TRANSFER,	MF_UNCHECKED);
				CheckMenuItem (GetMenu(hWnd), IDM_TB_TRANSFER,	MF_UNCHECKED);
				CheckMenuItem (GetMenu(hWnd), IDM_TB2_TRANSFER,	MF_UNCHECKED);
				CheckMenuItem (GetMenu(hWnd), IDM_TB3_TRANSFER,	MF_CHECKED);
			}
			break;
/************************************************************/
        case IDM_RT_TRANSFER:

			if (transfer_type != USE_REAL_TIME) {
			}
			break;
/************************************************************/
        case IDM_SPLAT_ISA_OUT:

			if (!splat_isa_out) 
			{
				splat_isa_out = 1;
			    CheckMenuItem (GetMenu(hWnd), IDM_SPLAT_ISA_OUT, MF_CHECKED);
			}
			else 
			{
				splat_isa_out = 0;
			    CheckMenuItem (GetMenu(hWnd), IDM_SPLAT_ISA_OUT, MF_UNCHECKED);
			}
			break;
/************************************************************/
        case IDM_XFER_TIME:

			if (!xfer_time) {
				xfer_time = 1;
			    CheckMenuItem (GetMenu(hWnd), IDM_XFER_TIME, MF_CHECKED);
			}
			else {
				xfer_time = 0;
			    CheckMenuItem (GetMenu(hWnd), IDM_XFER_TIME, MF_UNCHECKED);
			}
			break;
/************************************************************/

		case IDM_SETTIMER:
			if (!SetTimerDlg) {
				SetTimerDlg = CreateDialog (hInst, (LPCSTR)MAKEINTRESOURCE(IDD_TIMER), hWnd, (DLGPROC)SetTimerDlgProc);
				ShowWindow (SetTimerDlg, SW_SHOW);
			}
			break;

		case IDM_SRATE:

			if (!SRateDlg) { // check if instance exists already first before create
				SRateDlg = CreateDialog (hInst, (LPCSTR)MAKEINTRESOURCE(IDD_CAPTURE), hWnd, (DLGPROC)SRateDlgProc);
				ShowWindow (SRateDlg, SW_SHOW);
			}
			break;
/************************************************************/
		case IDM_IRANGE:

			if (!IRangeDlg) { // check if instance exists already first before create
				IRangeDlg = CreateDialog (hInst, (LPCSTR)MAKEINTRESOURCE(IDD_INPUT), hWnd, (DLGPROC)IRangeDlgProc);
				ShowWindow (IRangeDlg, SW_SHOW);
			}
			break;
/************************************************************/
		case IDM_TRIGGER:
			
			if (!TriggerDlg) {
				TriggerDlg = CreateDialog (hInst, (LPCSTR)MAKEINTRESOURCE(IDD_TRIGGER), hWnd, (DLGPROC)TriggerDlgProc);
				ShowWindow (TriggerDlg, SW_SHOW);
			}
			break;

/************************************************************/
		case IDM_ABOUT:
			
			if (!AboutDlg) {
				AboutDlg = CreateDialog (hInst, (LPCSTR)MAKEINTRESOURCE(IDD_ABOUT), hWnd, (DLGPROC)AboutDlgProc);
				ShowWindow (AboutDlg, SW_SHOW);
			}
			break;
/************************************************************/
		case IDM_T_CAP:
			
			if (!CapDlg) {
				CapDlg = CreateDialog (hInst, (LPCSTR)MAKEINTRESOURCE(IDD_DATA_CAP), hWnd, (DLGPROC)CapDlgProc);
				ShowWindow (CapDlg, SW_SHOW);
			}
			break;



/************************************************************/
		case IDM_T_PMT:
			
			if (!PmtDlg) {
				PmtDlg = CreateDialog (hInst, (LPCSTR)MAKEINTRESOURCE(IDD_PMT), hWnd, (DLGPROC)PmtDlgProc);
				ShowWindow (PmtDlg,SW_SHOW);
			}
			break;

/************************************************************/
		case IDM_T_START:
				CheckMenuItem (GetMenu(hWnd), IDM_T_START, MF_CHECKED);	
				CheckMenuItem (GetMenu(hWnd), IDM_T_STP,  MF_UNCHECKED);
				running = 1;
					PmtDlg = CreateDialog (hInst, (LPCSTR)MAKEINTRESOURCE(IDD_PMT), hWnd, (DLGPROC)PmtDlgProc);
				ShowWindow (PmtDlg,SW_SHOW);
				cont_trigger();
			break;
/************************************************************/
/************************************************************/
		case IDM_T_STP:
				CheckMenuItem (GetMenu(hWnd), IDM_T_START, MF_UNCHECKED);	
			CheckMenuItem (GetMenu(hWnd), IDM_T_STP,  MF_CHECKED);
			running = 0;
				reset_board();
			break;
/************************************************************/



		default:
			FORWARD_WM_COMMAND(hWnd, id, hWndCtl, codeNotify, DefWindowProc);
	}
}

/*-------------------------------------------------------------------------*/

void Cls_OnChar(HWND hWnd, TCHAR ch, int32 cRepeat) 
{
 	switch (ch) {
		case '-':
			if (zoom_x > 1)  {
					zoom_x >>= 1;
			}else if (board.depth > ((uInt32)(scrn_x) * zoom_x2))  {
					zoom_x2 <<= 1;
			}
			break;

		case '+':
			if (zoom_x2 > 1)  {
					zoom_x2 >>= 1;
			}else{
				if (zoom_x < 64)
					zoom_x <<= 1;
			}
			break;

		default:
			FORWARD_WM_CHAR(hWnd, ch, cRepeat, DefWindowProc);
	}
	Display (hWnd); // this call will allow to zoom on an existing display
}
			
/*------when the system or another application makes a request to paint 
a portion of an application's window---------------------------------------------------------*/

void	Cls_OnPaint(HWND hWnd) 
{
	HDC			hDC;                /* handle for the display device       */
	PAINTSTRUCT ps;                 /* holds PAINT information             */
	int32		i, j, points, size_y, offset_y; /* Vars used by paint code.*/
	RECT		rect, rect_mr;                  /* Vars used by paint code.*/
	int32		centre_line;
	int32		times;
/*	double		TimeBase = 0.000005; */
	double		TimeBase = 0.0005; 
	float		incell;      
	double		VertScale = 0.2;
	uInt16		trace_x, channel = GAGE_CHAN_A;
	uInt32		start;
	uInt32		count;
	int16		x, min, max, val, opmode ;
    uInt8		t=0;
	uInt8		tmp[20];
	uInt8		tmp2[64]; // for measurement info
	uInt32		Depth;
	uInt16		Local_zoom_x;

	// make local copies of the a_buffer, a_buffer16, b_buffer, and b_buffer16
	// to similar ptrs which will be used in this paint routine only
	
	uInt8	far *dsp_a_buffer[GAGE_B_L_MAX_CARDS];

	for (j = 0; j < boards_in_system; j++)
	{

		if ((transfer_type == USE_TRIGGER_VIEW_3) || (transfer_type == USE_TRANSFER_BUFFER_3))
		{
			dsp_a_buffer[j]=(TVT3_offset[j]) + a_buffer[j];
		}
	}

	opmode = board.opmode & 0x03;
	memset(&ps, 0x00, sizeof(PAINTSTRUCT));
	hDC = BeginPaint(hWnd, &ps);

	SetBkMode(hDC, TRANSPARENT);
   	GetClientRect (hWnd, &rect);

	/* if buildup_signal then do not clear only bottom 20 chars */
	if (!buildup_signal)
		FillRect(hDC, &rect, hWhiteBrush);
	else {
		rect_mr.right = 160; //20 chars
		rect_mr.left = 1;
		rect_mr.top = rect.bottom - 16;
		rect_mr.bottom = rect.bottom;
		FillRect(hDC, &rect_mr, hWhiteBrush);
	}
	SelectObject (hDC, hDotPen);
	
	if(TimeBase == 0 ) 
/* my setting TimeBase = 0.000005 ******/
		TimeBase = 0.000005;

	CalcGr(TimeBase, rect.right - rect.left,&incell );
	
	for(i = 0; i <= 10; i++) {
		MoveToEx (hDC, i * (rect.right - rect.left) / 10, rect.top, NULL); 	
		LineTo (hDC, i * (rect.right - rect.left) / 10, rect.bottom ); 
	}

	times = max(boards_in_system, 1);	
	size_y = (rect.bottom - rect.top) / (times * 2 * opmode );	 	
	
	for(i = 0; i <= (times * opmode << 3); i++) {
		MoveToEx (hDC, rect.left, i * size_y / 4, NULL); 	
		LineTo (hDC, rect.right,  i * size_y / 4);
	}                     
	points = rect.right - rect.left;
	scrn_x = (int16)rect.right;
	
	sprintf(tmp,"%08Ld",acgtimes++);
	TextOut(hDC,0,rect.bottom-16,tmp,8);
	if(splat_isa_out)
	{
		sprintf(tmp2,"splat TRVl %dns  Channeltron %d",regs.ptrvlt*50,regs.chn_enc);
		TextOut(hDC,0,rect.bottom-30,tmp2,strlen(tmp2));
	}

	if (xfer_time) 
	{ // check if transfer time set
		if (transfer_type == USE_TRIGGER_VIEW) 
		{
			sprintf(tmp2,"TVT   : %04LdKSamples in %04Ld msecs",board.depth/1024, time3);
		} 
		else if(transfer_type == USE_TRIGGER_VIEW_2) 
		{
			sprintf(tmp2,"TVT2  : %04LdKSamples in %04Ld msecs",board.depth/1024, time3);
		}
		else if(transfer_type == USE_TRIGGER_VIEW_3) 
		{
			sprintf(tmp2,"TVT3  : %04LdKSamples in %04Ld msecs",board.depth/1024, time3);
		}
		else if(transfer_type == USE_MEM_READ) 
		{
			sprintf(tmp2,"Mem Rd: %04LdKSamples in %04Ld msecs",board.depth/1024, time3);
		}
		else if (transfer_type == USE_TRANSFER_BUFFER) 
		{
			sprintf(tmp2,"TB    : %04LdKSamples in %04Ld msecs",board.depth/1024, time3);
		} 
		else if(transfer_type == USE_TRANSFER_BUFFER_2) 
		{
			sprintf(tmp2,"TB2  : %04LdKSamples in %04Ld msecs",board.depth/1024, time3);
		}
		else if(transfer_type == USE_TRANSFER_BUFFER_3) 
		{
			sprintf(tmp2,"TB3   : %04LdKSamples in %04Ld msecs",board.depth/1024, time3);
		}
		TextOut(hDC,70,rect.bottom-16,tmp2,strlen(tmp2));
	}
	for (j = 0; j < boards_in_system; j++) 
	{

		Depth = board.depth;
		start = 0;
		Local_zoom_x = (int) ((float)Depth/scrn_x + 1);

		if (opmode == GAGE_SINGLE_CHAN) 
		{
			SelectObject (hDC, hBlackPen);
			offset_y = (size_y * j * 2) + (size_y * sample_offset);
			centre_line = size_y * j * 2;	
#ifdef TRIGGER_TRACE
			sprintf(hTriggPenStr,"%08Lx",trigger_trace);
			TextOut(hDC,0,rect.bottom-16,hTriggPenStr,sizeof(hTriggPenStr)-2);
#endif

			view_start = 0;
			count = 0;

			if (Local_zoom_x > 1)  
			{
				trace_x = 0;
				min = max = dsp_a_buffer[j][count];
				while ((trace_x < (scrn_x - 1)) && (count < (Depth - 1))) 
				{
					for (x = 0 ; x < Local_zoom_x ; x++)  {	
						if (count >= (Depth - 1))
							break;
						if ((val = dsp_a_buffer[j][++count]) > max)  
						{
							max = val;
						}
						else if (val < min)
							min = val;
					}
					MoveToEx (hDC, trace_x, offset_y + (int16)(((float)(min) / sample_resolution) * (float)(size_y)), NULL);
/********************* Line To***********/
					LineTo (hDC, trace_x, offset_y + (int16)((((float)(max) / sample_resolution) * (float)(size_y))));
					SetPixel (hDC, trace_x, offset_y + (int16)((((float)(max) / sample_resolution) * (float)(size_y))), 0x0);
					trace_x++;
					min = max = dsp_a_buffer[j][count];
				}
			}
			else
			{
				MoveToEx (hDC, trace_x = 0, offset_y + (int16)(((float)(dsp_a_buffer[j][count++]) / sample_resolution) * (float)(size_y)), NULL);
				while (trace_x < (scrn_x - 1))  
				{
/********************* Line To***********/
					LineTo (hDC, trace_x++, offset_y + (int16)((((float)(dsp_a_buffer[j][count]) / sample_resolution) * (float)(size_y))));
					if (count++ >= (Depth - 1))
						break; 
				} 
			}
			
			SelectObject (hDC, hZeroPen);
			MoveToEx (hDC, 0, centre_line + size_y, NULL);
/********************* Line To***********/
			LineTo (hDC, points, centre_line + size_y);
			if (!CheckMessageQueue ())
				break;
		}
		else 
		{
			/*  Do Channel A, dual channel mode.  */
   			SelectObject (hDC, hBlackPen);
			size_y = (rect.bottom - rect.top) / (2 * boards_in_system * 2);
			offset_y = (size_y * j * 4) + (size_y * sample_offset);
			centre_line = size_y * j * 4;

			count = start;
#ifdef TRIGGER_TRACE		
			sprintf(hTriggPenStr,"%08Lx",trigger_trace);
			TextOut(hDC,0,rect.bottom-16,hTriggPenStr,sizeof(hTriggPenStr)-2);
#endif
			
			if (Local_zoom_x > 1)  
			{
				trace_x = 0;
				min = max = dsp_a_buffer[j][count];
				while ((trace_x < (scrn_x - 1)) && (count < (Depth - 1)))  
				{
					for (x = 0 ; x < Local_zoom_x ; x++)  
					{
						if (count >= (Depth - 1))
							break;

						if ((val = dsp_a_buffer[j][count++]) > max)  
						{
							max = val;
						}
						else if (val < min)
							min = val;
					}

					MoveToEx (hDC, trace_x, offset_y + (int16)(((float)(min) / sample_resolution) * (float)(size_y)), NULL);

/********************* Line To***********/
					LineTo (hDC, trace_x, offset_y + (int16)((((float)(max) / sample_resolution) * (float)(size_y))));
					
					SetPixel (hDC, trace_x, offset_y + (int16)((((float)(max) / sample_resolution) * (float)(size_y))), 0x0);
					
					trace_x++;
					min = max = dsp_a_buffer[j][count];
				}
			}
			else
			{
				MoveToEx (hDC, trace_x = 0, offset_y + (int16)(((float)(dsp_a_buffer[j][count++]) / sample_resolution) * (float)(size_y)), NULL);
				while (trace_x < (scrn_x - 1))  
				{
					LineTo (hDC, trace_x++, offset_y + (int16)((((float)(dsp_a_buffer[j][count]) / sample_resolution) * (float)(size_y))));

#ifdef TRIGGER_TRACE					
					if(trigger_trace<count)
			           SelectObject (hDC, hTriggPen);
#endif					
					if (count++ >= (Depth - 1))
						break;
				}
			}
			SelectObject (hDC, hZeroPen);
			MoveToEx (hDC, 0, centre_line + size_y, NULL);
		}
   	}
	EndPaint(hWnd, &ps);
/*	fclose( stream ); */
}
	 		
/*-------------------------------------------------------------------------*/
void	Cls_OnClose (HWND hWnd)
{
	int16 tmp;

	// Add abort here in case card not aborted yet.
	gage_abort_capture (GAGE_SOFTWARE);
	if (board_info.board_type & GAGE_ASSUME_CS2125)
		tmp = gage_power_control (GAGE_POWER_OFF);
	KillTimer(hWnd, wTimerID);
	DeleteObject(hZeroPen);
	DeleteObject(hDotPen);
	DestroyWindow (SRateDlg);
    DestroyWindow (IRangeDlg);
	DestroyWindow (TriggerDlg);
	DestroyWindow (AboutDlg);
	DestroyWindow (PmtDlg);
	DestroyWindow (CapDlg);
	DestroyWindow (hWnd);
	DestroyWindow (SetTimerDlg);
}

void	Cls_OnQuit (HWND hWnd)
{
	int16 tmp;

	if (board_info.board_type & GAGE_ASSUME_CS2125)
		tmp = gage_power_control (GAGE_POWER_OFF);
	KillTimer(hWnd, wTimerID);
	DeleteObject(hZeroPen);
	DeleteObject(hDotPen);
	DestroyWindow (SRateDlg);
    DestroyWindow (IRangeDlg);
	DestroyWindow (TriggerDlg);
	DestroyWindow (hWnd);
	DestroyWindow (SetTimerDlg);
}

/*-------------------------------------------------------------------------*/

void	Cls_OnDestroy(HWND hWnd) 
{
	PostQuitMessage(0);
}

/*-------------------------------------------------------------------------*/

BOOL	Cls_OnCreate(HWND hWnd, LPCREATESTRUCT lpCreateStruct) 
{
	wTimerID = SetTimer (hWnd, 1, wTimerInterval, (TIMERPROC) NULL);
	hBlackPen = GetStockObject (BLACK_PEN);

#ifdef TRIGGER_TRACE	
	hTriggPen = CreatePen (PS_SOLID, 3, 0x0000ff00);
#else
	hTriggPen = hBlackPen;
#endif

	hZeroPen = CreatePen (PS_DASH, 1, 0x000000ff);
	hDotPen = CreatePen (PS_DOT, 1, 0x0000ff00);           
	hWhiteBrush = GetStockObject (WHITE_BRUSH);
	hDisplayWnd = hWnd;
	return (TRUE);
}

/*-------------------------------------------------------------------------*/

void	Cls_OnTimer(HWND hWnd, UINT id) 
{
	number_of_timer_events++;
}

/*-------------------------------------------------------------------------*/

void	Cls_OnMove(HWND hWnd, int32 x, int32 y) 
{
	Display (hWnd);
}


/************************************************************************/
/*                                                                      */
/* Main Window Procedure                                                */
/*                                                                      */
/************************************************************************/

LRESULT CALLBACK WndProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
 	
//	regs.star = INP(bio+STAR);
	if ((regs.star & 0x0001) != 0)
	{
		CheckMenuItem (GetMenu(hWnd), IDM_T_START, MF_CHECKED);	
		CheckMenuItem (GetMenu(hWnd), IDM_T_STP,  MF_UNCHECKED);
	}
	else
	{
		CheckMenuItem (GetMenu(hWnd), IDM_T_START, MF_UNCHECKED);	
		CheckMenuItem (GetMenu(hWnd), IDM_T_STP,  MF_CHECKED);
	}	
	
	switch (Message)
   	{

		HANDLE_MSG(hWnd, WM_COMMAND, Cls_OnCommand);
/* The WM_COMMAND message is sent when the user selects 
a command item from a menu, when a control sends a 
notification message to its parent window, or when an 
accelerator keystroke is translated. */


		HANDLE_MSG(hWnd, WM_PAINT, Cls_OnPaint);  
/* An application sends the WM_PAINT message when the 
system or another application makes a request to paint 
a portion of an application's window. */
		
		HANDLE_MSG(hWnd, WM_DESTROY, Cls_OnDestroy);
/*The WM_DESTROY message is sent when a window is being 
destroyed. It is sent to the window procedure of the 
window being destroyed after the window is removed from 
the screen. */


		HANDLE_MSG(hWnd, WM_TIMER, Cls_OnTimer);
/*The WM_TIMER message is posted to the installing 
thread's message queue when a timer expires. You can 
process the message by providing a WM_TIMER case in the 
window procedure. Otherwise, the default window procedure 
will call the TimerProc callback function specified in 
the call to the SetTimer function used to install the 
timer. */

		HANDLE_MSG(hWnd, WM_MOVE, Cls_OnMove);
/*The WM_MOVE message is sent after a window has been 
moved. */

		HANDLE_MSG(hWnd, WM_CREATE, Cls_OnCreate);
/*The WM_CREATE message is sent when an application 
requests that a window be created by calling the CreateWindowEx 
or CreateWindow function. The window procedure of the 
new window receives this message after the window is 
created, but before the window becomes visible. 
The message is sent before the CreateWindowEx or 
CreateWindow function returns. */

		HANDLE_MSG(hWnd, WM_CHAR, Cls_OnChar);
/*The WM_CHAR message is posted to the window with the 
keyboard focus when a WM_KEYDOWN message is translated 
by the TranslateMessage function. WM_CHAR contains the 
character code of the key that was pressed. */

/****************************************************/

		// Add new handler for WM_QUIT in case of system shutting down before app is closed
		// Cls_OnQuit is same as Cls_OnClose but also call gage_bufaccess_destroy()
		case WM_QUIT:
			return HANDLE_WM_QUIT(hWnd, wParam, lParam, Cls_OnQuit);

		// Add new handler for WM_ENDSESSION in case of system shutting down before app
		//is closed. (Happens in WinNT) This avoid blue screen when closing WinNT before app.
		case WM_CLOSE:
		case WM_ENDSESSION:
			return HANDLE_WM_CLOSE(hWnd, wParam, lParam, Cls_OnClose);

	default:
			return(DefWindowProc(hWnd, Message, wParam, lParam));
  	}
	return 0L;
}     /* End of WndProc                                         	*/

/************************************************************************/
/*                                                                      */
/* Dialog Window Procedure                                              */
/*                                                                      */
/************************************************************************/


LRESULT CALLBACK DIALOGAMsgProc(HWND hWndDlg, UINT Message, WPARAM wParam, LPARAM lParam)
{

	lParam = lParam;
	switch(Message)
   	{
    	case WM_INITDIALOG:
	 	cwCenter(hWndDlg, 0);
	 	/* initialize working variables                               */
	 	break; /* End of WM_INITDIALOG                                */

		case WM_CLOSE:
	 	/* Closing the Dialog behaves the same as Cancel              */
	 	PostMessage(hWndDlg, WM_COMMAND, IDCANCEL, 0L);
	 	break; /* End of WM_CLOSE                                     */

		case WM_COMMAND:
			switch(wParam)
	   		{
	    		case IDOK:
		 			EndDialog(hWndDlg, TRUE);
		 			break;
		 		
	    		case IDCANCEL:
		 		/* Ignore data values entered into the controls        */
		 		/* and dismiss the dialog window returning FALSE       */
		 			EndDialog(hWndDlg, FALSE);
		 			break;
	   		}
	 		break;    /* End of WM_COMMAND                             */

	  	default:
			return FALSE;
   	}
 	return TRUE;
} /* End of DIALOGAMsgProc                                      */


/************************************************************************/
/*                                                                      */
/* nCwRegisterClasses Function                                          */
/*                                                                      */
/* The following function registers all the classes of all the windows  */
/* associated with this application. The function returns an error code */
/* if unsuccessful, otherwise it returns 0.                             */
/*                                                                      */
/************************************************************************/

int		nCwRegisterClasses(void)
{
 	WNDCLASS   wndclass;    /* struct to define a window class             */
 	memset(&wndclass, 0x00, sizeof(WNDCLASS));
     /* load WNDCLASS with window's characteristics                         */
 	wndclass.style = CS_HREDRAW | CS_VREDRAW | CS_BYTEALIGNWINDOW;
 	wndclass.lpfnWndProc = (WNDPROC)WndProc;
 	/* Extra storage for Class and Window objects                          */
 	wndclass.cbClsExtra = 0;
 	wndclass.cbWndExtra = 0;
 	wndclass.hInstance = hInst;
 	wndclass.hIcon = LoadIcon(hInst, "GSDLLDEM");
 	wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
 	/* Create brush for erasing background                                 */
 	wndclass.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
    wndclass.lpszMenuName = szAppName;   /* Menu Name is App Name */
 	wndclass.lpszClassName = szAppName; /* Class Name is App Name */
 	if(!RegisterClass(&wndclass))
   		return -1;
    return(0);
} /* End of nCwRegisterClasses                                          */

/************************************************************************/
/*  cwCenter Function                                                   */
/*                                                                      */
/*  centers a window based on the client area of its parent             */
/*                                                                      */
/************************************************************************/

void	cwCenter(HWND hWnd, int top)
{
 	POINT      pt;
 	RECT       swp;
 	RECT       rParent;
 	int32      iwidth;
 	int32      iheight;

 	/* get the rectangles for the parent and the child                     */
 	GetWindowRect(hWnd, &swp);
 	GetClientRect(hWndMain, &rParent);

 	/* calculate the height and width for MoveWindow                       */
 	iwidth = swp.right - swp.left;
 	iheight = swp.bottom - swp.top;

 	/* find the center point and convert to screen coordinates             */
 	pt.x = (rParent.right - rParent.left) / 2;
 	pt.y = (rParent.bottom - rParent.top) / 2;
 	ClientToScreen(hWndMain, &pt);

 	/* calculate the new x, y starting point                               */
 	pt.x = pt.x - (iwidth / 2);
 	pt.y = pt.y - (iheight / 2);

 	/* top will adjust the window position, up or down                     */
 	if(top)
   		pt.y = pt.y + top;

 	/* move the window                                                     */
 	MoveWindow(hWnd, pt.x, pt.y, iwidth, iheight, FALSE);
}

/************************************************************************/
/*  CwUnRegisterClasses Function                                        */
/*                                                                      */
/*  Deletes any refrences to windows resources created for this         */
/*  application, frees memory, deletes instance, handles and does       */
/*  clean up prior to exiting the window                                */
/*                                                                      */
/************************************************************************/

void	CwUnRegisterClasses(void)
{
 	WNDCLASS   wndclass;    /* struct to define a window class             */
 	memset(&wndclass, 0x00, sizeof(WNDCLASS));
    UnregisterClass(szAppName, hInst);
}    /* End of CwUnRegisterClasses    */             