view FXAnalyse.c @ 135:77539f2597b1

Code cleanup
author Daniele Nicolodi <daniele.nicolodi@obspm.fr>
date Wed, 22 Jan 2014 12:29:38 +0100
parents bd28161e5ac2
children 7b9cf3d4346e
line wrap: on
line source

#include <tcpsupp.h>
#include <utility.h>
#include <ansi_c.h>
#include <cvirte.h>		
#include <userint.h>
#include <formatio.h>
#include <string.h>
#include <future.h>

#include "YLCStuff.h"
#include "FXAnalyse.h" 
#include "Plot.h"
#include "Allan.h"
#include "DDS4xAD9912.h"
#include "DDS_Fox.h" 
#include "muParserDLL.h"
#include "stat.h"

#define SR_LOGGER_IP "145.238.204.91"
#define DATAFOLDER "Z:\\Measures-2013"

#define FREP_STEP_SIZE 50000.0

// number of channels read
#define NCHAN 4

// data acquisition event
struct event {
	struct timeval time;
	double data[NCHAN];
};

// data acquisition status
int acquiring;
// data queue
CmtTSQHandle dataQueue;
// data provider thread
CmtThreadFunctionID dataProviderThread;

// data providers
int CVICALLBACK FakeDataProvider (void *functionData);
int CVICALLBACK FileDataProvider (void *functionData);
int CVICALLBACK KKDataProvider (void *functionData);

// select which data provider to use
#define DataProvider KKDataProvider


double utc;
double Ch1, Ch2, Ch3, Ch4;
double Math1, Math2, Math3, Math4, Math5;
double N1, N2, N3;


// panels
static int MainPanel;
static int CalcNPanel;
static int EstimateN3Panel;
static int LoggingPanel;


struct adev {
	Allan_Data allan;
	double *data;
	const char *title;
	double normalization;
	int control;
};


#define ADEV_INIT(__channel, __normalization)	\
	{											\
		.data = & ## __channel,					\
		.title = #__channel,					\
		.normalization = __normalization,		\
		.control = PANEL_ADEV_ ## __channel		\
	}


int adev_toggle(struct adev *adev)
{
	if (adev->allan.active)
		Allan_ClosePanel(&(adev->allan));
	else
		Allan_InitPanel(&(adev->allan), adev->title,
			adev->normalization, MainPanel, adev->control);
	return adev->allan.active;
}


void adev_update(struct adev *adev)
{
	if (adev->allan.active)
		Allan_AddFrequency(&(adev->allan), *(adev->data));
}


struct adev adevs[] = {
	ADEV_INIT(Ch1, 1.84e12),
	ADEV_INIT(Ch2, 10.0e3),
	ADEV_INIT(Ch3, 429.228e12),
	ADEV_INIT(Ch4, 275.0e3),
	ADEV_INIT(Math1, 250.0e6),
	ADEV_INIT(Math2, 194.395e12),
	ADEV_INIT(Math3, 282.143e12),
	ADEV_INIT(Math4, 429.228e12),
	ADEV_INIT(Math5, 1.0),
	{ NULL }
};


struct plot {
	Plot_Data plot;
	double *data;
	const char *title;
	double min;
	double max;
	int control;
};


#define PLOT_INIT(__channel, __min, __max) 		\
	{											\
		.data = & ## __channel, 				\
		.title = #__channel,					\
		.min = __min,							\
		.max = __max,							\
		.control = PANEL_PLOT_ ## __channel		\
	}


int plot_toggle(struct plot *plot)
{
	if (plot->plot.active)
		Plot_ClosePanel(&(plot->plot));
	else
		Plot_InitPanel(&(plot->plot), plot->title,
			plot->min, plot->max, MainPanel, plot->control);
	return plot->plot.active;
}


void plot_update(struct plot *plot)
{
	if (plot->plot.active)
		Plot_AddFrequency(&(plot->plot), *(plot->data));
}

struct plot plots[] = {
	PLOT_INIT(Ch1, 54.999e6, 55.001e6),
	PLOT_INIT(Ch2, 0.0, 0.0),
	PLOT_INIT(Ch3, 0.0, 0.0),
	PLOT_INIT(Ch4, 0.0, 0.0),
	PLOT_INIT(Math1, 0.0, 0.0),
	PLOT_INIT(Math2, 0.0, 0.0),
	PLOT_INIT(Math3, 0.0, 0.0),
	PLOT_INIT(Math4, 0.0, 0.0),
	PLOT_INIT(Math5, 0.0, 0.0),
	{ NULL }
};


// 1xAD9956 DDS box
DDSParameter DDS1xAD9956;
// 4xAD9912 DDS box
DDS4xAD9912_Data DDS4xAD9912;

muParserHandle_t MathParser1, MathParser2, MathParser3, MathParser4, MathParser5;

double Ndiv = 8.0;

int settling = 0;

enum {
	MEASURING_N_NONE,
	MEASURING_N_Lo,
	MEASURING_N_Hg,
	MEASURING_N_Sr,
};

int measuring = MEASURING_N_NONE;

enum {
	N_MEASUREMENT_NONE,
	N_MEASUREMENT_INIT,
	N_MEASUREMENT_SLOPE,
	N_MEASUREMENT_ADJUST_FREQ_PLUS,
	N_MEASUREMENT_FREP_PLUS,
	N_MEASUREMENT_ADJUST_FREQ_MINUS,
	N_MEASUREMENT_FREP_MINUS,
};

int Measuring_1 = N_MEASUREMENT_NONE;
int Measuring_2 = N_MEASUREMENT_NONE;											  
int Measuring_3 = N_MEASUREMENT_NONE;

double FrequDDS1=110000000.0;
double Slope_1=0.0, Slope_2=0.0, Slope_3=0.0, Beatslope_2=0.0;
double SlopeTime1=40.0, SlopeTime2=40.0, SlopeTime3=40.0;
double Ch4Slope = 0.0;

double N_1=0.0, N_2=0.0, N_3=0.0;
double DeltaT_1=20.0, DeltakHz_1=500.0, t1_1=0.0, t2_1=0.0, t3_1=0.0, Frepplus_1=0.0, Frepminus_1=0.0;
double DeltaT_2=20.0, DeltakHz_2=500.0, t1_2=0.0, t2_2=0.0, t3_2=0.0, Frepplus_2=0.0, Frepminus_2=0.0;
double DeltaT_3=20.0, DeltakHz_3=500.0, t1_3=0.0, t2_3=0.0, t3_3=0.0;

int n_1=0, n_2=0, n_3=0;

double FrequencyDDSBesInit = 0.0;
double FrequencyDDS3Init = 0.0;

double DeltaDDS3=0.0,Delta10K_Plus=0.0,Delta10K_Minus=0.0;
double Nu1=0.0, Nu2= 200000-147000+282143746.557455e6;  

double f_rep_slope;
double f_rep_plus, f_rep_minus;
double f_beat_Sr_plus, f_beat_Sr_minus;

double Ch4Plus=0.0,Ch4Minus=0.0;

double Frequencystep1=10000.0, tbegin1=0.0, Frepbefore1=0.0, Frequency1=0.0;
double Frequencystep2=10.0, tbegin2=0.0, Frepbefore2=0.0, Ch2before=0.0, Frequency2=0.0;
double Frequencystep3=100000.0, tbegin3=0.0, Frepbefore3=0.0, Frequency3=0.0;

volatile bool Getsign1=FALSE,Getsign2=FALSE,Getsign3=FALSE;
double Sign1=1.0, Sign2=1.0, Sign3=0.0;


struct stat stat_math1, stat_ch2, stat_ch3, stat_ch4, freq;
struct rollmean rollmean_ch1, rollmean_ch2, rollmean_ch3, rollmean_ch4;


// dedrift
struct dedrift {
	int enabled;        // dedrift enabled
	int reference;      // reference frequency
	int invert;         // invert applied slope sign
	int doubleslope;    // double applied slope
	int keep_freq;      // keep current frequency value when dedrift is disabled
	int keep_slope;     // keep current slope value when dedrift is disabled
	double freq0;       // DDS center frequency
	double threshold;   // maximum allowed frequency change
	double applied;     // currently applied slope
	double interval;    // measurement duration
	double t0;          // beginning of currrent measurement interval
};

enum {
	DEDRIFT_REFERENCE_MICROWAVE = 0,
	DEDRIFT_REFERENCE_HG = 1,
};

struct dedrift dedrift = {
	.enabled = FALSE,
	.reference = DEDRIFT_REFERENCE_MICROWAVE,
	.invert = FALSE,
	.doubleslope = FALSE,
	.keep_freq = TRUE,
	.keep_slope = TRUE,
	.freq0 = 70e6,
	.threshold = 100.0,
	.applied = 0.0,
	.interval = 40.0,
	.t0 = 0.0
};


// recenter
struct recenter {
	int enabled;		// recenter enabled
	int Lo;				// recenter microwave beatnote
	int Sr;				// recenter Sr beatnote
	int Hg;				// recenter Hg beatnote
	double interval;	// interval
	double t0;			// beginning of current interval
};

struct recenter recenter = {
	.enabled = FALSE,
	.Lo = FALSE,
	.Sr = FALSE,
	.Hg = FALSE,
	.interval = 1800.0,
	.t0 = 0.0
};


char * thousands(char *buffer, int size, char *fmt, double val)
{
	// compute how many separators we need
	#pragma DisableFunctionRuntimeChecking log10
	int nsep = log10(fabs(val));
	nsep = (nsep > 0 ? nsep / 3 : 0);
	// format value
	int len = snprintf(buffer, size, fmt, val);
	char *src = buffer + len;
	char *dst = src + nsep;
	// copy till decimal separator
	while (*src != '.')
		*dst-- = *src--;
	// the next char is the decimal separator
	int n = -1;
	// copy till src and dst point to the same location
	while (src != dst) {
		*dst-- = *src--;
		// insert separator
		if (isdigit(*src) && (++n) && ((n % 3) == 0))
			*dst-- = ' ';
	}
	return buffer;
}


#define MIN(x, y) (x) < (y) ? (x) : (y)

// MJD functiom used by the Sr programs
static inline double utc2mjd(double utc)
{
	return 15020.0 + utc / 86400.0;
}


void logmsg(const char *frmt, ...)
{
	char msg[1024];
	int len = 0;
	
	// timestamp
	len += sprintf(msg, "%014.3f ", utc);
	time_t now = time(NULL);
	struct tm *t = localtime(&now);
	len += strftime(msg + len, sizeof(msg) - len, "%d-%m-%Y %H:%M:%S ", t);
	
	// message
	va_list args;
	va_start(args, frmt);
	len += vsnprintf(msg + len, sizeof(msg) - len, frmt, args);
	va_end(args);
	
	// add newline
	len = MIN(len, sizeof(msg) - 2);
	msg[len] = '\n';
	msg[len + 1] = '\0';
	
	// display message
	SetCtrlVal(LoggingPanel, LOGGING_LOGGING, msg);
}

// Sr data logger
int sendLogger(const char* id, double utc, double data)
{
	static unsigned int handle = 0;
	char buffer[1024];

	// try to connect and quit if unsuccessfull
	if (handle == 0) {
		if (ConnectToTCPServer(&handle, 3491, SR_LOGGER_IP, NULL, NULL, 1) < 0) {
			logmsg("Sr data logger connection error");
			return -1;
		}
		logmsg("connected to Sr data logger");
	}

	snprintf(buffer, sizeof(buffer), "%s %.7f %.8f", id, utc2mjd(utc), data);
	if (ClientTCPWrite(handle, buffer, strlen(buffer) + 1, 0) < 0) {
		// try to reconnect and resend
		handle = 0;
		sendLogger(id, utc, data);
	}
	
	return 0;
}

muParserHandle_t initMathParser() 
{
	muParserHandle_t parser = mupCreate();
	mupDefineOprtChars(parser, "abcdefghijklmnopqrstuvwxyzµ"
                        	   "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                        	   "+-*^/?<>=#!$%&|~'_");
	mupDefineVar(parser, "UTC", &utc);
	mupDefineVar(parser, "Ch1", &Ch1);
	mupDefineVar(parser, "Ch2", &Ch2);
	mupDefineVar(parser, "Ch3", &Ch3);
	mupDefineVar(parser, "Ch4", &Ch4);
	mupDefineVar(parser, "DDS1", &(DDS4xAD9912.Frequency1));   
	mupDefineVar(parser, "DDS2", &(DDS4xAD9912.Frequency2));
	mupDefineVar(parser, "DDS3", &(DDS4xAD9912.Frequency3));  
	mupDefineVar(parser, "DDS4", &(DDS4xAD9912.Frequency4));  
	mupDefineVar(parser, "N1", &N1);
	mupDefineVar(parser, "N2", &N2);
	mupDefineVar(parser, "N3", &N3);
	mupDefineVar(parser, "Nu1", &Nu1);
	mupDefineVar(parser, "Nu2", &Nu2);
	mupDefineVar(parser, "DeltaDDS3", &DeltaDDS3);
	mupDefineVar(parser, "Sign1", &Sign1);
	mupDefineVar(parser, "Sign2", &Sign2);
	mupDefineVar(parser, "Sign3", &Sign3);
	mupDefineVar(parser, "Ndiv", &Ndiv);
	mupDefinePostfixOprt(parser, "P", &Peta,  1);
	mupDefinePostfixOprt(parser, "T", &Tera,  1);
	mupDefinePostfixOprt(parser, "G", &Giga,  1);
	mupDefinePostfixOprt(parser, "M", &Mega,  1);
	mupDefinePostfixOprt(parser, "k", &kilo,  1);
	mupDefinePostfixOprt(parser, "m", &milli, 1);
	mupDefinePostfixOprt(parser, "u", &micro, 1);
	mupDefinePostfixOprt(parser, "µ", &micro, 1);
	mupDefinePostfixOprt(parser, "n", &nano,  1);
	mupDefinePostfixOprt(parser, "p", &pico,  1);
	mupDefinePostfixOprt(parser, "f", &femto, 1);
	
	return parser;
}


void writeData(const char *folder, const char *name, const char *id, 
		const char *timestr, double utc, double value)
{
	char line[1024];
	char filename[FILENAME_MAX];
	
	// construct filename in the form folder\\id-name.txt
	snprintf(filename, sizeof(filename), "%s\\%s-%s.txt", folder, id, name);
	
	int fd = OpenFile(filename, VAL_WRITE_ONLY, VAL_APPEND, VAL_ASCII);
	Fmt(line, "%s\t%f[p3]\t%f[p3]", timestr, utc, value);
	WriteLine(fd, line, -1);
	CloseFile(fd);
}

void writeData4(const char *folder, const char *name, const char *id, 
		const char *timestr, double utc, double v1, double v2, double v3, double v4)
{
	char line[1024];
	char filename[FILENAME_MAX];
	
	// construct filename in the form folder\\id-name.txt
	snprintf(filename, sizeof(filename), "%s\\%s-%s.txt", folder, id, name);
	
	int fd = OpenFile(filename, VAL_WRITE_ONLY, VAL_APPEND, VAL_ASCII);
	Fmt(line, "%s\t%f[p3]\t%f[p3]\t%f[p3]\t%f[p3]\t%f[p3]", timestr, utc, v1, v2, v3, v4);
	WriteLine(fd, line, -1);
	CloseFile(fd);
}

void CVICALLBACK DataAvailableCB (CmtTSQHandle queueHandle, unsigned int event,
		int value, void *callbackData);


int main (int argc, char *argv[])
{
	double frequency;
	char expr[1024];
	
	if (InitCVIRTE (0, argv, 0) == 0)
		return -1;
	
	if ((MainPanel = LoadPanel (0, "FXAnalyse.uir", PANEL)) < 0)
		return -1;
	if ((CalcNPanel = LoadPanel (MainPanel, "FXAnalyse.uir", CALCN)) < 0)
		return -1;
	if ((EstimateN3Panel = LoadPanel (MainPanel, "FXAnalyse.uir", ESTIMATEN3)) < 0)
		return -1;
	if ((LoggingPanel = LoadPanel (0, "FXAnalyse.uir", LOGGING)) < 0)
		return -1;
	
	// initialize 4x AD9959 DDS box
	DDS4xAD9912_Reset(&DDS4xAD9912);
	GetCtrlVal(MainPanel, PANEL_DDS1, &frequency);
	DDS4xAD9912_SetFrequency(&DDS4xAD9912, 1, frequency);
	GetCtrlVal(MainPanel, PANEL_DDS2, &frequency);
	DDS4xAD9912_SetFrequency(&DDS4xAD9912, 2, frequency);
	GetCtrlVal(MainPanel, PANEL_DDS3, &frequency);
	DDS4xAD9912_SetFrequency(&DDS4xAD9912, 3, frequency);
	GetCtrlVal(MainPanel, PANEL_DDS4, &frequency);
	DDS4xAD9912_SetFrequency(&DDS4xAD9912, 4, frequency);
	
	// initialyze 1x AD9956 DDS box
	DDSFox_Initialize(&DDS1xAD9956, "145.238.205.58", 6665, dedrift.freq0);
	
	Ch1 = Ch2 = Ch3 = Ch4 = 0.0;
	
	GetCtrlVal(MainPanel, PANEL_N1CHOICE, &N1);
	GetCtrlVal(MainPanel, PANEL_N2CHOICE, &N2);
	GetCtrlVal(MainPanel, PANEL_N3CHOICE, &N3);
	
	MathParser1 = initMathParser();
	GetCtrlVal(MainPanel, PANEL_MATHSTRING1, expr);
	mupSetExpr(MathParser1, expr);
	
	MathParser2 = initMathParser();
	mupDefineVar(MathParser2, "Math1", &Math1);
	mupDefineVar(MathParser2, "DDS", &(DDS4xAD9912.Frequency1));
	GetCtrlVal(MainPanel, PANEL_MATHSTRING2, expr);
	mupSetExpr(MathParser2, expr);
	
	MathParser3 = initMathParser();
	mupDefineVar(MathParser3, "Math1", &Math1);
	mupDefineVar(MathParser3, "Math2", &Math2);
	mupDefineVar(MathParser3, "DDS", &(DDS4xAD9912.Frequency2));
	GetCtrlVal(MainPanel, PANEL_MATHSTRING3, expr);
	mupSetExpr(MathParser3, expr);
	
	MathParser4 = initMathParser();
	mupDefineVar(MathParser4, "Math1", &Math1);
	mupDefineVar(MathParser4, "Math2", &Math2);
	mupDefineVar(MathParser4, "Math3", &Math3);
	GetCtrlVal(MainPanel, PANEL_MATHSTRING4, expr);
	mupSetExpr(MathParser4, expr);
	
	MathParser5 = initMathParser();
	mupDefineVar(MathParser5, "Math1", &Math1);
	mupDefineVar(MathParser5, "Math2", &Math2);
	mupDefineVar(MathParser5, "Math3", &Math3);
	mupDefineVar(MathParser5, "Math4", &Math4);
	GetCtrlVal(MainPanel, PANEL_MATHSTRING5, expr);
	mupSetExpr(MathParser5, expr);

	// data queue
	CmtNewTSQ(128, sizeof(struct event), 0, &dataQueue);

	// register callback to execute when data will be in the data queue
	CmtInstallTSQCallback(dataQueue, EVENT_TSQ_ITEMS_IN_QUEUE, 1,
		DataAvailableCB, NULL, CmtGetCurrentThreadID(), NULL);
	
	DisplayPanel(MainPanel);
	
	RunUserInterface();
	
	DiscardPanel(MainPanel);
	return 0;
}


int CVICALLBACK QuitCallback (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	switch (event)
	{
		case EVENT_COMMIT:
			QuitUserInterface(0);
			break;
	}
	return 0;
}

int CVICALLBACK CB_OnEventMain(int panel, int event,
		void *callbackData, int eventData1, int eventData2)
{
	int ActiveControl ;
	int StepIndex ;
	double Step ;
	
	switch (event) {
		case EVENT_KEYPRESS:
			switch (eventData1)	// ie the code of the key which has been stroke 
				{
				case VAL_RIGHT_ARROW_VKEY :
					ActiveControl = GetActiveCtrl(panel);
					if (ActiveControl==PANEL_DDS1 || ActiveControl==PANEL_DDS1STEP) {
						GetCtrlIndex(MainPanel, PANEL_DDS1STEP, &StepIndex);
						if (StepIndex<14){
							SetCtrlIndex(MainPanel, PANEL_DDS1STEP, ++StepIndex) ;
							GetCtrlVal(MainPanel, PANEL_DDS1STEP, &Step);
							SetCtrlAttribute(MainPanel, PANEL_DDS1, ATTR_INCR_VALUE, Step) ;
						};
					};
					if (ActiveControl==PANEL_DDS2 || ActiveControl==PANEL_DDS2STEP) {
						GetCtrlIndex(MainPanel, PANEL_DDS2STEP, &StepIndex);
						if (StepIndex<14){
							SetCtrlIndex(MainPanel, PANEL_DDS2STEP, ++StepIndex) ;
							GetCtrlVal(MainPanel, PANEL_DDS2STEP, &Step);
							SetCtrlAttribute(MainPanel, PANEL_DDS2, ATTR_INCR_VALUE, Step) ;
						};
					};
					if (ActiveControl==PANEL_DDS3|| ActiveControl==PANEL_DDS3STEP) {
						GetCtrlIndex(MainPanel, PANEL_DDS3STEP, &StepIndex);
						if (StepIndex<14){
							SetCtrlIndex(MainPanel, PANEL_DDS3STEP, ++StepIndex) ;
							GetCtrlVal(MainPanel, PANEL_DDS3STEP, &Step);
							SetCtrlAttribute(MainPanel, PANEL_DDS3, ATTR_INCR_VALUE, Step) ;
						};
					};
					if (ActiveControl==PANEL_DDS4|| ActiveControl==PANEL_DDS4STEP) {
						GetCtrlIndex(MainPanel, PANEL_DDS4STEP, &StepIndex);
						if (StepIndex<14){
							SetCtrlIndex(MainPanel, PANEL_DDS4STEP, ++StepIndex) ;
							GetCtrlVal(MainPanel, PANEL_DDS4STEP, &Step);
							SetCtrlAttribute(MainPanel, PANEL_DDS4, ATTR_INCR_VALUE, Step) ;
						};
					};
					break;
				case VAL_LEFT_ARROW_VKEY :
					ActiveControl = GetActiveCtrl(panel);
					if (ActiveControl==PANEL_DDS1 || ActiveControl==PANEL_DDS1STEP) {
						GetCtrlIndex(MainPanel, PANEL_DDS1STEP, &StepIndex);
						if (StepIndex>0){
							SetCtrlIndex(MainPanel, PANEL_DDS1STEP, --StepIndex) ;
							GetCtrlVal(MainPanel, PANEL_DDS1STEP, &Step);
							SetCtrlAttribute(MainPanel, PANEL_DDS1, ATTR_INCR_VALUE, Step) ;
						};
					};
					if (ActiveControl==PANEL_DDS2 || ActiveControl==PANEL_DDS2STEP) {
						GetCtrlIndex(MainPanel, PANEL_DDS2STEP, &StepIndex);
						if (StepIndex>0){
							SetCtrlIndex(MainPanel, PANEL_DDS2STEP, --StepIndex) ;
							GetCtrlVal(MainPanel, PANEL_DDS2STEP, &Step);
							SetCtrlAttribute(MainPanel, PANEL_DDS2, ATTR_INCR_VALUE, Step) ;
						};
					};
					if (ActiveControl==PANEL_DDS3 || ActiveControl==PANEL_DDS3STEP) {
						GetCtrlIndex(MainPanel, PANEL_DDS3STEP, &StepIndex);
						if (StepIndex>0){
							SetCtrlIndex(MainPanel, PANEL_DDS3STEP, --StepIndex) ;
							GetCtrlVal(MainPanel, PANEL_DDS3STEP, &Step);
							SetCtrlAttribute(MainPanel, PANEL_DDS3, ATTR_INCR_VALUE, Step) ;
						};
					};
					if (ActiveControl==PANEL_DDS4 || ActiveControl==PANEL_DDS4STEP) {
						GetCtrlIndex(MainPanel, PANEL_DDS4STEP, &StepIndex);
						if (StepIndex>0){
							SetCtrlIndex(MainPanel, PANEL_DDS4STEP, --StepIndex) ;
							GetCtrlVal(MainPanel, PANEL_DDS4STEP, &Step);
							SetCtrlAttribute(MainPanel, PANEL_DDS4, ATTR_INCR_VALUE, Step) ;
						};
					};
					break;
				case VAL_F2_VKEY :
					SetActiveCtrl(MainPanel, PANEL_DDS1);
					break;
				case VAL_F3_VKEY :
					SetActiveCtrl(MainPanel, PANEL_DDS2);
					break;
				case VAL_F4_VKEY :
					SetActiveCtrl(MainPanel, PANEL_DDS3);
					break;
				case VAL_F5_VKEY :
					SetActiveCtrl(MainPanel, PANEL_DDS4);
					break;
				};
			break;
			
	}
	return 0;
}


int CVICALLBACK CB_OnStart (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	switch (event)
	{
		case EVENT_COMMIT:
			if (acquiring)
				break;
			
			logmsg("Start");
			SetCtrlAttribute(panel, PANEL_STARTBUTTON, ATTR_DIMMED, TRUE);
			acquiring = 1;
			
			// start data provider thread
			CmtScheduleThreadPoolFunctionAdv(
				DEFAULT_THREAD_POOL_HANDLE, DataProvider, NULL,
				THREAD_PRIORITY_HIGHEST, NULL, 0, NULL, 0, &dataProviderThread);

			break;
	}
	return 0;
}

int CVICALLBACK CB_OnStop (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	switch (event) {
		case EVENT_COMMIT:
			if (! acquiring)
				break;
			
			logmsg("Stop");
			acquiring = 0;
			
			// wait for data provider thread to terminate
			CmtWaitForThreadPoolFunctionCompletion(
				DEFAULT_THREAD_POOL_HANDLE, dataProviderThread,
				OPT_TP_PROCESS_EVENTS_WHILE_WAITING);
			CmtReleaseThreadPoolFunctionID(
				DEFAULT_THREAD_POOL_HANDLE, dataProviderThread);
			
			SetCtrlAttribute(panel, PANEL_STARTBUTTON, ATTR_DIMMED, FALSE);
			
			break;
	}
	return 0;
}


void CVICALLBACK MessageCB (void *msg)
{
	if (msg != NULL)
		logmsg(msg);
}


void CVICALLBACK DataAvailableCB (CmtTSQHandle queueHandle, unsigned int ev,
		int value, void *callbackData)
{
	struct event event;
	int read;
	
	switch (ev) {
		case EVENT_TSQ_ITEMS_IN_QUEUE:
			// read data from the data queue
			while (value > 0) {
				
				read = CmtReadTSQData(queueHandle, &event, 1, TSQ_INFINITE_TIMEOUT, 0);
				if (read != 1)
					logmsg("Error!");
				value = value - read;
				
				utc = event.time.tv_sec + event.time.tv_usec * 1e-6;
				Ch1 = event.data[0];
				Ch2 = event.data[1];
				Ch3 = event.data[2];
				Ch4 = event.data[3];

				// update display
				SetCtrlVal(MainPanel, PANEL_UTC, utc);
				SetCtrlVal(MainPanel, PANEL_CH1, Ch1);
				SetCtrlVal(MainPanel, PANEL_CH2, Ch2);
				SetCtrlVal(MainPanel, PANEL_CH3, Ch3);  
				SetCtrlVal(MainPanel, PANEL_CH4, Ch4);
				
				// compute
				Math1 = mupEval(MathParser1);
				Math2 = mupEval(MathParser2);
				Math3 = mupEval(MathParser3);
				Math4 = mupEval(MathParser4);
				Math5 = mupEval(MathParser5);
				
				// update display.  numeric controllers do not format values
				// with a thousands separator: use string controllers and a 
				// custom formatting function
				char buffer[256];
				SetCtrlVal(MainPanel,PANEL_MATH1, thousands(buffer, sizeof(buffer), "%.6f", Math1));
				SetCtrlVal(MainPanel,PANEL_MATH2, thousands(buffer, sizeof(buffer), "%.3f", Math2));
				SetCtrlVal(MainPanel,PANEL_MATH3, thousands(buffer, sizeof(buffer), "%.3f", Math3));
				SetCtrlVal(MainPanel,PANEL_MATH4, thousands(buffer, sizeof(buffer), "%.3f", Math4));
				SetCtrlVal(MainPanel,PANEL_MATH5, thousands(buffer, sizeof(buffer), "%.3f", Math5));
				
				// update timeseries plots
				for (struct plot *plot = plots; plot->data; plot++)
					plot_update(plot);

				// update allan deviation plots
				for (struct adev *adev = adevs; adev->data; adev++)
					adev_update(adev);
				
				// Calcul de N
				
				switch (Measuring_1) {
					
					case N_MEASUREMENT_NONE:
						// not measuring
						break;
					
					case N_MEASUREMENT_INIT:
						// initialization step
						
						// set DDS1 to nominal frequency
						SetCtrlVal(MainPanel, PANEL_DDS1, FrequDDS1);
						DDS4xAD9912_SetFrequency(&DDS4xAD9912, 1, FrequDDS1);
						
						GetCtrlVal(MainPanel, PANEL_DDS2, &FrequencyDDSBesInit);
						t2_1 = t3_1 = 0.0;
						t1_1 = utc;
						
						stat_zero(&stat_math1);
						stat_zero(&stat_ch4);
						
						// next step
						Measuring_1 += 1;
						break;
						
					case N_MEASUREMENT_SLOPE:
						// slope measurement
						
						stat_accumulate(&stat_math1, Math1);
						stat_accumulate(&stat_ch4, Ch4);
						
						if ((utc - t1_1) > SlopeTime1) {
							Slope_1 = stat_math1.slope;
							Ch4Slope =  stat_ch4.slope;
							SetCtrlVal(CalcNPanel, CALCN_SLOPE, Slope_1);
							
							// frep positive step
							DDS4xAD9912_RampFrequency(&DDS4xAD9912, 1, FrequDDS1 + DeltakHz_1 * 1000.0, FREP_STEP_SIZE);
							SetCtrlVal(MainPanel, PANEL_DDS1, FrequDDS1 + DeltakHz_1 * 1000.0);
							
							// allow counter to settle
							settling = 3;
							
							// next step
							Measuring_1 += 1;
						}
						break;
						
					case N_MEASUREMENT_ADJUST_FREQ_PLUS:
					case N_MEASUREMENT_ADJUST_FREQ_MINUS:
						// adjust DDS frequency to keep beatnote within the bandpass filter
						
						if (settling > 0) {
							settling--;
							break;
						}
						
						double fDDS2 = DDS4xAD9912_GetFrequency(&DDS4xAD9912, 2);
						fDDS2 += 275000 - Ch4;
						SetCtrlVal(MainPanel, PANEL_DDS2, fDDS2);
						DDS4xAD9912_SetFrequency(&DDS4xAD9912, 2, fDDS2);
						
						// allow counter to settle
						settling = 3;
						
						// next step
						Measuring_1 += 1;
						break;								
						
					case N_MEASUREMENT_FREP_PLUS:
						// frep positive step
						
						if (settling > 0) {
							settling--;
							break;
						}
						
						if (t2_1 == 0.0)
							t2_1 = utc;
						
						Frepplus_1 = Frepplus_1 + Math1 - Slope_1 * (utc - t2_1);
						Ch4Plus = Ch4Plus + Ch4 - Ch4Slope * (utc - t2_1);
						n_1 += 1;
						
						if ((utc - t2_1) > DeltaT_1) {
							Frepplus_1 = Frepplus_1 / n_1;
							Ch4Plus = Ch4Plus / n_1; 
							n_1 = 0;
							
							// frep negative step
							DDS4xAD9912_RampFrequency(&DDS4xAD9912, 1, FrequDDS1 - DeltakHz_1 * 1000.0, FREP_STEP_SIZE);
							SetCtrlVal(MainPanel, PANEL_DDS1, FrequDDS1 - DeltakHz_1 * 1000.0);  
							
							// allow counter to settle
							settling = 3;
							
							// next step
							Measuring_1 += 1;
						}
						break;
						
					case N_MEASUREMENT_FREP_MINUS:
						// frep negative step
						
						if (settling > 0) {
							settling--;
							break;
						}
						
						if (t3_1 == 0.0)
							t3_1 = utc;
						
						Frepminus_1 = Frepminus_1 + Math1 - Slope_1 * (utc - t3_1);
						Ch4Minus = Ch4Minus + Ch4 - Ch4Slope * (utc - t3_1);
						n_1 += 1;
						
						if ((utc - t3_1) > DeltaT_1) {
							Frepminus_1 = Frepminus_1 / n_1;
							Ch4Minus = Ch4Minus / n_1;
							n_1 = 0;
							
							// compute N1
							N_1 = Sign1 * (2*Ndiv * DeltakHz_1 * 1000)/(Frepminus_1 - Frepplus_1 - Slope_1 * (t3_1 - t2_1));
							SetCtrlVal(CalcNPanel, CALCN_N, N_1);
						
							t1_1 = 0.0;
							t2_1 = 0.0;
							t3_1 = 0.0;
							Frepminus_1 = 0.0;
							Frepplus_1 = 0.0;
							
							// back to nominal frep
							DDS4xAD9912_RampFrequency(&DDS4xAD9912, 1, FrequDDS1, FREP_STEP_SIZE);
							SetCtrlVal(MainPanel, PANEL_DDS1, FrequDDS1);
							SetCtrlVal(MainPanel, PANEL_DDS2, FrequencyDDSBesInit);
							DDS4xAD9912_SetFrequency(&DDS4xAD9912, 2, FrequencyDDSBesInit);
							
							// done
							Measuring_1 = N_MEASUREMENT_NONE;
						}
						break;
				}

				switch (Measuring_2) {

					case N_MEASUREMENT_NONE:
						// not measuring
						break;
					
					case N_MEASUREMENT_INIT:
						// initialization step
						
						// set DDS1 to nominal frequency
						SetCtrlVal(MainPanel, PANEL_DDS1, FrequDDS1);
						DDS4xAD9912_SetFrequency(&DDS4xAD9912, 1, FrequDDS1);
						
						GetCtrlVal(MainPanel, PANEL_DDS2, &FrequencyDDSBesInit);
						GetCtrlVal(MainPanel, PANEL_DDS3, &FrequencyDDS3Init);
						t1_2 = utc;
						
						stat_zero(&stat_math1);
						stat_zero(&stat_ch2);
						
						Nu1 = N1 * (250000000 + Math1);
						
						// next step
						Measuring_2 += 1;
						break;
						
					case N_MEASUREMENT_SLOPE:
						// slope measurement
						
						stat_accumulate(&stat_math1, Math1);
						stat_accumulate(&stat_ch2, Ch2);

						if ((utc - t1_2) > SlopeTime2) {
							Slope_2 = stat_math1.slope;
							Beatslope_2 = stat_ch2.slope;
							SetCtrlVal(CalcNPanel, CALCN_SLOPE, Beatslope_2);
							
							// frep positive step
							double fDDS1 = FrequDDS1 + DeltakHz_2 * 1000;
							printf("fDDS1 = %g\n", fDDS1);
							DDS4xAD9912_RampFrequency(&DDS4xAD9912,1, fDDS1, FREP_STEP_SIZE);
							SetCtrlVal(MainPanel, PANEL_DDS1, fDDS1);
							DDS4xAD9912_SetFrequency(&DDS4xAD9912, 1, fDDS1);
							
							// adjust DDS3 to keep beatnote within the bandpass filter. prediction
							double fDDS3 = FrequencyDDS3Init - DeltakHz_2*1000*(-Sign1/Sign2)*Ndiv*(Nu2)/(Nu1) - Beatslope_2*(utc-t1_2);
							DeltaDDS3 = fDDS3 - DDS4xAD9912.Frequency3;
							printf("deltaDDS3 = %g\n", DeltaDDS3);
							SetCtrlVal(MainPanel, PANEL_DDS3, fDDS3);
							DDS4xAD9912_SetFrequency(&DDS4xAD9912, 3, fDDS3);
						
							// allow counter to settle
							settling = 3;
							
							// next step
							Measuring_2 += 1;
						}
						break;

					case N_MEASUREMENT_ADJUST_FREQ_PLUS:
					case N_MEASUREMENT_ADJUST_FREQ_MINUS:
						// adjust DDS frequency to keep beatnote within the bandpass filter
						
						if (settling > 0) {
							settling--;
							break;
						}
						
						double fDDS2 = DDS4xAD9912.Frequency2 + 275000 - Ch4;
						SetCtrlVal(MainPanel, PANEL_DDS2, fDDS2);
						DDS4xAD9912_SetFrequency(&DDS4xAD9912, 2, fDDS2);
						
						double fDDS3 = DDS4xAD9912.Frequency3 + 10000 - Ch2;
						DeltaDDS3 = DeltaDDS3 + 10000 - Ch2;
						SetCtrlVal(MainPanel, PANEL_DDS3, fDDS3);
						DDS4xAD9912_SetFrequency(&DDS4xAD9912, 3, fDDS3);

						// allow counter to settle
						settling = 3;

						// next step
						Measuring_2 += 1;
						break;
						
					case N_MEASUREMENT_FREP_PLUS:
						// frep positive step
						
						if (settling > 0) {
							settling--;
							break;
						}

						if (t2_1 == 0.0)
							t2_1 = utc;

						Frepplus_2 = Frepplus_2 + Math1 + 250000000 - Slope_2 * (utc - t2_2);
						Delta10K_Plus = Delta10K_Plus + 10000 - (Ch2 - Beatslope_2 * (utc - t2_2));
						n_2 += 1;
						
						if ((utc - t2_2) > DeltaT_2) {
							Frepplus_2 = Frepplus_2 / n_2;
							Delta10K_Plus = Delta10K_Plus / n_2;
							n_2 = 0;

							// negative frequency step
							double fDDS1 = FrequDDS1 - DeltakHz_2 * 1000;
							DDS4xAD9912_RampFrequency(&DDS4xAD9912, 1, fDDS1, FREP_STEP_SIZE);
							SetCtrlVal(MainPanel, PANEL_DDS1, fDDS1);
							DDS4xAD9912_SetFrequency(&DDS4xAD9912, 1, fDDS1);
							
							// adjust DDS3 to keep beatnote within the bandpass filter. prediction
							double fDDS3 = FrequencyDDS3Init + DeltakHz_2*1000*(-Sign1/Sign2)*Ndiv*(Nu2)/(Nu1);
							DeltaDDS3 = fDDS3 - DDS4xAD9912.Frequency3;
							SetCtrlVal(MainPanel, PANEL_DDS3, fDDS3);
							DDS4xAD9912_SetFrequency(&DDS4xAD9912, 3, fDDS3);

							// allow counter to settle
							settling = 3;
							
							// next step
							Measuring_2 += 1;
						}
						break;
						
					case N_MEASUREMENT_FREP_MINUS:
						// frep negative step
						
						if (settling > 0) {
							settling--;
							break;
						}
						
						if (t3_1 == 0.0)
							t3_1 = utc;

						Frepminus_2 = Frepminus_2 + Math1 + 250000000 - Slope_2 * (utc - t3_2);
						Delta10K_Minus =  Delta10K_Minus + 10000 - (Ch2 - Beatslope_2 * (utc - t3_2));
						n_2 += 1;

						if ((utc -t3_2) > DeltaT_2) {
							Frepminus_2 = Frepminus_2 / n_2;
							Delta10K_Minus = Delta10K_Minus / n_2;
							n_2 = 0;

							// compute N2
							N_2 = Sign2*(-DeltaDDS3+Delta10K_Plus-Delta10K_Minus-Beatslope_2*(t3_2-t2_2) )/(Frepminus_2-Frepplus_2-Slope_2*(t3_2-t2_2));
							SetCtrlVal(CalcNPanel, CALCN_N, N_2);
							
							// back to nominal frequency
							DDS4xAD9912_RampFrequency(&DDS4xAD9912, 1, FrequDDS1, FREP_STEP_SIZE);
							SetCtrlVal(MainPanel, PANEL_DDS1, FrequDDS1);
							DDS4xAD9912_SetFrequency(&DDS4xAD9912, 1, FrequDDS1);
							SetCtrlVal(MainPanel, PANEL_DDS2, FrequencyDDSBesInit);  
							DDS4xAD9912_SetFrequency (&DDS4xAD9912, 2, FrequencyDDSBesInit);
							SetCtrlVal(MainPanel, PANEL_DDS3, FrequencyDDS3Init-Beatslope_2*(utc-t1_2));
							DDS4xAD9912_SetFrequency (&DDS4xAD9912, 3, FrequencyDDS3Init-Beatslope_2*(utc-t1_2) );
							
							t1_2 = 0.0;
							t2_2 = 0.0;
							t3_2 = 0.0;
							Frepminus_2 = 0.0;
							Frepplus_2 = 0.0;
							Delta10K_Minus = 0.0;
							Delta10K_Plus = 0.0;

							// done
							Measuring_2 = N_MEASUREMENT_NONE;
						}
						break;
				}
				
				switch (Measuring_3) {
					
					case N_MEASUREMENT_NONE:
						// not measuring N3
						break;
						
					case N_MEASUREMENT_INIT:
						// init
						
						SetCtrlVal(MainPanel, 1, FrequDDS1);
						DDS4xAD9912_SetFrequency(&DDS4xAD9912, 1, FrequDDS1);
						settling = 3;
						
						t1_3 = utc;
						stat_zero(&stat_math1);
						f_rep_plus = f_rep_minus = 0.0;
						f_beat_Sr_plus = f_beat_Sr_minus = 0.0;
						
						// record current DDS frequencies
						FrequencyDDSBesInit = DDS4xAD9912.Frequency2;
						FrequencyDDS3Init = DDS4xAD9912.Frequency3;
						
						// next step
						Measuring_3 += 1;
						break;
						
					case N_MEASUREMENT_SLOPE:
						// slope measurement
						
						if (settling > 0) {
							settling--;
							break;
						}
						
						stat_accumulate(&stat_math1, Math1);
						
						if (utc - t1_3 > SlopeTime3) {
							// slope measurement
							f_rep_slope = stat_math1.slope;
							
							t2_3 = utc;
							
							// frep positive step
							SetCtrlVal(MainPanel, PANEL_DDS1, FrequDDS1 + DeltakHz_3 * 1000);
							DDS4xAD9912_RampFrequency(&DDS4xAD9912, 1, FrequDDS1 + DeltakHz_3 * 1000, FREP_STEP_SIZE);
							// compensate with DDS3 to keep measured beatnote in counter box range
							double fDDS3 = FrequencyDDS3Init + Sign1 * Sign3 * N3/N1 * Ndiv * DeltakHz_3 * 1000;
							SetCtrlVal(MainPanel, PANEL_DDS3, fDDS3);
							DDS4xAD9912_SetFrequency(&DDS4xAD9912, 3, fDDS3);
							
							// allow counter to settle
							settling = 3;
							
							// next step
							Measuring_3 += 1;
						}
						break;

					case N_MEASUREMENT_ADJUST_FREQ_PLUS:
					case N_MEASUREMENT_ADJUST_FREQ_MINUS:
						// adjust DDS frequency to keep beatnote within the bandpass filter

						if (settling > 0) {
							settling--;
							break;
						}
						
						// adjust DDS frequency to keep 55 MHz tracker oscillator locked
						double fDDS2 = DDS4xAD9912.Frequency2 + 275000 - Ch4;
						SetCtrlVal(MainPanel, PANEL_DDS2, fDDS2);
						DDS4xAD9912_SetFrequency(&DDS4xAD9912, 2, fDDS2);
						
						// allow counter to settle
						settling = 3;
						
						// next step
						Measuring_3 += 1;
						break;						
						
					case N_MEASUREMENT_FREP_PLUS:
						// frep positive step
						
						if (settling > 0) {
							settling--;
							break;
						}
						
						n_3++;
						f_rep_plus += Math1 + 250000000 - f_rep_slope * (utc - t3_2);
						f_beat_Sr_plus += Ch3;
						
						if (utc - t2_3 > DeltaT_3) {
							// positive step measurement
							f_rep_plus = f_rep_plus / n_3;
							f_beat_Sr_plus = f_beat_Sr_plus / n_3;
							
							n_3 = 0;
							t3_3 = utc;
							
							// frep negative step
							SetCtrlVal(MainPanel, PANEL_DDS1, FrequDDS1 - DeltakHz_3 * 1000);
							DDS4xAD9912_RampFrequency(&DDS4xAD9912, 1, FrequDDS1 - DeltakHz_3 * 1000, FREP_STEP_SIZE);
							// compensate with DDS3 to keep measured beatnote in counter box range
							double fDDS3 = FrequencyDDS3Init - Sign1 * Sign3 * N3/N1 * Ndiv * DeltakHz_3 * 1000;
							SetCtrlVal(MainPanel, PANEL_DDS3, fDDS3);
							DDS4xAD9912_SetFrequency(&DDS4xAD9912, 3, fDDS3);
							
							// allow counter to settle
							settling = 3;
							
							// next step
							Measuring_3 += 1;
						}
						break;
					
					case N_MEASUREMENT_FREP_MINUS:
						// frep negative step
						
						if (settling > 0) {
							settling--;
							break;
						}
						
						n_3++;
						f_rep_minus += Math1 + 250000000 - f_rep_slope * (utc - t3_2);
						f_beat_Sr_minus += Ch3;
						
						if (utc - t3_3 > DeltaT_3) {
							// negative step measurement
							f_rep_minus = f_rep_minus / n_3;
							f_beat_Sr_minus = f_beat_Sr_minus / n_3;
							
							// check delta frep
							double delta_f_rep_m = f_rep_plus - f_rep_minus;
							double delta_f_rep = Ndiv * 2.0 * DeltakHz_3 * 1000.0 / N1;
							logmsg("delta frep: measured=%.12e Hz expected=%.12e Hz difference=%.12e", 
								delta_f_rep_m, delta_f_rep, delta_f_rep_m - delta_f_rep);
							
							logmsg("f_beat_Sr_minus=%.12e", f_beat_Sr_minus);
							logmsg("f_beat_Sr_plus =%.12e", f_beat_Sr_plus);
							
							// compute N3
							double delta_f_beat_Sr = f_beat_Sr_plus - f_beat_Sr_minus + 2.0 * Sign1 * Sign3 * N3/N1 * Ndiv * DeltakHz_3 * 1000;
							double delta_f_beat_Sr_expected = delta_f_rep * N3;
							logmsg("delta fbeat: measured=%.12e expected=%.12e difference=%.12e",
								delta_f_beat_Sr, delta_f_beat_Sr_expected, delta_f_beat_Sr - delta_f_beat_Sr_expected);
							N_3 = delta_f_beat_Sr / delta_f_rep;
							logmsg("measured N3=%.3f", N_3);
							SetCtrlVal(CalcNPanel, CALCN_N, N_3);
							
							t1_3=0.0;
							t2_3=0.0;
							t3_3=0.0;
							n_3 = 0;
							
							// back to nominal frep
							SetCtrlVal(MainPanel, PANEL_DDS1, FrequDDS1);
							DDS4xAD9912_RampFrequency(&DDS4xAD9912, 1, FrequDDS1, FREP_STEP_SIZE);
							// back to initial DDS3 frequency
							SetCtrlVal(MainPanel, PANEL_DDS3, FrequencyDDS3Init);
							DDS4xAD9912_SetFrequency(&DDS4xAD9912, 3, FrequencyDDS3Init);
							// back to initial DDS2 frequency
							SetCtrlVal(MainPanel, PANEL_DDS2, FrequencyDDSBesInit);  
							DDS4xAD9912_SetFrequency(&DDS4xAD9912, 2, FrequencyDDSBesInit);
							
							// done
							Measuring_3 = N_MEASUREMENT_NONE;
						}
						break;
				}
				
				// beatnote sign determination
				
				if (Getsign1 == TRUE) {
					if (utc > tbegin1+2) {
						if (Math1 > Frepbefore1)
							Sign1 = -1.0;
						else
							Sign1 = +1.0;
						SetCtrlVal(MainPanel, PANEL_DDS1, Frequency1); 
						DDS4xAD9912_SetFrequency(&DDS4xAD9912, 1, Frequency1);
						Getsign1 = FALSE;
						SetCtrlVal(MainPanel, PANEL_SIGN1, Sign1);
					}
				}
				if (Getsign2 == TRUE) {
					if (utc > tbegin2+2){
						if (Math1 > Frepbefore2) { 
							if (Ch2 > Ch2before)
								Sign2 = +1.0;
							else
								Sign2 = -1.0;
						} else {
							if (Ch2 > Ch2before)
								Sign2 = -1.0;
							else 
								Sign2 = +1.0;
						}
						SetCtrlVal(MainPanel, PANEL_DDS1, Frequency2); 
						DDS4xAD9912_SetFrequency(&DDS4xAD9912, 1, Frequency2);
						Getsign2 = FALSE;
						SetCtrlVal(MainPanel, PANEL_SIGN2, Sign2);
					}
				}
				if (Getsign3 == TRUE) {
					if (utc > tbegin3+2){
						if (Ch3 > Frepbefore3)
							Sign3 = -1.0;
						else
							Sign3 = +1.0;
						SetCtrlVal(MainPanel, PANEL_DDS3, Frequency3); 
						DDS4xAD9912_SetFrequency(&DDS4xAD9912, 4, Frequency3);
						Getsign3 = FALSE;
						SetCtrlVal(MainPanel, PANEL_SIGN3, Sign3);
					}
				}
				
				// select reference
				double f = 0.0;
				switch (dedrift.reference) {
					case DEDRIFT_REFERENCE_MICROWAVE:
						f = Math2;
						break;
					case DEDRIFT_REFERENCE_HG:
						f = Ch2 * 1062.5 / 1542.2;
						break;
				}
				
				// stop dedrift if the comb is not locked
				if ((dedrift.enabled)
					& (dedrift.threshold != 0.0)
					& (freq.previous != 0.0)
					& (fabs(f - freq.previous) > dedrift.threshold)) {
						
					if (! dedrift.keep_slope) {
						dedrift.applied = 0.0;
						DDSFox_SetSweepRate(&DDS1xAD9956, dedrift.applied);
						SetCtrlVal(MainPanel, PANEL_SLOPE_APPLIED, dedrift.applied);
					}
					if (! dedrift.keep_freq) {
						DDSFox_Set(&DDS1xAD9956, dedrift.freq0, dedrift.applied);
					}
					
					stat_zero(&freq);
					SetCtrlVal(MainPanel, PANEL_SLOPE_MEASURED, freq.slope);
					dedrift.enabled = FALSE;
					SetCtrlVal(MainPanel, PANEL_MEASURE_SLOPE, 0);
				}
				
				// dedrifting 
				if (dedrift.enabled)
				{
					// update slope measurement
					stat_accumulate(&freq, f);
					
					// update indicator
					SetCtrlVal(MainPanel, PANEL_SLOPE_MEASURED, freq.slope);
					
					// update applied slope
					if ((utc - dedrift.t0) > dedrift.interval) {
						
						if (dedrift.invert)
							dedrift.applied -= freq.slope;
						else
							dedrift.applied += freq.slope;
						
						SetCtrlVal(MainPanel, PANEL_SLOPE_APPLIED, dedrift.applied);
						
						if (dedrift.doubleslope)
							DDSFox_SetSweepRate(&DDS1xAD9956, dedrift.applied * 2.0);
						else
							DDSFox_SetSweepRate(&DDS1xAD9956, dedrift.applied);
						
						logmsg("dedrift update (%+6g) %6g", freq.slope, dedrift.applied);
						
						stat_zero(&freq);
						dedrift.t0 = utc;
					}
				}
				
				// recenter
				if (recenter.enabled)
				{
					if (recenter.t0 == 0.0) {
						recenter.t0 = utc;
						rollmean_zero(&rollmean_ch2, ROLLMEAN_N_OBS);
						rollmean_zero(&rollmean_ch3, ROLLMEAN_N_OBS);
						rollmean_zero(&rollmean_ch4, ROLLMEAN_N_OBS);
					}
					
					rollmean_accumulate(&rollmean_ch2, Ch2);
					rollmean_accumulate(&rollmean_ch3, Ch3);
					rollmean_accumulate(&rollmean_ch4, Ch4);
					
					if ((utc - recenter.t0) > recenter.interval) {
		
						if (recenter.Lo) {
							// adjust DDS2 frequency to keep Ch4 reading at 275 kHz
							double freq = DDS4xAD9912_GetFrequency(&DDS4xAD9912, 2);
							freq = freq + 275000.0 - rollmean_ch4.mean;
							SetCtrlVal(MainPanel, PANEL_DDS2, freq);
							DDS4xAD9912_SetFrequency(&DDS4xAD9912, 2, freq);
						}
					
						if (recenter.Hg) {
							// adjust DDS3 frequency to keep Ch2 reading at 10 kHz
							double freq = DDS4xAD9912_GetFrequency(&DDS4xAD9912, 3);
							freq = freq + 10000 - rollmean_ch2.mean;
							SetCtrlVal(MainPanel, PANEL_DDS3, freq);
							DDS4xAD9912_SetFrequency(&DDS4xAD9912, 3, freq);
						}
					
						if (recenter.Sr) {
							// adjust DDS3 frequency to keep Ch3 reading at 10 kHz
							double freq = DDS4xAD9912_GetFrequency(&DDS4xAD9912, 3);
							freq = freq + 10000 - rollmean_ch3.mean;
							SetCtrlVal(MainPanel, PANEL_DDS3, freq);
							DDS4xAD9912_SetFrequency(&DDS4xAD9912, 3, freq);
						}
					
						recenter.t0 = utc;
						rollmean_zero(&rollmean_ch2, ROLLMEAN_N_OBS);
						rollmean_zero(&rollmean_ch3, ROLLMEAN_N_OBS);
						rollmean_zero(&rollmean_ch4, ROLLMEAN_N_OBS);
					}
				}
				
				// local time
				struct tm *ltime = localtime(&event.time.tv_sec);
				// round to milliseconds
				int msec = round(event.time.tv_usec / 1000.0);
				while (msec >= 1000) {
					ltime->tm_sec += 1;
					msec -= 1000;
				}
				// format local time
				char timestr[24];
				int len = strftime(timestr, sizeof(timestr), "%d/%m/%Y %H:%M:%S", ltime);
				snprintf(timestr + len, sizeof(timestr) - len, ".%03d", msec);
				// display local time
				SetCtrlVal(MainPanel, PANEL_TIME, timestr);
				
				// run id derived from current local date in the form YYMMDD
				char id[7];
				strftime(id, sizeof(id), "%y%m%d", ltime);
				
				int save;
				
				// write counter data to disk
				GetCtrlVal(MainPanel, PANEL_SAVE_RAW_DATA, &save);
				if (save) {
					writeData4(DATAFOLDER, "Raw", id, timestr, utc, Ch1, Ch2, Ch3, Ch4);
				}
				
				// write Lo frequency (Math2) to disk
				GetCtrlVal(MainPanel, PANEL_CHECKBOX_MATH2SAVE, &save);
				if (save) {
					writeData(DATAFOLDER, "Lo", id, timestr, utc, Math2);
				}
				
				// write Hg frequency (Math3) to disk
				GetCtrlVal(MainPanel, PANEL_CHECKBOX_MATH3SAVE, &save);
				if (save) {
					writeData(DATAFOLDER, "Hg", id, timestr, utc, Math3);
					writeData("C:\\Femto\\Results", "Hg", id, timestr, utc, Math3);
				}
				
				// write Sr frequency (Math4) to disk
				GetCtrlVal(MainPanel, PANEL_CHECKBOX_MATH4SAVE, &save);
				if (save) {
					writeData(DATAFOLDER, "Sr", id, timestr, utc, Math4);
				}
				
				// send Sr frequency (Math4) to Sr data logger
				GetCtrlVal(MainPanel, PANEL_SR_LOGGER, &save);
				if (save) {
					sendLogger("FEMTO2", utc, Math4);
				}
				
				
				// write ExtraMath (Math5) to disk
				GetCtrlVal(MainPanel, PANEL_CHECKBOX_MATH5SAVE, &save);
				if (save) {
					writeData(DATAFOLDER, "Ex", id, timestr, utc, Math5);
				}
				
				// write DDS freqs to disk
				GetCtrlVal(MainPanel, PANEL_SAVE_DDS_FREQS, &save);
				if (save) {
					writeData4(DATAFOLDER, "DDS", id, timestr, utc,
						DDS4xAD9912.Frequency1, DDS4xAD9912.Frequency2,
						DDS4xAD9912.Frequency3, DDS4xAD9912.Frequency4);
				}
				
			}		
			break;
	}
}


int CVICALLBACK CB_OnFreqPlot (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	switch (event)
	{
		case EVENT_COMMIT:
			for (struct plot *plot = plots; plot->data; plot++) {
				if (plot->control == control)
					plot_toggle(plot);
			}
			break;
	}
	return 0;
}


int CVICALLBACK CB_OnAllanPlot (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	switch (event)
	{
		case EVENT_COMMIT:
			for (struct adev *adev = adevs; adev->data; adev++) {
				if (adev->control == control)
					adev_toggle(adev);
			}
			break;
	}
	return 0;
}

int  CVICALLBACK CB_ChangeDDSOut (int panel, int control, int event, 
		 void *callbackData, int eventData1, int eventData2)
{
	double frequency ;
	
	switch (event) {
		case EVENT_COMMIT:
			GetCtrlVal(MainPanel, control, &frequency);
			
			switch (control) {
				case PANEL_DDS1:
					DDS4xAD9912_SetFrequency(&DDS4xAD9912, 1, frequency);
					break;
				case PANEL_DDS2:
					DDS4xAD9912_SetFrequency(&DDS4xAD9912, 2, frequency);
					break;
				case PANEL_DDS3:
					DDS4xAD9912_SetFrequency(&DDS4xAD9912, 3, frequency);
					break;
				case PANEL_DDS4:
					DDS4xAD9912_SetFrequency(&DDS4xAD9912, 4, frequency);
					break;
			}
	}
	return 0;
}

int  CVICALLBACK CB_ChangeDDSStep (int panel, int control, int event, 
		 void *callbackData, int eventData1, int eventData2)
{
	double Step ;
	
	switch (event)
		{
		case EVENT_COMMIT:
			GetCtrlVal(MainPanel, control, &Step);
			if (control==PANEL_DDS1STEP)   { SetCtrlAttribute(panel, PANEL_DDS1,   ATTR_INCR_VALUE, Step); }   
			if (control==PANEL_DDS2STEP)   { SetCtrlAttribute(panel, PANEL_DDS2,   ATTR_INCR_VALUE, Step); }
			if (control==PANEL_DDS3STEP)   { SetCtrlAttribute(panel, PANEL_DDS3,   ATTR_INCR_VALUE, Step); }   
			if (control==PANEL_DDS4STEP)   { SetCtrlAttribute(panel, PANEL_DDS4,   ATTR_INCR_VALUE, Step); } 
			break;
		case EVENT_RIGHT_CLICK:

			break;
			
		}
	return 0;
}

int CVICALLBACK CB_ChangeMath (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	int len;
	char *string;
		
	switch (event)
	{
		case EVENT_COMMIT:
			GetCtrlAttribute(panel, control, ATTR_STRING_TEXT_LENGTH, &len);
			string = (char *)malloc(sizeof(char) * (len + 1));
			GetCtrlVal(panel, control, string);
			switch (control) {
				case PANEL_MATHSTRING1:
					mupSetExpr(MathParser1, string);
					break;
				case PANEL_MATHSTRING2:
					mupSetExpr(MathParser2, string);
					break;
				case PANEL_MATHSTRING3:
					mupSetExpr(MathParser3, string);
					break;
				case PANEL_MATHSTRING4:
					mupSetExpr(MathParser4, string);
					break;
				case PANEL_MATHSTRING5:
					mupSetExpr(MathParser5, string);
					break;
			}
			free(string);
			break;
	}
	return 0;
}

int CVICALLBACK CB_ChangeN (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{

	switch (event)
		{
		case EVENT_COMMIT:
			if (control==PANEL_N1CHOICE) GetCtrlVal(MainPanel, control, &N1) ;
			if (control==PANEL_N2CHOICE) GetCtrlVal(MainPanel, control, &N2) ;
			if (control==PANEL_N3CHOICE) GetCtrlVal(MainPanel, control, &N3) ;
			break;
		}
	return 0;
}

int CVICALLBACK CB_OnPlus10k (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	double Frequency ;
	
	switch (event)
	{
		case EVENT_COMMIT:
			switch (control)
			{
				case PANEL_PLUS10KDDS1:
					GetCtrlVal(MainPanel, PANEL_DDS1, &Frequency);
					Frequency += 10000.0;
					DDS4xAD9912_SetFrequency(&DDS4xAD9912, 1, Frequency);	
					SetCtrlVal(MainPanel, PANEL_DDS1, Frequency);
					break;
				case PANEL_PLUS10KDDS2:
					GetCtrlVal(MainPanel, PANEL_DDS2, &Frequency);
					Frequency += 10000.0;
					DDS4xAD9912_SetFrequency(&DDS4xAD9912, 2, Frequency);	
					SetCtrlVal(MainPanel, PANEL_DDS2, Frequency);
					break;
				case PANEL_PLUS10KDDS3:
					GetCtrlVal(MainPanel, PANEL_DDS3, &Frequency);
					Frequency += 10000.0;
					DDS4xAD9912_SetFrequency(&DDS4xAD9912, 3, Frequency);	
					SetCtrlVal(MainPanel, PANEL_DDS3, Frequency);
					break;
				case PANEL_PLUS10KDDS4:
					GetCtrlVal(MainPanel, PANEL_DDS4, &Frequency);
					Frequency += 10000.0;
					DDS4xAD9912_SetFrequency(&DDS4xAD9912, 4, Frequency);	
					SetCtrlVal(MainPanel, PANEL_DDS4, Frequency);
					break;
			}
			break;
	}
	return 0;
}


int CVICALLBACK CB_OnMinus10k (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	double Frequency;
	
	switch (event)
	{
		case EVENT_COMMIT:
			switch (control)
			{
				case PANEL_MINUS10KDDS1:
					GetCtrlVal(MainPanel, PANEL_DDS1, &Frequency);
					Frequency -= 10000.0;
					DDS4xAD9912_SetFrequency(&DDS4xAD9912, 1, Frequency);
					SetCtrlVal(MainPanel, PANEL_DDS1, Frequency);
					break;
				case PANEL_MINUS10KDDS2:
					GetCtrlVal(MainPanel, PANEL_DDS2, &Frequency);
					Frequency -= 10000.0;
					DDS4xAD9912_SetFrequency(&DDS4xAD9912, 2, Frequency);	
					SetCtrlVal(MainPanel, PANEL_DDS2, Frequency);
					break;
				case PANEL_MINUS10KDDS3:
					GetCtrlVal(MainPanel, PANEL_DDS3, &Frequency);
					Frequency -= 10000.0;
					DDS4xAD9912_SetFrequency(&DDS4xAD9912, 3, Frequency);	
					SetCtrlVal(MainPanel, PANEL_DDS3, Frequency);
					break;
				case PANEL_MINUS10KDDS4:
					GetCtrlVal(MainPanel, PANEL_DDS4, &Frequency);
					Frequency -= 10000.0;
					DDS4xAD9912_SetFrequency(&DDS4xAD9912, 4, Frequency);
					SetCtrlVal(MainPanel, PANEL_DDS4, Frequency);
					break;
			}
			break;
	}
	return 0;
}


int CVICALLBACK CB_OnAcceptN (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	switch (event) {
		case EVENT_COMMIT:
			switch (measuring) {
				case MEASURING_N_Lo:
					N1 = round(N_1);
					SetCtrlVal(MainPanel, PANEL_N1CHOICE, N1);
					break;
				case MEASURING_N_Hg:
					N2 = round(N_2);
					SetCtrlVal(MainPanel, PANEL_N2CHOICE, N2);
					break;
				case MEASURING_N_Sr:
					N3 = round(N_3);
					SetCtrlVal(MainPanel, PANEL_N3CHOICE, N3);
					break;
			} 
			break;
	}
	return 0;
}


int CVICALLBACK CB_OnNCalculus (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{

	int visible;
	
	switch (event) {
		case EVENT_COMMIT:
			switch (control) {
				case PANEL_N1CALCULUS:
					GetPanelAttribute(CalcNPanel, ATTR_VISIBLE, &visible);
					if (! visible) {
						measuring = MEASURING_N_Lo;
						SetCtrlVal(CalcNPanel, CALCN_INTEGRATIONTIME, DeltaT_1);
						SetCtrlVal(CalcNPanel, CALCN_SLOPETIME, SlopeTime1);
						SetCtrlVal(CalcNPanel, CALCN_DELTAFREQ, DeltakHz_1);
						SetPanelAttribute(CalcNPanel, ATTR_TITLE, "Measure N_Lo");
						SetCtrlVal(CalcNPanel, CALCN_SLOPE, 0.0);
						SetCtrlVal(CalcNPanel, CALCN_N, 0.0);
						DisplayPanel(CalcNPanel);
					}
					break;
				case PANEL_N2CALCULUS:
					GetPanelAttribute(CalcNPanel, ATTR_VISIBLE, &visible);
					if (! visible) {
						measuring = MEASURING_N_Hg;
						SetCtrlVal(CalcNPanel, CALCN_INTEGRATIONTIME, DeltaT_2);
						SetCtrlVal(CalcNPanel, CALCN_SLOPETIME, SlopeTime2);
						SetCtrlVal(CalcNPanel, CALCN_DELTAFREQ, DeltakHz_2);
						SetPanelAttribute(CalcNPanel, ATTR_TITLE, "Measure N_Hg");
						SetCtrlVal(CalcNPanel, CALCN_SLOPE, 0.0);
						SetCtrlVal(CalcNPanel, CALCN_N, 0.0);
						DisplayPanel(CalcNPanel);
					} 
					break;
				case PANEL_N3CALCULUS:
					GetPanelAttribute(CalcNPanel, ATTR_VISIBLE, &visible);
					if (! visible) {
						measuring = MEASURING_N_Sr;
						SetCtrlVal(CalcNPanel, CALCN_INTEGRATIONTIME, DeltaT_3);
						SetCtrlVal(CalcNPanel, CALCN_SLOPETIME, SlopeTime3);
						SetCtrlVal(CalcNPanel, CALCN_DELTAFREQ, DeltakHz_3);
						SetPanelAttribute(CalcNPanel, ATTR_TITLE, "Measure N_Sr");
						SetCtrlVal(CalcNPanel, CALCN_SLOPE, 0.0);
						SetCtrlVal(CalcNPanel, CALCN_N, 0.0);
						DisplayPanel(CalcNPanel);
					}
					break;
			}
			break;
	}
	return 0;
}


int CVICALLBACK CB_OnStartNCalculus (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	switch (event) {
		case EVENT_COMMIT:
			switch (measuring) {
				case MEASURING_N_Lo:
					GetCtrlVal(CalcNPanel, CALCN_INTEGRATIONTIME, &DeltaT_1);
					GetCtrlVal(CalcNPanel, CALCN_SLOPETIME, &SlopeTime1);
					GetCtrlVal(CalcNPanel, CALCN_DELTAFREQ, &DeltakHz_1);
					Measuring_1 = TRUE;
					break;
				case MEASURING_N_Hg:
					GetCtrlVal(CalcNPanel, CALCN_INTEGRATIONTIME, &DeltaT_2);
					GetCtrlVal(CalcNPanel, CALCN_SLOPETIME, &SlopeTime2);
					GetCtrlVal(CalcNPanel, CALCN_DELTAFREQ, &DeltakHz_2);
					Measuring_2 = TRUE;
					break;
				case MEASURING_N_Sr:
					GetCtrlVal(CalcNPanel, CALCN_INTEGRATIONTIME, &DeltaT_3);
					GetCtrlVal(CalcNPanel, CALCN_SLOPETIME, &SlopeTime3);
					GetCtrlVal(CalcNPanel, CALCN_DELTAFREQ, &DeltakHz_3);
					Measuring_3 = TRUE;
					break;
			}
			break;
	}
	return 0;
}



int CVICALLBACK CB_OnNStop (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	switch (event) {
		case EVENT_COMMIT:
			HidePanel(CalcNPanel);
			switch (measuring) {
				case MEASURING_N_Lo:
					Measuring_1 = FALSE;
					SetCtrlVal(MainPanel, PANEL_DDS1, FrequDDS1);
					DDS4xAD9912_SetFrequency(&DDS4xAD9912, 1, FrequDDS1);
					SetCtrlVal(MainPanel, PANEL_DDS2, FrequencyDDSBesInit);
					DDS4xAD9912_SetFrequency(&DDS4xAD9912, 2, FrequencyDDSBesInit);
					break;
				case MEASURING_N_Hg:
					Measuring_2 = FALSE;
					SetCtrlVal(MainPanel, PANEL_DDS1, FrequDDS1);
					DDS4xAD9912_SetFrequency(&DDS4xAD9912, 1, FrequDDS1);
					SetCtrlVal(MainPanel, PANEL_DDS2, FrequencyDDSBesInit);
					DDS4xAD9912_SetFrequency(&DDS4xAD9912, 2, FrequencyDDSBesInit);
					SetCtrlVal(MainPanel, PANEL_DDS3, FrequencyDDS3Init);
					DDS4xAD9912_SetFrequency(&DDS4xAD9912, 3, FrequencyDDS3Init);
					break;
				case MEASURING_N_Sr:
					Measuring_3 = FALSE;
					SetCtrlVal(MainPanel, PANEL_DDS1, FrequDDS1);
					DDS4xAD9912_RampFrequency(&DDS4xAD9912, 1, FrequDDS1, FREP_STEP_SIZE);
					SetCtrlVal(MainPanel, PANEL_DDS2, FrequencyDDSBesInit);  
					DDS4xAD9912_SetFrequency(&DDS4xAD9912, 2, FrequencyDDSBesInit);
					SetCtrlVal(MainPanel, PANEL_DDS3, FrequencyDDS3Init);
					DDS4xAD9912_SetFrequency(&DDS4xAD9912, 3, FrequencyDDS3Init);
					break;
			}
			break;
	}
	return 0;
}


int  CVICALLBACK CB_OnFindSign (int panel, int control, int event, 
		void *callbackData, int eventData1, int eventData2)
{
	
	switch (event)
	{
		case EVENT_COMMIT:
			switch (control)
			{
				case PANEL_FINDSIGN1:
					tbegin1 = utc;
					Frepbefore1 = Math1;
					GetCtrlVal(MainPanel, PANEL_DDS1, &Frequency1) ;
					SetCtrlVal(MainPanel, PANEL_DDS1, Frequency1+Frequencystep1) ;  
					DDS4xAD9912_SetFrequency(&DDS4xAD9912, 1, Frequency1+Frequencystep1);
					Getsign1 = TRUE;
					break;
				case PANEL_FINDSIGN2:
					tbegin2 = utc;
					Frepbefore2 = Math1;
					Ch2before = Ch2;
					GetCtrlVal(MainPanel, PANEL_DDS1, &Frequency2) ;
					SetCtrlVal(MainPanel, PANEL_DDS1, Frequency2+Frequencystep2) ;
					DDS4xAD9912_SetFrequency(&DDS4xAD9912, 1, Frequency2+Frequencystep2);
					Getsign2 = TRUE;
					break;
				case PANEL_FINDSIGN3:
					tbegin3 = utc;
					Frepbefore3 = Math1;
					GetCtrlVal(MainPanel, PANEL_DDS4, &Frequency3) ;
					SetCtrlVal(MainPanel, PANEL_DDS4, Frequency3+Frequencystep3) ; 
					DDS4xAD9912_SetFrequency(&DDS4xAD9912, 4, Frequency3+Frequencystep3);
					Getsign3 = TRUE;
					break;
			}
			break;
	}
	return 0;
}


int  CVICALLBACK CB_OnFind275K (int panel, int control, int event, 
		 void *callbackData, int eventData1, int eventData2)
{
	double frequency;
	
	switch (event)
	{
		case EVENT_COMMIT:
			switch (control)
			{
				case PANEL_FIND275K2:
					GetCtrlVal(MainPanel, PANEL_DDS2, &frequency);
					frequency = frequency + 275000 - Ch4;
					SetCtrlVal(MainPanel, PANEL_DDS2, frequency) ;  
					DDS4xAD9912_SetFrequency(&DDS4xAD9912, 2, frequency);
					break;
					 
				case PANEL_FIND10K3:
					GetCtrlVal(MainPanel, PANEL_DDS3, &frequency);
					frequency = frequency + 10000 - Ch2;
					SetCtrlVal(MainPanel, PANEL_DDS3, frequency);
					DDS4xAD9912_SetFrequency(&DDS4xAD9912, 3, frequency);
					break;
			}
			break;
	}
	return 0;
}


 int  CVICALLBACK CB_OnChangeNdiv (int panel, int control, int event, 
		 void *callbackData, int eventData1, int eventData2)
{
	switch (event)
	{
		case EVENT_COMMIT:
			GetCtrlVal(MainPanel, PANEL_CHANGENDIV, &Ndiv);
			FrequDDS1 = 880000000.0 / Ndiv;
			SetCtrlVal(MainPanel, PANEL_DDS1, FrequDDS1);
			DDS4xAD9912_SetFrequency(&DDS4xAD9912, 1, FrequDDS1);
			break;
	}
	return 0;
}


 int  CVICALLBACK CB_MeasureSlope (int panel, int control, int event, 
		 void *callbackData, int eventData1, int eventData2)
{
	switch (event)
	{
		case EVENT_COMMIT:
			GetCtrlVal(panel, control, &dedrift.enabled);
			if (dedrift.enabled) {
				dedrift.t0 = utc;
				stat_zero(&freq);
				logmsg("dedrift start");
			} else {
				if (! dedrift.keep_slope) {
					dedrift.applied = 0.0;
					DDSFox_SetSweepRate(&DDS1xAD9956, dedrift.applied);
					SetCtrlVal(MainPanel, PANEL_SLOPE_APPLIED, dedrift.applied);
				}
				if (! dedrift.keep_freq) {
					DDSFox_Set(&DDS1xAD9956, dedrift.freq0, dedrift.applied);
				}
				stat_zero(&freq);
				SetCtrlVal(panel, PANEL_SLOPE_MEASURED, freq.slope);
				logmsg("dedrift stop");
			}
			break;
	}
	return 0;
}

 
int  CVICALLBACK CB_OnResetSlope (int panel, int control, int event, 
		void *callbackData, int eventData1, int eventData2)
{

	switch (event)
	{
		case EVENT_COMMIT:
			dedrift.applied = 0.0; 
			SetCtrlVal(panel, PANEL_SLOPE_APPLIED, dedrift.applied);
			DDSFox_Set(&DDS1xAD9956, dedrift.freq0, dedrift.applied);
			logmsg("dedrift reset");
			break;
	}
	return 0;
}
  
  
int  CVICALLBACK CB_ChangeSlopeTime (int panel, int control, int event, 
		void *callbackData, int eventData1, int eventData2)
{

	switch (event)
	{
		case EVENT_COMMIT:
			GetCtrlVal(MainPanel, PANEL_SLOPETIME, &dedrift.interval); 
			break;
	}
	return 0;
}


int  CVICALLBACK CB_OnCROX (int panel, int control, int event, 
		 void *callbackData, int eventData1, int eventData2)
{
	switch (event)
	{
		case EVENT_COMMIT:
			switch (control) {
				
				case PANEL_CHECKBOX_CORRFREQU:
					// enable frequency correction
				   	// GetCtrlVal(MainPanel, PANEL_CHECKBOX_CORRFREQU, &FrequCorrec);
					break;
			
				case PANEL_CHECKBOX_KEEP:
					// keep current dedrifting frequency when dedrifting is disabled
				   	GetCtrlVal(MainPanel, PANEL_CHECKBOX_KEEP, &dedrift.keep_freq);
					break;
					
				case PANEL_CHECKBOX_KEEPSLOPE:
					// keep current dedrifting slope when dedrifting is disabled
				   	GetCtrlVal(MainPanel, PANEL_CHECKBOX_KEEPSLOPE, &dedrift.keep_slope);
					break;
			}
 			break;
	}
	return 0;
}



int  CVICALLBACK CB_OnReCentering (int panel, int control, int event, 
		 void *callbackData, int eventData1, int eventData2)
{
	switch (event)
	{
		case EVENT_COMMIT:
			GetCtrlVal(panel, control, &recenter.enabled);
			recenter.t0 = 0.0;
 			break;
	}
	return 0;
}


int  CVICALLBACK CB_OnStopSlopeCancellingOnUnlocked (int panel, int control, int event, 
		 void *callbackData, int eventData1, int eventData2)
{
	int value;
	switch (event)
	{
		case EVENT_COMMIT:
			GetCtrlVal(MainPanel, PANEL_CHECKBOX_STOPIFAUTODE, &value);
			dedrift.threshold = value ? 100.0 : 0.0;
			break;
	}
	return 0;
}

int CVICALLBACK CB_OnSlopeReference (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	switch (event)
	{
		case EVENT_COMMIT:
			GetCtrlVal(MainPanel, PANEL_SLOPE_REFERENCE, &dedrift.reference);
			break;
	}
	return 0;
}


int CVICALLBACK CB_OnEstimateN (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	int visible;
	double wl;
	
	switch (event)
	{
		case EVENT_COMMIT:
			// be prepared to support more N estimates for different beat notes
			switch (control)
			{
				case PANEL_ESTIMATE_N3:
					GetPanelAttribute(EstimateN3Panel, ATTR_VISIBLE , &visible);
					if (! visible) {
						DisplayPanel(EstimateN3Panel);
					}
					// set current frep
					SetCtrlVal(EstimateN3Panel, ESTIMATEN3_FREP, 250e6 + Math1);
					// default wavelenght for Sr cavity
					GetCtrlVal(EstimateN3Panel, ESTIMATEN3_WAVELENGTH, &wl);
					if (wl == 0.0)
						SetCtrlVal(EstimateN3Panel, ESTIMATEN3_WAVELENGTH, 698.446);
					// reset N3 estimate
					SetCtrlVal(EstimateN3Panel, ESTIMATEN3_N, 0.0);
					break;
			}
			break;
	}
	
	return 0;
}			

int CVICALLBACK CB_OnNEstimateCancel (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	int visible;
	
	switch (event)
	{
		case EVENT_COMMIT:
			GetPanelAttribute(panel, ATTR_VISIBLE, &visible);
			if (visible)
				HidePanel(panel);
			break;
	}
	return 0;
}

int CVICALLBACK CB_OnNEstimateSet (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	switch (event)
	{
		case EVENT_COMMIT:
			GetCtrlVal(panel, ESTIMATEN3_N, &N3);
			SetCtrlVal(MainPanel, PANEL_N3CHOICE, N3);
			HidePanel(panel);
			break;
	}
	return 0;
}

int CVICALLBACK CB_OnNEstimate (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	double frep, wl, N;
	
	switch (event)
	{
		case EVENT_COMMIT:
			GetCtrlVal(panel, ESTIMATEN3_FREP, &frep);
			GetCtrlVal(panel, ESTIMATEN3_WAVELENGTH, &wl);
			N = round(299792458.0 / wl / 1e-9 / frep);
			SetCtrlVal(panel, ESTIMATEN3_N, N);
			break;
	}
	return 0;
}

int CVICALLBACK CB_SetSlope (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	switch (event)
	{
		case EVENT_COMMIT:
			GetCtrlVal(panel, control, &dedrift.applied);
			DDSFox_SetSweepRate(&DDS1xAD9956, dedrift.applied);
			break;
	}
	return 0;
}

int CVICALLBACK CB_InvertSlopeSign (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	switch (event)
	{
		case EVENT_COMMIT:
			GetCtrlVal(panel, control, &dedrift.invert);
			break;
	}
	return 0;
}

int CVICALLBACK CB_ResetDedriftDDS (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	switch (event)
	{
		case EVENT_COMMIT:
			// stop slope measurement and reset slope 
			dedrift.enabled = FALSE;
			SetCtrlVal(panel, PANEL_MEASURE_SLOPE, 0);
			dedrift.applied = 0.0;
			SetCtrlVal(panel, PANEL_SLOPE_APPLIED, dedrift.applied);
			// reset DDS
			DDSFox_Reset(&DDS1xAD9956);
			DDSFox_SetProfile(&DDS1xAD9956);
			DDSFox_SetDiv(&DDS1xAD9956, 1);
			DDSFox_Set(&DDS1xAD9956, dedrift.freq0, 0.0);
			break;
	}
	return 0;
}

int CVICALLBACK CB_ShowLog (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	int visible;
	switch (event)
	{
		case EVENT_COMMIT:
			GetCtrlVal(panel, PANEL_SHOWLOG, &visible);
			SetPanelAttribute(LoggingPanel, ATTR_VISIBLE, visible);
			break;
	}
	return 0;
}

int CVICALLBACK CB_OnLoggingPanelEvent(int panel, int event,
		void *callbackData, int eventData1, int eventData2)
{
	switch (event)
	{
		case EVENT_CLOSE:
			SetPanelAttribute(LoggingPanel, ATTR_VISIBLE, 0);
			SetCtrlVal(MainPanel, PANEL_SHOWLOG, 0);
			break;
	}
	return 0;
}

int CVICALLBACK CB_Sign3 (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	switch (event)
	{
		case EVENT_COMMIT:
			GetCtrlVal(panel, control, &Sign3);
			break;
	}
	return 0;
}

int CVICALLBACK CB_SlopeX2 (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	switch (event)
	{
		case EVENT_COMMIT:
			GetCtrlVal(panel, control, &dedrift.doubleslope);
			break;
	}
	return 0;
}

int CVICALLBACK CB_DedriftDDSFreq (int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2)
{
	switch (event)
	{
		case EVENT_COMMIT:
			GetCtrlVal(panel, control, &dedrift.freq0);
			DDSFox_Set(&DDS1xAD9956, dedrift.freq0, dedrift.applied);
			break;
	}
	return 0;
}