#include <NIDAQmx.h>
#include "SMMCVI6.h"
#include <easyio.h>
#include "hp836xx.h"
#include <gpib.h>
#include <analysis.h>
#include <dataacq.h>
#include "asynctmr.h"
#include "SMMCVI5.h"
#include <formatio.h>
#include <ansi_c.h>
#include <utility.h>
#include <userint.h>
#include "smmcvi5.h"
//#include "smmacq5.h"
/* data structure for queues */
#define SMMACQCMD struct t_smmacqcmd
SMMACQCMD {
int updn, indx, ixend, numvolts, numav;
};
#define SMMACQDATA struct t_tsmmacq
SMMACQDATA {
 int indx;
 double intens, auxfreq, *voltage, liax;
};
//old smmacq5.c
#include <NIDAQmx.h>
#include "SMMCVI6.h"
#include <easyio.h>
#include "SMMCVI5.h"
#include <ansi_c.h>
#include <dataacq.h>
#include <userint.h>
#include <formatio.h>
#include <utility.h>
#include <gpib.h>
//#include "smmacq5.h"
//old smmacq5.h
#define TRUEQ  1
#define FALSEQ 0
#define BMASK 0xff
#define ADDC  0x311      /* counter control port */
#define ADDD  0x310      /* counter data port */
#define WILTRON 0
#define HP834xB 1
//old smmacq5.c
static int acqThreadFlush;
short int tempvolts[100000];
static int not;
/* function prototypes from smmacq5.h*/
int updateScan(int updn, int indx, int nbuf);
int acqthread(void *dumy);
void SetFreq(int ix);
void PutSynth(char * str, int len);
void PutSynth2(char * str, int len);
void PutLASER(char * str, int len);
void PutDS345(char * str, int len);
void  LIACMD(char *str);
void  SACMD(char *str);
void  FGCMD(char *str);
void Read_Voltages(int numv, int numa, double *voltages);
//old smmacq5.c
/* local function prototypes */
int GetIntensity(double *intens, double *auxfreq);
//////////////////////////////
#define ColUp   VAL_YELLOW
#define ColDown VAL_MAGENTA
#define ColAv   VAL_WHITE
#define ColView VAL_GREEN
/* function prototypes */
void  CVICALLBACK acqCallback(int qHandle, unsigned int event, int value, void *callbackData);
//void  CVICALLBACK acqCallback2(int qHandle, unsigned int event, int value, void *callbackData);
void  SetPath(char *);
int   Convert_Parameters (void);
int   Convert_Freq (void);
double nintb(double a);
void  InitTimerBoard (void);
void  Plot_Average (int, int, int);
void  YScale(int ipt);
void  InitTimeScan (void);
void  InitScan (void);
void  BeginScan (void);
//new one here
//void  BeginVideo(void);
void  SetUp_Parameters (void);
void  SweepUpDown (void);
void  InitSynth (void);
void  CloseSynth(void);
void  beginDiode(void);
void   autosave(int);
/* global data */
int Exp,  SAType;
int    autopts, acqcmdTSQ, acqdataTSQ, acqmxnTSQ, synthID, synthID2;
int ds345Handle; laserHandle, synthHandle, synthHandle2, LIAhandle, SAhandle;
int LASER, TEMPV, TEMP2V, P1V, P2V, DAQ, LIA, FG, NUMPTPI, XRNUM, NPage, ZEEMAN, yigfilt, DAQNUM, DAQ2NUM, DAQNUM3;
double zhi, zlow;
unsigned int numvolts, numav;
int gain[8];
static int BP1, paused, exitmacro;
double low, high;
double WaitCPUTime, intenScale, freqScale;
double synthOffset, synthStart, synthStep, defFreq, synthEnd;
int ModSen, synthHarm, synthHarm2;
static double *XA, *YA, *YAV, *XAV, *YA2, *YAU;
static double *VOLTS, *VOLTSAV;
static double *YSV;
static double  FOffset, FStart, FStep, FEnd, diodeFSR, YTMAX, YTMin, T0;
static double YMin, Ymax, YVMin, YVMax, TESTVAL;
int TimeWait, TimeBase, tempPANEL;
static int acqThreadID, YA_Pts, YSV_Pts, viewSv, iplast, zeroed, incFreq, autosaven, volts, volts2;
static int PMAINP, PSETUP, PINIT, PTIMESW, PP1, PVOLTS;
static int SSwMode, SwMode, ipstart, ipend, iptnow, StepMode;
static int NumY, SvStart, SvPoint,  ScanMode, TESTBEEP;
static int sweeping, KHarm, ColSel, ColSelB, diode;
static char scanfile[82], filename[82], dirname[82], swork[262], swork2[262], autosavefile[262], autosavepath[262], *fsetup;
/* new parms for LIA*/
int whichlia;
int Modul, modharm, modintext, sensefine, sensecoarse, taufine, taucoarse;
float tone, modfreq, modamp;
const double sense[] = {0.000000002,0.000000005,0.00000001,0.00000002,0.00000005,
	0.0000001,0.0000002,0.0000005,0.000001,0.000002,0.000005,0.00001,0.00002,
	0.00005,0.00010,0.0002,0.0005,0.001,0.002,0.005,0.010,0.02,0.05,0.1,0.2,0.5,1.0};
const double tau[] = {0.00001,0.00003,0.0001,0.0003,0.001,0.003,0.010,0.030,0.1,0.3,1.0,3.0,10.0,30.0,100.0,300.0,1000.0,3000.0,10000.0,30000.0};
double sensitivity;
/*new parms for video*/
double raterate;
//
int NUMBERPOINTS;
short iNumChans = 3;
short piChanVect[3] = {1, 2, 1};
short piGainVect[3] = {-1, 1, -1};
static int not;
//New DAQ stuff
TaskHandle  DAQHandle=0, DAQInputs=0, DAQClock=0;
float64     DAQdata[2], *voltages;
int N;
//move structures out of subroutines
  SMMACQCMD acq;
  SMMACQDATA acqdata;
  SMMACQDATA aqrd;
void main ()
{
  short int BC;
  //Default is two analog outputs
  DAQmxCreateTask ("", &DAQHandle);
  DAQmxCreateAOVoltageChan (DAQHandle, "Dev1/ao0,Dev1/ao1", "", -10, 10, DAQmx_Val_Volts, "");
  DAQmxCreateTask ("", &DAQInputs);
  //if (Init_DA_Brds (1, &BC)|| BC != 316) numvolts = -1;
  SAType = 0;
  synthHandle = -1;
  synthHandle2 = -1;
  laserHandle = -1;
  ds345Handle = -1;
  LIA = 0;
  NUMPTPI = 1;
  FG = 0;
  YMin = -1000.0; Ymax = 1000.0;
  PMAINP  = LoadPanel (0, "smmcvi6.uir", MainP);
  PSETUP  = LoadPanel (0, "smmcvi6.uir", SETUP);
  PTIMESW = LoadPanel (0, "smmcvi6.uir", TIMESW);
  PINIT   = LoadPanel (0, "smmcvi6.uir", INIT);
  low = -0.1;
  high = 5.0;
  ModSen = 1;
  PP1   = LoadPanel (0, "smmcvi6.uir", P1);
  Change_Gain (PSETUP, 1, 1, 0, 0 , 0); //initialize DAQ board to last settings
//  change_mod_type (PSETUP, SETUP_MODINTEXT, 1, 0, 0, 0); //initialize SETUP screen to current modulation settings
  CmtNewTSQ (10, sizeof(SMMACQCMD), OPT_TSQ_DYNAMIC_SIZE, &acqcmdTSQ);
  CmtNewTSQ (160, sizeof(SMMACQDATA), OPT_TSQ_DYNAMIC_SIZE, &acqdataTSQ);
  CmtInstallTSQCallback (acqdataTSQ, EVENT_TSQ_ITEMS_IN_QUEUE, 1, acqCallback, NULL, CmtGetCurrentThreadID(), NULL);
  CmtScheduleThreadPoolFunctionAdv (DEFAULT_THREAD_POOL_HANDLE,   acqthread, NULL,  THREAD_PRIORITY_TIME_CRITICAL, NULL, 0, NULL, 0, &acqThreadID);
  SetActiveCtrl (PINIT, MainP_Pause);
  DisplayPanel (PINIT);
  SetActivePanel (PINIT);
  RunUserInterface ();
  /* shut down and prepare for exit */
  DiscardAsyncTimer (-1);
  updateScan(0,0,-1);  // closes acquisition thread
  CmtWaitForThreadPoolFunctionCompletion (DEFAULT_THREAD_POOL_HANDLE, acqThreadID, OPT_TP_PROCESS_EVENTS_WHILE_WAITING);
  CmtDiscardTSQ (acqcmdTSQ); CmtDiscardTSQ  (acqdataTSQ);
  CmtDiscardTSQ  (acqmxnTSQ);//bjd new
  CloseSynth();
} /*end main */
void SetPath(fname)
char *fname;
{
  int i;
  i = 1 + FindPattern (fname, 0, 80, "\\", 0, 1);
  strncpy (dirname, fname, i);
  dirname[i] = 0;
}
int Convert_Parameters (void)
/*  Get all parameters for scan from here */
{
int i;
  InitSynth ();
  if (Convert_Freq() == FALSEQ) return FALSE;
  GetCtrlVal (PSETUP, SETUP_filename, filename);
  SetPath(filename);
  GetCtrlVal (PSETUP, SETUP_NUMVOLTS, &numvolts);
  if (NumY > YA_Pts)  {
    if (YA_Pts) {free(XA); }//free(YA); free(YAV); free(VOLTS); free(VOLTSAV);}
    XA = (double *)malloc(sizeof(double) * NumY * (2 * numvolts + 4));
    YA = XA + NumY; YAV = YA + NumY;
    VOLTS = YAV + NumY;
    VOLTSAV = VOLTS + numvolts * NumY;
    YA_Pts = NumY;
   }
  GetCtrlVal (PSETUP, SETUP_TimeWait, &TimeWait);
  GetCtrlVal (PSETUP, SETUP_TimeBase, &TimeBase);
  /*new code for voltage readouts */
  for (i = 0; i < 8; ++i){
   SetCtrlAttribute (PMAINP, MainP_Voltage0-i, ATTR_VISIBLE, 0);
  }
  for (i = 0; i < acq.numvolts; ++i){
   SetCtrlAttribute (PMAINP, MainP_Voltage0-i, ATTR_VISIBLE, 1);
  }
  /* end new code*/
  TimeWait *= 10; TimeBase *= 10; // convert for 0.1 msec counter
  if (TimeWait < 2) TimeWait = 2;
  if (TimeBase < 10) TimeBase = 10;
  WaitCPUTime = 0.0001 * (TimeWait + TimeBase + 1);
  /* below scales +/- 10V to +/-10,000 integer intensity */
  intenScale = 400.0 / (double)TimeBase;
  freqScale = 2.56 / (double)TimeBase;
  InitTimerBoard ();
  zeroed = TRUEQ;  if (ScanMode != 4) InitScan (); sweeping = TRUE; //bjd move this to explicit call after InitScan
  zeroed = FALSE; BeginScan();
  return TRUE;
}
int Convert_Freq (void)
/*  Get all parameters for scan from here */
{
  double MsynthStart, MsynthStep, MsynthEnd, synthScal, MsynthMin, MsynthMax;
  int tHarm, resScal;
  GetCtrlVal (PSETUP, SETUP_Freq_Start, &FStart);
  GetCtrlVal (PSETUP, SETUP_Freq_End, &FEnd);
  GetCtrlVal (PSETUP, SETUP_Freq_Step, &FStep);
  GetCtrlVal (PSETUP, SETUP_Freq_Offset, &FOffset);
  GetCtrlVal (PSETUP, SETUP_Synth_Offset, &synthOffset);
  GetCtrlVal (PSETUP, SETUP_WilHarm, &synthHarm);
  GetCtrlVal (PSETUP, SETUP_KlyHarm, &KHarm);
  GetCtrlVal (PSETUP, SETUP_SYNTH, &synthID);
  GetCtrlVal (PSETUP, SETUP_FSR, &diodeFSR);
  GetCtrlVal (PSETUP, SETUP_FREQDATA, &incFreq);
//  GetCtrlVal (PSETUP, SETUP_VOLTDATA, &volts);
  GetCtrlVal (PSETUP, SETUP_VOLTDATA_2, &volts2);
  GetCtrlVal (PSETUP, SETUP_AutoSave, &autosaven);
  GetCtrlVal (PSETUP, SETUP_SweepMode, &SwMode);
  GetCtrlVal (PSETUP, SETUP_DAQ, &DAQNUM);
  GetCtrlVal (PSETUP, SETUP_DAQ_2, &DAQ2NUM);
  GetCtrlVal (PSETUP, SETUP_TEMPVOLTAGE, &TEMPV);
  GetCtrlVal (PSETUP, SETUP_TEMPVOLTAGE2, &TEMP2V);
  GetCtrlVal (PSETUP, SETUP_P1VOLTAGE, &P1V);
  GetCtrlVal (PSETUP, SETUP_P2VOLTAGE, &P2V);
  GetCtrlVal (PSETUP, SETUP_TESTBEEPNUM, &TESTBEEP);
  GetCtrlVal (PSETUP, SETUP_TESTBEEPVAL, &TESTVAL);
  GetCtrlVal (PSETUP, SETUP_Synth_Harmonic_2, &synthHarm2);
  GetCtrlVal (PSETUP, SETUP_YIGFILT, &yigfilt);
  SSwMode = SwMode;
  if (diode){
    tHarm = synthHarm;
    if (incFreq) incFreq = 1;
    MsynthStart = FStart - KHarm * diodeFSR - FOffset;
  } else {
    tHarm = synthHarm * KHarm;
    if(incFreq) incFreq = KHarm;
    MsynthStart = (FStart / KHarm - FOffset) / synthHarm;
  }
  if (synthID == WILTRON || Exp == 4) {
    synthScal = 1000.; resScal = 1;
    MsynthMin = 2000.; MsynthMax = 26500.;
  } else {
    synthScal = 1000000.;  resScal = 1;
    if (MsynthStart > 19800.)
      resScal = 4;
    else if(MsynthStart > 13350.)
      resScal = 3;
    else if(MsynthStart > 6900.)
      resScal = 2;
    MsynthMin = 10.; MsynthMax = 26500.;
  }
  defFreq = FOffset;
  if (FOffset < 0.) {
    incFreq = -incFreq; defFreq = -defFreq;
  }
  synthStart = resScal * nintb(MsynthStart * synthScal / (double) resScal);
  MsynthStart = synthStart / synthScal;
  synthStep  = resScal * nintb(FStep * synthScal / (double)(resScal * tHarm));
  MsynthStep = synthStep / synthScal;
  FStep = MsynthStep * tHarm;
  synthOffset = synthOffset * synthScal;//new for hetero
  if (diode){
    FStart = KHarm * diodeFSR + MsynthStart + FOffset;
  } else {
    FStart = KHarm * (MsynthStart * synthHarm + FOffset);
  }
  if (FEnd < FStart + FStep) FEnd = FStart + 100.0;
  NumY = (int)((FEnd - FStart) / FStep + 1.5);
  FEnd = FStart + (NumY - 1) * FStep;
  MsynthEnd = MsynthStart + (NumY - 1) * MsynthStep;
  synthEnd = MsynthEnd;
  SetCtrlVal (PSETUP, SETUP_SynthStart, MsynthStart);
  SetCtrlVal (PSETUP, SETUP_SynthEnd,   MsynthEnd);
  SetCtrlVal (PSETUP, SETUP_Freq_Start, FStart);
  SetCtrlVal (PSETUP, SETUP_Freq_End, FEnd);
  SetCtrlVal (PSETUP, SETUP_Freq_Step, FStep);
  if (MsynthStart < MsynthMin || MsynthEnd > MsynthMax){
    SetCtrlAttribute (PSETUP, SETUP_SynthStart, ATTR_TEXT_COLOR, VAL_RED);
    SetCtrlAttribute (PSETUP, SETUP_SynthEnd,   ATTR_TEXT_COLOR, VAL_RED);
    return FALSEQ;
  }
  SetCtrlAttribute (PSETUP, SETUP_SynthStart, ATTR_TEXT_COLOR, VAL_BLACK);
  SetCtrlAttribute (PSETUP, SETUP_SynthEnd,   ATTR_TEXT_COLOR, VAL_BLACK);
  if (synthHandle < 0) InitSynth ();
  if (SwMode >= 0)
    SetFreq(0);
  else
    SetFreq(NumY-1);
  if (yigfilt)  Change_YIGFILT(PSETUP, SETUP_YIGFILT, 1, 0, 0, 0);
  return TRUEQ;
}
double nintb(double a)
{ //  find nint(a) with provision for really big values
  static double big = (double)0x40000000; // 2^30
  double ax;
  int n, neg;
  neg = 0;
  if (a < 0.) {
    neg = 1; a = -a;
  }
  ax = a;
  if (ax < 1.e+15) {
    if (ax > big){ // remove a really big integer
      n = (int)(ax / big);
      ax -= n * big; // exact integer subtaction
    }
    n = (int) (ax + 0.5);
    a += n - ax;
  }
  if (neg) a = -a;
  return a;
}
void InitTimerBoard (void)
{
  outp (ADDC, 0xff); /* master reset */
  outp (ADDC,  027); /* pointer to master register */
  outp (ADDD,    0); /* master mode low byte = 0 */
  outp (ADDD, 0xc1); /* master mode  1100 0001 0000 0000 */
  /* 2 byte mode; input/output byte toggled */
  outp (ADDC,    1); /* pointer to mode register counter 1 */
  outp (ADDD, 0x42); /* time base: f3=100 micro seconds */
  outp (ADDD,   13); /* toggle output during count down, count once */
  outp (ADDC,    2); /* pointer to mode register counter 2 */
  outp (ADDD, 0x29); /* count up, terminal count: true */
  outp (ADDD, 0xb3); /* source3 input, counting during active TC2' */
  outp (ADDC,    3);/* pointer to mode register counter 3 */
  outp (ADDD, 0x29);/* count up, terminal count: true */
  outp (ADDD,    0);/* TCn-1 input, no gate */
  outp (ADDC,    4); /* pointer to mode register counter 4 */
  outp (ADDD, 0x29); /* count up, terminal count: true */
  outp (ADDD, 0xb4); /* source4 input, counting during active TC2' */
  outp (ADDC,    5);/* pointer to mode register counter 3 */
  outp (ADDD, 0x29);/* count up, terminal count: true */
  outp (ADDD,    0);/* TCn-1 input, no gate */
  /* LOADING COUNTERS */
  outp (ADDC, 011);/* pointer to load register counter 1 */
  outp (ADDD, TimeWait & BMASK); outp (ADDD, TimeWait >> 8);
  outp (ADDC, 021);/* pointer to hold register counter 1 */
  outp (ADDD, TimeBase & BMASK); outp (ADDD, TimeBase >> 8);
  outp (ADDC, 012);/* pointer to load register counter 2 */
  outp (ADDD, 0); outp (ADDD, 0);
  outp (ADDC, 013);/* pointer to load register counter 3 */
  outp (ADDD, 0); outp (ADDD, 0);
  outp (ADDC, 014);/* pointer to load register counter 4 */
  outp (ADDD, 0); outp (ADDD, 0);
  outp (ADDC, 015);/* pointer to load register counter 5 */
  outp (ADDD, 0); outp (ADDD, 0);
}
void Plot_Average (ipt, PP, P_GRAPH)
int ipt, PP, P_GRAPH;
{
  double YMax2, Yoff, KFac;
  int i, ret, n, ipmin, ii;
  /* plotting Average spec */
  ret = DeleteGraphPlot (PP, P_GRAPH, -1, 1);
  Yoff = 0.25 * (Ymax - YMin);
  YMax2 = Ymax + Yoff;
  ret = SetAxisRange (PP, P_GRAPH, VAL_MANUAL, FStart, FEnd,
                      VAL_MANUAL, YMin, YMax2);
  if (zeroed == TRUEQ) return;
  if (ipt < 0) { /* update average with full scan */
    KFac = 1. / (double) NPage;
    for (i = 0; i < NumY; i++)  {
      YAV[i] += KFac * (YA[i] - YAV[i]);
       for (ii = 0; ii < numvolts; ++ii){
        VOLTSAV[i + ii*NumY] += KFac * ( VOLTS[i + ii*NumY] - VOLTSAV[i + ii * NumY]);
       }
    }
    ipmin = 0; n = NumY;
  } else if (SwMode < 0) {
    ipmin = ipt; n = NumY - ipt;
  } else {
    ipmin = 0; n = ipt + 1;
  }
  if (n) {
    ret = PlotXY (PP, P_GRAPH, &XA[ipmin], &YA[ipmin], n, VAL_DOUBLE,
                        VAL_DOUBLE, VAL_THIN_LINE, VAL_NO_POINT,
                        VAL_SOLID, 1, ColSelB);
  }
  if (ipt < 0 || NPage > 1) {
    ret = PlotWaveform (PP, P_GRAPH, YAV, NumY, VAL_DOUBLE, 1.0, Yoff,
                        FStart, FStep, VAL_THIN_LINE, VAL_NO_POINT, VAL_SOLID,
                        1, ColAv);
  }
 if (autosaven) autosave(ipt);  //bjd add autosave at end of each sweep 4/5/02
}
void  YScale(int ipt)
{
  double Yval;
  int i, n, ipmin;
  if (SwMode < 0) {
    ipmin = ipt; n = NumY - ipt;
  } else {
    ipmin = 0; n = ipt + 1;
  }
  if (n) {
    YVMin = YA[ipmin] - 0.5; YVMax = YVMin + 1.;
    for(i = 1; i < n; ++i, ++ipmin) {
      Yval = YA[ipmin];
      if (Yval < YVMin) {
        YVMin = Yval;
      } else if (Yval > YVMax) {
        YVMax = Yval;
      }
    }
  }
  if (NPage > 1) {
    if (n == 0) {
      YVMin = YAV[0] - 0.5; YVMax = YVMin + 1.; n = NumY;
    }
    for(i = 0; i < NumY; ++i) {
      Yval = YAV[i];
      if (Yval < YVMin) {
        YVMin = Yval;
      } else if (Yval > YVMax) {
        YVMax = Yval;
      }
    }
  }
  if (viewSv) {
    if (n == 0) {
      YVMin = YSV[0] - 0.5; YVMax = YVMin + 1.;
    }
    for(i = 0; i < SvPoint; ++i) {
      Yval = YSV[i];
      if (Yval < YVMin) {
        YVMin = Yval;
      } else if (Yval > YVMax) {
        YVMax = Yval;
      }
    }
  }
}
void InitTimeScan (void)
{
  SetInputMode (PTIMESW, TIMESW_Pause, FALSEQ);
  sweeping = TRUEQ;
  SetCtrlAttribute (PTIMESW, TIMESW_Pause, ATTR_LABEL_TEXT, "  Pause  ");
}
void InitScan (void)
{
  double Xval;
  SwMode = SSwMode;
  SweepUpDown (); iptnow = ipend; /* for screen resize */
  Xval = FStart + ipstart * FStep;
  SetCtrlVal (PMAINP, MainP_NumScan, NPage);
  SetCtrlVal (PMAINP, MainP_PtID, ipstart);
  SetCtrlVal (PMAINP, MainP_FreqNow, Xval);
  if (zeroed) SetInputMode (PMAINP, MainP_AutoScale, FALSEQ);
  SetInputMode (PMAINP, MainP_BackUp, FALSE);
  SetInputMode (PMAINP, MainP_BackUpMore, FALSE);
  SetInputMode (PMAINP, MainP_Setup, TRUEQ);
  SetInputMode (PMAINP, MainP_ScanMd, TRUE);
  SetInputMode (PMAINP, MainP_Start, TRUE);
  SetInputMode (PMAINP, MainP_Pause, FALSE);
  SetInputMode (PMAINP, MainP_BackUp, FALSE);
  SetInputMode (PMAINP, MainP_BackUpMore, FALSE);
  SetInputMode (PMAINP, MainP_JogUp, FALSE);
  SetInputMode (PMAINP, MainP_JogUpMore, FALSE);
  SetInputMode (PMAINP, MainP_ShowP1, TRUE);
//  SetInputMode (PMAINP, SETUP_P1_BUTTON, TRUE);
//  SetInputMode (PMAINP, SETUP_P2_BUTTON, TRUE);
  SetActiveCtrl (PMAINP, MainP_Start);
  //sweeping = TRUE; //bjd move this to explicit call after InitScan
  SetCtrlAttribute (PMAINP, MainP_Pause, ATTR_LABEL_TEXT, "  Pause  ");
}
void BeginScan (void)
{
  int i;
  DAQ = 0;
  GetCtrlVal (PSETUP, SETUP_VFLIA, &NUMPTPI);
  GetCtrlVal (PSETUP, SETUP_ZEEMAN, &ZEEMAN);
  //LIA = !NUMPTPI;
  LIA  = 0;
  if (NUMPTPI == 0) LIA = 1;
  if (zeroed) return;
  SweepUpDown (); iptnow = ipstart;
  SetFreq(ipstart);
  NPage = 1; viewSv = FALSEQ; zeroed = TRUEQ;
  SetCtrlVal (PMAINP, MainP_NumScan, NPage);
  DeleteGraphPlot (PMAINP, MainP_GRAPH, -1, 1);
  SetAxisRange (PMAINP, MainP_GRAPH, VAL_MANUAL, FStart, FEnd,
                      VAL_MANUAL, YMin, Ymax);
  for (i = 0; i < NumY; i++)  {
    XA[i] = 0.0; YA[i] = 0.0; YAV[i] = 0.0;
  }
}
void SetUp_Parameters (void)
{
  GetCtrlVal (PINIT, INIT_Exp, &Exp);
  switch (Exp){
  case 0:
    fsetup = "\\cvi\\smm\\fsetkly.sav";
    diode = FALSEQ;
    break;
  case 1:
    fsetup = "\\cvi\\smm\\fsetbwo.sav";
    diode = FALSEQ;
    break;
  case 2:
    fsetup = "\\cvi\\smm\\fsetdir.sav";
    diode = FALSEQ;
    break;
  case 3:
    fsetup = "\\cvi\\smm\\fsetdiod.sav";
    diode = TRUEQ;
    break;
  case 4:
  	fsetup = "\\cvi\\smm\\fsethet.sav";
  	break;
  case 5:
	fsetup = "\\cvi\\smm\\fsetvid.sav";
	diode = FALSEQ;
	ModSen = 10;
	break;
  }
  RecallPanelState (PSETUP, fsetup, 1);
  GetCtrlVal (PSETUP, SETUP_filename, filename);
  SetPath(filename);
  SetCtrlAttribute (PSETUP, SETUP_FSR,      ATTR_VISIBLE, diode);
  SetCtrlAttribute (PSETUP, SETUP_DIODE,    ATTR_VISIBLE, diode);
  if (Exp == 4) {
  	SetCtrlAttribute (PSETUP, SETUP_SYNTH_2,    ATTR_VISIBLE, 1);
  	SetCtrlAttribute (PSETUP, SETUP_Synth_Offset,    ATTR_VISIBLE, 1);
  	SetCtrlAttribute (PSETUP, SETUP_Synth_Harmonic_2,    ATTR_VISIBLE, 1);
  	SetCtrlAttribute (PSETUP, SETUP_Wilt_Power_2,    ATTR_VISIBLE, 1);
  	}
  if (Exp != 4) {
  	SetCtrlAttribute (PSETUP, SETUP_SYNTH_2,    ATTR_VISIBLE, 0);
  	SetCtrlAttribute (PSETUP, SETUP_Synth_Offset,    ATTR_VISIBLE, 0);
  	SetCtrlAttribute (PSETUP, SETUP_Synth_Harmonic_2,    ATTR_VISIBLE, 0);
  	SetCtrlAttribute (PSETUP, SETUP_Wilt_Power_2,    ATTR_VISIBLE, 0);
  	}
  SetActiveCtrl (PSETUP, SETUP_Scan);
  DisplayPanel (PSETUP);
  SetActivePanel (PSETUP);
}
void SweepUpDown (void)
{
  if (SwMode > 0)  {
    ColSel = ColUp;
    ColSelB = ColDown;
    ipstart = 0;
    ipend = NumY - 1;
  } else  if (SwMode < 0)  {
    ColSel = ColDown;
    ColSelB = ColUp;
    ipstart = NumY - 1;
    ipend = 0;
  }
}
void InitSynth (void)
{
  char buffer[20], serpol;
  double synthPower, exp;
  int i, error, level;
  int new, len, temp, new2;
  float t;
  short int BC;
  GetCtrlVal(PSETUP, SETUP_MODINTEXT, &modintext);
  GetCtrlVal(PSETUP, SETUP_NUMAV, &numav);
  GetCtrlVal(PSETUP, SETUP_AUTOPTS, &autopts);
  GetCtrlVal (PSETUP, SETUP_SYNTH, &new);
  if (new != synthID) CloseSynth();
  synthID = new;
  GetCtrlVal (PSETUP, SETUP_Wilt_Power, &synthPower);
  GetCtrlVal (PSETUP, SETUP_Mod, &Modul);
  GetCtrlVal (PSETUP, SETUP_Synth_Harmonic_2, &synthHarm2);
  if (synthID == WILTRON){
    if (synthHandle < 0) synthHandle = ibfind("ANRITSU");//wlt67XXB_init (5, 0, &synthHandle);
    Fmt (swork, "%s<L1 %f[p1]DM", synthPower);
    PutSynth(swork, NumFmtdBytes());
 	change_mod(PSETUP, SETUP_Mod, 1, 0, 0, 0);
 } else if (synthID == 1){
     if (synthHandle < 0) synthHandle = ibfind("HP8340B");
	 change_mod(PSETUP, SETUP_Mod, 1, 0, 0, 0);
     change_HPLEVEL(PSETUP, SETUP_LEVEL, 1, 0, 0, 0);
  }
  //new code only for two synthesizer operation, 2nd synth has no modulation
  if (Exp == 4){   //DECIDED NOT TO CHANGE POWER AT THIS POINT
   GetCtrlVal (PSETUP, SETUP_SYNTH_2, &new2);
   if (new2 != synthID2) CloseSynth();
   synthID2 = new2;
   if (synthID2 == WILTRON){
    if (synthHandle2 < 0) synthHandle2 = ibfind("ANRITSU");
   } else if (synthID2 == 1){
    if (synthHandle2 < 0) synthHandle2 = ibfind("HP8340B");
   }
  }
  //new code added for GPIB control of Stanford Research Systems SR850 LIA
  //if (LIA) {
    GetCtrlVal (PSETUP, SETUP_ModFrequency, &modfreq);
    GetCtrlVal (PSETUP, SETUP_MODHARM, &modharm);
    GetCtrlVal (PSETUP, SETUP_MODINTEXT, &modintext);
    GetCtrlVal (PSETUP, SETUP_ModAmplitude, &modamp);
    GetCtrlVal (PSETUP, SETUP_SENSEFINE, &sensefine);
    GetCtrlVal (PSETUP, SETUP_SENSECOARSE, &sensecoarse);
    GetCtrlVal (PSETUP, SETUP_TAUFINE, &taufine);
    GetCtrlVal (PSETUP, SETUP_TAUCOARSE, &taucoarse);
    GetCtrlVal (PSETUP, SETUP_VFLIA, &NUMPTPI);
    GetCtrlVal (PSETUP, SETUP_XRLIA, &XRNUM);
    Fmt (buffer, "%s<DDEF 1,%d,0", XRNUM);   //OK with SR844
    LIACMD(buffer);//try to set display output to X/R
    if (taucoarse + taufine < 0) {
      SetCtrlVal (PSETUP, SETUP_TAUFINE, 0);
      taufine = 0;
      }
    Fmt (buffer, "%s<HARM %d", modharm);
    LIACMD(buffer);
    Fmt (buffer, "%s<FMOD %d", modintext);
    LIACMD(buffer);
    Fmt (buffer, "%s<FREQ %f[p3]", modfreq*1000); //Set up the (internal) modulation frequency
    LIACMD(buffer);
    Fmt (buffer, "%s<SLVL %f[p3]", modamp); //Set up the (internal) modulation amplitude
    LIACMD(buffer);
    Fmt (buffer, "%s<SENS %d", sensefine + sensecoarse); //Set up the sensitivity
    LIACMD(buffer);
    Fmt (buffer, "%s<OFLT %d", taufine + taucoarse);  // Set up the Time Constant
    LIACMD(buffer);
    Fmt (buffer, "%s<OUTX %d", 1);   //Set the LIA to output responses to GPIB
    LIACMD(buffer);
/*    temp = fmod (sensefine, 3);
    exp = ((sensecoarse/3) - 6) + ((sensefine - temp)/3);
    if (temp){
    	temp = 5 * temp;
    	} else {
    	temp = 2;
    	}		  */
    sensitivity = sense[sensefine+sensecoarse];//0.001*temp * pow(10, exp); //18 -> 0 (V), 9 -> -3 (mV), 0 -> -6 (uV)
  //}
  GetCtrlVal(PSETUP, SETUP_NUMVOLTS, &numvolts);
  if (numvolts){
   //Init_DA_Brds (1, &BC);
   Change_Gain (PSETUP, 1, 1, 0, 0 , 0);
   }
  GetCtrlVal (PSETUP, SETUP_YIGFILT, &yigfilt);
  if(yigfilt) Change_YIGFILT(PSETUP, SETUP_YIGFILT, 1, 0, 0, 0);
}
void CloseSynth(void)
{
char buffer[20];
  if (synthHandle > -1) {
   if (synthID == WILTRON){
    ibonl (synthHandle, 0);
   } else {
    ibonl (synthHandle, 0);
   }
   synthHandle = -1;
  }
  if (synthHandle2 > -1) {
   if (synthID2 == WILTRON){
    ibonl (synthHandle2, 0);
   } else {
    ibonl (synthHandle2, 0);
   }
   synthHandle2 = -1;
  }
  if (LIAhandle){
  	Fmt (buffer, "%s<OUTX %d", 0);   //Set the LIA to stop output responses to GPIB
  	LIACMD(buffer);
   	LIA = 0;
  }
}
void  CVICALLBACK acqCallback(int qHandle, unsigned int event, int value, void *callbackData)
{ // TSQ callback for plotting
  double Intens, Intens2, vtmp, auxFreq, Xval, tempnum;
  int i, ipt, nmax, ipmin, ipmax, k;
  char temp[14];
  if (event){
  ipmin = NumY - 1; ipmax = 0;
  while (value) {
    --value;
    if (CmtReadTSQData (qHandle, &aqrd, 1, 100, 0) <= 0) break;
    iptnow = iplast = ipt = aqrd.indx;
    Intens = aqrd.intens;
    Intens2 = aqrd.auxfreq;
    if ((ScanMode == 1) || (ScanMode == 2) || (ScanMode == 4)){
      zeroed = FALSEQ;
      if (ipt > ipmax) ipmax = ipt;
      if (ipt < ipmin) ipmin = ipt;
      Xval = FStart + ipt * FStep;
      if (incFreq) Xval += incFreq * (aqrd.auxfreq - defFreq);
      XA[ipt] = Xval; YA[ipt] = Intens;
      if (acq.numvolts){
      k = 0;	//attempt to write to Voltage array
       for (i = 0; i < acq.numvolts ; ++i){
     	//if (gain[i]){
    		VOLTS[ipt + i*NumY] = aqrd.voltage[i];
    		//k = k+1;
    	//}
       } //end 0-8 loop
      } //end if volts
      if (value == 0) {
        SetCtrlVal (PMAINP, MainP_FreqNow, Xval);
        SetCtrlVal (PMAINP, MainP_Inten, (int)Intens);
        //if (ZEEMAN) SetCtrlVal (PMAINP, MainP_Inten_2, (int)YA[ipt]);
        SetCtrlVal (PMAINP, MainP_PtID, ipt);
        if (ipstart) { /* scan down */
          if (ipmax < ipstart) ++ipmax;
        } else if (ipmin > 0){
          --ipmin;
        }
        PlotXY (PMAINP, MainP_GRAPH, &XA[ipmin], &YA[ipmin],
                ipmax - ipmin + 1, VAL_DOUBLE, VAL_DOUBLE,
                VAL_THIN_LINE, VAL_NO_POINT, VAL_SOLID, 1, ColSel);
        //show DAQ voltages/ converted temperatures and LIA intensity
      	k = 0;		  //newline
      	for (i = 0; i < acq.numvolts; ++i){  //change numvolts => 8
         //if (gain[i]){		   //newline
         //	SetCtrlVal(PMAINP, MainP_Voltage0-i, aqrd.voltage[i]);//SetCtrlVal(PMAINP, MainP_Voltage0-i, aqrd.voltage[i]);
         	SetCtrlVal(PMAINP, MainP_Voltage0-i, VOLTS[ipt + i*NumY]);
         //	ii = ipt + k * NumY;//ii = ipt + i * NumY;
         //	VOLTS[ii] = aqrd.voltage[i];//VOLTS[ii] = aqrd.voltage[i];
         	if (TESTBEEP == i && fabs(aqrd.voltage[i]) < TESTVAL) Beep ();//if (TESTBEEP == i && fabs(aqrd.voltage[i]) < TESTVAL) Beep ();
            if (TEMPV == i){
                vtmp = ((-0.894404135*(1000*VOLTS[ipt + i * NumY])*(1000*VOLTS[ipt + i * NumY]))+(26.18244969*(1000*VOLTS[ipt + i * NumY]))+272.366707);
         		//vtmp = 272.3666717 - 894.404135*VOLTS[ipt + k * NumY]*VOLTS[ipt + k * NumY]+26182.44969*VOLTS[ipt + k * NumY];
				   //changed 2-19-03 bjd equation was inaccurate below 240 K
        		SetCtrlVal(PMAINP, MainP_TEMP, vtmp);
        	}
        	if (TEMP2V == i){
         		vtmp = ((-0.894404135*(1000*VOLTS[ipt + i * NumY])*(1000*VOLTS[ipt + i * NumY]))+(26.18244969*(1000*VOLTS[ipt + i * NumY]))+272.366707);
         		//vtmp = 272.3666717 - 894.404135*VOLTS[ipt + k * NumY]*VOLTS[ipt + k * NumY]+26182.44969*VOLTS[ipt + k * NumY];
				   // bjd changed 2-19-03 equation inaccurate below 240 K
       		SetCtrlVal(PMAINP, MainP_TEMP2, vtmp);
        	}
        //	k = k + 1;//newline
         //}				   //newline   end if gain
        } //end for i 0 to 7
      }  //end if value == 0
    if (autosaven && (((ipt) % autopts) == 1)) autosave(ipt);
    if (ipt == ipend) {
        Beep ();
        ipmin = NumY; ipmax = -1;
        if (ScanMode == 1)  { /* Start */
          MainP_Saven(PMAINP, 0, EVENT_COMMIT, NULL, 0, 0);
          InitScan();
          sweeping = TRUEQ; //bjd move this to explicit call after InitScan
        } else  if ((ScanMode == 2) || (ScanMode == 4)) { /* Average */
          SwMode = -SwMode;
          SweepUpDown (); /* set color and init point */
          if (sweeping) updateScan(SwMode, ipstart, ipend);
          Plot_Average (-1, PMAINP, MainP_GRAPH);
          NPage++;
          SetCtrlVal (PMAINP, MainP_NumScan, NPage);
        }
      }
    }else{ //time sweep
      Xval = Timer () - T0;
      if(ZEEMAN) Intens = Intens2-Intens;
      SetCtrlVal (PTIMESW, TIMESW_CurY, (int)Intens);
      SetCtrlVal (PTIMESW, TIMESW_LapTime, Xval);
      if (YTMAX < Intens)  {
        YTMAX = Intens;
        SetAxisRange (PTIMESW, TIMESW_GRAPH, VAL_NO_CHANGE,
                          0.0, 1.0, VAL_MANUAL, YTMin, YTMAX);
      } else  if (YTMin > Intens)  {
        YTMin = Intens;
        SetAxisRange (PTIMESW, TIMESW_GRAPH,  VAL_NO_CHANGE,
                          0.0, 1.0, VAL_MANUAL, YTMin, YTMAX);
      }
      PlotStripChart (PTIMESW, TIMESW_GRAPH, &Intens, 1, 0, 0,
                            VAL_DOUBLE);
      if (ipt == ipend && sweeping) updateScan(1, 0, ipend);
    }
  }
  }//end if event
}
int CVICALLBACK auto_path_change (int panel, int control, int event,
                          void *callbackData, int eventData1, int eventData2)
{
  switch (event) {
    case EVENT_COMMIT:
      if(DirSelectPopup (dirname, "Choose Directory Location for Autosave", 1, 1,
						 swork) <= 0) break;
      swork[81] = 0; strcpy(autosavepath, swork);
      ResetTextBox (PSETUP, SETUP_filename_2, autosavepath);
      //SetPath(filename);
      break;
  }
  return 0;
}
void autosave(ipt)
{
  FILE *file_hand;
  double ytmp, xtmp, xval, vtmp, vtmp2, p1sum, p1av, p2sum, p2av, tsum, tav, tsum2, t2av, dsv;
  int i, j, id, NRPage, isv, ret, icmp, initial, ii, numy, k, ASvPoint;
       if (SwMode > 0) {SvStart = 0; isv = ipt, ASvPoint = ipt;};//mid-upsweep
       if (SwMode ==  -1) {SvStart = ipt; isv = NumY - ipt; ASvPoint = isv;}  //mid down-sweep
       if ((ipt > (NumY - 1)) || (ipt < 1)) {SvStart = 0; isv = NumY; ASvPoint = NumY;} //end up or down-sweep
       GetCtrlVal(PSETUP, SETUP_filename_2, autosavepath);
       Fmt (autosavefile, "%s<%s\\%d%s", autosavepath, NPage, ".hp");
       file_hand = fopen (autosavefile, "w");
       SetInputMode (PMAINP, MainP_View, TRUEQ);
       SetPath(filename);
       sprintf (swork,"DATE %s TIME %s SH %d IT %d SENS %3.0g TAU %g MF %6.3f MA %6.3f",
		 		 DateStr(), TimeStr(), synthHarm, TimeBase/10, sense[sensefine+sensecoarse],
				 tau[taufine+taucoarse], modfreq, modamp);
       fprintf(file_hand, "%s\n", swork);
       fprintf(file_hand, "%s%d\n", "autosave #", NPage);
       xtmp = FStart + FStep * SvStart;
       numy = 1; //fixed for now to only show spectral data
/*        if (volts) {
         if (gain[TEMPV]) numy = numy+1;
         if (gain[TEMP2V]) numy = numy+1;
         if (gain[P1V]) numy = numy+1;
         if (gain[P2V]) numy = numy+1;
        }   */
        p1sum = 0.0;
        p2sum = 0.0;
        tsum = 0.0;
        tsum2 = 0.0;
		k = 0;
        for (ii = 0; ii < 8; ++ii){
         if (gain[ii]) {
          for ( id = 0; id < ASvPoint; ++id){
           i = id + SvStart;
           if (TEMPV == ii) tsum = tsum + 1000000*VOLTS[i + k * NumY]; //(273.15 - 875.9*VOLTSAV[i + k * NumY]*VOLTSAV[i + k * NumY]+26522.0*VOLTSAV[i + k * NumY]);
						 //bjd change to output thermocouple Voltage in microvolts
           if (TEMP2V == ii) tsum2 = tsum2 + 1000000*VOLTS[i + k * NumY]; //(273.15 - 875.9*VOLTSAV[i + k * NumY]*VOLTSAV[i + k * NumY]+26522.0*VOLTSAV[i + k * NumY]);
						 //bjd change to output thermocouple Voltage in microvolts
           if (P1V == ii) p1sum = p1sum + 1000*VOLTS[i + k * NumY];
           if (P2V == ii) p2sum = p2sum + 1000*VOLTS[i + k * NumY];
          }
         k = k+1;
         }
        }
        if (volts2) numy = numy + numvolts;
        fprintf(file_hand,"%10.3f %13.6f %d %d %d %d ", xtmp, FStep, ASvPoint, NPage, KHarm, numy);
        fprintf(file_hand,"%10.3f %10.3f %10.3f %10.3f START\n", p1sum/ASvPoint, p2sum/ASvPoint, tsum/ASvPoint, tsum2/ASvPoint);
        icmp = 10;
        for (id = 0; id < ASvPoint;)  {
          i = SvStart + id;
          if (volts2) for (j = 0; j < numvolts; ++j){ dsv = 1000*VOLTS[i + j * NumY]; fprintf(file_hand,"%10.3f ", dsv);}
          ytmp = YA[i];
          dsv = (ytmp + 20000.5) - 20000;
          fprintf(file_hand,"%10.3f ", dsv);
          if ((++id) % icmp == 0) fputc('\n',file_hand);
        }
        if (id % icmp) fputc('\n',file_hand);
        fclose (file_hand);
      }
     //}
///*** Main Panel Callback Functions defined below ****///
int CVICALLBACK MainP_Quitn (int panel, int control, int event,
                          void *callbackData, int eventData1, int eventData2)
{
int ret;
  switch (event) {
    case EVENT_COMMIT:
      QuitUserInterface (0);
      break;
  }
  return 0;
}
int CVICALLBACK MainP_Setupn (int panel, int control, int event,
                         void *callbackData, int eventData1, int eventData2)
{
  switch (event) {
    case EVENT_COMMIT:
      updateScan(0,0,0);
      HidePanel (PMAINP);
      SetUp_Parameters ();
      break;
  }
  return 0;
}
int CVICALLBACK MainP_Viewn (int panel, int control, int event,
                         void *callbackData, int eventData1, int eventData2)
{
  double FBgn;
  if (event == EVENT_COMMIT && SvPoint) {
    FBgn = FStart + SvStart * FStep;  viewSv = TRUEQ;
    PlotWaveform (PMAINP, MainP_GRAPH, YSV, SvPoint,
                  VAL_DOUBLE, 1.0, 0., FBgn, FStep,
                  VAL_THIN_LINE, VAL_NO_POINT, VAL_SOLID, 1,
                  ColView);
  }
  return 0;
}
int CVICALLBACK MainP_Startn (int panel, int control, int event,
                          void *callbackData, int eventData1, int eventData2)
{
FILE *file_hand;
static int numwinlist,  tsum, tsum2, k, ii, iii, tav, t2av, numy, icmp, id, len;
int numwindows, ret, numsweeps, i, isv, autoon;
double synthPower, range, increment, *cfreq, ytmp, xval, xtmp, dsv, p1sum, p2sum, p1av, p2av, temp, mdelay;
double MODFREQ, MODAMP;
	if (event == EVENT_COMMIT){
      SetInputMode (PMAINP, MainP_Setup, FALSEQ);
      SetInputMode (PMAINP, MainP_ScanMd, FALSEQ);
      SetInputMode (PMAINP, MainP_Start, FALSEQ);
      SetInputMode (PMAINP, MainP_Quit, TRUEQ);
      SetInputMode (PMAINP, MainP_Save, TRUEQ);
      SetInputMode (PMAINP, MainP_Delete, TRUEQ);
      SetInputMode (PMAINP, MainP_Pause, TRUEQ);
      SetInputMode (PMAINP, MainP_AutoScale, TRUEQ);
      SetInputMode (PMAINP, MainP_AutoScale, TRUEQ);
      SetInputMode (PMAINP, MainP_ShowP1, FALSEQ);
      GetCtrlVal (PMAINP, MainP_ScanMd, &ScanMode);
      if ((ScanMode == 1) || (ScanMode == 2)){
        BeginScan();
        iptnow = ipstart;
        updateScan(SwMode,ipstart,ipend);
        SetActiveCtrl (PMAINP, MainP_Pause); /* bjd */
      } else if (ScanMode == 3){
        //BeginVideo();
        //updateScan(SwMode,ipstart,ipend);
        //SetActiveCtrl (PMAINP, MainP_Pause); /* bjd */
      } else if (ScanMode == 4){
       sweeping = TRUE;
		//repeat from here
	   while (sweeping){
	    GetCtrlVal(PSETUP, SETUP_filename_3, scanfile);
		file_hand = fopen (scanfile, "r");
    	if (file_hand){
    	 fgets(swork2,82,file_hand); //read rest of first line
    	 len = strlen(swork2);
    	 swork2[len-1] = '\0';
    	 ResetTextBox (PSETUP, SETUP_filename_3, swork2);
    	 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%d", &numwindows);
    	 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%f", &range);
    	 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
     	 Scan (swork2, "%s>%f", &increment);
    	 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%d", &numsweeps);
    	 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%d", &KHarm);
    	 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%d", &synthHarm);
    	 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%f", &FOffset);
    	 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%f", &synthPower);
    	 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%f", &temp);
    	 SetCtrlVal(PSETUP, SETUP_VOLTSOUT, temp);
			GetCtrlVal(PSETUP, SETUP_VOLTSOUT, &DAQdata[0]);
			GetCtrlVal(PSETUP, SETUP_YIGVOLTS, &DAQdata[1]);
			DAQmxWriteAnalogF64(DAQHandle,1,1,1.0,DAQmx_Val_GroupByChannel,DAQdata,NULL,NULL);
		 //AOUpdateChannel (DAQ2NUM, "0", temp);
		 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%f", &temp);
		 Delay(temp);
    	 fgets(swork2,82,file_hand); //read rest of first line
    	//Scan (swork2, "%s>%d%f%f%d%d%d%f%f", &numwindows, &range, &increment, &numsweeps, &KHarm, &synthHarm, &FOffset, &synthPower);
		 if (numwindows >= numwinlist) {
    	   cfreq = (double *)malloc(sizeof(double) * numwindows);
    	 }
    	 numwinlist = numwindows;
		 for (i = 0; i < numwindows; ++i) {
		  FillBytes (swork2, 0, 262, '\0');
		  k = 0;
		  while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
		  Scan (swork2, "%s>%f", &cfreq[i]);
		 }
		 fgets(swork2,82,file_hand);//read rest of second line
		 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%d", &modintext);
    	 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%d", &Modul);
    	 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%f", &MODFREQ);
    	 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%f", &MODAMP);
    	 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%d", &taucoarse);
    	 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%d", &taufine);
    	 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%d", &sensecoarse);
    	 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%d", &sensefine);
    	 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%d", &XRNUM);
    	 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%d", &modharm);
    	 fgets(swork2,82,file_hand);//read third line
		 //Scan (swork2, "%s>%d%d%f%f%d%d%d%d%d%d", &modintext, &Modul, &modfreq, &modamp, &taucoarse, &taufine, &sensecoarse, &sensefine, &XRNUM, &modharm);
		 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%d", &SwMode);
    	 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%d", &NUMPTPI);
    	 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%d", &TimeWait);
    	 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%d", &TimeBase);
    	 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%d", &autoon);
    	 FillBytes (swork2, 0, 262, '\0');k = 0;while (!strchr (swork2, ',')) { swork2[k] = fgetc(file_hand); ++k;}
    	 Scan (swork2, "%s>%d", &autopts);
		 fgets(swork2,82,file_hand);//read fourth line
		 //Scan (swork2, "%s>%d%d%d%d%d%d", &SwMode, &NUMPTPI, &TimeWait, &TimeBase, &autoon, &autopts);
    	 if (file_hand){													//#10
    	   	ret = fclose (file_hand);
    	 if(ret== 0) file_hand = 0;
    	} //end if file_hand
    	FillBytes (swork2, 0, 262, '\0');	 //clear array
        //change scan parameters other than range
        SetCtrlVal(PSETUP, SETUP_KlyHarm, KHarm);
        SetCtrlVal(PSETUP, SETUP_WilHarm, synthHarm);
        SetCtrlVal(PSETUP, SETUP_Freq_Offset, FOffset);
        SetCtrlVal(PSETUP, SETUP_Wilt_Power, synthPower);
        //SetCtrlVal(PSETUP, SETUP_Mod, Modul);
        //SetCtrlVal(PSETUP, SETUP_MODINTEXT, modintext);
        //SetCtrlVal(PSETUP, SETUP_ModFrequency, MODFREQ);
        //SetCtrlVal(PSETUP, SETUP_ModAmplitude, MODAMP);
        SetCtrlVal(PSETUP, SETUP_TAUCOARSE, taucoarse);
        SetCtrlVal(PSETUP, SETUP_TAUFINE, taufine);
        SetCtrlVal(PSETUP, SETUP_SENSECOARSE, sensecoarse);
        SetCtrlVal(PSETUP, SETUP_SENSEFINE, sensefine);
        SetCtrlVal(PSETUP, SETUP_XRLIA, XRNUM);
        SetCtrlVal(PSETUP, SETUP_MODHARM, modharm);
        SetCtrlVal(PSETUP, SETUP_SweepMode, SwMode);
        SetCtrlVal(PSETUP, SETUP_VFLIA, NUMPTPI);
        SetCtrlVal(PSETUP, SETUP_TimeWait, TimeWait);
        SetCtrlVal(PSETUP, SETUP_TimeBase, TimeBase);
        SetCtrlVal(PSETUP, SETUP_AutoSave, autoon);
        SetCtrlVal(PSETUP, SETUP_AUTOPTS, autopts);
        SSwMode = SwMode;
        exitmacro = 1;
        //open loop through cfreqs
        for (iii = 0; iii < numwindows; ++iii){
        if (exitmacro){
          FStart = cfreq[iii] - 0.5*range;
          FEnd   = cfreq[iii] + 0.5*range;
          //change cfreqs
  			SetCtrlVal (PSETUP, SETUP_Freq_Step,  increment);
  			SetCtrlVal (PSETUP, SETUP_Freq_Start,  FStart);
  			SetCtrlVal (PSETUP, SETUP_Freq_End,  FEnd);
  			SwMode = 1;
			Convert_Parameters ();
        	BeginScan();
        	GetCtrlVal (PSETUP, SETUP_MACRO_DELAY, &mdelay);
        	Delay(mdelay);  //set for detector shock time
        	iptnow = ipstart;
        	updateScan(SwMode,ipstart,ipend);  //opens aquisition thread
			SetCtrlAttribute(PMAINP, MainP_Pause, ATTR_DIMMED, 0);
			SetActiveCtrl (PMAINP, MainP_Pause); /* bjd */
        	//sweeping = TRUE;
        	while((NPage < (numsweeps + 1)) && sweeping ){
        	 GetUserEvent (0, &panel, &control);
        	 } //may need to thread this to allow interaction
		if (sweeping ) {
			updateScan(0, 0, 0);//kills active thread
            //save scan
        	file_hand = fopen (filename, "a");
        	SetInputMode (PMAINP, MainP_View, TRUE);
        	SvPoint = NumY;
        	SetPath(filename);
			sprintf (swork,"DATE %s TIME %s SH %d IT %d SENS %3.0g TAU %g MF %6.3f MA %6.3f",
				 DateStr(), TimeStr(), synthHarm, TimeBase/10, sense[sensefine+sensecoarse],
				 tau[taufine+taucoarse], modfreq, modamp);
        	//fprintf(file_hand, "DATE %s  TIME %s ", DateStr(), TimeStr());
        	//fprintf(file_hand,"SH %d IT %d SENS %3.0g TAU %g MF %6.3f MA %6.3f\n",synthHarm, TimeBase/10, sense[sensefine+sensecoarse], tau[taufine+taucoarse], modfreq, modamp);
        	fprintf(file_hand, "%s\n", swork);
			fprintf(file_hand, "%s\n", swork2);
        	//xtmp = FStart + FStep * SvStart;
        	p1sum = 0.0;
        	p2sum = 0.0;
        	tsum = 0.0;
        	tsum2 = 0.0;
        	if (NPage < 2){ YAV = YA; VOLTSAV = VOLTS;}
			k = 0;
        	for (ii = 0; ii < 8; ++ii){
        	 if (gain[ii]) {
        	  for ( i = 0; i < SvPoint; ++i){
        	   if (TEMPV == ii) tsum = tsum + 1000000*VOLTSAV[i + k * NumY]; //(273.15 - 875.9*VOLTSAV[i + k * NumY]*VOLTSAV[i + k * NumY]+26522.0*VOLTSAV[i + k * NumY]);
						 //bjd change to output thermocouple Voltage in microvolts
        	   if (TEMP2V == ii) tsum2 = tsum2 + 1000000*VOLTSAV[i + k * NumY]; //(273.15 - 875.9*VOLTSAV[i + k * NumY]*VOLTSAV[i + k * NumY]+26522.0*VOLTSAV[i + k * NumY]);
						 //bjd change to output thermocouple Voltage in microvolts
        	   if (P1V == ii) p1sum = p1sum + 1000*VOLTSAV[i + k * NumY];
        	   if (P2V == ii) p2sum = p2sum + 1000*VOLTSAV[i + k * NumY];
        	  }
        	 k = k+1;
        	 }
        	}
        	p1av = p1sum/SvPoint;
        	p2av = p2sum/SvPoint;
        	tav = (int) tsum/SvPoint;
        	t2av = (int) tsum2/SvPoint;
        	numy = 1;
        	if (volts) {
        	 if (gain[TEMPV]) numy = numy+1;
        	 if (gain[TEMP2V]) numy = numy+1;
        	 if (gain[P1V]) numy = numy+1;
        	 if (gain[P2V]) numy = numy+1;
        	}
        	if (volts2) numy = numy + numvolts;
        	fprintf(file_hand,"%10.3f %10.6f %d %d %d %d ", FStart, FStep, SvPoint, numsweeps, KHarm, numy);
        	fprintf(file_hand,"%6.3f %6.3f %d %d START\n", p1av, p2av, tav, t2av);
        	if (SvPoint > YSV_Pts)  {
        	  if (YSV_Pts) free(YSV);
        	  YSV = (double *) malloc(sizeof(double) * SvPoint);	   //bjd change YSV from sizeof(int) to sizeof(double) 5-3-05
        	  if (YSV == NULL) SvPoint = 0;
        	  YSV_Pts = SvPoint;
        	}
        	icmp = (incFreq)? 5: 10;
        	for (id = 0; id < SvPoint;)  {
        	  i = SvStart + id;
        	  if (NPage > 1)  {
        	    ytmp = YAV[i]; xval = 0.;
        	  } else  {
       	 	   ytmp = YA[i]; xval = XA[i] - xtmp;
        	  }
        	  if (incFreq) {
        	    isv = 1000. * xval;
        	    if (isv > 99999) isv = 99999;
        	    else if(isv < -99999) isv = -99999;
        	    fprintf(file_hand,"%6d ",isv);
        	  }
        	  k = 0;
        	  if (volts) {
        	   for (ii = 0; ii < 8; ++ii){
        	    if (gain[ii]){
        	    if (TEMPV == ii){
        	     isv = (int) 1000000*VOLTSAV[i + k * NumY]; //(273.15 - 875.9*VOLTSAV[i + k * NumY]*VOLTSAV[i + k * NumY]+26522.0*VOLTSAV[i + k * NumY]);
					 //bjd change to output thermocouple Voltage in microvolts
        	    fprintf(file_hand,"%6d ",isv);
        	    }
        	    if (TEMP2V == ii){
        	     isv = (int)  1000000*VOLTSAV[i + k * NumY]; //(273.15 - 875.9*VOLTSAV[i + k * NumY]*VOLTSAV[i + k * NumY]+26522.0*VOLTSAV[i + k * NumY]);
						 //bjd change to output thermocouple Voltage in microvolts
        	    fprintf(file_hand,"%6d ",isv);
        	    }
        	    if (P1V == ii){
        	     isv =(int) 1000 * VOLTSAV[i + k * NumY];
        	     fprintf(file_hand,"%6d ",isv);
        	    }
        	    if (P2V == ii){
        	     isv = (int) 1000 * VOLTSAV[i + k * NumY];//(0.00005*(pow(VOLTSAV[i + ii * NumY],3))-0.0005*(pow(VOLTSAV[i + ii * NumY],2))+1.0021*VOLTSAV[i + ii * NumY]-0.0005);
        	     fprintf(file_hand,"%6d ",isv);
        	    }
        	    k = k+1;
        	   } //end if gain
        	   } /* next ii*/
        	  }  /* end if volts */
        	  if (volts2) {
        	    for (ii = 0; ii < numvolts; ++ii){
        	     	isv = (int) 1000 * VOLTSAV[i+ii*NumY];
        	     	fprintf(file_hand,"%6d ",isv);
        	    }
        	  }
        	  //YSV[id] = isv = (int) (ytmp + 20000.5) - 20000;
        	  YSV[id] = dsv = (ytmp + 20000.5) - 20000;
        	  //fprintf(file_hand,"%6d ",isv);
        	  fprintf(file_hand,"%10.3f ", dsv);
        	  if ((++id) % icmp == 0) fputc('\n',file_hand);
        	  xtmp += FStep;
        	}
        	if (id % icmp) fputc('\n',file_hand);
        	fclose (file_hand);
        }//end loop
       } //end if sweeping
       } //end if exitmacro
        if (numwinlist) free(cfreq);	numwinlist = 0;
       }//repeat file read
      }
      } else if (ScanMode == 0){ // time sweep
        HidePanel (PMAINP);
        SetCtrlVal (PTIMESW, TIMESW_Freq, FStart + iplast * FStep);
        InitTimeScan();
        DisplayPanel (PTIMESW);
        SetActivePanel (PTIMESW);
      }
  }
  return 0;
}
int CVICALLBACK MainP_Pausen (int panel, int control, int event, void *callbackData, int eventData1, int eventData2)
{
  switch (event) {
  case EVENT_COMMIT:
    //sweeping = (!sweeping);
    if (paused)  {
      updateScan(SwMode, iptnow, ipend);
      SetCtrlAttribute (PMAINP, MainP_Pause, ATTR_LABEL_TEXT, "  Pause  ");
      SetInputMode (PMAINP, MainP_BackUp, FALSE);
      SetInputMode (PMAINP, MainP_BackUpMore, FALSE);
      SetInputMode (PMAINP, MainP_JogUp, FALSE);
      SetInputMode (PMAINP, MainP_JogUpMore, FALSE);
      SetActiveCtrl (PMAINP, MainP_Pause);
      SetInputMode (PMAINP, MainP_ShowP1, FALSE);
//      SetInputMode (PMAINP, SETUP_P1_BUTTON, FALSE);
//      SetInputMode (PMAINP, SETUP_P2_BUTTON, FALSE);/* bjd */
    } else  {
      updateScan(0, 0, 0);
      SetCtrlAttribute (PMAINP, MainP_Pause, ATTR_LABEL_TEXT, "Continue");
      SetInputMode (PMAINP, MainP_BackUp, TRUE);
      SetInputMode (PMAINP, MainP_BackUpMore, TRUE);
      SetInputMode (PMAINP, MainP_JogUp, TRUE);
      SetInputMode (PMAINP, MainP_JogUpMore, TRUE);
      SetInputMode (PMAINP, MainP_ShowP1, TRUE);
//      SetInputMode (PMAINP, SETUP_P1_BUTTON, TRUE);
//      SetInputMode (PMAINP, SETUP_P2_BUTTON, TRUE);
    }
    paused = !paused;
    break;
  }
  return 0;
}
int CVICALLBACK MainP_Saven (int panel, int control, int event,
                          void *callbackData, int eventData1, int eventData2)
{
  FILE *file_hand;
  double ytmp, xtmp, xval, p1sum, p2sum, p1av, p2av, tsum, tsum2, dsv;
  int i, id, NRPage, isv, ret, icmp, ipt, tav, t2av, ii, numy, k;
  switch (event) {
    case EVENT_COMMIT:
      i = sweeping; sweeping = FALSE;  /* simulate a pause */
      updateScan(0, 0, 0);
      ipt = iptnow;
      if (NPage > 1)  {
        SvStart = 0; isv = NumY; NRPage = NPage - 1;
      } else  {
        NRPage = NPage;
        if (SwMode > 0)  {
          SvStart = 0; isv = ipt + 1;
        } else  if (SwMode ==  -1)  {
          SvStart = ipt; isv = NumY - SvStart;
        }
      }
      if (isv < 2)  {
        MessagePopup ("WARNING", "No New Data Points, Not Saved");
        return 0;
      }
    ret = GenericMessagePopup ("Query", "Comment?", "Save",
                 "Cancel", "Save & Continue", swork2, 59, 0,
                 VAL_GENERIC_POPUP_INPUT_STRING,
                 VAL_GENERIC_POPUP_BTN1,
                 VAL_GENERIC_POPUP_BTN2);
      sweeping = i; /* restore state */
      if (ret > 1) updateScan(SwMode, iptnow, ipend);
      if (ret == 1 || ret == 3)  {
        if (ret == 1) InitScan();
        sweeping = TRUE; //bjd move this to explicit call after InitScan
        file_hand = fopen (filename, "a");
        if (file_hand == NULL)  {
          MessagePopup ("WARNING", "Bad File");
          return 0;
        }
        SetInputMode (PMAINP, MainP_View, TRUE);
        SvPoint = isv;
        SetPath(filename);
		sprintf (swork,"DATE %s TIME %s SH %d IT %d SENS %3.0g TAU %g MF %6.3f MA %6.3f",
				 DateStr(), TimeStr(), synthHarm, TimeBase/10, sense[sensefine+sensecoarse],
				 tau[taufine+taucoarse], modfreq, modamp);
        //fprintf(file_hand, "DATE %s  TIME %s ", DateStr(), TimeStr());
        //fprintf(file_hand,"SH %d IT %d SENS %3.0g TAU %g MF %6.3f MA %6.3f\n",synthHarm, TimeBase/10, sense[sensefine+sensecoarse], tau[taufine+taucoarse], modfreq, modamp);
        fprintf(file_hand, "%s\n", swork);
		fprintf(file_hand, "%s\n", swork2);
        xtmp = FStart + FStep * SvStart;
        p1sum = 0.0;
        p2sum = 0.0;
        tsum = 0.0;
        tsum2 = 0.0;
        if (NPage < 2){ YAV = YA; VOLTSAV = VOLTS;}
		k = 0;
        for (ii = 0; ii < 8; ++ii){
         if (gain[ii]) {
          for ( i = 0; i < SvPoint; ++i){
           if (TEMPV == ii) tsum = tsum + 1000000*VOLTSAV[i + k * NumY]; //(273.15 - 875.9*VOLTSAV[i + k * NumY]*VOLTSAV[i + k * NumY]+26522.0*VOLTSAV[i + k * NumY]);
						 //bjd change to output thermocouple Voltage in microvolts
           if (TEMP2V == ii) tsum2 = tsum2 + 1000000*VOLTSAV[i + k * NumY]; //(273.15 - 875.9*VOLTSAV[i + k * NumY]*VOLTSAV[i + k * NumY]+26522.0*VOLTSAV[i + k * NumY]);
						 //bjd change to output thermocouple Voltage in microvolts
           if (P1V == ii) p1sum = p1sum + 1000*VOLTSAV[i + k * NumY];
           if (P2V == ii) p2sum = p2sum + 1000*VOLTSAV[i + k * NumY];
          }
         k = k+1;
         }
        }
        p1av = p1sum/SvPoint;
        p2av = p2sum/SvPoint;
        tav = (int) tsum/SvPoint;
        t2av = (int) tsum2/SvPoint;
        numy = 1;
        if (volts) {
         if (gain[TEMPV]) numy = numy+1;
         if (gain[TEMP2V]) numy = numy+1;
         if (gain[P1V]) numy = numy+1;
         if (gain[P2V]) numy = numy+1;
        }
        if (volts2) numy = numy + numvolts;
        fprintf(file_hand,"%10.3f %10.6f %d %d %d %d ", xtmp, FStep, SvPoint, NRPage, KHarm, numy);
        fprintf(file_hand,"%6.3f %6.3f %d %d START\n", p1av, p2av, tav, t2av);
        if (SvPoint > YSV_Pts)  {
          if (YSV_Pts) free(YSV);
          YSV = (double *) malloc(sizeof(double) * SvPoint);	   //bjd change YSV from sizeof(int) to sizeof(double) 5-3-05
          if (YSV == NULL) SvPoint = 0;
          YSV_Pts = SvPoint;
        }
        icmp = (incFreq)? 5: 10;
        for (id = 0; id < SvPoint;)  {
          i = SvStart + id;
          if (NPage > 1)  {
            ytmp = YAV[i]; xval = 0.;
          } else  {
            ytmp = YA[i]; xval = XA[i] - xtmp;
          }
          if (incFreq) {
            isv = 1000. * xval;
            if (isv > 99999) isv = 99999;
            else if(isv < -99999) isv = -99999;
            fprintf(file_hand,"%6d ",isv);
          }
          k = 0;
          if (volts) {
           for (ii = 0; ii < 8; ++ii){
            if (gain[ii]){
            if (TEMPV == ii){
             isv = (int) 1000000*VOLTSAV[i + k * NumY]; //(273.15 - 875.9*VOLTSAV[i + k * NumY]*VOLTSAV[i + k * NumY]+26522.0*VOLTSAV[i + k * NumY]);
					 //bjd change to output thermocouple Voltage in microvolts
            fprintf(file_hand,"%6d ",isv);
            }
            if (TEMP2V == ii){
             isv = (int)  1000000*VOLTSAV[i + k * NumY]; //(273.15 - 875.9*VOLTSAV[i + k * NumY]*VOLTSAV[i + k * NumY]+26522.0*VOLTSAV[i + k * NumY]);
						 //bjd change to output thermocouple Voltage in microvolts
            fprintf(file_hand,"%6d ",isv);
            }
            if (P1V == ii){
             isv =(int) 1000 * VOLTSAV[i + k * NumY];
             fprintf(file_hand,"%6d ",isv);
            }
            if (P2V == ii){
             isv = (int) 1000 * VOLTSAV[i + k * NumY];//(0.00005*(pow(VOLTSAV[i + ii * NumY],3))-0.0005*(pow(VOLTSAV[i + ii * NumY],2))+1.0021*VOLTSAV[i + ii * NumY]-0.0005);
             fprintf(file_hand,"%6d ",isv);
            }
            k = k+1;
           } //end if gain
           } /* next ii*/
          }  /* end if volts */
          if (volts2) {
            for (ii = 0; ii < numvolts; ++ii){
            // 	isv = (int) 1000 * VOLTSAV[i+ii*NumY];
             	dsv =  1000 * VOLTSAV[i+ii*NumY];
            // 	fprintf(file_hand,"%6d ",isv);
             	fprintf(file_hand,"%10.3f ",dsv);
            }
          }
          //YSV[id] = isv = (int) (ytmp + 20000.5) - 20000;
          YSV[id] = dsv = (ytmp + 20000.5) - 20000;
          //fprintf(file_hand,"%6d ",isv);
          fprintf(file_hand,"%10.3f ", dsv);
          if ((++id) % icmp == 0) fputc('\n',file_hand);
          xtmp += FStep;
        }
        if (id % icmp) fputc('\n',file_hand);
        fclose (file_hand);
      }
      if(ret == 1) {InitScan();sweeping = TRUE;} //bjd move this to explicit call after InitScan;
      break;
  }
  return 0;
}
int CVICALLBACK MainP_Deleten (int panel, int control, int event,
                          void *callbackData, int eventData1, int eventData2)
{
  int itmp;
  switch (event) {
    case EVENT_COMMIT:
      updateScan(0,0,0); //itmp = sweeping; sweeping = FALSE;
      if(ConfirmPopup ("WARNING", "Delete the data ?"))  {
        InitScan ();
        exitmacro = 0;  //added to kill macro loop
        //sweeping = TRUE; //bjd move this to explicit call after InitScan
        BeginScan();
      } else {
        //sweeping = itmp;
        if (sweeping) updateScan(SwMode,iptnow,ipend);
      }
      break;
  }
  return 0;
}
int CVICALLBACK MainP_Jogn (int panel, int control, int event,
                          void *callbackData, int eventData1, int eventData2)
{
  int i, ipt;
  switch (event) {
  case EVENT_COMMIT:  /* only during pause */
    i = SwMode; ipt = iptnow;
    if (control == MainP_JogUpMore) i *= 10;
    i += ipt;
    if (i < 0) i = 0;
    if (i >= NumY) i = NumY - 1;
    updateScan(SwMode, ipt + SwMode, i);
    SetActiveCtrl (PMAINP, MainP_Pause); /* bjd */
    break;
  }
  return 0;
}
int CVICALLBACK MainP_BackUpn (int panel, int control, int event,
                          void *callbackData, int eventData1, int eventData2)
{
  int i;
  switch (event) {
  case EVENT_COMMIT:  /* only during pause */
    i = -SwMode;
    if (control == MainP_BackUpMore) i *= 10;
    i += iptnow - SwMode;
    if (i < 0) i = 0;
    if (i >= NumY) i = NumY - 1;
    Plot_Average(i, PMAINP, MainP_GRAPH);
    SetActiveCtrl (PMAINP, MainP_Pause);
    i += SwMode;
    updateScan(SwMode,i,i);
    SetActiveCtrl (PMAINP, MainP_Pause); /* bjd */
    break;
  }
  return 0;
}
int CVICALLBACK Auto (int panel, int control, int event,
                          void *callbackData, int eventData1, int eventData2)
{
  switch (event) {
  case EVENT_COMMIT:
    if (zeroed == FALSE) {
      YScale(iptnow); // update YVMin, YVMax
      YMin = YVMin; Ymax = YVMax;
      /* plot the scan so far.    */
      Plot_Average(iptnow, PMAINP, MainP_GRAPH);
      SetActiveCtrl (PMAINP, MainP_Pause); /* bjd */
    }
    break;
  }
  return 0;
}
int CVICALLBACK MoveUp (int panel, int control, int event,
                        void *callbackData, int eventData1, int eventData2)
{
  double diff;
  switch (event) {
    case EVENT_COMMIT:
      diff = 0.125*(Ymax- YMin); YMin -= diff; Ymax -= diff;
      Plot_Average(iptnow, PMAINP, MainP_GRAPH);
      SetActiveCtrl (PMAINP, MainP_Pause); /* bjd */
      break;
  }
  return 0;
}
int CVICALLBACK Zoomout (int panel, int control, int event,
                          void *callbackData, int eventData1, int eventData2)
{
  double diff;
  switch (event) {
    case EVENT_COMMIT:
      diff = 0.35*(Ymax- YMin); YMin -= diff; Ymax += diff;
      Plot_Average(iptnow, PMAINP, MainP_GRAPH);
      SetActiveCtrl (PMAINP, MainP_Pause); /* bjd */
      break;
  }
  return 0;
}
int CVICALLBACK MoveDown (int panel, int control, int event,
                          void *callbackData, int eventData1, int eventData2)
{
  double diff;
  switch (event) {
    case EVENT_COMMIT:
      diff = (Ymax - YMin)* 0.1500000; YMin += diff; Ymax += diff;
      Plot_Average(iptnow, PMAINP, MainP_GRAPH);
      SetActiveCtrl (PMAINP, MainP_Pause); /* bjd */
      break;
  }
  return 0;
}
int CVICALLBACK Zoomin (int panel, int control, int event,
                          void *callbackData, int eventData1, int eventData2)
{
  double diff;
  switch (event) {
    case EVENT_COMMIT:
      diff = 0.375*(Ymax- YMin); YMin += diff; Ymax -= diff;
      Plot_Average(iptnow, PMAINP, MainP_GRAPH);
      SetActiveCtrl (PMAINP, MainP_Pause); /* bjd */
      break;
  }
  return 0;
}
int CVICALLBACK Manual (int panel, int control, int event,
                        void *callbackData, int eventData1, int eventData2)
{
  int imax,imin,i;
  switch (event) {
    case EVENT_COMMIT:
      i = PromptPopup ("", "Max and Min Intensity ?", swork, 40);
      sscanf (swork, "%d %d", &imax, &imin);
      if (imax < imin) {
        i = imax; imax = imin; imin = i;
      }
      if (imax == imin) ++imax;
      Ymax = imax; YMin = imin;
      Plot_Average(iptnow, PMAINP, MainP_GRAPH);
      SetActiveCtrl (PMAINP, MainP_Pause); /* bjd */
      break;
  }
  return 0;
}
/****  End Main Panel Callback Functions ****/
/******** Begin TimeSweep Callback Functions *******/
int CVICALLBACK Startn (int panel, int control, int event,
                        void *callbackData, int eventData1, int eventData2)
{
  double diff, Ftime, FS, FStep;
  int n, KH, WH;
  char buf[17];
  switch (event) {
    case EVENT_COMMIT:
      GetCtrlVal (PTIMESW, TIMESW_Freq, &Ftime);
      GetCtrlVal(PSETUP, SETUP_Freq_Start, &FS);
      GetCtrlVal(PSETUP, SETUP_Freq_Step, &FStep);
      n = (Ftime - FStart) / FStep + 0.5;
      Ftime = FStart + n * FStep;
      SetCtrlVal (PTIMESW, TIMESW_Freq, Ftime);
      //synthStart += n * synthStep; synthStep = 0.;
      updateScan(1, n, -1);//updateScan(1, 0, ipend);	  //new code uses -1 flag to recognize time sweep
      T0 = Timer ();
      SetInputMode (PTIMESW, TIMESW_Pause, TRUE);
      //diff = 0.25 * (Ymax - YMin); YTMin = YMin - diff; YTMAX = Ymax + diff;
      GetCtrlVal(PTIMESW, TIMESW_HIGH, &YTMAX);
      GetCtrlVal(PTIMESW, TIMESW_LOW, &YTMin);
      SetAxisRange (PTIMESW, TIMESW_GRAPH,  VAL_NO_CHANGE,
                          0.0, 1.0, VAL_MANUAL, YTMin, YTMAX);
      SetTraceAttribute (PTIMESW, TIMESW_GRAPH, 1,
                               ATTR_PLOT_STYLE, VAL_THIN_STEP);
      break;
  }
  return 0;
}
int CVICALLBACK Deleten (int panel, int control, int event,
                          void *callbackData, int eventData1, int eventData2)
{
  int itmp;
  switch (event) {
    case EVENT_COMMIT:
      updateScan(0,0,0); itmp = sweeping; sweeping = FALSE;
      if(ConfirmPopup ("WARNING", "Delete the data ?"))  {
        InitTimeScan ();
      } else {
        sweeping = itmp;
        if (sweeping) updateScan(1, 0, ipend);
      }
      break;
  }
  return 0;
}
int CVICALLBACK Pausen (int panel, int control, int event,
                        void *callbackData, int eventData1, int eventData2)
{
  switch (event) {
    case EVENT_COMMIT:
      sweeping = (!sweeping);
      if (sweeping)  {
        updateScan(1, 0, ipend);
        SetCtrlAttribute (PTIMESW, TIMESW_Pause, ATTR_LABEL_TEXT," Pause  ");
      } else {
        updateScan(0, 0, ipend);
        SetCtrlAttribute (PTIMESW, TIMESW_Pause, ATTR_LABEL_TEXT,"Continue");
      }
      break;
  }
  return 0;
}
int CVICALLBACK Returnn (int panel, int control, int event,
                         void *callbackData, int eventData1, int eventData2)
{
  switch (event) {
    case EVENT_COMMIT:
      //if (sweeping) updateScan(1, 0, ipend); //bjd add new
      Convert_Freq (); InitScan();  sweeping = TRUE; //bjd move this to explicit call after InitScan
      HidePanel (PTIMESW);
      DisplayPanel (PMAINP);
      SetActivePanel (PMAINP);
      break;
  }
  return 0;
}
/******* End TimeSweep Callback Functions ******/
int CVICALLBACK quit_init (int panel, int control, int event,
                          void *callbackData, int eventData1, int eventData2)
{
  switch (event) {
    case EVENT_COMMIT:
      HidePanel(PINIT);
      SetUp_Parameters ();
      Convert_Freq();
      break;
  }
  return 0;
}
/******* Begin Setup CallBack Functions ******/
int CVICALLBACK Change_Experiment (int panel, int control, int event,
                          void *callbackData, int eventData1, int eventData2)
{
  switch (event) {
    case EVENT_COMMIT:
      HidePanel(PSETUP);
      DisplayPanel (PINIT);
      SetActivePanel (PINIT);
      break;
  }
  return 0;
}
int CVICALLBACK UpX (int panel, int control, int event,
                     void *callbackData, int eventData1, int eventData2)
{
  double XX;
  switch (event) {
    case EVENT_COMMIT:
      GetCtrlVal (PSETUP, SETUP_Freq_Start, &FStart);
      GetCtrlVal (PSETUP, SETUP_Freq_End, &FEnd);
      GetCtrlVal (PSETUP, SETUP_X, &XX);
      FStart += XX; FEnd += XX;
      SetCtrlVal (PSETUP, SETUP_Freq_Start, FStart);
      SetCtrlVal (PSETUP, SETUP_Freq_End, FEnd);
      Convert_Freq();
      break;
  }
  return 0;
}
int CVICALLBACK DownX (int panel, int control, int event,
                       void *callbackData, int eventData1, int eventData2)
{
  double XX;
  switch (event) {
    case EVENT_COMMIT:
      GetCtrlVal (PSETUP, SETUP_Freq_Start, &FStart);
      GetCtrlVal (PSETUP, SETUP_Freq_End, &FEnd);
      GetCtrlVal (PSETUP, SETUP_X, &XX);
      FStart -= XX; FEnd -= XX;
      SetCtrlVal (PSETUP, SETUP_Freq_Start, FStart);
      SetCtrlVal (PSETUP, SETUP_Freq_End, FEnd);
      Convert_Freq();
      break;
  }
  return 0;
}
int CVICALLBACK StepUpn (int panel, int control, int event,
                         void *callbackData, int eventData1, int eventData2)
{
  double XX;
  switch (event) {
    case EVENT_COMMIT:
      GetCtrlVal (PSETUP, SETUP_Freq_Start, &FStart);
      GetCtrlVal (PSETUP, SETUP_Freq_End, &FEnd);
      XX = FEnd - FStart; FStart += XX; FEnd += XX;
      SetCtrlVal (PSETUP, SETUP_Freq_Start, FStart);
      SetCtrlVal (PSETUP, SETUP_Freq_End, FEnd);
      Convert_Freq();
      break;
  }
  return 0;
}
int CVICALLBACK StepDownn (int panel, int control, int event,
                           void *callbackData, int eventData1, int eventData2)
{
  double XX;
  switch (event) {
    case EVENT_COMMIT:
      GetCtrlVal (PSETUP, SETUP_Freq_Start, &FStart);
      GetCtrlVal (PSETUP, SETUP_Freq_End, &FEnd);
      XX = FEnd - FStart; FStart -= XX; FEnd -= XX;
      SetCtrlVal (PSETUP, SETUP_Freq_Start, FStart);
      SetCtrlVal (PSETUP, SETUP_Freq_End, FEnd);
      Convert_Freq();
      break;
  }
  return 0;
}
int CVICALLBACK Scann (int panel, int control, int event,
                      void *callbackData, int eventData1, int eventData2)
{
  switch (event){
  case EVENT_COMMIT:
    if(Convert_Parameters ()){
      if (SavePanelState (PSETUP, fsetup, 1))
        MessagePopup ("", "Error saving setup file");
      HidePanel(PSETUP);
      DisplayPanel (PMAINP);
      SetActivePanel (PMAINP);
      sweeping = TRUE;
    }
    break;
  }
  return 0;
}
int CVICALLBACK quitn (int panel, int control, int event,
                       void *callbackData, int eventData1, int eventData2)
{
  switch (event) {
    case EVENT_COMMIT:
      if (SavePanelState (PSETUP, fsetup, 1))
        MessagePopup ("", "Error saving setup file");
      QuitUserInterface (0);
      break;
  }
  return 0;
}
int CVICALLBACK filecmdn (int panel, int control, int event,
                          void *callbackData, int eventData1, int eventData2)
{
  switch (event) {
    case EVENT_COMMIT:
      if(FileSelectPopup (dirname, "*.lwa", "", "Save data",
                          VAL_OK_BUTTON, 0, 0, 1, 0, swork) <= 0) break;
      swork[81] = 0; strcpy(filename, swork);
      ResetTextBox (PSETUP, SETUP_filename, filename);
      SetPath(filename);
      break;
  }
  return 0;
}
int CVICALLBACK filecmdn2 (int panel, int control, int event,
                          void *callbackData, int eventData1, int eventData2)
{
  switch (event) {
    case EVENT_COMMIT:
      if(DirSelectPopup (dirname, "Autosave Path", 1, 1, swork) <= 0) break;
      swork[81] = 0; strcpy(filename, swork);
      ResetTextBox (PSETUP, SETUP_filename_2, filename);
      break;
  }
  return 0;
}
int CVICALLBACK filecmdn3 (int panel, int control, int event,
                          void *callbackData, int eventData1, int eventData2)
{
  switch (event) {
    case EVENT_COMMIT:
      if(FileSelectPopup (dirname, "*.sca", "", "Open Scan Parameter File",
                          VAL_OK_BUTTON, 0, 0, 1, 0, swork) <= 0) break;
      swork[81] = 0; strcpy(filename, swork);
      ResetTextBox (PSETUP, SETUP_filename_3, filename);
      SetPath(filename);
      break;
  }
  return 0;
}
int CVICALLBACK fix_synth (int panel, int control, int event,
    void *callbackData, int eventData1, int eventData2)
{
  switch (event) {
    case EVENT_COMMIT:
        InitSynth();
      break;
  }
  return 0;
}
int CVICALLBACK do_freq (int panel, int control, int event,
    void *callbackData, int eventData1, int eventData2)
{
  switch (event) {
    case EVENT_COMMIT:
    Convert_Freq();
    break;
  }
  return 0;
}
int CVICALLBACK setup_keyboard_control (int panel, int event, void *callbackData,
		int eventData1, int eventData2)
{
double temp;
	switch (event)
		{
		case EVENT_GOT_FOCUS:
			break;
		case EVENT_LOST_FOCUS:
			break;
		case EVENT_CLOSE:
			break;
		case EVENT_KEYPRESS:
			if (SETUP_filename != GetActiveCtrl(PSETUP)){
			//key power control: u, d
             if ((eventData1 & VAL_ASCII_KEY_MASK) == 117){ //the 'u' key was pressed
              	GetCtrlVal(PSETUP, SETUP_Wilt_Power, &temp);
              	SetCtrlVal(PSETUP, SETUP_Wilt_Power, ++temp);
              	synth_power(PSETUP, SETUP_Wilt_Power, 1, 0, 0, 0);
			 }
			 if ((eventData1 & VAL_ASCII_KEY_MASK) == 100){ //the 'd' key was pressed
              	GetCtrlVal(PSETUP, SETUP_Wilt_Power, &temp);
              	SetCtrlVal(PSETUP, SETUP_Wilt_Power, --temp);
              	synth_power(PSETUP, SETUP_Wilt_Power, 1, 0, 0, 0);
			 }
			//key modulation control: f,a,n, z
			 if ((eventData1 & VAL_ASCII_KEY_MASK) == 97) {
			 	SetCtrlVal(PSETUP, SETUP_Mod, 1);//the 'a' key was pressed
			 	change_mod (PSETUP, SETUP_Mod, 1, 0, 0, 0);
			 	}
			 if ((eventData1 & VAL_ASCII_KEY_MASK) == 102) {
			 	SetCtrlVal(PSETUP, SETUP_Mod, 2);//the 'f' key was pressed
			 	change_mod (PSETUP, SETUP_Mod, 1, 0, 0, 0);
			 	}
			 if ((eventData1 & VAL_ASCII_KEY_MASK) == 110) {
			 	SetCtrlVal(PSETUP, SETUP_Mod, 0);//the 'n' key was pressed
			 	change_mod (PSETUP, SETUP_Mod, 1, 0, 0, 0);
			 	}
			 if ((eventData1 & VAL_ASCII_KEY_MASK) == 122) {
			 	GetCtrlVal(PSETUP, SETUP_ZEEMAN, &ZEEMAN);
			 	SetCtrlVal(PSETUP, SETUP_ZEEMAN, !ZEEMAN);
			 }//the 'z' key was pressed
			 if ((eventData1 & VAL_ASCII_KEY_MASK) == 101) {
			 	SetCtrlVal(PSETUP, SETUP_MODINTEXT, 0);
			 	change_mod_type (PSETUP, SETUP_Mod, 1, 0, 0, 0);
			 }//the 'e' key was pressed
			 if ((eventData1 & VAL_ASCII_KEY_MASK) == 108) {
			 	SetCtrlVal(PSETUP, SETUP_MODINTEXT, 1);
			 	change_mod_type (PSETUP, SETUP_Mod, 1, 0, 0, 0);
			 }//the 'ell' key was pressed
			 if ((eventData1 & VAL_ASCII_KEY_MASK) == 115) {
			 	SetCtrlVal(PSETUP, SETUP_MODINTEXT, 2);
			 	change_mod_type (PSETUP, SETUP_Mod, 1, 0, 0, 0);
			 }//the 's' key was pressed
			}//end if filename
			break;
		}
	return 0;
}
/***** End Setup CallBack Functions *****/
int CVICALLBACK DiodeSetup (int panel, int control, int event,
   void *callbackData, int eventData1, int eventData2)
{
  switch (event) {
    case EVENT_COMMIT:
    if(Convert_Parameters ()){
      if (SavePanelState (PSETUP, fsetup, 1))
        MessagePopup ("", "Error saving setup file");
      beginDiode(); //  entry to diode screens
    }
    break;
  }
  return 0;
}
/*meter PANEL continuously reads from DAQ board until Hide button is pressed */
int CVICALLBACK SHOWP1 (int panel, int control, int event,
    void *callbackData, int eventData1, int eventData2)
{
int i, j, k, panel2, ctrl;
double *MV;
//char temphandle[20];
int32 Nout;
  switch (event) {
    case EVENT_COMMIT:
	  tempPANEL = GetActivePanel ();
	  SetCtrlVal(PP1, P1_PLOW, low);
	  SetCtrlVal(PP1, P1_PHIGH, high);
      DisplayPanel (PP1);
      BP1 = 1;
      Change_Gain(PSETUP, 1, 1, 0, 0, 0);
 	  GetCtrlVal(PSETUP, SETUP_TEMPVOLTAGE, &TEMPV);
	  GetCtrlVal(PSETUP, SETUP_TEMPVOLTAGE2, &TEMP2V);
	  GetCtrlVal(PSETUP, SETUP_P1VOLTAGE, &P1V);
	  GetCtrlVal(PSETUP, SETUP_P2VOLTAGE, &P2V);
  for (i = 0; i < 8; ++i){
   SetCtrlAttribute (PP1, P1_VDISP_1-i, ATTR_VISIBLE, 0);
   SetCtrlAttribute (PP1, P1_UNITS_1-i, ATTR_CTRL_VAL, "");
  }
  MV = malloc (acq.numvolts * sizeof(double));
  k = 0;
  for (i = 0; k < acq.numvolts; ++i){
   if (gain[i]){
    SetCtrlAttribute (PP1, P1_VDISP_1-k, ATTR_VISIBLE, 1);
    if (gain[i] > 20)  {
		SetCtrlAttribute (PP1, P1_UNITS_1-k, ATTR_CTRL_VAL, "mV");
		MV[k] = 1000;
	} else {
		SetCtrlAttribute (PP1, P1_UNITS_1-k, ATTR_CTRL_VAL, "V");
		MV[k] = 1;
    }
	++k;
   } //end if gain
  } //end for
	  j=0;
      while (BP1 == 1){
       GetUserEvent(FALSE, &panel2, &ctrl);
       switch (ctrl){
        case P1_HIDEP1:
         BP1 = 0;
         break;
        case !P1_HIDEP1:
         BP1 = 1;
         break;
        }
        if (BP1 && acq.numvolts){
			Read_Voltages(acq.numvolts, acq.numav,  acqdata.voltage);
			//default action is to read all of the values then average each channel into the first numvolts fields
			++j;
			SetCtrlVal(PP1, P1_COUNT, j);
			for (i = 0; i < acq.numvolts; ++i) {
			 SetCtrlVal(PP1, P1_VDISP_1-i, MV[i]*acqdata.voltage[i]);
			}
         if ((P1V < acq.numvolts)){
			 SetCtrlVal(PP1, P1_V1DISP, acqdata.voltage[P1V]);
			 SetCtrlVal(PP1, P1_Pressure_Meter, acqdata.voltage[P1V]);
		 }
         if ((P2V < acq.numvolts)){
			 SetCtrlVal(PP1, P1_V2DISP, acqdata.voltage[P2V]);
         	 SetCtrlVal(PP1, P1_coarse, acqdata.voltage[P2V]);
			 SetCtrlVal(PP1, P1_Fine, fmod(acqdata.voltage[P2V], 1));
		 }
		 if (TEMPV < numvolts) SetCtrlVal(PP1, P1_T1DISP, 272.3666707 - 894.404135*(acqdata.voltage[TEMPV])*(acqdata.voltage[TEMPV])+26182.44969*(acqdata.voltage[TEMPV]));
         if (TEMP2V < numvolts) SetCtrlVal(PP1, P1_T2DISP, 272.3666707 - 894.404135*(acqdata.voltage[TEMP2V])*(acqdata.voltage[TEMP2V])+26182.44969*(acqdata.voltage[TEMP2V]));
         //if ((TEMPV < numvolts) && gain[TEMPV]) SetCtrlVal(PP1, P1_T1DISP, (-0.894404135*(voltages[TEMPV])*(voltages[TEMPV]))+(26.18244969*(voltages[TEMPV]))+272.366707);
         //if ((TEMP2V < numvolts) && gain[TEMP2V]) SetCtrlVal(PP1, P1_T2DISP, (-0.894404135*(voltages[TEMP2V])*(voltages[TEMP2V]))+(26.18244969*(voltages[TEMP2V]))+272.366707);
        }
      }
      HidePanel(PP1);
      DisplayPanel(tempPANEL);
      break;
  }
  return 0;
}
int CVICALLBACK HIDEP1 (int panel, int control, int event,
    void *callbackData, int eventData1, int eventData2)
{
  switch (event) {
    case EVENT_COMMIT:
      BP1 = 0;
      HidePanel(PP1);
      SetActivePanel (tempPANEL);
      break;
  }
  return 0;
}
 /* individual commands from SETUP panel */
int CVICALLBACK Change_Gain (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
int i, j, k, l;
const double val[4];
double max, min;
char chan_name[9];
	switch (event)
		{
		case EVENT_COMMIT:
		acq.numvolts = 0;
		DAQmxClearTask (DAQInputs);
		DAQmxCreateTask ("", &DAQInputs);
		/*for (j = 1; j < 9; ++j){
			for (i = 1; i < 5; ++i){
				GetTableCellVal (PSETUP, SETUP_VOLTAGEGAINS, MakePoint (i, j), &val[i-1]);
			}
			MaxMin1D (val, 4, &max, &k, &min, &l);
			gain[j-1] = pow(10.0,(1-k));
			//if (gain[j-1] < 1) gain[j-1] = -1;
			if (max == 0) gain[j-1] = 0;
			if (gain[j-1]) {
				numvolts = numvolts + 1;
			    sprintf (chan_name, "Dev1/ai%d", j-1);
			    DAQmxCreateAIVoltageChan (DAQInputs, chan_name, "", DAQmx_Val_NRSE, -gain[j-1], gain[j-1], DAQmx_Val_Volts, "");
			} //end if gain
		}  */
		for (j = 0; j < 8; ++j){
			GetCtrlVal(PSETUP, SETUP_ai_0+j, &gain[j]);
			if (gain[j]) {
				acq.numvolts = acq.numvolts + 1;
			    sprintf (chan_name, "Dev1/ai%d", j);
				max = (double) 10.0/gain[j];
				//scale from 1,2,20,200 to 10.0,5.0,0.5,0.05 and set ranges for channels
				DAQmxCreateAIVoltageChan (DAQInputs, chan_name, "", DAQmx_Val_NRSE, -max, max, DAQmx_Val_Volts, "");
			} //end if gain
		} //end for j
	    GetCtrlVal(PSETUP, SETUP_NUMAV, &acq.numav);
	    acqdata.voltage = malloc (acq.numav * acq.numvolts * (sizeof(float64)));
		aqrd.voltage = malloc (acq.numav * acq.numvolts * (sizeof(float64)));
		SetCtrlVal(PSETUP, SETUP_NUMVOLTS, acq.numvolts);
		break;
		}
	return 0;
}
int CVICALLBACK Changegrays (int panel, int control, int event,
    void *callbackData, int eventData1, int eventData2)
{
  switch (event) {
    case EVENT_COMMIT:
      GetCtrlVal(PSETUP, SETUP_NUMVOLTS, &numvolts);
      if (numvolts > 0){
        //SetCtrlAttribute(PSETUP, SETUP_VOLTDATA, ATTR_DIMMED, 0);
        SetCtrlAttribute(PSETUP, SETUP_VOLTDATA_2, ATTR_DIMMED, 0);
      } else {
        //SetCtrlAttribute(PSETUP, SETUP_VOLTDATA, ATTR_DIMMED, 1);
        SetCtrlAttribute(PSETUP, SETUP_VOLTDATA_2, ATTR_DIMMED, 1);
      }
      break;
  }
  return 0;
}
int CVICALLBACK synth_power (int panel, int control, int event,
    void *callbackData, int eventData1, int eventData2)
{
char buffer[20];
int new, level;
double synthPower;
  switch (event) {
    case EVENT_COMMIT:
    GetCtrlVal (PSETUP, SETUP_SYNTH, &new);
    if (new != synthID) CloseSynth();
    synthID = new;
    GetCtrlVal (PSETUP, SETUP_Wilt_Power, &synthPower);
     if (synthID == WILTRON){
      //if (synthHandle < 0) wlt67XXB_init (5, 0, &synthHandle);
      Fmt (swork, "%s<L1 %f[p1]DM", synthPower);
      PutSynth(swork, NumFmtdBytes());
    } else {
      //if (synthHandle < 0) HP834xB_init(19, 1, 0, &synthHandle);
      change_HPLEVEL(PSETUP, SETUP_LEVEL, 1, 0, 0, 0);
      Fmt (swork, "%s<PL %f[p1]DM", synthPower);
      PutSynth(swork, NumFmtdBytes());
      //HP834xB_rf_output(synthHandle, 1, synthPower, 0, 0.0, 0, 0, 0.0);
    }
      break;
  }
  return 0;
}
int CVICALLBACK synth_power_2 (int panel, int control, int event,
    void *callbackData, int eventData1, int eventData2)
{
char buffer[20];
int new, level;
double synthPower2;
  switch (event) {
    case EVENT_COMMIT:
    GetCtrlVal (PSETUP, SETUP_SYNTH_2, &new);
    if (new != synthID2) CloseSynth();
    synthID2 = new;
    GetCtrlVal (PSETUP, SETUP_Wilt_Power_2, &synthPower2);
     if (synthID2 == WILTRON){
      //if (synthHandle < 0) wlt67XXB_init (5, 0, &synthHandle);
      Fmt (swork, "%s<L1 %f[p1]DM", synthPower2);
      PutSynth2(swork, NumFmtdBytes());
    } else {
      //if (synthHandle < 0) HP834xB_init(19, 1, 0, &synthHandle);
      change_HPLEVEL(PSETUP, SETUP_LEVEL, 1, 0, 0, 0);
      Fmt (swork, "%s<PL %f[p1]DM", synthPower2);
      PutSynth2(swork, NumFmtdBytes());
      //HP834xB_rf_output(synthHandle, 1, synthPower, 0, 0.0, 0, 0, 0.0);
    }
      break;
  }
  return 0;
}
int CVICALLBACK change_mod (int panel, int control, int event,
    void *callbackData, int eventData1, int eventData2)
{
char buffer[20];
int new;
  switch (event) {
    case EVENT_COMMIT:
      GetCtrlVal (PSETUP, SETUP_SYNTH, &new);
      if (new != synthID) CloseSynth();
      synthID = new;
      GetCtrlVal (PSETUP, SETUP_Mod, &Modul);
      GetCtrlVal (PSETUP, SETUP_MODINTEXT, &modintext);
	  change_mod_type (PSETUP, SETUP_MODINTEXT, 1, 0, 0, 0);
//** must break up synthesizer specific functions and arbitrary device functions
	  if (synthID == 1){  //HP settings - waveform must be external
     	if (Modul == 0) {
      		PutSynth("AM0",3);
      		PutSynth("FM0",3);
      	} else if (Modul == 1) {
      		PutSynth("FM0",3);
      		PutSynth("AM1",3);
      		GetCtrlVal (PSETUP, SETUP_MODINTEXT, &modintext);
      	} else if (Modul == 2)  {
      		PutSynth("AM0",3);
      		PutSynth("FM1",3);
      	}
      } else if (synthID == 0){ //Wiltron - ANRITSU settings
        if (Modul == 0) {
          PutSynth("AM0",3);
          PutSynth("FM0",3);
        } else if (Modul == 1) {
          PutSynth("FM0",3);
          if (modintext < 2 || modintext == 3) PutSynth("AM1",3);
		  if (modintext == 2) PutSynth("AM7",3);
        } else if (Modul == 2)  {
          PutSynth("AM0",3);
		  ModSen = 1;
		  if (modintext < 2 || modintext == 3) PutSynth("FM2",3);
          if (modintext == 2) PutSynth("FM9",3);
		  if (Exp == 5) {PutSynth("FMU",3); ModSen = 1;} //video mode!!
		  Fmt (swork, "%s<FMS%dMV", ModSen);
		  PutSynth(swork, NumFmtdBytes());
		}
      }
	  //commands for external (to synthesizer) waveforms
      if (Modul == 1) {
          if (modintext == 3) PutDS345("FUNC 1", 6);
          if (modintext == 0) FGCMD("FUNC:SHAP SQU");//FGCMD("FU2");
      } else if (Modul == 2){
          if (modintext == 3) PutDS345("FUNC 0", 6);
          if (modintext == 0) FGCMD("FUNC:SHAP SIN");//FGCMD("FU1");
      }
      break;
  }
  return 0;
}
int CVICALLBACK change_mod_type (int panel, int control, int event,
    void *callbackData, int eventData1, int eventData2)
{
int check;
char buffer[20], str[20];
  switch (event) {
    case EVENT_COMMIT:
      GetCtrlVal (PSETUP, SETUP_MODINTEXT, &modintext);
      GetCtrlVal (PSETUP, SETUP_Mod, &Modul);
      if (modintext != 1) Fmt (buffer, "%s<FMOD %d", 0);
      if (modintext == 1) Fmt (buffer, "%s<FMOD %d", 1);
      LIACMD(buffer);
      if (modintext == 0) {
        //if (synthID == WILTRON && Modul == 1) PutSynth("AM1", 3);
        //if (synthID == WILTRON && Modul == 2) PutSynth("FML", 3);
        SetCtrlAttribute (PSETUP, SETUP_TONE, ATTR_DIMMED, 0); //external settings are allowed
        SetCtrlAttribute (PSETUP, SETUP_Tone, ATTR_DIMMED, 0);
        //find external amplitude and adjust screen value
        if (FG < 1) FG = ibfind("HPFG");//if (!FG) FG = ibdev (0, 25, NO_SAD, T10s, 1, 0);
        check = iberr;
        if (FG > 0 && check == 0) {
         //ibwrt(FG, "QAP", 3);     /* Send the AMPLITUDE query command   */
         ibwrt(FG, "VOLT?", 5);     /* Send the AMPLITUDE query command   */
   		 if (ibsta & ERR) {
       		MessagePopup ("Error", "GPIB device not listening");
   		 }
		 ibrd(FG, buffer, 20);     /* Read up to 20 bytes from the device    */
   		 if (ibsta & ERR) {
      		MessagePopup ("Error", "GPIB device not talking");
   		 }
   		 buffer[19] = '\0';
		 modamp = atof (buffer);//modamp = atof (&buffer[4]);
         SetCtrlVal(PSETUP, SETUP_ModAmplitude, modamp);
         //find external frequency and adjust screen value
         //ibwrt(FG, "QFR", 3);     /* Send the FREQUENCY query command   */
         ibwrt(FG, "FREQ?", 5);     /* Send the FREQUENCY query command   */
   		 if (ibsta & ERR) {
       		MessagePopup ("Error", "GPIB device not listening");
   		 }
		 ibrd(FG, buffer, 20);     /* Read up to 20 bytes from the device    */
   		 if (ibsta & ERR) {
      		MessagePopup ("Error", "GPIB device not talking");
   		 }
   		 buffer[19] = '\0';
		 modfreq = atof (buffer);//modfreq = atof (&buffer[4]);
         SetCtrlVal(PSETUP, SETUP_ModFrequency, modfreq/1000);
        } //end if (FG > 0)
      } else if (modintext == 1){
        //if (synthID == WILTRON && Modul == 1) PutSynth("AM1", 3);
        //if (synthID == WILTRON && Modul == 2) PutSynth("FML", 3);
        SetCtrlAttribute (PSETUP, SETUP_TONE, ATTR_DIMMED, 1); //LIA settings only
        SetCtrlAttribute (PSETUP, SETUP_Tone, ATTR_DIMMED, 1);
       //find internal amplitude and adjust screen value
        LIACMD("OUTX1");
        ibwrt(LIAhandle, "SLVL?", 5);     /* Send the AMPLITUDE query command   */
   		if (ibsta & ERR) {
      		MessagePopup ("Error", "GPIB device not listening");
   		}
		ibrd(LIAhandle, buffer, 20);     /* Read up to 20 bytes from the device    */
   		if (ibsta & ERR) {
      		MessagePopup ("Error", "GPIB device not talking");
   		}
   		buffer[19] = '\0';
		modamp = atof (&buffer[0]);
        SetCtrlVal(PSETUP, SETUP_ModAmplitude, modamp);
        //find internal frequency and adjust screen value
        ibwrt(LIAhandle, "FREQ?", 5);     /* Send the AMPLITUDE query command   */
   		if (ibsta & ERR) {
      		MessagePopup ("Error", "GPIB device not listening");
   		}
		ibrd(LIAhandle, buffer, 20);     /* Read up to 20 bytes from the device    */
   		if (ibsta & ERR) {
      		MessagePopup ("Error", "GPIB device not talking");
   		}
   		buffer[19] = '\0';
		modfreq = atof (&buffer[0]);
        SetCtrlVal(PSETUP, SETUP_ModFrequency, modfreq/1000);
        } else if (modintext == 2){
         SetCtrlAttribute (PSETUP, SETUP_TONE, ATTR_DIMMED, 1);
         SetCtrlAttribute (PSETUP, SETUP_Tone, ATTR_DIMMED, 1);
       //ANRITSU settings only
       //find internal amplitude and adjust screen value
         if (Modul == 1 && modintext == 2 && synthID == WILTRON) {//query internal AM settings
          //ibwrt(synthHandle, "AM7", 3);
  		  PutSynth("AM7", 3);
          //ibwrt(synthHandle, "OAD1", 4);     /* Query the AM depth   */
  		  ibwrt(synthHandle, "OAD1", 4);
  		  //PutSynth("OAD1", 4);
   		  if (ibsta & ERR) {
      		MessagePopup ("Error", "GPIB device not listening");
   		  }
		  ibrd(synthHandle, buffer, 20);     /* Read up to 20 bytes from the device    */
   		  if (ibsta & ERR) {
      		MessagePopup ("Error", "GPIB device not talking");
   		  }
   		  buffer[19] = '\0';
		  modamp = atof (&buffer[0]);
          SetCtrlVal(PSETUP, SETUP_ModAmplitude, modamp);
          //find internal frequency and adjust screen value
          //ibwrt(synthHandle, "OAR", 3);     /* Send the FREQUENCY query command   */
  		  PutSynth("OAR", 3);
   		  if (ibsta & ERR) {
      		MessagePopup ("Error", "GPIB device not listening");
   		  }
		  ibrd(synthHandle, buffer, 20);     /* Read up to 20 bytes from the device    */
   		  if (ibsta & ERR) {
      		MessagePopup ("Error", "GPIB device not talking");
   		  }
   		  buffer[19] = '\0';
		  modfreq = atof (&buffer[0]);
          SetCtrlVal(PSETUP, SETUP_ModFrequency, modfreq/1000);
        } else if (Modul == 2 && modintext == 2){//query internal FM
          //ibwrt(synthHandle, "FM9", 3);Fmt (buf, "OAD1");
  		  PutSynth("FM9", 3);
          //ibwrt(synthHandle, "OFD", 3);     /* Query the FM depth   (Hz)*/
  		  PutSynth("OFD", 3);
   		  if (ibsta & ERR) {
      		MessagePopup ("Error", "GPIB device not listening");
   		  }
		  ibrd(synthHandle, buffer, 20);     /* Read up to 20 bytes from the device    */
   		  if (ibsta & ERR) {
      		MessagePopup ("Error", "GPIB device not talking");
   		  }
   		  buffer[19] = '\0';
		  modamp = atof (&buffer[0]);
          SetCtrlVal(PSETUP, SETUP_ModAmplitude, modamp/1000000);//should give depth in Volts
          //find internal frequency and adjust screen value
          //ibwrt(synthHandle, "OFR", 3);     /* Send the FREQUENCY query command   */
  		  PutSynth("OFR", 3);
   		  if (ibsta & ERR) {
      		MessagePopup ("Error", "GPIB device not listening");
   		  }
		  ibrd(synthHandle, buffer, 20);     /* Read up to 20 bytes from the device    */
   		  if (ibsta & ERR) {
      		MessagePopup ("Error", "GPIB device not talking");
   		  }
   		  buffer[19] = '\0';
		  modfreq = atof (&buffer[0]);
          SetCtrlVal(PSETUP, SETUP_ModFrequency, modfreq/1000);
        } //end if Modul ?
        } else if (modintext == 3){
		if (ds345Handle < 0) ds345Handle = ibfind("DS345");
		if (ds345Handle > -1){
         //ibwrt(FG, "QAP", 3);     /* Send the AMPLITUDE query command   */
         ibwrt(ds345Handle, "AMPL?", 5);     /* Send the AMPLITUDE query command   */
   		 if (ibsta & ERR) {
       		MessagePopup ("Error", "GPIB device not listening");
   		 }
		 ibrd(ds345Handle, buffer, 20);     /* Read up to 20 bytes from the device    */
   		 if (ibsta & ERR) {
      		MessagePopup ("Error", "GPIB device not talking");
   		 }
   		 buffer[19] = '\0';
		 modamp = atof (buffer);//modamp = atof (&buffer[4]);
         SetCtrlVal(PSETUP, SETUP_ModAmplitude, modamp);
         //find external frequency and adjust screen value
         //ibwrt(FG, "QFR", 3);     /* Send the FREQUENCY query command   */
         ibwrt(ds345Handle, "FREQ?", 5);     /* Send the FREQUENCY query command   */
   		 if (ibsta & ERR) {
       		MessagePopup ("Error", "GPIB device not listening");
   		 }
		 ibrd(ds345Handle, buffer, 20);     /* Read up to 20 bytes from the device    */
   		 if (ibsta & ERR) {
      		MessagePopup ("Error", "GPIB device not talking");
   		 }
   		 buffer[19] = '\0';
		 modfreq = atof (buffer);//modfreq = atof (&buffer[4]);
         SetCtrlVal(PSETUP, SETUP_ModFrequency, modfreq/1000);
        } else {
		 MessagePopup ("WARNING", "DS345 NOT FOUND");
        }
        }
      break;
  }
  return 0;
}
int CVICALLBACK change_det_harm (int panel, int control, int event,
    void *callbackData, int eventData1, int eventData2)
{
char buffer[20];
  switch (event) {
    case EVENT_COMMIT:
      GetCtrlVal (PSETUP, SETUP_MODHARM, &modharm);
      Fmt (buffer, "%s<HARM %d", modharm);
      LIACMD(buffer);
      break;
  }
  return 0;
}
int CVICALLBACK change_mod_amp (int panel, int control, int event,
    void *callbackData, int eventData1, int eventData2)
{
char buffer[20];
  switch (event) {
    case EVENT_COMMIT:
      GetCtrlVal (PSETUP, SETUP_ModAmplitude, &modamp);
      GetCtrlVal (PSETUP, SETUP_MODINTEXT, &modintext);
      GetCtrlVal (PSETUP, SETUP_Mod, &Modul);
      if (modintext == 0){
        //Fmt (buffer, "%s<AP%f[p3]VO", modamp); //Set up the (internal) modulation amplitude
        Fmt (buffer, "%s<VOLT %f[p3]", modamp); //Set up the (internal) modulation amplitude
        FGCMD(buffer);
      } else if(modintext == 1){
        Fmt (buffer, "%s<SLVL %f[p3]", modamp); //Set up the (internal) modulation amplitude
        LIACMD(buffer);
      } else if(modintext == 2){
        if (Modul == 1) Fmt (buffer, "%s<ADP1 %f[p3] PCT", modamp); //Set up the (internal) modulation amplitude
        if (Modul == 2) Fmt (buffer, "%s<FDV %f[p6] MH", modamp); //Set up the (internal) modulation amplitude
        PutSynth(buffer, NumFmtdBytes());
      } else if(modintext == 3){
        if (Modul == 1) Fmt (buffer, "%s<AMPL %f[p3]VP", modamp); //Set up the (internal) modulation amplitude
        if (Modul == 2) Fmt (buffer, "%s<AMPL %f[p3]VP", modamp); //Set up the (internal) modulation amplitude
        PutDS345(buffer, NumFmtdBytes());
        if (Modul == 1) {
        	Fmt (buffer, "%s<DPTH 100"); //Set up the (internal) modulation amplitude
        	PutDS345(buffer, NumFmtdBytes());
        }
      }
      break;
  }
  return 0;
}
int CVICALLBACK change_time_constant (int panel, int control, int event,
    void *callbackData, int eventData1, int eventData2)
{
char buffer[20];
  switch (event) {
    case EVENT_COMMIT:
      GetCtrlVal (PSETUP, SETUP_TAUFINE, &taufine);
      GetCtrlVal (PSETUP, SETUP_TAUCOARSE, &taucoarse);
	  if (whichlia < 2){
		if (taucoarse + taufine < 0) {
         SetCtrlVal (PSETUP, SETUP_TAUFINE, 0);
         taufine = 0;
        }
       Fmt (buffer, "%s<OFLT %d", taufine + taucoarse);  // Set up the Time Constant
      } else if (whichlia == 2){
      }
	  LIACMD(buffer);
      break;
  }
  return 0;
}
int CVICALLBACK change_sensitivity (int panel, int control, int event,
    void *callbackData, int eventData1, int eventData2)
{
int temp;
double exp;
char buffer[20];
  switch (event) {
    case EVENT_COMMIT:
      GetCtrlVal (PSETUP, SETUP_SENSEFINE, &sensefine);
      GetCtrlVal (PSETUP, SETUP_SENSECOARSE, &sensecoarse);
	  GetCtrlVal(PSETUP, SETUP_LIA, &whichlia);
	  if (whichlia < 2){
       Fmt (buffer, "%s<SENS %d", sensefine + sensecoarse); //Set up the sensitivity
      } else if (whichlia == 2){
	   Fmt (buffer, "%s<G%d\n", sensefine + sensecoarse);
	  }
	  LIACMD(buffer);
      sensitivity = sense[sensefine+sensecoarse];//0.001*temp * pow(10, exp); //18 -> 0 (V), 9 -> -3 (mV), 0 -> -6 (uV)
      break;
  }
  return 0;
}
int CVICALLBACK change_mod_freq (int panel, int control, int event,
    void *callbackData, int eventData1, int eventData2)
{
char buffer[20];
int toneburst, count;
  switch (event) {
    case EVENT_COMMIT:
      GetCtrlVal (PSETUP, SETUP_ModFrequency, &modfreq);
      GetCtrlVal (PSETUP, SETUP_MODINTEXT, &modintext);
      GetCtrlVal (PSETUP, SETUP_Mod, &Modul);
      if (modintext == 0){
        //Fmt (buffer, "%s<FR%f[p3]KZ", modfreq); //Set up the (internal) modulation amplitude
        Fmt (buffer, "%s<FREQ %f[p3]", modfreq*1000); //Set up the (internal) modulation amplitude
        FGCMD(buffer);
      } else if(modintext == 1) {
        Fmt (buffer, "%s<FREQ %f[p3]", modfreq*1000); //Set up the (internal) modulation frequency
        LIACMD(buffer);
      } else if(modintext == 2){
        if (Modul == 1) Fmt (buffer, "%s<AMR %f[p6]KH", modfreq); //Set up the (internal) modulation frequency
        if (Modul == 2) Fmt (buffer, "%s<FMR %f[p6]KH", modfreq); //Set up the (internal) modulation frequency
        PutSynth(buffer, NumFmtdBytes());
      } else if(modintext == 3){
        Fmt (buffer, "%s<FREQ %f[p6]", modfreq*1000); //Set up the modulation frequency
        PutDS345(buffer, NumFmtdBytes());
      }
      GetCtrlVal(PSETUP, SETUP_TONE, &toneburst);
      if (toneburst){
        count = 0.5*modfreq/tone;
        Fmt (buffer, "%s<BM:NCYC %d", count); //Set up the burst with duty cycle of 0.5
        FGCMD(buffer);
        }
	  break;
  }
  return 0;
}
int CVICALLBACK Setup_Tone (int panel, int control, int event,
    void *callbackData, int eventData1, int eventData2)
{
int val, choice, count;
char buffer[20];
  switch (event) {
    case EVENT_COMMIT:
      GetCtrlVal(PSETUP, SETUP_TONE, &val);
      if (val){
        SetCtrlVal(PSETUP, SETUP_MODINTEXT, 0);
        SetCtrlAttribute (PSETUP, SETUP_MODINTEXT, ATTR_DIMMED, 1);
        Fmt (buffer, "%s<FMOD %d", 2);
        LIACMD(buffer);
        //Fmt(buffer, "%s<SR%d", 1); /*sets internal trigger*/
        Fmt(buffer, "%s<BM:SOUR INT"); /*sets internal trigger*/
        FGCMD(buffer);
        //Fmt(buffer, "%s<MO%d", 2);   /*sets gate*/
        //FGCMD(buffer);
        //Fmt(buffer, "%s<FU%d", 1);  // sets burst to sine-wave
        Fmt(buffer, "%s<FUNC:SHAP SIN");  // sets tone to sine-wave
        FGCMD(buffer);
        /*choice = GenericMessagePopup ("Toneburst Modulation",
                                      "You are setting up the spectrometer for Toneburst Modulation, Make Sure LIA REFERENCE cable goes to FG TRIGGER out, select FM for DIrect multiplication, or NONE for PLL",
                                      "Keep Current F & V",
                                      "Load Default F & V",
                                      "Read F & V from External", buffer, 19, 0,
                                      VAL_GENERIC_POPUP_BTN2,
                                      VAL_GENERIC_POPUP_BTN1,
                                      VAL_GENERIC_POPUP_BTN1);
        if (choice == 1){
          change_mod_freq (PSETUP, 0, 1, 0, 0, 0);
          change_mod_amp (PSETUP, 0, 1, 0, 0, 0);
          change_tone (PSETUP, 0, 1, 0, 0, 0);
        } else if(choice == 2){ */
          SetCtrlVal(PSETUP, SETUP_Tone, 0.5000);
          tone = 0.5000;
          SetCtrlVal(PSETUP, SETUP_ModFrequency, 100.0);
          SetCtrlVal(PSETUP, SETUP_ModAmplitude, 0.1);
          change_mod_freq (PSETUP, 0, 1, 0, 0, 0);
          change_mod_amp (PSETUP, 0, 1, 0, 0, 0);
          change_tone (PSETUP, 0, 1, 0, 0, 0);
        /*} else if(choice == 3){
          //FGCMD("QAP");
          FGCMD("VOLT?");
          ibrd(FG, &buffer, 20);
          sscanf(buffer, "%f", &modamp);
          SetCtrlVal(PSETUP, SETUP_ModAmplitude, modamp);
          //FGCMD("QTI");
          FGCMD("BM:INT RATE?");
          ibrd(FG, &buffer, 20);
          sscanf(buffer, "%f", &tone);
          SetCtrlVal(PSETUP, SETUP_Tone, tone);
          //FGCMD("QFR");
          FGCMD("FREQ?");
          ibrd(FG, &buffer, 20);
          sscanf(buffer, "%f", &modfreq);
          SetCtrlVal(PSETUP, SETUP_ModFrequency, 0.0001*modfreq);
        } */
        count = 0.5*modfreq/tone;
        Fmt (buffer, "%s<BM:NCYC %d", count); //Set up the burst with duty cycle of 0.5
        FGCMD(buffer);
		FGCMD("BM:STAT 1");
      } else {
        SetCtrlAttribute (PSETUP, SETUP_MODINTEXT, ATTR_DIMMED, 0);
        //MessagePopup ("No Toneburst", "You have turned off ToneBurst Modulation, if you are continuing to use the external modulation source connect the LIA REFERENCE to FG SYNC");
        //Fmt(buffer, "%s<MO%d", 1);   /*sets free-run mode*/
        FGCMD("BM:STAT 0");
        //Fmt(buffer, "%s<MO%d", 1);   /*sets free-run mode*/
        //FGCMD(buffer);
        Fmt(buffer, "%s<FUNC:SHAP SIN");  //sets tone to sine-wave
        //Fmt(buffer, "%s<FU%d", 1);  //sets tone to sine-wave
        FGCMD(buffer);
      }
      break;
  }
  return 0;
}
int CVICALLBACK change_tone (int panel, int control, int event,
    void *callbackData, int eventData1, int eventData2)
{
char buffer[30];
int count;
  switch (event) {
    case EVENT_COMMIT:
      GetCtrlVal(PSETUP, SETUP_Tone, &tone);
      //Fmt (buffer, "%s<TI%f[p3]MS", 1/tone); //Set up the (internal) modulation amplitude
      Fmt (buffer, "%s<BM:INT:RATE %f[p3]", tone*1000); //Set up the (internal) modulation amplitude
      FGCMD(buffer);
      count = 0.5*modfreq/tone;
      Fmt (buffer, "%s<BM:NCYC %d", count); //Set up the burst with duty cycle of 0.5
      FGCMD(buffer);
      break;
  }
  return 0;
}
int CVICALLBACK change_VFLIA (int panel, int control, int event,
    void *callbackData, int eventData1, int eventData2)
{
  switch (event) {
    case EVENT_COMMIT:
       GetCtrlVal(PSETUP, SETUP_VFLIA, &NUMPTPI);
       //LIA = !NUMPTPI;
       LIA = 0;
	   if (NUMPTPI == 0) LIA = 1;
	   break;
  }
  return 0;
}
int CVICALLBACK change_HPLEVEL (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
int level;
	switch (event)
		{
		case EVENT_COMMIT:
     		GetCtrlVal(PSETUP, SETUP_LEVEL, &level);
     		if (level == 0) PutSynth("A1", 2);
     		if (level == 4) PutSynth("SHAZ", 4);
     		if (level == 2) PutSynth("A3", 2);
     		//HP834xB_leveling(synthHandle, level, 0.0, 0.0);
			break;
		}
	return 0;
}
int CVICALLBACK ChangePRange (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	switch (event)
		{
		case EVENT_COMMIT:
			GetCtrlVal(PP1, P1_PLOW, &low);
			GetCtrlVal(PP1, P1_PHIGH, &high);
			SetCtrlAttribute (PP1, P1_Pressure_Meter, ATTR_MAX_VALUE, high);
			SetCtrlAttribute (PP1, P1_Pressure_Meter, ATTR_MIN_VALUE, low);
			break;
		}
	return 0;
}
int CVICALLBACK change_XRLIA (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	char buffer[20];
	switch (event)
		{
		case EVENT_COMMIT:
			  GetCtrlVal(PSETUP, SETUP_XRLIA, &XRNUM);
			  Fmt (buffer, "%s<DDEF 1,%d,0", XRNUM);
              LIACMD(buffer);
			break;
		}
	return 0;
}
int CVICALLBACK Change_SA_Type (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
double Frequency;
char buffer[20];
	switch (event)
		{
		case EVENT_COMMIT:
			  Frequency = 10;
			  GetCtrlVal(PSETUP, SETUP_SA_type, &SAType);
			  if (SAType == 1){
			   GetCtrlVal(PSETUP, SETUP_SweepMode, &SwMode);
			   if (SwMode > 0) GetCtrlVal(PSETUP, SETUP_SynthStart, &Frequency);
			   if (SwMode < 0) GetCtrlVal(PSETUP, SETUP_SynthEnd, &Frequency);
			   if (Frequency > 26500) {
			   	SetCtrlVal(PSETUP, SETUP_SA_type, 0);
			   	Frequency = 10;
			   	}
			  } else if (SAType == 2) {
			   GetCtrlVal(PSETUP, SETUP_Synth_Offset, &Frequency);
			   if (Frequency > 26500) {
			   	SetCtrlVal(PSETUP, SETUP_SA_type, 0);
			    Frequency = 10;
			    }
			  }
			  Fmt (buffer, "%s<CENTER %f[p3] MZ", Frequency);
              SACMD(buffer);
			break;
		}
	return 0;
}
int CVICALLBACK Change_YIGFILT (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
double temp;// second;
	switch (event)
		{
		case EVENT_COMMIT:
			GetCtrlVal (PSETUP, SETUP_YIGFILT, &yigfilt);
			GetCtrlVal(PSETUP, SETUP_DAQ, &DAQNUM);
			if(yigfilt){
			   //turn on this AO
			   SetCtrlAttribute (PSETUP, SETUP_YIGVOLTS, ATTR_VISIBLE, 1);
			   //find out what the current frequency is and calculate voltage
			   GetCtrlVal(PSETUP, SETUP_SweepMode, &SwMode);
			   if (SwMode > 0) GetCtrlVal(PSETUP, SETUP_SynthStart, &temp);
			   if (SwMode < 0) GetCtrlVal(PSETUP, SETUP_SynthEnd, &temp);
			   // 12 - 18 GHz filter: temp = -2.004e-10*(temp*temp) + 0.00059254*temp - 0.6388;//0.5882*(temp/1000) - 0.5882;
			   // 8 - 20 GHz filter
			   if((temp >= 8055) && (temp < 16000)) {
				 temp = 1.2502392938E-12*pow(temp,3) - 5.3871524613E-08*pow(temp,2) + 1.3282817039E-03*temp - 8.1902944608E+00;
			   } else if ((temp >= 16000) && (temp < 26500)) {
			   	temp = -2.3779020659E-12*pow(temp,3) + 1.2406292196E-07*pow(temp,2) - 1.5934373386E-03*temp + 7.8619869118E+00;
				   //temp = 0.0005507111*(temp-8000)+0.000000000010073*pow((temp-8000),2.0)+0.0000000000000328617*pow((temp-8000),3.0);
			   } else {
			    temp = 0;
			   }
			   SetCtrlVal(PSETUP, SETUP_YIGVOLTS, temp);
			   if ((temp >= 10.0) || (temp <= 0.0)){
				SetCtrlAttribute (PSETUP, SETUP_YIGVOLTS, ATTR_TEXT_COLOR, VAL_RED);
			   } else {
			    GetCtrlVal(PSETUP, SETUP_VOLTSOUT, &DAQdata[0]);
			    GetCtrlVal(PSETUP, SETUP_YIGVOLTS, &DAQdata[1]);
				SetCtrlAttribute (PSETUP, SETUP_YIGVOLTS, ATTR_TEXT_COLOR, VAL_BLACK);
			    DAQmxWriteAnalogF64(DAQHandle,1,1,1.0,DAQmx_Val_GroupByChannel,DAQdata,NULL,NULL);
			   }
			   //SetCtrlVal(PSETUP, SETUP_VOLTSOUT, temp);
			}
			break;
		}		  //SETUP_YIGVOLTS = 67
	return 0;
}
int CVICALLBACK fix_lia (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	switch (event)
		{
		case EVENT_COMMIT:
			GetCtrlVal(PSETUP, SETUP_LIA, &whichlia);
			break;
		}
	return 0;
}
int CVICALLBACK Zeeman (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	switch (event)
		{
		case EVENT_COMMIT:
			GetCtrlVal (PSETUP, SETUP_ZEEMAN, &ZEEMAN);
			break;
		}
	return 0;
}
//these two functions swap the analog output controls
int CVICALLBACK fix_daq (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	switch (event)
		{
		case EVENT_COMMIT:
			GetCtrlVal(PSETUP, SETUP_DAQ, &DAQNUM);
			SetCtrlVal(PSETUP, SETUP_DAQ_2, !DAQNUM);
			GetCtrlVal(PSETUP, SETUP_DAQ_2, &DAQ2NUM);
			break;
		}
	return 0;
}
int CVICALLBACK fix_daq2 (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	switch (event)
		{
		case EVENT_COMMIT:
			GetCtrlVal(PSETUP, SETUP_DAQ_2, &DAQ2NUM);
			SetCtrlVal(PSETUP, SETUP_DAQ, !DAQ2NUM);
			GetCtrlVal(PSETUP, SETUP_DAQ, &DAQNUM);
			break;
		}
	return 0;
}
int CVICALLBACK Change_Volts (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
double temp;
	switch (event)
		{
		case EVENT_COMMIT:
			/*GetCtrlVal(PSETUP, SETUP_DAQ_2, &DAQ2NUM);
			GetCtrlVal(PSETUP, SETUP_VOLTSOUT, &temp);
			AOUpdateChannel (DAQ2NUM, "0", temp);	   */
			GetCtrlVal(PSETUP, SETUP_VOLTSOUT, &DAQdata[0]);
			GetCtrlVal(PSETUP, SETUP_YIGVOLTS, &DAQdata[1]);
			if ((DAQdata[0] >= 10.1) || (DAQdata[0] < 0.0) || (DAQdata[1] >= 10.1) || (DAQdata[1] < 0.0)){
				SetCtrlAttribute (PSETUP, SETUP_YIGVOLTS, ATTR_TEXT_COLOR, VAL_RED);
			} else {
		    	SetCtrlAttribute (PSETUP, SETUP_YIGVOLTS, ATTR_TEXT_COLOR, VAL_BLACK);
			    DAQmxWriteAnalogF64(DAQHandle,1,1,1.0,DAQmx_Val_GroupByChannel,DAQdata,NULL,NULL);
			}
			break;
		}
	return 0;
}
/******** LASER SETUP *********/
int CVICALLBACK Change_LASER (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
double laserfreq, laserwavelength;
char buf[35];
	switch (event)
		{
		case EVENT_COMMIT:
		    if (laserHandle < 0) laserHandle = ibfind("LASER");
			GetCtrlVal(PSETUP, SETUP_LASERFREQ, &laserfreq);
			laserwavelength = 10000000/laserfreq;
			Fmt (buf, "%s<WAVE %f[p2]", laserwavelength);
   			PutLASER(buf, NumFmtdBytes());
			break;
		}
	return 0;
}
int CVICALLBACK Change_LASER_CURRENT (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
double lasercurrent;
char buf[35];
	switch (event)
		{
		case EVENT_COMMIT:
		    if (laserHandle < 0) laserHandle = ibfind("LASER");
		    if (laserHandle > -1){
				GetCtrlVal(PSETUP, SETUP_LASERCURRENT, &lasercurrent);
				Fmt (buf, "%s<CURR %f[p1]", lasercurrent);
   				PutLASER(buf, NumFmtdBytes());
   			} else {
			 MessagePopup ("WARNING", "LASER NOT FOUND");
   			}
			break;
		}
	return 0;
}
int CVICALLBACK CHANGE_DS345 (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
double ds345volts;
char buf[35];
	switch (event)
		{
		case EVENT_COMMIT:
			if (ds345Handle < 0) ds345Handle = ibfind("DS345");
			if (ds345Handle > -1){
				GetCtrlVal(PSETUP, SETUP_DS345_VOLTS, &ds345volts);
				Fmt (buf, "%s<OFFS %f[p6]", ds345volts);
   				PutDS345(buf, NumFmtdBytes());
   			} else {
			 MessagePopup ("WARNING", "DS345 NOT FOUND");
   			}
			break;
			break;
		}
	return 0;
}
int updateScan(int updn, int indx, int ixend)
{   // set up scan parameters
//  SMMACQCMD acq;
  int waitread, i, temp;//new var temp added for time sweep logic
  temp = 0;				//new
  if (updn > 0){
  	if (ixend < 0) {	//new
  		temp = 1;			//new
  		ixend = indx + 10;   //new
  	}						 //new
    if (indx > ixend) return -1;
    if (temp) ixend = -1;	   //new
    updn =  1; acqThreadFlush = 0;
  } else if (updn < 0) {
    if (indx < ixend) return -1;
    updn = -1; acqThreadFlush = 0;
  } else { /* updn == 0 */
    acqThreadFlush = 1;
    if (ixend >= 0) return 0;  /* ixend < 0 kills thread */
  }
  acq.updn = updn; acq.indx = indx; acq.ixend = ixend;
  acq.numvolts = numvolts; acq.numav = numav;
  //acqmxn.nnpage = NPage;
  CmtWriteTSQData (acqcmdTSQ, &acq, 1, TSQ_INFINITE_TIMEOUT, NULL);
  return updn;
}
int acqthread(void *dumy)
{ // mother function for data acquisition thread
//  SMMACQCMD acq;
//  SMMACQDATA acqdata;
  char buffer[20], serpol;
  double synthPower, temp, temp2,tempf, KFac;
  float tempint, intint;
  float64 temp64[2], *tempvolts;
  int i, j, t, nPts, len, daqpt;
  //double gain;
  acq.updn = 0;
  for(;;){
    while (acq.updn == 0 || acqThreadFlush){
      CmtReadTSQData (acqcmdTSQ, &acq, 1, TSQ_INFINITE_TIMEOUT, NULL);
      if (acq.updn == 0) return 0;  /* terminate thread */
    }
     //bjd moved SetFreq discrete command into V/F or LIA cases
    if (NUMPTPI == 1){		  //v/f
     SetFreq(acq.indx);
     temp = 0;
     GetIntensity (&temp, &acqdata.auxfreq);
     acqdata.intens = temp;
     temp2 = 0;
	 if (ZEEMAN){
	  //AOUpdateChannel (DAQNUM3, "0", zhi);
		DAQmxWriteAnalogF64(DAQHandle,1,1,1.0,DAQmx_Val_GroupByChannel, DAQdata,NULL,NULL);
		temp64[1] = DAQdata[1];
		temp64[0] = 0;
	  GetIntensity (&temp, &temp2);
	  acqdata.intens -= temp;
		DAQmxWriteAnalogF64(DAQHandle,1,1,1.0,DAQmx_Val_GroupByChannel, temp64,NULL,NULL);
//	  AOUpdateChannel (DAQNUM3, "0", zlow);
	 }//end if ZEEMAN
	 daqpt = 1;//(int) fmod(acq.indx, acq.numav);//change numav to be point spacing for DAQ measurments
	 if (acq.numvolts && daqpt) {
		 if (acq.indx == 0) tempvolts = malloc (acq.numav*acq.numvolts*sizeof(float64));
		 Read_Voltages(acq.numvolts, acq.numav,  tempvolts);
		 acqdata.voltage = tempvolts;
	 } else {
		 acqdata.voltage = tempvolts;
	 }
	/**********/
     acqdata.indx = acq.indx;
     CmtWriteTSQData (acqdataTSQ, &acqdata, 1, TSQ_INFINITE_TIMEOUT, NULL);
     if (acq.indx == acq.ixend)
      acq.updn = 0;
     else
      if (acq.ixend > -1) acq.indx += acq.updn;			//bjd add
    } else if (LIA){			//lia
     SetFreq(acq.indx);
     Delay (WaitCPUTime);
     ibwrt(LIAhandle, "OUTR?1", 6);  //reads channel 1 display
     ibrd(LIAhandle, buffer, 20);
     sscanf(buffer, "%f", &tempint);
     acqdata.intens = 10000*tempint/sensitivity;
	if (ZEEMAN){
	  //AOUpdateChannel (DAQNUM3, "0", zhi);
      	DAQmxWriteAnalogF64(DAQHandle,1,1,1.0,DAQmx_Val_GroupByChannel,DAQdata,NULL,NULL);
		temp64[1] = DAQdata[1];
		temp64[0] = 0;
	  Delay (WaitCPUTime);
      ibwrt(LIAhandle, "OUTR?1", 6);  //reads channel 1 display
      ibrd(LIAhandle, buffer, 20);
      sscanf(buffer, "%f", &tempint);
      acqdata.intens -= 10000*tempint/sensitivity;
	  //AOUpdateChannel (DAQNUM3, "0", zlow);
	 	DAQmxWriteAnalogF64(DAQHandle,1,1,1.0,DAQmx_Val_GroupByChannel,temp64,NULL,NULL);
	}
	daqpt = 0;//(int) fmod(acq.indx, acq.numav);//change numav to be point spacing for DAQ measurments
	if (acq.numvolts && !daqpt) {
		if ((acq.indx == 0) || (acq.ixend == 0)) tempvolts = malloc (acq.numav*acq.numvolts*sizeof(float64));
		Read_Voltages(acq.numvolts, acq.numav,  tempvolts);
		acqdata.voltage = tempvolts;
	} else if (acq.ixend == 0) {
		tempvolts = malloc (acq.numav*acq.numvolts*sizeof(float64));
		acqdata.voltage = tempvolts;
    }
	/**********/
     acqdata.indx = acq.indx;
     CmtWriteTSQData (acqdataTSQ, &acqdata, 1, TSQ_INFINITE_TIMEOUT, NULL);
     if (acq.indx == acq.ixend)
       acq.updn = 0;
     else
       if (acq.ixend > -1) acq.indx += acq.updn;  //bjd add
	} else if (NUMPTPI == 2) {//take data through DAQ interface
     SetFreq(acq.indx);
     Delay (WaitCPUTime);
     if (acq.numvolts) Read_Voltages(acq.numvolts, acq.numav,  acqdata.voltage);
     acqdata.intens = 1000*acqdata.voltage[0];	   //hardwire to ai0
	 if (ZEEMAN){
      DAQmxWriteAnalogF64(DAQHandle,1,1,1.0,DAQmx_Val_GroupByChannel,DAQdata,NULL,NULL);
	  temp64[1] = DAQdata[1];
	  temp64[0] = 0;
	  Delay (WaitCPUTime);
      if (acq.numvolts) Read_Voltages(acq.numvolts, acq.numav,  acqdata.voltage);
      acqdata.intens -= 1000*acqdata.voltage[0];
      DAQmxWriteAnalogF64(DAQHandle,1,1,1.0,DAQmx_Val_GroupByChannel,temp64,NULL,NULL);
	}
     /**********/
     acqdata.indx = acq.indx;
     CmtWriteTSQData (acqdataTSQ, &acqdata, 1, TSQ_INFINITE_TIMEOUT, NULL);
     if (acq.indx == acq.ixend)
       acq.updn = 0;
     else
       if (acq.ixend > -1) acq.indx += acq.updn;
	}
  }
  return 0;
}
void Read_Voltages(int numv, int numa, double *voltages)
{
int i, j, k, NN;
	DAQmxReadAnalogF64 (DAQInputs, numa, 1.0, DAQmx_Val_GroupByScanNumber, voltages, numa*numv, &NN, 0);
	k = 0;
	for (i = 0; i < 8; ++i){
    	if (gain[i]) {
		 for (j = 1; j < numa; ++j){
		    voltages[k] += voltages[k+j*numv];//put sum into first set
    	 }
    	 voltages[k] /= numa;		  //create average
		 ++k;
		}
    }
}
void SetFreq (int ipt)
{
  char buf[35];
  int tempi;
  double synthNow, temp, tempvolts;
  synthNow = synthStart + ipt * synthStep;
  //if (Exp < 4 ){ try to get action from setup buttons while in video mode
  if (Exp < 4 || ipt == 0){
   if (synthID == WILTRON){
    Fmt (buf, "%s<F1 %f[p0]KH", synthNow);
   } else {
     Fmt (buf, "%s<CW%f[p0]HZ", synthNow);
   }
   PutSynth(buf, NumFmtdBytes());
   }
  else if (Exp == 4){//must use kHz for both synthesizers
   synthNow = synthStart + ipt * synthStep;
   if (synthID == WILTRON){
    Fmt (buf, "%s<F1 %f[p0]KH", synthNow);
   } else {
     Fmt (buf, "%s<CW%f[p0]KZ", synthNow);
   }
   PutSynth(buf, NumFmtdBytes());
   //synthNow = synthStart - synthOffset + ipt * synthStep;
   synthNow =  synthHarm*(synthNow - synthOffset)/synthHarm2;
   if (synthID2 == WILTRON){
    Fmt (buf, "%s<F1 %f[p1]KH", synthNow);
   } else {
     Fmt (buf, "%s<CW%f[p1]KZ", synthNow);
   }
   PutSynth2(buf, NumFmtdBytes());
  } else if (Exp == 5){  //video mode?
	tempvolts = (double) ipt * 0.001 * synthHarm * synthStep/ModSen;
  	Fmt (buf, "%s<OFFS %f[p6]", tempvolts);
   	PutDS345(buf, NumFmtdBytes());
  }
/****tune YIG filter with measured polynomial for voltage***/
  //every 5 steps
  tempi = (int) fmod(ipt, yigfilt);
  if(yigfilt && !tempi) {
   	temp = synthNow/1000000;//	  convert from Hz to MHz
   	// 8 - 20 GHz filter:
	if(temp >= 8055) {
	 //temp =  0.0005519098*(temp-8055.41)*(1.0014863-2.015840e-6*(temp-8055.41));
	 temp = -2.3779020659E-12*pow(temp,3) + 1.2406292196E-07*pow(temp,2) - 1.5934373386E-03*temp + 7.8619869118E+00;
	} else {
	 temp = 0;
	}
   	// 12 - 18 GHz filter:  temp = -2.004e-10*(temp*temp) + 0.00059254*temp - 0.6388;//0.5882*(temp/1000) - 0.5882;
	//AOUpdateChannel (DAQNUM, "0", temp);
	DAQdata[1] = temp;
	if ((temp < 10.0) && (temp > 0.0)) DAQmxWriteAnalogF64(DAQHandle,1,1,1.0,DAQmx_Val_GroupByChannel,DAQdata,NULL,NULL);
  }
/****tune synth analyzer to track RF or IF**/
  if (SAType == 1){
   Fmt (buf, "%s<CENTER %f[p3] HZ", synthNow);
   SACMD(buf);
  } else if (SAType == 2) {
   Fmt (buf, "%s<CENTER %f[p3] HZ", synthOffset);
   SACMD(buf);
  }
}
void LIACMD (char *str)
{
int check;
char serPol;
	 if (LIAhandle < 1) LIAhandle = ibfind("LIA");
	 check = iberr;
     //if (!LIAhandle) LIAhandle = ibdev (0, 8, NO_SAD, T10s, 1, 0);
     if (LIAhandle > 0){
      ibwrt(LIAhandle, str, strlen(str));
      /*do {
        ibrsp(LIAhandle, &serPol);
        } while ((serPol&2)==0);*/
     }
}
void SACMD (char *str)
{
int check;
char serPol;
	 if (SAhandle < 1) SAhandle = ibfind("ANALYZER");
	 check = iberr;
     if (SAhandle > 0){
      ibwrt(SAhandle, str, strlen(str));
     }
}
void FGCMD (char *str)
{
     if (FG < 1) FG = ibfind("HPFG");
     //if (!FG) FG = ibdev (0, 25, NO_SAD, T10s, 1, 0);
     if (FG > 0) ibwrt(FG, str, strlen(str));
}
void PutSynth(char *str, int len)
{
  int ret;
  if (synthHandle < 0) return;
  if (synthID == WILTRON){
    ret = ibwrt(synthHandle, str, len);
    if (ret > 7999) {
    MessagePopup ("WARNING", "Synthesizer not responding");
    }
  } else {
    ret = ibwrt(synthHandle, str, len);
    if (ret > 7999) {
    MessagePopup ("WARNING", "Synthesizer not responding");
    }
  }
}
void PutSynth2(char *str, int len)
{
  int ret;
  if (synthHandle2 < 0) return;
  if (synthID2 == WILTRON){
    ret = ibwrt(synthHandle2, str, len);
    if (ret > 7999) {
    MessagePopup ("WARNING", "Synthesizer 2 not responding");
    }
  } else {
    ret = ibwrt(synthHandle2, str, len);
    if (ret > 7999) {
    MessagePopup ("WARNING", "Synthesizer 2 not responding");
    }
  }
}
void PutLASER(char *str, int len)
{
  int ret;
  if (laserHandle < 0) return;
    ret = ibwrt(laserHandle, str, len);
    if (ret > 7999) MessagePopup ("WARNING", "LASER not responding");
}
void PutDS345(char *str, int len)
{
  int ret;
  if (ds345Handle < 0) return;
    ret = ibwrt(ds345Handle, str, len);
    if (ret > 7999) MessagePopup ("WARNING", "DS345 not responding");
}
int GetIntensity (double *intens, double *auxfreq)
{
  int bigword;
  *auxfreq = defFreq;
  outp (ADDC, 0xe9);/* set output counter 1 high */
  outp (ADDC, 0x7f);/* load and arm counter 1,2,3,4,5 */
  Delay (WaitCPUTime);
  if((inp (ADDC) & 2) == 0) { /* check for out1 low*/
    *intens = -10000.; return -1;
  }else{
    outp (ADDC, 0xbe);/* save counter 2,3,4,5 into hold register */
    outp (ADDC, 023);/* pointer to hold register 3 */
    bigword  = inp (ADDD) & BMASK;
    bigword += (inp (ADDD) & BMASK) << 8;
    outp (ADDC, 022);/* pointer to hold register 2 */
    bigword  = (bigword << 16) + (inp (ADDD) & BMASK);
    bigword += (inp (ADDD) & BMASK) <<8;
    *intens = intenScale * bigword - 10000;
    outp (ADDC, 025);/* pointer to hold register 5 */
    bigword  = inp (ADDD) & BMASK;
    bigword += (inp (ADDD) & BMASK) << 8;
    outp (ADDC, 024);/* pointer to hold register 4 */
    bigword  = (bigword << 16) + (inp (ADDD) & BMASK);
    bigword += (inp (ADDD) & BMASK) <<8;
    if (bigword) *auxfreq = freqScale * bigword;
    return 0;
  }
}
int CVICALLBACK Change_Trigger (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	int i, trigger, num, NN;
	float64 *outs, temp64[2];
	switch (event)
	{
		case EVENT_COMMIT:
		/*	DeleteGraphPlot (PSETUP, SETUP_GRAPH, -1, VAL_IMMEDIATE_DRAW);
			GetCtrlVal(PSETUP, SETUP_Freq_Start, &FStart);
			GetCtrlVal(PSETUP, SETUP_Freq_End, &FEnd);
			GetCtrlVal(PSETUP, SETUP_Freq_Step, &FStep);
			num = (int) fabs((FEnd - FStart)/FStep);
			voltages = malloc (num*sizeof(float64));
            outs = malloc (num*sizeof(float64));
			for (i = 0; i < num; ++i) outs[i] = (float) (num-i)/num;
			GetCtrlVal(PSETUP, SETUP_TRIGGER, &trigger);
			DAQmxClearTask (DAQClock);
		    DAQmxCreateTask ("", &DAQClock);
			DAQmxCreateCOPulseChanTime (DAQClock, "Dev1/ctr0", "", DAQmx_Val_Seconds, DAQmx_Val_Low, 0.0, 0.5/trigger, 0.5/trigger);
			DAQmxCfgImplicitTiming (DAQClock, DAQmx_Val_FiniteSamps, num);
			DAQmxClearTask (DAQInputs);
		    DAQmxCreateTask ("", &DAQInputs);
			DAQmxCreateAIVoltageChan(DAQInputs, "Dev1/ai0", "", DAQmx_Val_NRSE, -10, 10, DAQmx_Val_Volts, "");
			DAQmxCfgSampClkTiming (DAQInputs, "", trigger, DAQmx_Val_Rising, DAQmx_Val_FiniteSamps, num);
//			DAQmxCfgDigEdgeStartTrig (DAQInputs, "/Dev1/PFI0", DAQmx_Val_Falling);
			DAQmxClearTask (DAQHandle);
		    DAQmxCreateTask ("", &DAQHandle);
			DAQmxCreateAOVoltageChan (DAQHandle, "Dev1/ao0", "", -10, 10, DAQmx_Val_Volts, "");
//			DAQmxWriteAnalogF64(DAQHandle,1,1,1.0,DAQmx_Val_GroupByChannel,&outs[num-1],NULL,NULL);
			DAQmxCfgSampClkTiming (DAQHandle, "", trigger, DAQmx_Val_Rising, DAQmx_Val_FiniteSamps, num);
			//DAQmxCfgSampClkTiming(taskHandle,"/Dev1/PFI0",1000.0,DAQmx_Val_Rising,DAQmx_Val_ContSamps,1000)
//			DAQmxCfgSampClkTiming (DAQHandle, "/Dev1/PFI0", trigger, DAQmx_Val_Rising, DAQmx_Val_FiniteSamps, num);
//			DAQmxSetTimingAttribute (DAQHandle, DAQmx_SampClk_Src, "/Dev1/PFI0");
//			DAQmxSetTimingAttribute (DAQHandle, DAQmx_SampTimingType, DAQmx_Val_SampClk);
			DAQmxCfgDigEdgeStartTrig (DAQHandle, "/Dev1/PFI0", DAQmx_Val_Rising);
			DAQmxWriteAnalogF64 (DAQHandle, num, 0, 10.0, DAQmx_Val_GroupByChannel, outs, NULL, 0);
//		    temp64[0] = 0.5;
	        temp64[1] = 1.0;
			DAQmxWriteAnalogF64 (DAQHandle, 2, 0, 10.0, DAQmx_Val_GroupByChannel, temp64, NULL, 0);
//
			DAQmxStartTask(DAQHandle);
			DAQmxStartTask(DAQInputs);
			DAQmxStartTask(DAQClock);
			DAQmxReadAnalogF64 (DAQInputs, num, 10.0, DAQmx_Val_GroupByScanNumber, voltages, num, &NN, 0);
			PlotY (PSETUP, SETUP_GRAPH, voltages, num, VAL_DOUBLE, VAL_THIN_LINE, VAL_NO_POINT, VAL_SOLID, 1, VAL_RED);
			*/
			break;
	}
	return 0;
}