//---------------------------------------------------------------------------

#include <process.h>
#include <vcl.h>
#pragma hdrstop
#include <stdio.h>                                                  
#include <winioctl.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <mbstring.h>
#include <math.h>
#include <sysdefs.h>



#include "dstring.h"
#include "Main.h"
#include "Vend_AX.h"

#include "Data.h"
#include "Protocol.h"
//#include "Plot.h"


extern INTEL_HEX_RECORD Vend_Ax[];
extern INTEL_HEX_RECORD Vend_Ax_Fx2[];

#pragma package(smart_init)
#pragma resource "*.dfm"




TMainForm *MainForm;

//---------------------------------------------------------------------------
__fastcall TMainForm::TMainForm(TComponent* Owner)
  : TForm(Owner)
{
  hDevice= NULL;
  PIPE_TYPE_STRINGS[0] = "CTL";
  PIPE_TYPE_STRINGS[1] = "ISO";
  PIPE_TYPE_STRINGS[2] = "BLK";
  PIPE_TYPE_STRINGS[3] = "INT";
  PIPE_DIRECTION[0] =  "OUT";
  PIPE_DIRECTION[1] =  "IN ";
  m_nTarg = 0;
  Memo->Clear();
  build_time = __TIME__;
  build_date = __DATE__;
  sprintf(tempbuff,"EZ-USB Bulk Test - built %s %s",build_time,build_date);
  Memo->SetTextBuf(tempbuff);
  DriverName->SetTextBuf("EZUSB-0");
  Vend_Req->SetTextBuf("0xA2");
  Vend_Req_Value->SetTextBuf("0x0000");
  Vend_Req_Index->SetTextBuf("0xBEEF");
  Vend_Req_Len->SetTextBuf("0x16");
  Interface_Num_Box->SetTextBuf("0");
  Alternate_Setting_Box->SetTextBuf("1");

  interfaceNum = 0;
  alternateSetting = 1;

  int Size = DriverName->GetTextLen();  //Get length of string in DriverName
  Size++;                               //Add room for null character
  //char *DrName = new char[Size];        //Creates Buffer dynamic variable

  //DriverName->GetTextBuf(DrName,Size);  //Puts DriverName->Text into DrName
  //pcDriverName = DrName;
  pcDriverName = "EZUSB-0";                //Use it as pcDriverName

  bAutoHoldRun = true;
  m_Verbose = false;
  //Verbose_Check_Box->Checked = true;
  Loading_Monitor = false;
  Loading_Code = false;                                               
  m_strPathUSBRoot = "C:\\Cypress\\Usb";
  //m_strMonFileName = m_strPathUSBRoot + "\\Target\\Monitor\\Ezusb\\mon-ext-sio0.hex";
  m_strMonFileName  = "C:\\FRR\\USB\\mon-int-sio0.hex";
  m_strCodeFileName = "C:\\FRR\\USB\\FRR_CODE\\Code.hex";
  m_strFPGAFileName = "C:\\FRR\\USB\\FRR_FPGA\\fpga.dat";
  
  //Load_MonitorBtnClick(NULL);
  Code_LoadBtnClick(NULL);
  //Sleep(100);
  Set_Interface_BtnClick(NULL);
  Get_Pipe_InfoBtnClick(NULL);
  Send_Dummy();
  Toggle();
  //Sleep(200);
  //FPGA_OUTBtnClick(this);
  //Send_Dummy();
  //Toggle();
  //Sleep(100);
  //Exe_StartBtnClick(this);
  //Send_Dummy();
  //Sleep(100);
  //FPGA_OUTBtnClick(this);
  //Code_LoadBtnClick(NULL);
  EXE_ON = false;
  DAC_SelUpDown->Position = 0;
  for(int i = 0; i < 8; i++) DAC[i] = i * 100;
  DACselect = 0;
  for(int i = 0; i < 4; i++) FDAC[i] = i * 20 + 128;
  FDACselect = 0;
  FirstRead = true;
  //delete[] DrName;
}

void __fastcall TMainForm::FormActivate(TObject *Sender)
{

  //SimForm->MemoPtr = Memo;
  DataForm->MemoPtr = Memo;

}

void __fastcall TMainForm::QuitBtnClick(TObject *Sender)
{
  Close();
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::CLEARBtnClick(TObject *Sender)
{
  Memo->Clear();
}

//---------------------------------------------------------------------------

void __fastcall TMainForm::RunBtnClick(TObject *Sender)
{
   RunInd->Brush->Color   = clLime;
   Memo->Lines->Add("==== Toggle 8051 Reset: RUN");
   if (bOpenDriver (&hDevice, pcDriverName) != TRUE)
   {
      Memo->Lines->Add(" ***** Failed to Open Device");
      hDevice = NULL;
   }
   else
   if(m_Verbose) Memo->Lines->Add("==== Driver Opened Successfully");
   Memo->Lines->Add(" ");
   VENDOR_REQUEST_IN	myRequest;
   myRequest.bRequest =  0xA0;
   myRequest.wValue =    0x7F92;
   myRequest.wIndex =    0x00;
   myRequest.wLength =   0x01;
   myRequest.bData =     0;
   myRequest.direction = 0x00;

   if (hDevice != NULL)
   {
      bResult = DeviceIoControl (hDevice,
      IOCTL_Ezusb_VENDOR_REQUEST,         //--- IOCTL type
      &myRequest,                         //--- pointer to an input buffer
      sizeof(VENDOR_REQUEST_IN),          //--- size of the input buffer
      NULL,                               //--- pointer to an return buffer
      0,                                  //--- size of the return buffer
      (unsigned long *)&nBytes,           //--- actual bytes returned
      NULL);                              //--- not overlapped
   }/* if valid driver handle */

   if (bResult==TRUE)
   {
   // do nothing
   }
   else
   Memo->Lines->Add(" ***** Reset Failed");
  // Close the handle
   CloseHandle (hDevice);
}

void __fastcall TMainForm::HoldBtnClick(TObject *Sender)
{
   RunInd->Brush->Color   = clBlack;
   Memo->Lines->Add("==== Toggle 8051 Reset: HOLD");
   if (bOpenDriver (&hDevice, pcDriverName) != TRUE)
   {
      Memo->Lines->Add(" ***** Failed to Open Device");
      hDevice = NULL;
   }
   else
   if(m_Verbose)Memo->Lines->Add("==== Driver Opened Successfully");
   if(m_Verbose)Memo->Lines->Add(" ");
   VENDOR_REQUEST_IN	myRequest;
   myRequest.bRequest =  0xA0;
   myRequest.wValue =    0x7F92;
   myRequest.wIndex =    0x00;
   myRequest.wLength =   0x01;
   myRequest.bData =     1;
   myRequest.direction = 0x00;

   if (hDevice != NULL)
   {
      bResult = DeviceIoControl (hDevice,
      IOCTL_Ezusb_VENDOR_REQUEST,         //--- IOCTL type
      &myRequest,                         //--- pointer to an input buffer
      sizeof(VENDOR_REQUEST_IN),          //--- size of the input buffer
      NULL,                               //--- pointer to an return buffer
      0,                                  //--- size of the return buffer
      (unsigned long *)&nBytes,           //--- actual bytes returned
      NULL);                              //--- not overlapped
   }/* if valid driver handle */

   if (bResult==TRUE)
   {
   // do nothin
   }
   else
   Memo->Lines->Add(" ***** Reset Failed");
  // Close the handle
   CloseHandle (hDevice);
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::Get_Device_DescriptorBtnClick(TObject *Sender)
{
  pvBuffer = malloc (sizeof (Usb_Device_Descriptor) + 128);
  if (bOpenDriver (&hDevice, pcDriverName) != TRUE)  // Open the driver
  {
    Memo->Lines->Add(" ***** Failed to Open Driver");
    hDevice = NULL;
  }
	if (hDevice != NULL)
	{
    bResult = DeviceIoControl (hDevice,               // Perform the Get-Descriptor IOCTL
    IOCTL_Ezusb_GET_DEVICE_DESCRIPTOR,
    pvBuffer,
    sizeof (Usb_Device_Descriptor),
    pvBuffer,
    sizeof (Usb_Device_Descriptor),
    (unsigned long *)&nBytes,
    NULL);
  }/* if valid driver handle */

  if (bResult==TRUE)
  {
    ParseDeviceDescriptor(pvBuffer);
  }
  else
  {
    Memo->Lines->Add(" ***** Get Device Descriptor Failed");
  }
  CloseHandle (hDevice); // Close the handle
  free (pvBuffer); // Free the memory
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::Get_Configuration_DescriptorBtnClick(TObject *Sender)
{
  /* The configuration descriptor is obtained using two separate calls.  The
  // first call is done to determine the size of the entire configuration descriptor,
  // and the second call is done with that total size specified.  For more information,
     refer to the USB Specification, Chapter 9. */

//Get some memory, plus some guardband area
  pvBuffer = malloc (sizeof (Usb_Configuration_Descriptor) + 128);
  if (bOpenDriver (&hDevice, pcDriverName) != TRUE)
  {
    Memo->Lines->Add(" ***** Failed to Open Driver");
    hDevice = NULL;
  }
  // Get the first bytes of the configuration descriptor to determine the size of
  // the entire configuration descriptor.
  if (hDevice != NULL)
  {
    bResult = DeviceIoControl (hDevice,
    IOCTL_Ezusb_GET_CONFIGURATION_DESCRIPTOR,
    pvBuffer,
    sizeof (Usb_Configuration_Descriptor),
    pvBuffer,
    sizeof (Usb_Configuration_Descriptor),
    (unsigned long *)&nBytes,
    NULL);
  }/* if valid driver handle */

  if (bResult!=TRUE)
  {
    Memo->Lines->Add(" ***** Get Configuration Descriptor Failed");
    CloseHandle (hDevice);
    free (pvBuffer);
  }
	else
  {
    unsigned long ulLength = GET_CONFIG_DESCRIPTOR_LENGTH(pvBuffer);
    assert (ulLength >= 0);
    pvBuffer = realloc (pvBuffer, ulLength);     // Now we know the size of pvBuffer
    if (pvBuffer)
    {
      bResult = DeviceIoControl (hDevice,        // Perform the second Get-Descriptor IOCTL
      IOCTL_Ezusb_GET_CONFIGURATION_DESCRIPTOR,
      pvBuffer,
      ulLength,
      pvBuffer,
      ulLength,
      (unsigned long *)&nBytes,
      NULL);
      if (bResult==TRUE)
      {
        ParseConfigurationDescriptor(pvBuffer);
      }
      else
      {
        Memo->Lines->Add(" ***** Get Configutation Descriptor IOCTL failed");
      }
    }
    else
    { // Inform user that mem alloc failed
      Memo->Lines->Add(" ***** Memory Allocation failed in Get Configutration Descriptor");
    }
    CloseHandle (hDevice); // Close the handle
    free (pvBuffer); // Free the memory
  }
}

void __fastcall TMainForm::GetStringBtnClick(TObject *Sender)
// The string descriptor is obtained using two separate calls.  The
// first call is done to determine the size of the entire string descriptor,
// and the second call is done with that total size specified.
// For more information, please refer to the USB Specification, Chapter 9.
// Get some memory, plus some guardband area
{
   char                   temp[64]  = "";
   GET_STRING_DESCRIPTOR_IN input;
   pvBuffer = malloc (sizeof (Usb_String_Descriptor) + 128);
   if (bOpenDriver (&hDevice, pcDriverName) != TRUE)
   {
      Memo->Lines->Add("Failed to Open Driver");
      hDevice = NULL;
   }
   input.Index = 0x00;;
   input.LanguageId = 27; // NOTE: frameworks ignores it anyway
   wsprintf (temp, "GetStringDescriptor: Index=%d", input.Index);
   Memo->Lines->Add(temp);
   // Get the first bytes of the descriptor to determine the size of
   // the entire descriptor.
   if (hDevice != NULL)
   {// Perform the Get-Descriptor IOCTL
      bResult = DeviceIoControl (hDevice,
      IOCTL_Ezusb_GET_STRING_DESCRIPTOR,
      &input,
      sizeof (GET_STRING_DESCRIPTOR_IN),
      pvBuffer,
      sizeof (Usb_String_Descriptor),
      (unsigned long *)&nBytes,
      NULL);
   }/* if valid driver handle */
			
   if (bResult!=TRUE)
   {// This will happen with no string defined
      Memo->Lines->Add(" ***** Get String Descriptor Failed");
      CloseHandle (hDevice);
      free (pvBuffer);
   }/* if */

   unsigned long ulLength = GET_STRING_DESCRIPTOR_LENGTH(pvBuffer);
   assert (ulLength >= 0);
   // Now get the entire descriptor
   pvBuffer = realloc (pvBuffer, ulLength);
   if (pvBuffer)
   {
      bResult = DeviceIoControl (hDevice,
      IOCTL_Ezusb_GET_STRING_DESCRIPTOR,
      &input,
      ulLength,
      pvBuffer,
      ulLength,
      (unsigned long *)&nBytes,
      NULL);

      if (bResult==TRUE)
      {
         ParseStringDescriptor(pvBuffer);
      }
      else
      {// Inform user that the Ioctl failed
         Memo->Lines->Add(" ***** GetStringDescriptor Ioctl failed");
      }
   }
   else
   // Inform user that mem alloc failed
   Memo->Lines->Add(" ***** Memory Allocation failed in GetStringDescriptor");
   CloseHandle (hDevice); // Close the handle
   free (pvBuffer); // Free the memory
}

void __fastcall TMainForm::Get_Pipe_InfoBtnClick(TObject *Sender)
{
   UCHAR InterfaceInfo[1024];
   PUSBD_INTERFACE_INFORMATION pInterface;
   PUSBD_PIPE_INFORMATION pPipe;
   Memo->Lines->Add("  ");
   Memo->Lines->Add("Pipe Info");
   Memo->Lines->Add("--------------------------------------");
   if (bOpenDriver (&hDevice, pcDriverName) != TRUE)
   {
      Memo->Lines->Add(" ***** Failed to Open Driver");
      hDevice = NULL;
   }
	if (hDevice != NULL)
   {// Perform the Get-Descriptor IOCTL
      bResult = DeviceIoControl (hDevice,
      IOCTL_Ezusb_GET_PIPE_INFO,
      NULL,
      0,
      InterfaceInfo,
      sizeof(InterfaceInfo),
      (unsigned long *)&nBytes,
      NULL);
   }/* if valid driver handle */

   if (bResult==TRUE)
   {
      int i;
      char                   temp[64]  = "";
      wsprintf (temp, "Interface Size %d",nBytes);
      Memo->Lines->Add(temp);
      pInterface = (PUSBD_INTERFACE_INFORMATION) InterfaceInfo;
      pPipe = pInterface->Pipes;
      for (i = 0; i < (int) pInterface->NumberOfPipes; i++)
      {
         wsprintf (temp, "Pipe: %2d   Type: %s Endpoint: %2d %s  MaxPktSize: 0x%x",i,PIPE_TYPE_STRINGS[pPipe[i].PipeType],(pPipe[i].EndpointAddress & 0x0F),
         PIPE_DIRECTION[(pPipe[i].EndpointAddress >> 7)],pPipe[i].MaximumPacketSize);
         Memo->Lines->Add(temp);
      }
   }
   else
   Memo->Lines->Add(" ***** Get Pipe Info failed");
   CloseHandle (hDevice);
}

#define MAXSTR 256 // Maximum length of Intel Hex file string
int intel_in(FILE *fpIn, TMemCache* pMemCache, DWORD &ioOffset,
						char endianFlags, BOOLEAN spaces)
{
	int i;
	char str[MAXSTR];
	unsigned byte;
	
	int curSeg = 0;			// current seg record 
	int recType;
	unsigned addr;
	int cnt;
	unsigned int totalRead = 0;
	int CNTFIELD ;
	int ADDRFIELD;
	int RECFIELD ;
	int DATAFIELD;
	
	// offsets of fields within record -- may change later due to "spaces" setting
	CNTFIELD    = 1;
	ADDRFIELD   = 3;
	RECFIELD    = 7;
	DATAFIELD   = 9;
	
	if (!fpIn)
		return(0);
	
	addr = 0;
	
	pMemCache->nSeg = 0;
	while(fgets(str,MAXSTR,fpIn))
	{
		//USB_Control->Memo->Lines->Add("     -- dldhex:%s");
		if(str[0]!=':')
		{
			return(-1);
		}
		
		/* get the record type */
		if (spaces || str[1] == ' ')
		{
			CNTFIELD    = 1 + 1;
			ADDRFIELD   = 3 + 2;
			RECFIELD    = 7 + 3;
			DATAFIELD   = 9 + 4;
		}
		
		sscanf(str+RECFIELD,"%2x",&recType);
		
		PCHAR ptr = (PCHAR)pMemCache->pImg;
		switch(recType)
		{
		case 2: /*seg record*/
			sscanf(str+DATAFIELD,"%4x",&curSeg);
			curSeg *= 0x10;
			break;

		case 0: /*data record*/
			sscanf(str+CNTFIELD,"%2x",&cnt);
			sscanf(str+ADDRFIELD,"%4x",&addr);
			if(addr >= TGT_IMG_SIZE)
			{
				MainForm->Memo->Lines->Add(" ***** Error loading file: address out of range\n");
				return(totalRead);
			}
			ptr += addr; // get pointer to location in image
			
			if(pMemCache->nSeg && 
				(pMemCache->pSeg[pMemCache->nSeg-1].TAddr ==
				addr - pMemCache->pSeg[pMemCache->nSeg-1].Size) &&
				(pMemCache->pSeg[pMemCache->nSeg-1].Size + cnt <= MAX_EP0_XFER_SIZE) )
			{ // if the segment is contiguous to the last segment, and it's not too big yet
				pMemCache->pSeg[pMemCache->nSeg-1].Size += cnt; // append to previous segment
			}
			else
			{ // start a new segment
				pMemCache->pSeg[pMemCache->nSeg].TAddr = addr;
				pMemCache->pSeg[pMemCache->nSeg].Size = cnt;
				pMemCache->pSeg[pMemCache->nSeg].pData = ptr;
				pMemCache->nSeg++;
			}
			for(i=0; i<cnt; i++)
			{
				sscanf(str+DATAFIELD+i*2,"%2x",&byte);
				*(ptr + i) = byte;
				totalRead++;
			}
			break;
			
		case 1: /*end record*/
			return(totalRead);
			//break;

		default:
			break;
		}
	}
	return(-1);		// missing end record
}

void TMainForm::Ezusb_DownloadIntelHex(PINTEL_HEX_RECORD pHexRecord)
{
   PINTEL_HEX_RECORD ptr = pHexRecord;
	unsigned char* pbuf = (unsigned char *)BlkBuf;
	unsigned char* ptmp = NULL;

	ptr = pHexRecord;
	MainForm->HoldBtnClick(NULL);

	while (ptr->Type == 0)
	{ //load low mem
		if((ptmp != NULL) &&
			(m_DldOffset+m_DldLen == ptr->Address) &&
			((m_DldLen+ptr->Length) <= MAX_EP0_XFER_SIZE) )
		{ // continue a segment
			memcpy(ptmp, ptr->Data, ptr->Length);
			m_DldLen += ptr->Length;
			ptmp += ptr->Length;
		}
		else
		{ // start a new segment
			if(ptmp != NULL)
			{ // send prev segment first
				Anchor_Download();
				break;
			}
			ptmp = pbuf;
			memcpy(ptmp, ptr->Data, ptr->Length);
			m_DldLen = ptr->Length;
			m_DldOffset = ptr->Address;
			ptmp += ptr->Length;
		}
      ptr++;
	}
	if(ptmp != NULL)
	{ // send final segment
		Anchor_Download();
	}
	RunBtnClick(NULL);
}

#define ONE_K       0x400
#define ONE_MEG     (ONE_K * ONE_K)

// Assign data only if successfully scanned data.
// Return 0 if no data scanned
int my_sscanf(LPCSTR cBuffer, DWORD *data)
{
	char *ptr;
   char buffer[0x100];
	int value;

   strcpy(buffer, cBuffer);

	ptr = strchr(strlwr(buffer), 'k');
   if(ptr)
	{
		*ptr = 0;
		if (sscanf(buffer, "%d", &value))
		{
			*data = value * ONE_K;
			return 1;
		}
		*ptr = 'K';		// failed, but let's put it back
	}

	ptr = strchr(strlwr(buffer), 'm');
   if(ptr)
	{
		*ptr = 0;
		if (sscanf(buffer, "%d", &value))
		{
			*data = value * ONE_MEG;
			return 1;
		}
		*ptr = 'M';		// failed, but let's put it back
	}

	ptr = strpbrk(buffer, "xX");
   if(ptr)
	{
		if (sscanf(ptr+1, "%x", &value))
			{
				*data = value;
				return 1;
			}
	}
	else if (sscanf(buffer, "%d", &value))
	{
		*data = value;
		return 1;
	}
	return 0;
}


void __fastcall TMainForm::Vend_ReqBtnClick(TObject *Sender)
{
   DWORD myDword;
   char tempbuff[MAX_DRIVER_NAME];
   VENDOR_OR_CLASS_REQUEST_CONTROL	myRequest;
   unsigned char *buffer;
   buffer = (unsigned char*)(VenBuf);
   ULONG bufferSize = 0;
   //double a = 2.2;
   //for (int k = 0; k < 99999; k++) a = sqrt(a);
   if(m_Verbose) Memo->Lines->Add("==== Vendor Request");
   if (bOpenDriver (&hDevice, pcDriverName) != TRUE)
   {
      Memo->Lines->Add(" ***** Failed to Open Driver");
      hDevice = NULL;
   }
   if (hDevice != NULL)
   {

      //if (USB_OUTSel->Checked) myRequest.direction = 0;
      //else myRequest.direction = 1;

      Vend_Req->GetTextBuf(tempbuff, MAX_DRIVER_NAME);
      my_sscanf(tempbuff,&myDword);
      myRequest.request = (unsigned char) myDword;

      Vend_Req_Index->GetTextBuf(tempbuff, MAX_DRIVER_NAME);
      my_sscanf(tempbuff,&myDword);
      myRequest.index = (unsigned short) myDword;

      Vend_Req_Value->GetTextBuf(tempbuff, MAX_DRIVER_NAME);
      my_sscanf(tempbuff,&myDword);
      myRequest.value = (unsigned short) myDword;

      Vend_Req_Len->GetTextBuf(tempbuff, MAX_DRIVER_NAME);
      my_sscanf(tempbuff,&myDword);
      bufferSize = (unsigned short) myDword;

      myRequest.requestType=2;      // vendor specific request type (2)
      myRequest.recepient=0;        // recepient is device (0)

      bResult = DeviceIoControl (hDevice,
         IOCTL_EZUSB_VENDOR_OR_CLASS_REQUEST,
         &myRequest,
         sizeof(VENDOR_OR_CLASS_REQUEST_CONTROL),
         buffer,
         bufferSize,
         (unsigned long *)&nBytes,
         NULL);

      if (bResult==TRUE)
      {
         if(m_Verbose) DumpBuffer(buffer,bufferSize);
      }
      else
      {
         Memo->Lines->Add(" ***** Vendor Request failed");
      }
   }
   CloseHandle (hDevice);
}

void TMainForm::Anchor_Download()
{
   ANCHOR_DOWNLOAD_CONTROL downloadControl;
   int numread = 0;
   char temp[64]  = "";
   unsigned char* buffer;

   buffer = (unsigned char*)(BlkBuf);
   numread = m_DldLen;
   downloadControl.Offset = (USHORT)m_DldOffset;
   wsprintf (temp, "Anchor Download %d bytes: addr=%x",numread, downloadControl.Offset);
   if(m_Verbose) Memo->Lines->Add(temp);
   if (bOpenDriver (&hDevice, pcDriverName) != TRUE)
   {
      Memo->Lines->Add(" ***** Failed to Open Driver for LoadFile");
      hDevice = NULL;
   }
   if (hDevice != NULL)
   {
      if (m_DldOffset < 0x2000)
      {
         bResult = DeviceIoControl (hDevice,
            IOCTL_EZUSB_ANCHOR_DOWNLOAD,
            &downloadControl,
            sizeof(ANCHOR_DOWNLOAD_CONTROL),
            buffer,
            numread,
            (unsigned long *)&nBytes,
            NULL);
         if(bResult)
         {
            if(m_Verbose) DumpBuffer(buffer,numread);
         }
         else Memo->Lines->Add(" ***** IOCTL_ANCHOR_DOWNLOAD Failed");
      }
      else
      {
         VENDOR_OR_CLASS_REQUEST_CONTROL	myRequest;
         myRequest.request = (BYTE) 0xA3;
         myRequest.value = (WORD) m_DldOffset;
         myRequest.index = (WORD) 0x00;
         myRequest.direction = 0;
         myRequest.requestType = 2;
         myRequest.recepient = 0;

         bResult = DeviceIoControl (hDevice,
            IOCTL_EZUSB_VENDOR_OR_CLASS_REQUEST,
            &myRequest,
            sizeof(VENDOR_OR_CLASS_REQUEST_CONTROL),
            buffer,
            numread,
            (unsigned long *)&nBytes,
            NULL);

         if (bResult==TRUE)
         {
            if(m_Verbose) DumpBuffer(buffer,numread);
         }
         else Memo->Lines->Add(" ***** IOCTL_EZUSB_VENDOR_OR_CLASS Failed");

      }
      CloseHandle (hDevice);
   }
}

void __fastcall TMainForm::Load_MonitorBtnClick(TObject *Sender)
{
   Loading_Monitor = true;
   Loading_Code = false;
   DownloadBtnClick(NULL);
}

void __fastcall TMainForm::Code_LoadBtnClick(TObject *Sender)
{
   Loading_Code = true;
   Loading_Monitor = false;
   DownloadBtnClick(NULL);
}
//---------------------------------------------------------------------------


void __fastcall TMainForm::DownloadBtnClick(TObject *Sender)
{
   unsigned char* pbuf =      (unsigned char *)BlkBuf;
   unsigned char* pVenbuf =   (unsigned char *)VenBuf;
   BOOLEAN  Proceed = false;
   //char  temp[64]  = "";
   char FileName[64];
   AnsiString sFileName;
   AnsiString sExt;
   unsigned char* buffer;
   ANCHOR_DOWNLOAD_CONTROL downloadControl;
   if (Loading_Monitor)
   {
      sFileName = m_strMonFileName;                                      //char* FileName = new char[sFileName.Length() +1];
      strcpy(FileName, sFileName.c_str());
      Proceed = true;
   }
   else
   if (Loading_Code)
   {
      sFileName = m_strCodeFileName;
      //char* FileName = new char[sFileName.Length() +1];
      strcpy(FileName, sFileName.c_str());                            
      Proceed = true;
   }
   /*
   else
   {
      OpenFileDlg->InitialDir = DataForm->CurrentDir;
      //DataForm->OpenFileDialog->InitialDir += "\\Protocols";
      DataForm->OpenFileDialog->Filter = "Hex files (*.hex)|*.HEX";
      if (OpenFileDlg->Execute())
      {
         sFileName = OpenFileDlg->FileName;
         //char* FileName = new char[sFileName.Length() +1];
         strcpy(FileName, sFileName.c_str());
         Proceed = true;
      }
   }
   */
   if (Proceed)
   {
      Loading_Monitor = false;
      Loading_Code    = false;
      FILE *fp;
      sExt = sFileName.SubString(sFileName.Length() -2, 3);
      if(sExt == "hex") //intel hex format
      {
         if ((fp = fopen(FileName,"rb")) != NULL)
         {
            char endianConversion = 0;    // Mask for endian conversion
	   	   DWORD offset = 0;         		// Offset -- set to -1 to get offset from srec or hex file
            m_MemCache.pImg = &m_MemImg;
            intel_in(fp, &m_MemCache, offset, endianConversion, FALSE);
            fclose(fp);

            for(int k=0; k< m_MemCache.nSeg; k++)
		      { //check for high mem first; load loader first if necessary
			      if(m_MemCache.pSeg[k].TAddr >= 0x2000)
			      {
				      if(m_nTarg)
				      { // if Fx2
					      Memo->Lines->Add("loading Fx2 loader");
                     //Ezusb_DownloadIntelHex(Vend_Ax_Fx2);
                     break;
				      }
				      else
				      { // if Ezusb
					      Memo->Lines->Add("loading Ezusb loader");
					      Ezusb_DownloadIntelHex(Vend_Ax);
				   	   break;
				      }
   				   /*
	   			   CString tmpDldFile = (theApp.m_nTarg) ?
		   		   	theApp.m_strPathUSBRoot + "\\Target\\LoadExt\\Vend_Ax_Fx2.bix" : theApp.m_strPathUSBRoot + "\\Target\\LoadExt\\Vend_Ax.bix";
			      	if( CFile::GetStatus( tmpDldFile, status ) )
			      	{ // if loader file exists
				      	TRACE("loading loader:%s\n", tmpDldFile);
				   	   LoadFile(tmpDldFile);
   				   	break;
	   		   	}
		   	   	else
			      	{
				      	theApp.report_error("Error Loading Vend_Ax (external loader) file; Load failed.\n");
				      	return;
   				   }
	   			   */
               }
            }
            for(int i=0; i<m_MemCache.nSeg; i++)
            { //load all high mem first
			      if(m_MemCache.pSeg[i].TAddr >= 0x2000)
      			{
	      			char text[80];
		      		memcpy(pVenbuf, m_MemCache.pSeg[i].pData, m_MemCache.pSeg[i].Size);
			      	Vend_Req->SetTextBuf("0xA3");
				      sprintf(text, "0x%x", m_MemCache.pSeg[i].TAddr);
   				   Vend_Req_Value->SetTextBuf(text);
   	   			sprintf(text, "%d", m_MemCache.pSeg[i].Size);
	   	   		Vend_Req_Len->SetTextBuf(text);
                  //USB_INSel->Checked = false;
                  //USB_OUTSel->Checked = true;
                  Vend_ReqBtnClick(NULL);
   			   }
            }
            if(bAutoHoldRun) HoldBtnClick(NULL);
            for(int j=0; j<m_MemCache.nSeg; j++)
            { //load all low mem last
		      	if(m_MemCache.pSeg[j].TAddr < 0x2000)
			      {
                  m_DldLen =     m_MemCache.pSeg[j].Size;
                  m_DldOffset =  m_MemCache.pSeg[j].TAddr;
	   	   		memcpy(pbuf, m_MemCache.pSeg[j].pData, m_MemCache.pSeg[j].Size);
                  Anchor_Download();
               }
            }
            if(bAutoHoldRun) RunBtnClick(NULL);
         }
         else if(sExt == "bix") //bix format
         {
         if ((fp = fopen(FileName,"rb")) != NULL)
            {
		         m_DldLen = fread(pbuf, sizeof(unsigned char), MAX_FILE_SIZE, fp);
               fclose(fp);
   		      m_DldOffset = 0;
               if(bAutoHoldRun) HoldBtnClick(NULL);
               //SendOp(OP_ANCHOR_DLD);
               if(bAutoHoldRun) RunBtnClick(NULL);
            }
	   	   else
   		   {
               Memo->Lines->Add(" ***** Error opening Input file.\n");
		      }
   	   }
	      else
	      {
            Memo->Lines->Add(" ***** Wrong file type. \Please select .hex or .bix file to download.\n");
   	   }
         //if(bAutoHoldRun) RunBtnClick(NULL);
      }
   }
}


//---------------------------------------------------------------------------

//PARSERS ----------------------
/**************************************************
 * ParseDeviceDescriptor proc                     *
 *                                                *
 * Purpose:                                       *
 *      Parses the device descriptor data and     *
 *      displays the interpretation to the        *
 *      windows specified                         *
 *                                                *
 * Input:                                         *
 *      pvBuffer:                                 *
 *          Pointer to a buffer that contains the *
 *          raw device descriptor data.           *
 *      hOutputBox:                               *
 *          Handle to the window where the        *
 *          resultant interpreted data is to go.  *
 *                                                *
 * Return Value:                                  *
 *          None                                  *
 **************************************************/


void ParseDeviceDescriptor(PVOID pvBuffer)
{
   pUsb_Device_Descriptor pDevDescr = (pUsb_Device_Descriptor) pvBuffer;
   //int                    nItems    = 0;
   char                   temp[64]  = "";

   MainForm->Memo->Lines->Add("  ");
   MainForm->Memo->Lines->Add("Device Descriptor:  ");
   MainForm->Memo->Lines->Add("-------------------------");

   wsprintf (temp, "bLength:             %d", pDevDescr->bLength);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "bDescriptorType:     %d", pDevDescr->bDescriptorType);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "bcdUSB:              %d", pDevDescr->bcdUSB);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "bDeviceClass:        %#x", pDevDescr->bDeviceClass);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "bDeviceSubClass:     %#x", pDevDescr->bDeviceSubClass);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "bDeviceProtocol:     %#x", pDevDescr->bDeviceProtocol);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "bMaxPacketSize0:     %#x", pDevDescr->bMaxPacketSize0);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "idVendor:            %#x", pDevDescr->idVendor);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "idProduct:           %#x", pDevDescr->idProduct);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "bcdDevice:           %#x", pDevDescr->bcdDevice);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "iManufacturer:       %#x", pDevDescr->iManufacturer);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "iProduct:            %#x", pDevDescr->iProduct);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "iSerialNumber:       %#x", pDevDescr->iSerialNumber);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "bNumConfigurations:  %#x", pDevDescr->bNumConfigurations);
   MainForm->Memo->Lines->Add(temp);
}// ParseDeviceDescriptor

/**************************************************
 * ParseConfigurationDescriptor proc              *
 *                                                *
 * Purpose:                                       *
 *      Parses the config descriptor data and     *
 *      displays the interpretation to the        *
 *      windows specified                         *
 *                                                *
 * Input:                                         *
 *      pvBuffer:                                 *
 *          Pointer to a buffer that contains the *
 *          raw device descriptor data.           *
 *      hOutputBox:                               *
 *          Handle to the window where the        *
 *          resultant interpreted data is to go.  *
 *                                                *
 * Return Value:                                  *
 *          None                                  *
 **************************************************/

void
ParseConfigurationDescriptor(PVOID pvBuffer)
{
   pUsb_Configuration_Descriptor pCD = (pUsb_Configuration_Descriptor) pvBuffer;
   pUsb_Interface_Descriptor     pID = NULL;
   pUsb_Endpoint_Descriptor      pED = NULL;

   //int                    nItems    = 0;
   char                   temp[64]  = "";
   int                    i         = 0;

   wsprintf (temp, " ");
   MainForm->Memo->Lines->Add(" ");
   MainForm->Memo->Lines->Add("Config Descriptor");
   MainForm->Memo->Lines->Add("-------------------------");

   wsprintf (temp, "bLength:             0x%x", pCD->bLength);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "bDescriptorType:     %d", pCD->bDescriptorType);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "wTotalLength:        %d (0x%x)", pCD->wTotalLength, pCD->wTotalLength);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "bNumInterfaces:      %d", pCD->bNumInterfaces);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "bConfigurationValue: %d", pCD->bConfigurationValue);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "iConfiguration:      %d", pCD->iConfiguration);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "bmAttributes:        0x%x", pCD->bmAttributes);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "MaxPower:            %d", pCD->MaxPower);
   MainForm->Memo->Lines->Add(temp);

   MainForm->Memo->Lines->Add("  ");
   // Interface Descriptor
   pID = (pUsb_Interface_Descriptor) (((char*)pCD) + pCD->bLength);

   MainForm->Memo->Lines->Add("Interface Descriptor:  ");
   MainForm->Memo->Lines->Add("-------------------------");

   wsprintf (temp, "bLength:             0x%x", pID->bLength);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "bDescriptorType:     %d", pID->bDescriptorType);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "bInterfaceNumber:    %d", pID->bInterfaceNumber);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "bAlternateSetting:   %d", pID->bAlternateSetting);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "bNumEndpoints:       %d", pID->bNumEndpoints);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "bInterfaceClass:     %d (0x%x)", pID->bInterfaceClass, pID->bInterfaceClass);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "bInterfaceSubClass:  %d (0x%x)", pID->bInterfaceSubClass, pID->bInterfaceSubClass);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "bInterfaceProtocol:  %d (0x%x)", pID->bInterfaceProtocol, pID->bInterfaceProtocol);
   MainForm->Memo->Lines->Add(temp);

   wsprintf (temp, "iInterface:          %d", pID->iInterface);
   MainForm->Memo->Lines->Add(temp);

   MainForm->Memo->Lines->Add("  ");

 // Endpoint Descriptor
   pED = (pUsb_Endpoint_Descriptor) (((char*)pID) + pID->bLength);
   for (i = 0; i < pID->bNumEndpoints; i ++)
   {
      wsprintf (temp, "Endpoint Descriptor %d  ", i);
      MainForm->Memo->Lines->Add(temp);
      MainForm->Memo->Lines->Add("----------------------");

      wsprintf (temp, "bLength:          0x%x", pED->bLength);
      MainForm->Memo->Lines->Add(temp);

      wsprintf (temp, "bDescriptorType:  %d", pED->bDescriptorType);
      MainForm->Memo->Lines->Add(temp);

      wsprintf (temp, "bEndpointAddress: 0x%x", pED->bEndpointAddress);
      MainForm->Memo->Lines->Add(temp);

      wsprintf (temp, "bmAttributes:     0x%x", pED->bmAttributes);
      MainForm->Memo->Lines->Add(temp);

      wsprintf (temp, "wMaxPacketSize:   %d", pED->wMaxPacketSize);
      MainForm->Memo->Lines->Add(temp);

      wsprintf (temp, "bInterval:        %d", pED->bInterval);
      MainForm->Memo->Lines->Add(temp);

      MainForm->Memo->Lines->Add("**********************");

		pED = (pUsb_Endpoint_Descriptor) (((char*)pED) + (pED->bLength));
    }// for
}// ParseConfigurationDescriptor

void ParseStringDescriptor(PVOID pvBuffer)
{
   pUsb_String_Descriptor pCD = (pUsb_String_Descriptor) pvBuffer;
   //pUsb_Interface_Descriptor     pID = NULL;
   //pUsb_Endpoint_Descriptor      pED = NULL;

   //int                    nItems    = 0;
   char                   temp[64]  = "";
   int                    i         = 0;

	wsprintf (temp, "StringDescriptor=");
	for(i=0; i<((pCD->bLength/2)-1) && i<sizeof(temp); i++)
		wsprintf (temp+17+i, "%c", pCD->bString[i]);
   MainForm->Memo->Lines->Add(temp);
}/* ParseStringDescriptor */

void DumpBuffer(PVOID pvBuffer, ULONG length)
{
   //int                    nItems    = 0;
   char                   temp[64]  = "";
   char                   temp2[64]  = "";
   ULONG	i;
	ULONG   j;
	PUCHAR	ptr;

	if(length>MAX_FILE_SIZE)
	{
      MainForm->Memo->Lines->Add("Buffer Contents not printed due to large size ...");
	}
	ptr = (PUCHAR) pvBuffer;

	for (i = 0; i < ((length + 16 - 1) / 16); i++)
	{
		wsprintf(temp,"%04X ",(i*16));
		for (j = 0; j < 16; j++)
		{
			if (((i * 16) + j) < length)
			{
				wsprintf(temp2,"%02X ",*ptr++);
				strcat(temp,temp2);
			}
		}
      MainForm->Memo->Lines->Add(temp);
	}
}

//---------------------------------------------------------------------------

void __fastcall TMainForm::Verbose_Check_BoxClick(TObject *Sender)
{
   m_Verbose = !m_Verbose;
   Verbose_Check_Box->Checked = m_Verbose;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::Set_Interface_BtnClick(TObject *Sender)
{
   char                   temp[64]  = "";
   SET_INTERFACE_IN input;
   DWORD myDword;
   char tempbuf[8];
   Interface_Num_Box->GetTextBuf(tempbuff, 8);
   my_sscanf(tempbuff,&myDword);
   interfaceNum = (unsigned char) myDword;

   Alternate_Setting_Box->GetTextBuf(tempbuff, 8);
   my_sscanf(tempbuff,&myDword);
   alternateSetting = (unsigned char) myDword;

   if (bOpenDriver (&hDevice, pcDriverName) != TRUE)
   {
      Memo->Lines->Add(" ***** Failed to Open Driver");
      hDevice = NULL;
   }
   input.interfaceNum = interfaceNum;
   input.alternateSetting = alternateSetting;
   if (hDevice != NULL)
   {
      wsprintf (temp, "==== Set Interface: Interface=%x: Alt Setting=%x",
					input.interfaceNum, input.alternateSetting);
      Memo->Lines->Add(temp);
      bResult = DeviceIoControl (hDevice,
      IOCTL_Ezusb_SETINTERFACE,
      &input,
      sizeof(SET_INTERFACE_IN),
      NULL,
      0,
      (unsigned long *)&nBytes,
      NULL);
					
   }/* if valid driver handle */
   CloseHandle (hDevice); // Close the handle

}
//---------------------------------------------------------------------------


void __fastcall TMainForm::Get_FrameBtnClick(TObject *Sender)
{
   char  temp[64]  = "";
   ULONG frameNum = 0;
	if (bOpenDriver (&hDevice, pcDriverName) != TRUE)
   {
      Memo->Lines->Add(" ***** Failed to Open Driver in Get Frame");
      hDevice = NULL;
   }
   if (hDevice != NULL)
   {
      bResult = DeviceIoControl (hDevice,
         IOCTL_EZUSB_GET_CURRENT_FRAME_NUMBER,
         NULL,
         0,
         &frameNum,
         sizeof(ULONG),
         (unsigned long *)&nBytes,
         NULL);
      if (bResult == TRUE)
      {
         wsprintf (temp, "Current Frame Number: %lu",frameNum);
         Memo->Lines->Add(temp);
      }
      else Memo->Lines->Add(" ***** GetFrameNum failed");
      CloseHandle (hDevice); // Close the handle
   }
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::EXE_Start()
{
   char *response;
   char temp[64]  = "";
   Command_Length = wsprintf (Command, "EXE_Start");
   wsprintf(temp, "----> %s", Command);
   Memo->Lines->Add(temp);
   Send_Command();
   //if (memcmp((char *) Target_Response(), &Command[0], 9) == 0)  //Echo received
   {
      wsprintf (temp, "----- Execution started");
      Memo->Lines->Add(temp);
      Memo->Lines->Add("");
   }
}

void __fastcall TMainForm::DAC_SetBtnClick(TObject *Sender)
{
   char *response;
   char temp[64]  = "";

   Command_Length = wsprintf (Command, "DAC_SET        %d   %d", DACselect, DAC[DACselect]);
   wsprintf(temp, "----> %s", Command);
   Memo->Lines->Add(temp);
   Send_Command();
   {
      wsprintf (temp, "----- DAC Set");
      Memo->Lines->Add(temp);
      Memo->Lines->Add("");
   }
   Toggle();
}

void __fastcall TMainForm::FDAC_SetBtnClick(TObject *Sender)
{
   char *response;
   char temp[64]  = "";

   Command_Length = wsprintf (Command, "FDAC_SET        %d   %d", FDACselect, FDAC[FDACselect]);
   wsprintf(temp, "----> %s", Command);
   Memo->Lines->Add(temp);
   Send_Command();
   {
      wsprintf (temp, "----- FDAC Set");
      Memo->Lines->Add(temp);
      Memo->Lines->Add("");
   }
   Toggle();
}

void __fastcall TMainForm::SetFGain(int d1, int d2)
{
   char *response;
   char temp[64]  = "";

   Command_Length = wsprintf (Command, "FDAC_SET        %d   %d", 0, d1);
   wsprintf(temp, "----> %s", Command);
   Memo->Lines->Add(temp);
   Send_Command();
   {
      wsprintf (temp, "----- FDAC Set");
      Memo->Lines->Add(temp);
      Memo->Lines->Add("");
   }
   Toggle();
   Command_Length = wsprintf (Command, "FDAC_SET        %d   %d", 1, d2);
   wsprintf(temp, "----> %s", Command);
   Memo->Lines->Add(temp);
   Send_Command();
   {
      wsprintf (temp, "----- FDAC Set");
      Memo->Lines->Add(temp);
      Memo->Lines->Add("");
   }
   Toggle();
}

void __fastcall TMainForm::Toggle()
{
   if (bOpenDriver (&hDevice, pcDriverName) != TRUE)
   {
      Memo->Lines->Add(" ***** Failed to Open in Toggle_HOLD");
      hDevice = NULL;
   }
   else
   if(m_Verbose)Memo->Lines->Add("==== Driver Opened Successfully");
   if(m_Verbose)Memo->Lines->Add(" ");
   VENDOR_REQUEST_IN	myRequest;
   myRequest.bRequest =  0xA0;
   myRequest.wValue =    0x7F92;
   myRequest.wIndex =    0x00;
   myRequest.wLength =   0x01;
   myRequest.bData =     1;
   myRequest.direction = 0x00;

   if (hDevice != NULL)
   {
      bResult = DeviceIoControl (hDevice,
      IOCTL_Ezusb_VENDOR_REQUEST,         //--- IOCTL type
      &myRequest,                         //--- pointer to an input buffer
      sizeof(VENDOR_REQUEST_IN),          //--- size of the input buffer
      NULL,                               //--- pointer to an return buffer
      0,                                  //--- size of the return buffer
      (unsigned long *)&nBytes,           //--- actual bytes returned
      NULL);                              //--- not overlapped
   }/* if valid driver handle */

   if (bResult==TRUE)
   {
   // do nothin
   }
   else
   Memo->Lines->Add(" ***** IOCTL Failed in Toggle_HOLD");
  // Close the handle
   CloseHandle (hDevice);
//-------------------------------------------------------
   if (bOpenDriver (&hDevice, pcDriverName) != TRUE)
   {
      Memo->Lines->Add(" ***** Failed to Open Device in Toggle_RUN");
      hDevice = NULL;
   }
   else
   if(m_Verbose) Memo->Lines->Add("==== Driver Opened Successfully");
   Memo->Lines->Add(" ");
   myRequest.bData =     0;
   if (hDevice != NULL)
   {
      bResult = DeviceIoControl (hDevice,
      IOCTL_Ezusb_VENDOR_REQUEST,         //--- IOCTL type
      &myRequest,                         //--- pointer to an input buffer
      sizeof(VENDOR_REQUEST_IN),          //--- size of the input buffer
      NULL,                               //--- pointer to an return buffer
      0,                                  //--- size of the return buffer
      (unsigned long *)&nBytes,           //--- actual bytes returned
      NULL);                              //--- not overlapped
   }/* if valid driver handle */

   if (bResult==TRUE)
   {
   // do nothing
   }
   else
   Memo->Lines->Add(" ***** IOCTL Failed in Toggle_RUN");
  // Close the handle
   CloseHandle (hDevice);
   Sleep(20);
}

void __fastcall TMainForm::FIFO_Read_First()
{
   char *response;
   char temp[64]  = "";
   BULK_TRANSFER_CONTROL bulkControl;
   unsigned char buffer[64]= "";
   AnsiString operand;
   //unsigned char *buffer;
   int datain[16];
   int dd;
   ULONG length;
   int idata, n, d0, d1, d2, d3, rri, ffi;
   int Byte_Received, nobytes, nop;
   length = 64;
   fifo_bytes = 64;
   Command_Length = wsprintf (Command, "FIFO_Read    %d", fifo_bytes);
   bulkControl.pipeNum = 2;
   if (bOpenDriver (&hDevice, pcDriverName) != TRUE)
   {
      Memo->Lines->Add(" ....   Failed to Open Driver in FIFO Command");
      hDevice = NULL;
   }
   if (hDevice != NULL)
   {
      bOpenDriver (&hDevice, pcDriverName);
      bResult = DeviceIoControl (hDevice,
         IOCTL_EZUSB_BULK_WRITE,
         &bulkControl,
         sizeof (BULK_TRANSFER_CONTROL),
         &Command[0],
         Command_Length,
         (unsigned long *)&nBytes,
         NULL);
      CloseHandle (hDevice);
      if(bResult == FALSE) Memo->Lines->Add("..... IOCTL failed in FIFO Command");
      wsprintf(temp, "----> %s", Command);
      Memo->Lines->Add(temp);
   }
   Sleep(10);
   bOpenDriver (&hDevice, pcDriverName);
   if (bOpenDriver (&hDevice, pcDriverName) != TRUE)
   {
      Memo->Lines->Add(" ....   Failed to Open Driver for FIFO Command");
      hDevice = NULL;
   }
   if (hDevice != NULL)
   {
      Byte_Received = 0;
      nop = 0;
      do
      {
         bulkControl.pipeNum = 1;
         bResult = DeviceIoControl (hDevice,
            IOCTL_EZUSB_BULK_READ,
            &bulkControl,
            sizeof (BULK_TRANSFER_CONTROL),
            &buffer[0],
            length,
            (unsigned long *)&nBytes,
            NULL);
         if(bResult == FALSE)
         {
            wsprintf (temp, " ---- IOCTL failed in FIFO Read; Bytes received: %d  ", Byte_Received);
            Memo->Lines->Add(temp);
         }
         Byte_Received += nBytes;
         idata = int(nBytes/4);
         for(n = 0; n < idata; n++)
         {
            d0 = buffer[4*n];
            d1 = buffer[4*n + 1];
            d2 = buffer[4*n + 2];
            d3 = buffer[4*n + 3];
            rri = d0 + (d1 & 0x0f) * 256;
            ffi = ((d1 & 0xf0)/16) + d2 * 16;
            //wsprintf (temp, "%5d  %5d  %5d  %5d   %5d" , d0, d1, d2, d3, rri);
            DataForm->ri[nop] = (DataForm->ri[nop] * (DataForm->NoAver - 1) + rri)/DataForm->NoAver;
            DataForm->fi[nop] = (DataForm->fi[nop] * (DataForm->NoAver - 1) + ffi)/DataForm->NoAver;
            nop ++ ;
         }
      }while(Byte_Received < fifo_bytes);
      CloseHandle (hDevice);
   }
   wsprintf (temp, "<---- Bytes IN:    %d", Byte_Received);
   Memo->Lines->Add(temp);
   Toggle();
}


void __fastcall TMainForm::FIFO_Read_BtnClick(TObject *Sender)
{
   char *response;
   char temp[64]  = "";
   BULK_TRANSFER_CONTROL bulkControl;
   unsigned char buffer[64]= "";
   AnsiString operand;
   //unsigned char *buffer;
   int datain[16];
   int dd;
   ULONG length;
   int idata, n, d0, d1, d2, d3, rri, ffi;
   int Byte_Received, nobytes, nop;
   if(FirstRead) FIFO_Read_First();
   FirstRead = false;
   length = 64;
   fifo_bytes = DataForm->Samples * 4;
   fifo_bytes = int(fifo_bytes/64 + 1) * 64;
   Command_Length = wsprintf (Command, "FIFO_Read    %d", fifo_bytes);
   Sleep(10);
   bulkControl.pipeNum = 2;
   if (bOpenDriver (&hDevice, pcDriverName) != TRUE)
   {
      Memo->Lines->Add(" ....   Failed to Open Driver in FIFO Command");
      hDevice = NULL;
   }
   if (hDevice != NULL)
   {
      bOpenDriver (&hDevice, pcDriverName);
      bResult = DeviceIoControl (hDevice,
         IOCTL_EZUSB_BULK_WRITE,
         &bulkControl,
         sizeof (BULK_TRANSFER_CONTROL),
         &Command[0],
         Command_Length,
         (unsigned long *)&nBytes,
         NULL);
      CloseHandle (hDevice);
      if(bResult == FALSE) Memo->Lines->Add("..... IOCTL failed in FIFO Command");
      wsprintf(temp, "----> %s", Command);
      Memo->Lines->Add(temp);
   }
   //Sleep(10);
   bOpenDriver (&hDevice, pcDriverName);
   if (bOpenDriver (&hDevice, pcDriverName) != TRUE)
   {
      Memo->Lines->Add(" ....   Failed to Open Driver for FIFO Command");
      hDevice = NULL;
   }
   if (hDevice != NULL)
   {
      Byte_Received = 0;
      nop = 0;
      do
      {
         bulkControl.pipeNum = 1;
         bResult = DeviceIoControl (hDevice,
            IOCTL_EZUSB_BULK_READ,
            &bulkControl,
            sizeof (BULK_TRANSFER_CONTROL),
            &buffer[0],
            length,
            (unsigned long *)&nBytes,
            NULL);
         if(bResult == FALSE)
         {
            wsprintf (temp, " ---- IOCTL failed in FIFO Read; Bytes received: %d  ", Byte_Received);
            Memo->Lines->Add(temp);
         }
         Byte_Received += nBytes;
         //fifo_bytes -= nBytes;
         //wsprintf (temp, " Bytes received: %d  %d ", nBytes, byte);
         //Memo->Lines->Add(temp);
         idata = int(nBytes/4);
         for(n = 0; n < idata; n++)
         {
            d0 = buffer[4*n];
            d1 = buffer[4*n + 1];
            d2 = buffer[4*n + 2];
            d3 = buffer[4*n + 3];
            rri = d0 + (d1 & 0x0f) * 256;
            ffi = ((d1 & 0xf0)/16) + d2 * 16;
            //wsprintf (temp, "%5d  %5d  %5d  %5d   %5d" , d0, d1, d2, d3, rri);
            DataForm->ri[nop] = (DataForm->ri[nop] * (DataForm->NoAver - 1) + rri)/DataForm->NoAver;
            DataForm->fi[nop] = (DataForm->fi[nop] * (DataForm->NoAver - 1) + ffi)/DataForm->NoAver;
            nop ++ ;
            //Memo->Lines->Add(temp);
            //rri = buffer[idata] + (buffer[idata + 1] & 0x0f) * 256;
            //ffi = (buffer[idata + 1] & 0xf0) / 4 + buffer[idata + 2] * 16;
         }
      }while(Byte_Received < fifo_bytes);
      CloseHandle (hDevice);
   }
   wsprintf (temp, "<---- Bytes IN:    %d", Byte_Received);
 //  Memo->Lines->Add(temp);
   DataForm->ProfileChart->LeftAxis->Automatic = false;
   DataForm->CORR1->Clear();
   DataForm->Profile->Clear();
   DataForm->CORR->Clear();
   DataForm->Profile->Active = false;
   DataForm->CORR->Active = false;

   //delete DataForm->Profile;
   //delete DataForm->CORR;
   //DataForm->Profile = new TFastLineSeries(DataForm);
   //DataForm->CORR = new TFastLineSeries(DataForm);

   for (int i = 0; i < DataForm->Samples - 8; i++)
   {
      DataForm->Profile->AddXY(i, DataForm->fi[i], "", clTeeColor);
      DataForm->CORR->AddXY(i, DataForm->ri[i], "", clTeeColor);
   }
   DataForm->Profile->Active = true;
   DataForm->CORR->Active = true;
   DataForm->ProfileChart->LeftAxis->Automatic = true;
   DataForm->Show();
   Toggle();

   //long memleft = coreleft();
   //long ileft = memleft;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::Send_Dummy()
{
   ULONG length;
   BULK_TRANSFER_CONTROL bulkControl;
   Command_Length = wsprintf (Command, "Dummy" );
   if (bOpenDriver (&hDevice, pcDriverName) != TRUE)
   {
      Memo->Lines->Add(" *****   Failed to Open Driver");
      hDevice = NULL;
   }
   if (hDevice != NULL)
   {
      bulkControl.pipeNum = 2;
      bResult = DeviceIoControl (hDevice,
         IOCTL_EZUSB_BULK_WRITE,
         &bulkControl,
         sizeof (BULK_TRANSFER_CONTROL),
         &Command[0],
         Command_Length,
         (unsigned long *)&nBytes,
         NULL);
      if(bResult == TRUE)
      {
         Memo->Lines->Add("----- USB OUT OK");
         if(m_Verbose) DumpBuffer(Command,nBytes);
      }  else Memo->Lines->Add(" ***** WRITE IOCTL failed in Send_Dummy");
    }
    CloseHandle (hDevice);
}

void __fastcall TMainForm::FPGA_OUTBtnClick(TObject *Sender)
{
   int iFileHandle, iFileLength;
   int len, byteleft, bytecopy;
   char *buffer = NULL;
   char *pdestbuffer;
   char *response;
   char temp[64]  = "";
   BULK_TRANSFER_CONTROL bulkControl;
   char FileName[64];
   AnsiString sFileName;
   AnsiString sExt;
   iFileHandle = FileOpen(m_strFPGAFileName, fmOpenRead);
   iFileLength = FileSeek(iFileHandle,0,2);
   FileSeek(iFileHandle,0,0);
//--------- command syntax: 16 characters, and list of numerical arguments
   Command_Length = wsprintf (Command, "FPGA_Load       %d", iFileLength );
   wsprintf(temp, "----> %s", Command);
   Memo->Lines->Add(temp);
   Send_Command();
   int transfer = 0;
   //if (memcmp((char *) Target_Response(), &Command[0], 16) == 0)  //Echo received
   {
      wsprintf (temp, "----- FPGA Ready to configure");
      Memo->Lines->Add(temp);
      if (bOpenDriver (&hDevice, pcDriverName) != TRUE)
      {
         Memo->Lines->Add(" *****   Failed to Open Driver in FPGA");
         hDevice = NULL;
      }
      if (hDevice != NULL)
      {
         Sleep(10);                      //Wait till controller jumps into FPGA function
         bulkControl.pipeNum = 6;         //OUT pipe for FPGA control
         byteleft  = iFileLength;
         while(byteleft > 0)
         {
            bytecopy = byteleft;
            if(bytecopy > 60000) bytecopy = 60000;     //Use transfer buffer of 60k
            buffer = (char *)malloc(bytecopy);
            FileRead(iFileHandle, buffer, bytecopy);

            Sleep(10);
            bResult = DeviceIoControl (hDevice,
               IOCTL_EZUSB_BULK_WRITE,
               &bulkControl,
               sizeof (BULK_TRANSFER_CONTROL),
               buffer,
               bytecopy,
               (unsigned long *)&nBytes,
               NULL);
            transfer ++;
            if(bResult == TRUE)
            {
               wsprintf (temp, "----- FPGA Write transfer  %d", transfer);
               Memo->Lines->Add(temp);
               if(m_Verbose) DumpBuffer(buffer,bytecopy);
            }  else
            {
               wsprintf (temp, " ***** FPGA Write IOCTL failed at %d transfer", transfer);
                Memo->Lines->Add(temp);
            }
            byteleft -= bytecopy;
            free(buffer);
         }
         CloseHandle (hDevice);
      }
      Memo->Lines->Add("===== FPGA Loaded");
      Memo->Lines->Add("");
   }
   FileClose(iFileHandle);
   // Need to upload the code          WHY???
   //Code_LoadBtnClick(NULL);
   Toggle();
   Send_Dummy();
   Toggle();
}

void __fastcall TMainForm::SEQ_Load()
{
   int iFileHandle, iFileLength;
   int len, byteleft, bytecopy;
   char *buffer = NULL;
   char *pdestbuffer;
   char *response;
   char temp[64]  = "";
   int iflash = 1;
   int flen;
   BULK_TRANSFER_CONTROL bulkControl;
   AnsiString operand;
   {
      DataForm->Samples = 0;
      iFileHandle = FileOpen(SeqFileName, fmOpenRead);
      iFileLength = FileSeek(iFileHandle,0,2);
      FileSeek(iFileHandle,0,0);
//--------- command syntax: 16 characters, and list of numerical arguments
      Command_Length = wsprintf (Command, "SEQU_Load       %d", iFileLength );
      wsprintf(temp, "----> %s", Command);
      Memo->Lines->Add(temp);
      Send_Command();
      //if (memcmp((char *) Target_Response(), &Command[0], 16) == 0)  //Echo received
      {
         wsprintf (temp, "----- Sequencer Ready to configure");
         Memo->Lines->Add(temp);
         if (bOpenDriver (&hDevice, pcDriverName) != TRUE)
         {
            Memo->Lines->Add(" *****   Failed to Open Driver");
            hDevice = NULL;
         }
         Sleep(1);
         if (hDevice != NULL)
         {
                                 //Wait for controller to jump in SEQB function
            bulkControl.pipeNum = 6;         //OUT pipe for Sequencer control
            byteleft  = iFileLength;
            while(byteleft > 0)
            {
               bytecopy = byteleft;
               if(bytecopy > 0xF000) bytecopy = 0xF000;     //Use transfer buffer of 60k
               buffer = (char *)malloc(bytecopy);
               FileRead(iFileHandle, buffer, bytecopy);
 //--- DEBUG for sequencer data------------------------
               DataForm->Samples = 212;
               int noseq = int(bytecopy/4);
               DataForm->SeqTime = 200;
               int presc = 0;
               int delay = 0;
               boolean prescalerON = false;
               for(int iseq = 0; iseq < noseq; iseq++)
               {
                  operand = "";
                  wsprintf(temp, "OP %5d", iseq);
                  operand += temp;
                  operand += ":  ";
                  unsigned char ib;
                  if((iseq > 0) && (iseq < noseq - 1))
                  {
                     ib = buffer[iseq * 4];
                     presc = (ib & 0x0c) >> 2;
                     flen = (ib & 0xf0) >> 4;
                     ib = buffer[iseq * 4 + 1];
                     flen += (ib & 0x0f) << 4;
                     delay = (ib & 0xf0) >> 4;
                     ib = buffer[iseq * 4 + 2];
                     delay += ib << 4;
                     ib = buffer[iseq * 4 + 3];
                     delay += ib << 12;
                     if(presc == 0) prescalerON = false;     //corrrection for the pulse stretch
                     if(prescalerON) flen ++;
                     if(presc > 0) prescalerON = true;

                     if ((!DataForm->AllSamples) && ((delay - flen) > 12))
                     {
                        if(iseq < noseq - 2)
                        {
                           buffer[iseq * 4] &= 0xfd;
                           DataForm->Samples += flen + 23;       //12 is the Extra Count No
                        }
                        else
                        {
                           DataForm->Samples += delay;
                           DataForm->Samples ++;
                        }
                     }
                     else
                     {
                        DataForm->Samples += delay;
                        DataForm->Samples ++;
                     }
                     if(presc == 0) DataForm->SeqTime += delay;
                     if(presc == 1) DataForm->SeqTime += delay * 64;
                     if(presc == 2) DataForm->SeqTime += delay * 64 * 64;
                     if(presc == 3) DataForm->SeqTime += delay * 64 * 64 * 64;
                     iflash ++;
                  }
                  ib = buffer[iseq * 4 + 3];
                  int cc = 128;
                  int is;
                  for(is = 0; is < 8; is ++)
                  {
                     if (ib >=cc)
                     {
                        operand += '1';
                        ib -= cc;
                     }
                     else operand += '0';
                     cc /= 2;
                  }
                  operand += ' ';
                  ib = buffer[iseq * 4 + 2];
                  cc = 128;
                  for(is = 0; is < 8; is ++)
                  {
                     if (ib >=cc)
                     {
                        operand += '1';
                        ib -= cc;
                     }
                     else operand += '0';
                     cc /= 2;
                  }
                  operand += ' ';
                  ib = buffer[iseq * 4 + 1];
                  cc = 128;
                  for(is = 0; is < 8; is ++)
                  {
                     if (ib >=cc)
                     {
                        operand += '1';
                        ib -= cc;
                     }
                     else operand += '0';
                     cc /= 2;
                  }
                  operand += ' ';
                  ib = buffer[iseq * 4];
                  cc = 128;
                  for(is = 0; is < 8; is ++)
                  {
                     if (ib >=cc)
                     {
                        operand += '1';
                        ib -= cc;
                     }
                     else operand += '0';
                     cc /= 2;
                  }
                  operand += ' ';
                  //Memo->Lines->Add(operand);
               }
               bResult = DeviceIoControl (hDevice,
                  IOCTL_EZUSB_BULK_WRITE,
                  &bulkControl,
                  sizeof (BULK_TRANSFER_CONTROL),
                  buffer,
                  bytecopy,
                  (unsigned long *)&nBytes,
                  NULL);
               if(bResult == TRUE)
               {
                  //Memo->Lines->Add("---- SEQUENCER Write IOCTL passed");
                  if(m_Verbose) DumpBuffer(buffer,bytecopy);
               }     else Memo->Lines->Add(" ***** Sequencer Write IOCTL failed");
               byteleft -= bytecopy;
               free(buffer);
            }
            CloseHandle (hDevice);
         }
         Memo->Lines->Add("===== Sequencer Loaded");
         Memo->Lines->Add("");
      }
      FileClose(iFileHandle);
   }
   Toggle();
   DataForm->Samples -= int(iflash * 0.2);
   //DataForm->nodata = iflash;
   //DataForm->Samples += 8;
   //if (DataForm->AllSamples) DataForm->Samples -= 8;
   //DataForm->Samples -= 4;
   DataForm->SeqTime *= 0.8 * 0.001 * 1.5;
   //else DataForm->Samples += 5;
}

void __fastcall TMainForm::SEQ_OUTBtnClick(TObject *Sender)
{
   AnsiString FileName, operand;
   OpenFileDlg->InitialDir = DataForm->CurrentDir;
   OpenFileDlg->InitialDir += "\\Protocols";
   OpenFileDlg->Filter = "Sequencer files (*.seq)|*.SEQ";
   if(OpenFileDlg->Execute())
   {
      SeqFileName = OpenFileDlg->FileName;
      SEQ_Load();
   }
   SEQ_Load();
}


/**************************************************
* bOpenDriver proc                               *
*                                                *
* Purpose:                                       *
*      Opens the device driver using symbolic    *
*      name provided                             *
*                                                *
* Input:                                         *
*      phDeviceHandle:                           *
*          Pointer to Device Driver handle where *
*          the file handle is placed.            *
*      devname:                                  *
*          Null terminated string containing the *
*          device name                           *
*                                                *
* Return Value:                                  *
*      Boolean that indicates if the driver was  *
*      successfully opened or not.               *
*                                                *
**************************************************/
BOOLEAN bOpenDriver (HANDLE * phDeviceHandle, PCHAR devname)
{
   char completeDeviceName[64] = "";
   //char pcMsg[64] = "";

   strcat (completeDeviceName,
      "\\\\.\\"
      );

   strcat (completeDeviceName,
		    devname
          );

   *phDeviceHandle = CreateFile(   completeDeviceName,
      GENERIC_WRITE,
      FILE_SHARE_WRITE,
      NULL,
      OPEN_EXISTING,
      0,
      NULL);

   if (*phDeviceHandle == INVALID_HANDLE_VALUE) {
      return (FALSE);
   } else {
      return (TRUE);
   } /*else*/


}//OpenDevice



//---------------------------------------------------------------------------

void TMainForm::Send_Command()
{
   ULONG length;
   BULK_TRANSFER_CONTROL bulkControl;
   bulkControl.pipeNum = 2;
   if (bOpenDriver (&hDevice, pcDriverName) != TRUE)
   {
      Memo->Lines->Add(" *****   Failed to Open Driver");
      hDevice = NULL;
   }
   if (hDevice != NULL)
   {
      bResult = DeviceIoControl (hDevice,
         IOCTL_EZUSB_BULK_WRITE,
         &bulkControl,
         sizeof (BULK_TRANSFER_CONTROL),
         &Command[0],
         Command_Length,
         (unsigned long *)&nBytes,
         NULL);
      if(bResult == TRUE)
      {
         if(m_Verbose) Memo->Lines->Add("===== WRITE IOCTL passed");
         if(m_Verbose) DumpBuffer(Command,nBytes);
      }  else Memo->Lines->Add(" ***** WRITE IOCTL failed in Send_Command");
    }
    CloseHandle (hDevice);
}

char *TMainForm::Target_Response()
{
   ULONG length;
   length = 64;
   BULK_TRANSFER_CONTROL bulkControl;
   char temp[64]  = "";
   char buffer[64]= "";

   if (bOpenDriver (&hDevice, pcDriverName) != TRUE)
   {
      Memo->Lines->Add(" *****   Failed Target response");
      hDevice = NULL;
   }
   bulkControl.pipeNum = 1;
   if (hDevice != NULL)
   {
      bResult = DeviceIoControl (hDevice,
         IOCTL_EZUSB_BULK_READ,
         &bulkControl,
         sizeof (BULK_TRANSFER_CONTROL),
         &buffer[0],
         length,
         (unsigned long *)&nBytes,
         NULL);
      if(bResult == TRUE)
      {
         if (m_Verbose) Memo->Lines->Add("===== READ IOCTL passed");
         wsprintf (temp, "<---- %s", buffer);
         Memo->Lines->Add(temp);
      }
      else
      {
         Memo->Lines->Add(" ***** READ Target Response Failed");
      }
   }
   CloseHandle (hDevice);
   return (&buffer[0]);
}

void __fastcall TMainForm::StopBtnClick(TObject *Sender)
{
   char temp[64]  = "";
   Command_Length = wsprintf (Command, "STOP Parser");
   wsprintf(temp, "----> %s", Command);
   Memo->Lines->Add(temp);
   Send_Command();
   if (memcmp((char *) Target_Response(), &Command[0], 8) == 0)  //Echo received
   {
      wsprintf (temp, "===== USB Parser terminated \n");
      Memo->Lines->Add(temp);
   }
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::FPGATESTBtnClick(TObject *Sender)
{
   char temp[64]  = "";
   Command_Length = wsprintf (Command, "FPGA_TEST");
   wsprintf(temp, "----> %s", Command);
   Memo->Lines->Add(temp);
   Send_Command();
   if (memcmp((char *) Target_Response(), &Command[0], 8) == 0)  //Echo received
   {
      wsprintf (temp, "===== Testing FPGA \n");
      Memo->Lines->Add(temp);
   }

}
//---------------------------------------------------------------------------

void __fastcall TMainForm::EXIT1Click(TObject *Sender)
{
   Close();
}
//---------------------------------------------------------------------------


void __fastcall TMainForm::Read_DataDlg_Click(TObject *Sender)
{
   DataForm->Show();
   DataForm->FitSheet->Show();
   DataForm->Read_Data_DlgClick(Sender);
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::Read_Results_DlgClick(TObject *Sender)
{
   DataForm->Show();
   DataForm->FitSheet->Show();
   DataForm->Read_Results_DlgClick(Sender);
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::GetProtocol1Click(TObject *Sender)
{
   DataForm->Show();
   DataForm->ProtocolSheet->Show();
   ProtocolForm->Get_Protocol();                                                    
}
//---------------------------------------------------------------------------





void __fastcall TMainForm::Exe_StartBtnClick(TObject *Sender)
{
   EXE_Start();
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::DAC_SelUpDownClick(TObject *Sender,
      TUDBtnType Button)
{
   char str[10];
   DACselect = DAC_SelUpDown->Position;
   itoa(DACselect, str,10);
   DACSelect->Caption = str;
   sprintf(str, "%4d",DAC[DACselect]);
   DACEd->SetTextBuf(str);
}
//---------------------------------------------------------------------------


void __fastcall TMainForm::DACEdChange(TObject *Sender)
{
   DAC[DACselect] = atoi(DACEd->Text.c_str());
   if(DAC[DACselect] > 8191) DAC[DACselect] = 8191;
   if(DAC[DACselect] <0) DAC[DACselect] = 0;
}
//---------------------------------------------------------------------------


void __fastcall TMainForm::FDAC_SelUpDownClick(TObject *Sender,
      TUDBtnType Button)
{
   char str[10];
   FDACselect = FDAC_SelUpDown->Position;
   itoa(FDACselect, str,10);
   FDACSelect->Caption = str;
   sprintf(str, "%4d",FDAC[FDACselect]);
   FDACEd->SetTextBuf(str);
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::FDACEdChange(TObject *Sender)
{
   FDAC[FDACselect] = atoi(FDACEd->Text.c_str());
   if(FDAC[FDACselect] > 255) FDAC[FDACselect] = 255;
   if(FDAC[FDACselect] <128) FDAC[FDACselect] = 128;
}
//---------------------------------------------------------------------------


