#include <utility.h>
#include <analysis.h>
#include <ansi_c.h>
#include <cvirte.h>		/* Needed if linking in external compiler; harmless otherwise */
#include <userint.h>
#include <stdio.h>
#include <string.h>
#include "MainWindow.h"
#include "PmcaCom.h"

/*------------------------------  NOTE --------------------------------------
	this code was initially written with the PMCA 8000 in Mind. A few Changes
	have to be made to get some features to work for the 8000A.
-----------------------------------------------------------------------------*/	


/*-- Global Variables -------------------------------------*/
int loopmax = 5;		/*-- # of times to retry Communication with PMCA --*/
int TempId = 0;			/*-- Note: 	Quick fix for Changing Connect to DisConnect and Vice Versa */
int TempId2 = 0;

int loadacqpanel = 0;
int McaConnected = 0;
int startacq = 0;

static int pref;  		/*-- loadpanel: Preference  --*/
static int mainwindow;	/*-- loadpanel: MainWindow  --*/
static int acqsetup;	/*-- loadpanel: AcqSetup    --*/
static int mcasetup;    /*-- loadpanel: McaSetup    --*/

PmcaDeviceType getdevice;

char datebuff[32];

int port;				/*-- Com Port ---*/
int rate;				/*-- Baud Rate --*/
int group;
int gain;

double	Datapoint[16384];/*-- Stores the Plot Points from file --*/
unsigned long Buffer[16384];   /*-- Stores the Plot Points from MCA  --*/

/*-- Updates the Preferences Panel -------------------------*/
int ComPort = 0;
int BaudRate = 0;

/*-- Updates the Acquisition Model -------------------------*/
int	SelectTimerIndex = 0;
int SelectGroup = 0;
int SetPreset = 0;

int SetPeakModeIndex = 0;
short SetThreshold = 2;
int SetGain = 0;

/*-- Updates The Mca Setup Panel ---------------------------*/
int batteryindex = 0;
int lock = 0;
/*----------------------------------------------------------*/

int main (int argc, char *argv[])
{
	int status;
	
	if (InitCVIRTE (0, argv, 0) == 0)	/* Needed if linking in external compiler; harmless otherwise */
		return -1;	/* out of memory */
	if ((mainwindow = LoadPanel (0, "MainWindow.uir", MainWindow)) < 0)
		return -1;
	DisplayPanel (mainwindow);
	RunUserInterface ();
	
	return 0;
}

void CVICALLBACK Shutdown (int menuBar, int menuItem, void *callbackData,
		int panel)
{
	int status;
	
	status = PmcaDisconnect();
	/*-- Delay Loop --*/
	Delay (1); 
	
	status = PmcaTerminateCom();	/*-- Terminates all Communication Threads --*/
	
	/*-- Delay Loop --*/
	Delay (2); 
	
	/*-- CLose the Screen and Exit Program --*/
	QuitUserInterface (0);
}

void CVICALLBACK OpenFile (int menuBar, int menuItem, void *callbackData,
		int panel)
{
	int index2;
    int plothandle2;
    double x,y;

	double NUM;
	
	int find  = 48;
	int find1 = 49;
	int find2 = 50; 
	int find3 = 51; 
	int find4 = 52; 
	int find5 = 53; 
	
	int plothandle = -1;	/*-- -1 deletes all plots in the graph --*/
	
	static int min_index;
	static double MinRange;
	static int max_index;
	static double MaxRange;
	
	char *found = NULL; 
	char *Compare = NULL;
	char *Compare2 = NULL;
	char *Compare3 = NULL;
	char *Compare4 = NULL;
	char *Compare5 = NULL;
	char *Compare6 = NULL;

	int index = 0;
	char ReadData[40];
	char PlotData[40];
	
	char gainstring1[] = "GAIN - 256";
	char gainstring2[] = "GAIN - 512";
	char gainstring3[] = "GAIN - 1024";
	char gainstring4[] = "GAIN - 2048";
	char gainstring5[] = "GAIN - 4096";
	char gainstring6[] = "GAIN - 8192";
	
	char CompareString1[] = "<<DATA>>";
	char CompareString2[] = "GAIN";
	char CompareString3[] = "<<END>>";
	char CompareString4[] = "PRESET";
	char CompareString5[] = "REAL_TIME";
	char CompareString6[] = "LIVE_TIME";
	char CompareString7[] = "START_TIME";	
	
	/*-- Variables for Opening the Selected File ----------*/
	int	FileOpenError;
	char FileOpenPath_Name[MAX_PATHNAME_LEN + 1];
	FILE *filehandler;  	

	/*-- Select File---------------------------------------*/
	FileOpenError = FileSelectPopup ("", "*.mca",
									 "*.mca;*.asc;*.asp", "Open",
									 VAL_LOAD_BUTTON, 0, 0, 1, 1,
									 FileOpenPath_Name);
	/*-- Refresh Graph ------------------------------------*/
	DeleteGraphPlot (mainwindow, MainWindow_GRAPH, plothandle,
					 VAL_IMMEDIATE_DRAW);
	
	/*-- Reads Plot data from .mca file -------------------*/
	if ( (filehandler = fopen (FileOpenPath_Name, "r")) != NULL)
	{
		/*-- Scan the .mca file ---------------------------*/
		while (Compare == NULL)
			{
				fgets(ReadData,40,filehandler);

				/*-- Look for PRESET -----*/
				Compare3 = strstr (ReadData, CompareString4);				
				if (Compare3 != NULL)
					SetCtrlAttribute (mainwindow, MainWindow_Preset, ATTR_CTRL_VAL, ReadData);

				/*-- Look for REAL_TIME --*/
				Compare4 = strstr (ReadData, CompareString5);				
				if (Compare4 != NULL)
					SetCtrlAttribute (mainwindow, MainWindow_Real_Time, ATTR_CTRL_VAL, ReadData);

				/*-- Look for LIVE_TIME --*/
				Compare5 = strstr (ReadData, CompareString6);				
				if (Compare5 != NULL)
					SetCtrlAttribute (mainwindow, MainWindow_Live_Time, ATTR_CTRL_VAL, ReadData);

				/*-- Look for START_TIME --*/
				Compare6 = strstr (ReadData, CompareString7);				
				if (Compare6 != NULL)
					SetCtrlAttribute (mainwindow, MainWindow_Start_Time, ATTR_CTRL_VAL, ReadData);						
					
				/*-- Look for <<DATA>> --*/
				Compare = strstr (ReadData, CompareString1);
				
				/*-- Look for GAIN ------*/
				Compare2 = strstr (ReadData, CompareString2);
				if (Compare2 != NULL)
				{	/* --- if --- */
					
					/*-- Find the Gain Setting --*/
					found = strchr (ReadData, find);
					if (found != NULL)
						{
							NUM = 256;
							/*-- Display the Gain on the panel --*/
							SetCtrlAttribute (mainwindow, MainWindow_Gain, ATTR_CTRL_VAL, gainstring1);							
						}							
					else
						{	/* --- 1 --- */
							found = strchr (ReadData, find1);  
							if (found != NULL)
							{
								NUM = 512;	
								/*-- Display the Gain on the panel --*/
								SetCtrlAttribute (mainwindow, MainWindow_Gain, ATTR_CTRL_VAL, gainstring2);	
							}								
							else
								{	/* --- 2 --- */ 
									found = strchr (ReadData, find2);
									if (found != NULL)
									{
										NUM = 1024;
										/*-- Display the Gain on the panel --*/
										SetCtrlAttribute (mainwindow, MainWindow_Gain, ATTR_CTRL_VAL, gainstring3);	
									}	
									else
										{	/* --- 3 --- */ 
											found = strchr (ReadData, find3);
											if (found != NULL)
											{
												NUM = 2048;
												/*-- Display the Gain on the panel --*/
												SetCtrlAttribute (mainwindow, MainWindow_Gain, ATTR_CTRL_VAL, gainstring4);	
											}	
												
											else
												{	/* --- 4 --- */ 
													found = strchr (ReadData, find4);
													if (found != NULL)
													{
														NUM = 4096;
														/*-- Display the Gain on the panel --*/
														SetCtrlAttribute (mainwindow, MainWindow_Gain, ATTR_CTRL_VAL, gainstring5);	
													}														
													else
														{	/* --- 5 --- */ 
															found = strchr (ReadData, find5);
															if (found != NULL)
															{
																NUM = 8192;
																/*-- Display the Gain on the panel --*/
																SetCtrlAttribute (mainwindow, MainWindow_Gain, ATTR_CTRL_VAL, gainstring6);	
															}																
														}	/* --- 5 --- */ 	
												}	/* --- 4 --- */ 
										}	/* --- 3 --- */ 							
								}	/* --- 2 --- */ 										
						}	/* --- 1 --- */ 										
					
					}	/* --- if --- */  
			}

		/* Scan the .mca file to obtain the plot points ---*/
		Compare = NULL;

		while (Compare == NULL)
			{
				fgets(PlotData,40,filehandler);
				Compare = strstr (PlotData, CompareString3);
				
				if (Compare == NULL)
					{					
						Datapoint[index] = atof (PlotData);
						index = index + 1;
					}						
			}			
			
							
		fclose(filehandler);
		
	/* --- Plot the Datapoints -----------------------------*/
	PlotY (mainwindow, MainWindow_GRAPH, Datapoint, NUM,
		   VAL_DOUBLE, VAL_VERTICAL_BAR, VAL_SIMPLE_DOT, VAL_SOLID,
		   1, VAL_RED);
	
	/* --- Determine the Maximum Count ---------------------*/
	MaxMin1D (Datapoint, NUM, &MaxRange, &max_index, &MinRange,
			  &min_index);
			  
	/* -- Display the Max and Min --------------------------*/
	SetCtrlVal (mainwindow, MainWindow_NUMERIC_4, MinRange);
	SetCtrlVal (mainwindow, MainWindow_NUMERIC_3, MaxRange); 
	SetCtrlVal (mainwindow, MainWindow_NUMERIC_2, NUM);
	
	/* -- Set the Cursor Value -----------------------------*/
    GetGraphCursor (mainwindow, MainWindow_GRAPH, 1, &x, &y);
    GetGraphCursorIndex (mainwindow, MainWindow_GRAPH, 1, &plothandle2, &index2);
    SetCtrlVal (mainwindow, MainWindow_NUMERIC_5, x);
    SetCtrlVal (mainwindow, MainWindow_NUMERIC_6, Datapoint[index2]);
        
	}
	
}

	/* -- Displays a About PMCA Pop-Up window --------------*/
void CVICALLBACK AboutPMCA (int menuBar, int menuItem, void *callbackData,
		int panel)
{
	MessagePopup ("About PMCA",
				  "                    PMCA Version 1.0                         \n\n                    Copyright Amptek(C) 1998                         \n\n                    PMCA 8000");  
}
	/* -- Displays current cursor Position ----------------*/
int CVICALLBACK UpDateMarker(int panel, int control, int event,
							void *callbackData, int eventData1, int eventData2)
{
    double x,y;
    int plothandle, index;

    if ((event == EVENT_LEFT_CLICK) || (event == EVENT_COMMIT) || (event == EVENT_GOT_FOCUS)) 
    {
        GetGraphCursor (mainwindow, MainWindow_GRAPH, 1, &x, &y);
        GetGraphCursorIndex (mainwindow, MainWindow_GRAPH, 1, &plothandle, &index);
        
        SetCtrlVal (mainwindow, MainWindow_NUMERIC_5, x);
		
		if (index != -1)
        {        		
        	SetCtrlVal (mainwindow, MainWindow_NUMERIC_6, Datapoint[index]);
		}        		
    }
    return(0);
}

	/* -- Setup preferences for the PMCA -----------------*/
void CVICALLBACK SetPref (int menuBar, int menuItem, void *callbackData,
		int panel)
{
	
	int status;
	/*--- Displays Preference Panel ---------------------------------------*/
	pref = LoadPanel (mainwindow, "MainWindow.uir", Preference);
	
	/*-- Set current ComPort display --*/
	status = SetCtrlIndex (pref, Preference_RING, ComPort);
			
	/*-- Set current BaudRate display --*/
	status = SetCtrlIndex (pref, Preference_RING_2, BaudRate);
	
	DisplayPanel (pref);
	/*---------------------------------------------------------------------*/
}

/*	NOTE: You cannot use the .lib file created in Microsoft Visual C/C++. You
	have to use/create a .lib that is compatible with LabWindows. This is how
	you do it:
	
	1. Add the header file PmcaCom.h to your project.
	2. Open the header file.
	3. Go to Options, then select Generate DLL import library.
	4. Select PmcaDll.Dll
*/

void CVICALLBACK Connect (int menuBar, int menuItem, void *callbackData,
		int panel)
{
	/*--- Power on and connect to PMCA ------------------------------------*/
    int count;
    int stat;
    int DisConId; /*-- New Menu Item ID for the DisConnect Control Added --*/
    
    int On_Off = 0;
    int menubarhandle;
    
    char menuname[]= "DisConnected";
    char message[] = "CONNECTED";
    
 	
    stat = PmcaPowerUp(port); /*-- Powers Up the MCA --*/
    
    for (count = 0; count < loopmax; count++)
    {
    	stat = PmcaConnect(port, rate, PMCA_AUTO_DETECT);
    	
    	if (stat == 0)
    	{
    		On_Off = 1; /*-- Turn On LED --*/
    		
    		/*-- Turn on the Connected LED --*/
    		SetCtrlVal (mainwindow, MainWindow_LED, On_Off);
    		/*-- Displays Current Connected Status --*/
			SetCtrlVal (mainwindow, MainWindow_DisCon_Con, message);
			/*-- Gets the Menu Bar Handle --*/
			menubarhandle = GetPanelMenuBar (mainwindow);
			/*-- Discards the Connect in the menu Bar --*/
			if (TempId == 0)
				DiscardMenuItem (menubarhandle, MainMenu_Mca_Connect); 
			else
				DiscardMenuItem (menubarhandle, TempId); 
			/*-- Adds the Connect to the MenuList ---------*/
			/* DisConId = NewMenuItem (menubarhandle, MainMenu_Mca,"DisConnect", MainMenu_Mca_Sprator7, 0, 
							DisConnect, 0);

			/*-- UnDim the Menu Bar items --*/
			SetMenuBarAttribute (menubarhandle, MainMenu_Mca_AcqSetup, ATTR_DIMMED, 0);
			SetMenuBarAttribute (menubarhandle, MainMenu_Mca_StartAcq, ATTR_DIMMED, 0);
			SetMenuBarAttribute (menubarhandle, MainMenu_Mca_ResTime, ATTR_DIMMED, 0);
			SetMenuBarAttribute (menubarhandle, MainMenu_Mca_McaSet, ATTR_DIMMED, 0);
		
			/*-- UnDim the Command Buttons on the MainWindow Panel --*/
			SetCtrlAttribute (mainwindow, MainWindow_COMMANDBUTTON_5, ATTR_DIMMED, 0); 
			SetCtrlAttribute (mainwindow, MainWindow_COMMANDBUTTON_4, ATTR_DIMMED, 0);  
			SetCtrlAttribute (mainwindow, MainWindow_COMMANDBUTTON_7, ATTR_DIMMED, 0);  
			SetCtrlAttribute (mainwindow, MainWindow_COMMANDBUTTON_6, ATTR_DIMMED, 0);  
			SetCtrlAttribute (mainwindow, MainWindow_RINGSLIDE, ATTR_DIMMED, 0);
			SetCtrlAttribute (mainwindow, MainWindow_UPDATEPLOT, ATTR_DIMMED, 0); 
			/*----------------------------------------------------------------------------*/
			
			TempId = DisConId;
			
			McaConnected = 1;
			
			break;
		}    	

	}		
	
	if (stat !=0)
	{
		MessagePopup ("Connect to MCA", "Cannot Connect to MCA");
	}
	
	return;
}

void CVICALLBACK DisConnect (int menuBar, int menuItem, void *callbackData,
		int panel)
{
	int On_Off;
	
	int status;
	int delay;
	int response;
	int menubarhandle;
	int DisConId;

	char message[] = "disconnected";
	
	response = ConfirmPopup ("DisConnect from MCA",
							 "You are about to DisConnect from the MCA: Are you sure?");
	
	if (response == 1)
	{
		status = PmcaDisconnect();
		/*-- Delay Loop --*/
		Delay (2);
	
		status = PmcaTerminateCom();	/*-- Terminates all Communication Threads --*/
	
		/*-- Delay Loop --*/
		Delay (2); 
	
		On_Off = 0; /*-- Turn Off LED --*/
		
		/*-- Turn on the Connected LED --*/
    	SetCtrlVal (mainwindow, MainWindow_LED, On_Off);
    	/*-- Displays Current Connected Status --*/
		SetCtrlVal (mainwindow, MainWindow_DisCon_Con, message);
		/*-- Gets the Menu Bar Handle --*/
		menubarhandle = GetPanelMenuBar (mainwindow);
		/*-- Discards the DisConnect in the menu Bar --*/
		DiscardMenuItem (menubarhandle, TempId); 
		/*-- Adds the Connect to the MenuList ---------*/
		DisConId = NewMenuItem (menubarhandle, MainMenu_Mca,"Connect", MainMenu_Mca_Sprator7, 0,
					Connect, 0);

		/*-- Dim the Menu Bar items --*/
			SetMenuBarAttribute (menubarhandle, MainMenu_Mca_AcqSetup, ATTR_DIMMED, 1);
			SetMenuBarAttribute (menubarhandle, TempId2, ATTR_DIMMED, 1);
			SetMenuBarAttribute (menubarhandle, MainMenu_Mca_ResTime, ATTR_DIMMED, 1);
			SetMenuBarAttribute (menubarhandle, MainMenu_Mca_McaSet, ATTR_DIMMED, 1);
			
		/*-- UnDim the Command Buttons on the MainWindow Panel --*/
		/*-- UnDim the Command Buttons on the MainWindow Panel --*/
			SetCtrlAttribute (mainwindow, MainWindow_COMMANDBUTTON_5, ATTR_DIMMED, 1); 
			SetCtrlAttribute (mainwindow, MainWindow_COMMANDBUTTON_4, ATTR_DIMMED, 1);  
			SetCtrlAttribute (mainwindow, MainWindow_COMMANDBUTTON_7, ATTR_DIMMED, 1);  
			SetCtrlAttribute (mainwindow, MainWindow_COMMANDBUTTON_6, ATTR_DIMMED, 1);  
			SetCtrlAttribute (mainwindow, MainWindow_RINGSLIDE, ATTR_DIMMED, 1);
			SetCtrlAttribute (mainwindow, MainWindow_UPDATEPLOT, ATTR_DIMMED, 1); 
		/*----------------------------------------------------------------------------*/
			
		TempId = DisConId;							
		
		McaConnected = 0;
	}
	
	return;
}

int CVICALLBACK SetPreference (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	int status;
	int panelstatus;
	
	/*-- Pointers to store the Value of a Control ---------*/
	int *index;
	int Newindex;
	
	int *index2;
	int Newindex2;
	
	double *getnumeric;
	double Newnumeric;
	
	index = &Newindex;
	index2 = &Newindex2;
	
	getnumeric = &Newnumeric;
	/*-----------------------------------------------------*/

	switch (event)
		{
		case EVENT_COMMIT:
			/*-- Get the Com Port selected from the Com Port Drop Box ----*/
			status = GetCtrlIndex (pref, Preference_RING, index);
			
			if (*index == 0)
				port = 1;

			if (*index == 1)
				port = 2;

			if (*index == 2)
				port = 3;
				
			if (*index == 3)
				port = 4;
			
			/*-- Store current ComPort for future display --*/
			ComPort = *index;			

			/*-- Get the Baud Rate selected from the Baud Rate Drop Box ----*/
			status = GetCtrlIndex (pref, Preference_RING_2, index2); 

			if (*index2 == 0)
				rate = 9600;

			if (*index2 == 1)
				rate = 19200;

			if (*index2 == 2)
				rate = 38400;
				
			if (*index2 == 3)
				rate = 57600;

			if (*index2 == 4)
				rate = 115200;

			/*-- Store current BaudRate for future display --*/
			BaudRate = *index2;				
			
			/*-- Close the Panel --------------------------------------------*/
			panelstatus = DiscardPanel (pref);
			
			
			break;
		}
	return 0;
}

int CVICALLBACK Cancel (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	int status;
	int panelstatus;
	
	switch (event)
		{
		case EVENT_COMMIT:
			/*-- Set current ComPort display --*/
			status = SetCtrlIndex (pref, Preference_RING, ComPort);
			
			/*-- Set current BaudRate display --*/
			status = SetCtrlIndex (pref, Preference_RING_2, BaudRate);
	
			/*-- Discard the Preference Panel -----------------------*/
			panelstatus = DiscardPanel (pref); 
			break;
		}
	return 0;
}

void CVICALLBACK PrintScreen (int menuBar, int menuItem, void *callbackData,
		int panel)
{
	int printstatus;
	MessagePopup ("IMPORTANT: PRINT WARNING",
				  "ALWAYS SELECT BIT MAP PRINTING");
	
	printstatus = PrintPanel (mainwindow, "", 1, VAL_VISIBLE_AREA,
							  1);
	
}

int CVICALLBACK DevType (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	char stdmessage[]  = "                 PMCA_8000";  
	char stdmessage2[] = "                PMCA_8000A";
	char stdmessage3[] = "              PMCA_AUTO_DETECT";
	
	switch (event)
		{
		case EVENT_COMMIT:
			/*-- Get the PMCA Device Type ------*/
			getdevice = PmcaGetDeviceType();
			
			/*-- Display the PMCA Device Type --*/
			if (getdevice == PMCA_8000)
			{
				MessagePopup ("PMCA DEVICE TYPE", stdmessage);
			}
			
			if (getdevice == PMCA_8000A)
			{
				MessagePopup ("PMCA DEVICE TYPE", stdmessage2); 
			}

			if (getdevice == PMCA_AUTO_DETECT)
			{
				MessagePopup ("PMCA DEVICE TYPE", stdmessage3); 
			}
			
			break;
		}
	return 0;
}

int CVICALLBACK GetBatInfo (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	int status;
	
	char stdmessage[]  = "                     ALKALINE";  
	char stdmessage2[] = "                       NiCD";
	char stdmessage3[] = "                      ERROR";
	
	char stdmessage4[]  = "-------------------------- OK -----------------------";  
	char stdmessage5[] =  "------------------------- BAD -----------------------";
	char stdmessage6[] =  "------------------------ ERROR ----------------------";
	
	
	
	switch (event)
		{
		case EVENT_COMMIT:
			/*-- Get PMCA Battery Type --*/
			status = PmcaGetBatteryType();
			while (status < 0)
			{
				status = PmcaGetBatteryType();
				
			}
			
			if (status == 0)
				{
					MessagePopup ("PMCA BATTERY TYPE", stdmessage);
				}
			else
				if (status == 1)
				{
					MessagePopup ("PMCA BATTERY TYPE", stdmessage2);
				}
			else
					MessagePopup ("PMCA BATTERY TYPE", stdmessage3);  
			
			/*-- Get PMCA Battery Condition --*/
			status = PmcaGetBatteryCondition();
			while (status < 0)
			{
				status = PmcaGetBatteryCondition(); 
			}				
			
			/*---------------------------------*/
			
			if (status == 0)
				{
					MessagePopup ("PMCA BATTERY CONDITION", stdmessage4);
				}
			else
				if (status == 1)
				{
					MessagePopup ("PMCA BATTERY CONDITION", stdmessage5);
				}
			else
					MessagePopup ("PMCA BATTERY CONDITION", stdmessage6);  			
			
			
			/*-- Get PMCA Battery Capacity --*/
			status = PmcaGetBatteryCapacity();
			while (status < 0)
			{
				status = PmcaGetBatteryCapacity();
			}
			
			/*---------------------------------*/
			
			if (status >= 0)
			{
				if	(status <= 100)
					{
						if (status <= 25)
						{
							SetCtrlAttribute (mainwindow, MainWindow_RINGSLIDE,
											  ATTR_CTRL_INDEX, 1);
							
						}
						else
						if ((status > 25) && (status <=50))
						{
							SetCtrlAttribute (mainwindow, MainWindow_RINGSLIDE,
											  ATTR_CTRL_INDEX, 2);
						}
						else
						if ((status > 50) && (status <=75))
						{
							SetCtrlAttribute (mainwindow, MainWindow_RINGSLIDE,
											  ATTR_CTRL_INDEX, 3);				
						}
						else
							SetCtrlAttribute (mainwindow, MainWindow_RINGSLIDE,
											  ATTR_CTRL_INDEX, 4);						
					
					}
				else
					MessagePopup ("PMCA BATTERY CAPACITY", "-------------------- EXTERNAL POWER --------------------");
			
			}
			else
				MessagePopup ("PMCA BATTERY CAPACITY", "------------------------ ERROR ----------------------");				
										
			break;
		}
	return 0;
}

int CVICALLBACK Clear (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	int status;
	
	switch (event)
		{
		case EVENT_COMMIT:
			MessagePopup ("CLEAR DATA AND TIME", "          Clearing Data and time");
			
			status = PmcaClearDataAndTime(); 
			while (status < 0)
			{
				status = PmcaClearDataAndTime(); 
			}				
			break;
		}
	return 0;
}

int CVICALLBACK GetDateTime (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	int status;
	
	switch (event)
		{
		case EVENT_COMMIT:
			if (getdevice == PMCA_8000A)
			{
				status = PmcaGetDateAndTime(datebuff);
				
				while (status < 0)
				{
					status = PmcaGetDateAndTime(datebuff); 
				}		
				
				MessagePopup ("GET DATE AND TIME", datebuff);
			}
			else
				MessagePopup ("GET DATE AND TIME", "This is a PMCA 8000: NO DATE AND TIME STAMP");
								
			break;
		}
	return 0;
}

void CVICALLBACK AcqSetup (int menuBar, int menuItem, void *callbackData,
		int panel)
{
		
	/*--- Displays Acquisition Setup Panel ---------------------------------------*/
	acqsetup = LoadPanel (mainwindow, "MainWindow.uir", AcqMode);
	
	if (getdevice == PMCA_8000A)
	{
	/*-- UnDim Group if PMCA Device Type is 8000A -------*/
	SetCtrlAttribute (acqsetup, AcqMode_RING, ATTR_DIMMED, 0);
	}
	
	/*-- Set current Select Timer display ---------------*/
	SetCtrlIndex (acqsetup, AcqMode_RING_3, SelectTimerIndex);

	/*-- Set current Set Peak Mode Timer display --------*/
	SetCtrlIndex (acqsetup, AcqMode_RING_4, SetPeakModeIndex);

	/*-- Set current Select Select Group display --*/
	SetCtrlIndex (acqsetup, AcqMode_RING, SelectGroup);
	
	/*-- Set current Select Select Gain display --*/
	SetCtrlIndex (acqsetup, AcqMode_RING_2, SetGain);	

	/*-- Set current Select Set Threshold display --*/
	SetCtrlAttribute (acqsetup, AcqMode_NUMERIC_2, ATTR_CTRL_VAL, SetThreshold);
	
	/*-- Set current Select Set Preset display --*/
	SetCtrlAttribute (acqsetup, AcqMode_NUMERIC, ATTR_CTRL_VAL, SetPreset);	
	
	DisplayPanel (acqsetup);
}

int CVICALLBACK AcqCancel (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	int panelstatus;
	
	switch (event)
		{
		case EVENT_COMMIT:
		
		/*-- Set current Select Timer display ---------------*/
		SetCtrlIndex (acqsetup, AcqMode_RING_3, SelectTimerIndex);

		/*-- Set current Set Peak Mode Timer display --------*/
		SetCtrlIndex (acqsetup, AcqMode_RING_4, SetPeakModeIndex);

		/*-- Set current Select Select Group display --*/
		SetCtrlIndex (acqsetup, AcqMode_RING, SelectGroup);
	
		/*-- Set current Select Select Gain display --*/
		SetCtrlIndex (acqsetup, AcqMode_RING_2, SetGain);	

		/*-- Set current Select Set Threshold display --*/
		SetCtrlAttribute (acqsetup, AcqMode_NUMERIC_2, ATTR_CTRL_VAL, SetThreshold);
	
		/*-- Set current Select Set Preset display --*/
		SetCtrlAttribute (acqsetup, AcqMode_NUMERIC, ATTR_CTRL_VAL, SetPreset);	

		panelstatus = DiscardPanel (acqsetup);
			break;
		}
	return 0;
}

int CVICALLBACK AcqOk (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	int status;
	int *temporary;
	int initialize;
	int panelstatus;
	
	temporary = &initialize;
	
	switch (event)
		{
		case EVENT_COMMIT:
		
		loadacqpanel = 1;
		
		/*-- Set current Select Timer display -------*/
		GetCtrlIndex (acqsetup, AcqMode_RING_3, temporary );
		SelectTimerIndex = *temporary;

		if (SelectTimerIndex == 0) /*-- Real --*/
		{
			status = PmcaSelectRealTimer();
			
			while (status != 0)
			{
				status = PmcaSelectRealTimer();
			}
		}
		else						/*-- Live --*/
		{
			status = PmcaSelectLiveTimer();
			
			while (status != 0)
			{
				status = PmcaSelectLiveTimer();
			}
		
		}
		
		/*-- Set current Set First Peak Mode Timer display --*/
		GetCtrlIndex (acqsetup, AcqMode_RING_4, temporary);
		SetPeakModeIndex = *temporary;

		if (SetPeakModeIndex == 0) /*-- First --*/
		{
			status = PmcaSetFirstPeakMode();
			
			while (status != 0)
			{
				status = PmcaSetFirstPeakMode();
			}
		}
		else						/*-- Live --*/
		{
			status = PmcaSetAbsolutePeakMode();
			
			while (status != 0)
			{
				status = PmcaSetAbsolutePeakMode();
			}
		
		}
		
		/*-- Set current Select Select Group display --*/
		GetCtrlIndex (acqsetup, AcqMode_RING, temporary);
		SelectGroup = *temporary;
		group = *temporary;
	
		if (getdevice == PMCA_8000A)
		{
			status = PmcaSetGroup(group);
			
			while (status != 0)
			{
				status = PmcaSetGroup(group);
			}
		}			
		
		/*-- Set current Select Select Gain display --*/
		GetCtrlIndex (acqsetup, AcqMode_RING_2, temporary);
		SetGain = *temporary;
		
		if (*temporary == 0)
			gain = 256;
		else
		if (*temporary == 1)
			gain = 512;
		else
		if (*temporary == 2)
			gain = 1024;
		else
		if (*temporary == 3)
			gain = 2048;
		else
		if (*temporary == 4)
			gain = 4096;
		else
			gain = 8192;


		status = PmcaSetGain(gain);
		
		while (status != 0)
		{
			status = PmcaSetGain(gain);  
		}
		
		/*-- Set current Select Set Threshold display --*/
		GetCtrlVal (acqsetup, AcqMode_NUMERIC_2, temporary);
		SetThreshold = *temporary;
	
		status = PmcaSetThreshold(SetThreshold);
		
		while (status != 0)
		{
			status = PmcaSetThreshold(SetThreshold);
		}			
		
		/*-- Set current Select Set Preset display --*/
		GetCtrlVal (acqsetup, AcqMode_NUMERIC, temporary);
		SetPreset = *temporary;	
	
		status = PmcaSetAcquisitionTime(SetPreset);
		
		while (status != 0)
		{
			status = PmcaSetAcquisitionTime(SetPreset);
		}	
		
		panelstatus = DiscardPanel (acqsetup);			
			
			break;

		}
		
	return 0;
}

void CVICALLBACK McaSet (int menuBar, int menuItem, void *callbackData,
		int panel)
{
	/*--- Displays Acquisition Setup Panel ---------------------------------------*/
	mcasetup = LoadPanel (mainwindow, "MainWindow.uir", McaSetup);
	
	/*-- Set current Battery display ---------------*/
	SetCtrlIndex (mcasetup, McaSetup_RING_2, batteryindex);

	/*-- Set current Select Set Preset display --*/
	SetCtrlAttribute (mcasetup, McaSetup_NUMERIC, ATTR_CTRL_VAL, lock);	
	
	DisplayPanel (mcasetup);
}

int CVICALLBACK McaOk (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	int status;
	int *temporary;
	int initialize;
	int panelstatus;
	
	PmcaBatteryType pmcabattery; 
	
	temporary = &initialize;
	
	switch (event)
		{
		case EVENT_COMMIT:
		GetCtrlIndex (mcasetup, McaSetup_RING_2, temporary);
		batteryindex = *temporary;
		
		if (*temporary == 1)
			pmcabattery = PMCA_LI;
		else
		if (*temporary == 2)
			pmcabattery == PMCA_NICAD;
		
		if (*temporary != 0)
			{
				status = PmcaSetBatteryType(pmcabattery);
			
				while (status != 0)
				{
					status = PmcaSetBatteryType(pmcabattery);
				}
			
			}

		/*-- Set the Lock --------------------------------*/
		GetCtrlVal (acqsetup, McaSetup_NUMERIC, temporary);
		lock = *temporary;	
	
		status = PmcaSetLock(lock);
			
				while (status != 0)
				{
					status = PmcaSetLock(lock);
				}
	
			panelstatus = DiscardPanel (mcasetup);
			
			break;
		}
	
	return 0;
}

int CVICALLBACK McaCancel (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	int panelstatus;
	
	switch (event)
		{
		case EVENT_COMMIT:
			/*-- Set current Battery display ---------------*/
			SetCtrlIndex (mcasetup, McaSetup_RING_2, batteryindex);

			/*-- Set current Select Set Preset display --*/
			SetCtrlAttribute (mcasetup, McaSetup_NUMERIC, ATTR_CTRL_VAL, lock);	
	
			panelstatus = DiscardPanel (mcasetup);
			
			break;
		}
	return 0;
}

void CVICALLBACK StopAcq (int menuBar, int menuItem, void *callbackData,
		int panel)
{
	int count;
	int status;
	int StopAcqId;
	int menubarhandle;

	status = PmcaStopAcquisition();
	
	while (status != 0)
	{
		status = PmcaStopAcquisition();
	}
	
	/*-- Gets the Menu Bar Handle --*/
	menubarhandle = GetPanelMenuBar (mainwindow);
	
	/*-- Discards the Stop Acquisition in the menu Bar --*/
	DiscardMenuItem (menubarhandle, TempId2); 
	
	/*-- Adds the Connect to the MenuList ---------*/
	StopAcqId = NewMenuItem (menubarhandle, MainMenu_Mca,"Start Acquisition", MainMenu_Mca_Sprator5, 0,
					StartAcq, 0);
	
	TempId2 = StopAcqId;						
	
	/*-- Get Data from the MCA --------------------------*/
	status = PmcaGetData(Buffer, 0, gain);
	
	/*-- Clear Graph ------------------------------------*/
	DeleteGraphPlot (mainwindow, MainWindow_GRAPH, -1,
					 VAL_IMMEDIATE_DRAW);
	
	for (count = 0; count <= gain; count++)
		{
			Datapoint[count] = Buffer[count];	
		}
	
	PlotY (mainwindow, MainWindow_GRAPH, Datapoint, gain, VAL_DOUBLE, VAL_VERTICAL_BAR, VAL_SIMPLE_DOT, VAL_SOLID,
		   1, VAL_RED);
}

void CVICALLBACK StartAcq (int menuBar, int menuItem, void *callbackData,
		int panel)
{
	int status;
	int count;
	
	int StopAcqId;
	int menubarhandle;
	
	/*-- Display GAIN --*/
	//status =  PmcaGetGain();
	
	//SetCtrlAttribute (mainwindow, MainWindow_Gain, ATTR_CTRL_VAL, status);
					
	/*-- Display PRESET -----*/
	//SetCtrlAttribute (mainwindow, MainWindow_Preset, ATTR_CTRL_VAL, ReadData);
	
	/*-- Display REAL_TIME --*/
	//SetCtrlAttribute (mainwindow, MainWindow_Real_Time, ATTR_CTRL_VAL, ReadData);
	/*-- Display REAL_TIME --*/
	//SetCtrlAttribute (mainwindow, MainWindow_Real_Time, ATTR_CTRL_VAL, ReadData);

	/*-- Look for LIVE_TIME --*/
	//SetCtrlAttribute (mainwindow, MainWindow_Live_Time, ATTR_CTRL_VAL, ReadData);

	/*-- Look for START_TIME --*/
	//SetCtrlAttribute (mainwindow, MainWindow_Start_Time, ATTR_CTRL_VAL, ReadData);						
				
				
	/*-- Start Acquisition -----*/ 
	status = PmcaStartAcquisition(1);
	
	while (status != 0)
	{
		status = PmcaStartAcquisition(1);
	}
	
	/*-- Get Data from the MCA --------------------------*/
	status = PmcaGetData(Buffer, 0, gain);
	
	/*-- Gets the Menu Bar Handle --*/
	menubarhandle = GetPanelMenuBar (mainwindow);
			
	/*-- Discards the Connect in the menu Bar --*/
	if (TempId2 == 0)
		DiscardMenuItem (menubarhandle, MainMenu_Mca_StartAcq); 
	else
		DiscardMenuItem (menubarhandle, TempId2); 
	/*-- Adds the Connect to the MenuList ---------*/
		StopAcqId = NewMenuItem (menubarhandle, MainMenu_Mca,"Stop Acquisition", MainMenu_Mca_Sprator5, 0, 
							StopAcq, 0);

	TempId2 = StopAcqId;
	
	/*-- Clear Graph ------------------------------------*/
	DeleteGraphPlot (mainwindow, MainWindow_GRAPH, -1,
					 VAL_IMMEDIATE_DRAW);
	
	for (count = 0; count <= gain; count++)
		{
			Datapoint[count] = Buffer[count];	
		}
	
	PlotY (mainwindow, MainWindow_GRAPH, Datapoint, gain, VAL_DOUBLE, VAL_VERTICAL_BAR, VAL_SIMPLE_DOT, VAL_SOLID,
		   1, VAL_RED);

   Delay (1);

	}

void CVICALLBACK ClearData (int menuBar, int menuItem, void *callbackData,
		int panel)
{
	int status;

	/*-- Clears data in the Current Group and Screen --*/  
	if (McaConnected == 1)
	{
		status = PmcaClearData();
	
		while (status < 0)
		{
			status = PmcaClearData();
		}		
	}		
	
	/*-- Clear Graph ------------------------------------*/
	DeleteGraphPlot (mainwindow, MainWindow_GRAPH, -1,
					 VAL_IMMEDIATE_DRAW);
					 
	/*-- Clear Display --*/
	SetCtrlAttribute (mainwindow, MainWindow_Preset, ATTR_CTRL_VAL, "PRESET");
	SetCtrlAttribute (mainwindow, MainWindow_Real_Time, ATTR_CTRL_VAL, "REAL_TIME");
	SetCtrlAttribute (mainwindow, MainWindow_Live_Time, ATTR_CTRL_VAL, "LIVE_TIME");
	SetCtrlAttribute (mainwindow, MainWindow_Start_Time, ATTR_CTRL_VAL, "START_TIME");
	
	SetCtrlVal (mainwindow, MainWindow_NUMERIC_4, 0.0);
	SetCtrlVal (mainwindow, MainWindow_NUMERIC_3, 1023.0); 
	SetCtrlVal (mainwindow, MainWindow_NUMERIC_2, 1023.0);

    SetCtrlVal (mainwindow, MainWindow_NUMERIC_6, 0.0);
}

void CVICALLBACK ResTime (int menuBar, int menuItem, void *callbackData,
		int panel)
{
	
	int status;
	
	/*-- Resets acquisition time in the current group --*/
	status = PmcaClearTime();
	
	while (status < 0)
	{
		status = PmcaClearTime();
	}		
}

int CVICALLBACK UpdatePlot (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	int status;
	int count;
	
	switch (event)
		{
		case EVENT_COMMIT:
			/*-- Get Data from the MCA --------------------------*/
			status = PmcaGetData(Buffer, 0, gain);
	
			/*-- Clear Graph ------------------------------------*/
			DeleteGraphPlot (mainwindow, MainWindow_GRAPH, -1,
					 VAL_IMMEDIATE_DRAW);
	
			for (count = 0; count <= gain; count++)
			{
				Datapoint[count] = Buffer[count];	
			}
	
			PlotY (mainwindow, MainWindow_GRAPH, Datapoint, gain, VAL_DOUBLE, VAL_VERTICAL_BAR, VAL_SIMPLE_DOT, VAL_SOLID,
		   1, VAL_RED);
		   
			break;
		}
	return 0;
}
