/*
 * David Muller; German Alfaro
 * davehmuller@gmail.com; alfaro.germanevera@gmail.com
 * 2/2014 Robert Glatts, rglatts@ucsd.edu (rcg)
 *
 * 4/2018 Thom Maughan, tm@mbari.org
 */


/*
 * System.c contains a variety of functions related to sensors and basic system utilities.
 */

#include "system.h"
#include "sample.h"
#include "user_io.h"
#include "ads1248_iso.h"
#include "ads1248_noniso.h"

#include "board_util.h"
#include "ctd_base.h"
#include "ctd_sbe37.h"
#include "optode.h"
#include "sleep.h"
#include "microsd.h"
#include "fatfs/src/ff.h"
#include "uartstdio.h"	// User local version with larger RX buffer
#include "pwm.h"
#include "i2c_fram.h"
#include "config.h"


extern struct systemSamplingData sys_samp;

extern int microSD_flg;

extern int optode_stateMachine(int optodeState);

extern void adc_onchip_init(void);
extern uint32_t * read_all_adc(void);
extern void fram_store(void);
extern void ADS1248_gpio3(uint32_t state);

void fram_retrieve(void);


// Global variables
extern struct optodeDriver optode;
extern struct microCatDriver microCat;
extern struct ctdDriver ctd;   // struct defd in ctd_base.h


uint32_t sys_data_chksum32;

extern float fBiasPos;  // used for read_bias_bat();
extern float fBiasNeg;

extern unsigned char prnBuf[SIZEOF_PRNBUF+4];      // size is defd in system.h

unsigned long timer_10ms = 0;       // ulong is uint32_t on this processor
unsigned long timer_1ms = 0;
unsigned long timer_1us = 0;


extern uint32_t adc_data[];
extern int dbg_flag;
extern int profileTarget;
extern int profile2Target;
extern int ads1248noniso_flg;



#define TIME_TXSAMPLE_MSEC      30      // was 50


/*****************************************************************************
*
* System tick interrupt handler.  Updated to 1ms for system timing.
* Requires: Requires ROM_SysTickPeriodSet(ROM_SysCtlClockGet() / 1000); in init.c
* Also, provides 10 ms tick for various timing requirements.
* FatFs requires a timer tick every 10 ms for internal timing purposes.
*
*****************************************************************************/
void SysTickHandler(void)
{
    timer_1ms++;
    if((timer_1ms % 10) == 0)
    {
        disk_timerproc();   // FatFs
        timer_10ms++;           // For Timer_10ms()
    }

    //pwmSoln_stateMachine(-1);         // manages PG1,PG3 GPIO outputs,  -1 says use global state variables
    //pwmPump_stateMachine(-1);
}

/****************************************************************************
 * Timer_10ms()
 *
 * Returns value of 10 ms system tick variable. Can be used for general
 * purpose timing where a simple delay is not workable.
 * Call with "reset" true to reset timer to zero.
 * RCG 4/14
 ***************************************************************************/
unsigned long Timer_10ms(bool reset)
{
	if(reset) timer_10ms = 0L;
	return timer_10ms;
}

/****************************************************************************
 * Timer_1ms()
 *
 * Returns value of 1 ms system tick variable. General purpose timing

 ***************************************************************************/
unsigned long Timer_1ms(bool reset)
{
    if(reset) timer_1ms = 0L;
    return timer_1ms;
}

uint32_t compute_sys_data_chksum(void)
{
    int indx;
    uint8_t *bytePtr;
    uint32_t chkSum32 = 0;

    bytePtr = (uint8_t *)&sys_data;

    for(indx=0; indx<sizeof(sys_data); indx++)
    {
        chkSum32 += *bytePtr;     // add byte at a time, sum into 32 bit checksum (later use a more bulletproof alg)
        bytePtr++;
    }
    return(chkSum32);
}


void initSysDataVolatileVariables(void)
{
    uprintf("\r\nWarning: Initialized volatile sys data variables\r\n");

    sys_samp.state = IDLE;
    sys_samp.nextWakeUp = ROM_HibernateRTCGet()+sys_data.sampling_period;
    sys_samp.next_gdata_fptr = 0L;      // deprecated (not used, need to confirm)
    sys_samp.current_sample = 0;
    sys_samp.AD24_std = 0.0;
    //sys_samp.deploy_time = 0;     // TODO

}




/*
 * Retrieves the saved sys_data variables from their storage
 * location in EEPROM (when the device hibernates, sys_data variables
 * are stored in EEPROM if there is a change - 500K write cycle limit).
 * If no value has been assigned to a sys_data variable, a default
 * value is assigned.
 */
void retrieveSysDataVariables(void)
{
	uint32_t ulStatus;

	//enable the EEPROM
	ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_EEPROM0);

	ulStatus = EEPROMInit();
	if( ulStatus != EEPROM_INIT_OK)
	{
		uprintf("EEPROM Initialization error.\r\n");
	}

	//read the sys_data struct out of EEPROM.  Last argument ensures # of bytes is multiple of 4
	EEPROMRead((uint32_t*) &sys_data, 0x400, (sizeof(sys_data) + 3) & ~3);

	//perform 'error checking'  THOMTHOM
	// Criteria for 'bad' EEPROM sys_data
	// uSD is 0xff
	//sys_data_error_check();


    retrieveSysSampFRAMVariables();  // sys_samp

}


int verifySysDataVariables(void)
{
    if (sys_data.app_cfg[APPCFG_EXEC_SWITCHERONI] > EXEC_MAXDEFD)
    {
        sys_data.app_cfg[APPCFG_EXEC_SWITCHERONI] = EXEC_DEFAULT;
        return(FALSE);
    }

    return(TRUE);
}

// THOM ToDo: merge these checks into verifySysDataVariables
int sys_data_error_check(void)
{
    int errorFlg;

    errorFlg = 0;

    if(sys_data.Vtherm_trials > 40)
        errorFlg++;
    if(sys_data.Vtherm_sps == 0 || sys_data.Vtherm_sps > 40)
        errorFlg++;

    if(sys_data.Vrsi_trials > 40)
        errorFlg++;
    if(sys_data.Vrsi_sps == 0 || sys_data.Vrsi_sps > 40)
        errorFlg++;

    if(sys_data.Vrse_trials > 40)
        errorFlg++;
    if(sys_data.Vrse_sps == 0 || sys_data.Vrse_sps > 40)
        errorFlg++;

    if(sys_data.low_batt_volt > 100)
        errorFlg++;

    if(sys_data.baud_rate > 115200L || sys_data.baud_rate < 9600L)
        errorFlg++;

    if(errorFlg > 1)
    {
        init_sys_data_default();  // THOM Todo - look at assessing data error before re-init
    }


}

#ifdef OLDCODE
//def structs in main.c
struct systemDataVolatile sys_data_vol;
struct systemDataVolatile sys_data_chg;         // used to write to hibernate module battery backed register file

void write_nonvol_ram(void)         // system.c
{
    //int indx;

    // Need to enable the Hibernation peripheral after wake/reset, before using it.
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_HIBERNATE);

        // EnableExpClk should always be called, even if the module was already enabled,
        // because this function also initializes some timing parameters.
    ROM_HibernateEnableExpClk(ROM_SysCtlClockGet());

    // store volatile config data
    HibernateDataSet((uint32_t *)&sys_data_chg, SYSDATACHG_NUMWORDS);
    //uprintf("\r\nwrite_nonvol_ram() st=%u, nwup=%u, ngfptr=%u, cursam=%u, std=%u\r\n");
}

void read_nonvol_ram(void)         // system.c
{
    // Need to enable the Hibernation peripheral after wake/reset, before using it.
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_HIBERNATE);

        // EnableExpClk should always be called, even if the module was already enabled,
        // because this function also initializes some timing parameters.
    ROM_HibernateEnableExpClk(ROM_SysCtlClockGet());

    HibernateDataGet((uint32_t *)&sys_data_chg, SYSDATACHG_NUMWORDS);     // last parm is number of 4byte words

    //uprintf("\r\nread_nonvol_ram() st=%u, nwup=%u, ngfptr=%u, cursam=%u, std=%u\r\n");
}

#endif

// return 0 on success
uint32_t storeSysDataVariables(void)
{

    storeSysSampFRAMVariables();   // Note 6 Oct 2022: if this fails, it is not caught.

    // store the sys_data structure (_vol is used to prevent changes in eeprom - this needs to be improved when we drop support for older hardware)
    // returns 0 on success
    return(EEPROMProgram((uint32_t*) &sys_data, 0x400, (sizeof(sys_data) + 3) & ~3));
}

void initSysSampFRAMVariables(void)
{

    sys_samp.state = IDLE;                  //430 IDLE, DEPLOYED, COMMAND,  NOT USER MODIFIABLE                        <<<<<------
    sys_samp.nextWakeUp = 0;            //434 Next intended RTC match (wake-up time) NOT USER MODIFIABLE           <<<<<------
    sys_samp.next_gdata_fptr = 0;       //438 The file position of the next gdata sample. NOT USER MODIFIABLE      <<<<<------
    sys_samp.current_sample = 0;        //442 The current data record to be stored. NOT USER MODIFIABLE            <<<<<------
    sys_samp.AD24_std = 0.0;                 //464 standard deviation for AD24                                          <<<<--------
    sys_samp.initNum= 0x55AA55AA;
    fram_sys_samp_store();

}


uint32_t  storeSysSampFRAMVariables(void)
{

    if(sys_samp.initNum != 0x55AA55AA)
    {
        uprintf("FRAM sys_samp.init, Num is not 0x55AA55AA\r\n");
        //initSysSampFRAMVariables();
        sys_samp.initNum= 0x55AA55AA;
        return(1);      // return non-zero to indicate fail (matches return signature of storeSysDataVariables()
    }


    fram_sys_samp_store();  // defd in i2c_fram.c
    return(0);
}

void retrieveSysSampFRAMVariables(void)
{


    fram_sys_samp_retrieve();  // defd in i2c_fram.c

    if(sys_samp.initNum != 0x55AA55AA)
    {
        uprintf("FRAM sys_samp.init, Num is not 0x55AA55AA\r\n");
        initSysSampFRAMVariables();
        sys_samp.initNum= 0x55AA55AA;
    }


}

void initSysDataVariables(void)
{
    init_sys_data_default();     // defd in config.c
}




// Calculates temperature from Durafet's thermistor. V_therm is the voltage from thermistor, measured using isolated 24-bit ADC.
// TCOffset is an user input, to correct thermistor to be more accurate.
float DuraFET_temp(float V_therm, float TCOffset)
{
	// Declare variables
    float TC;
	double Rtherm;
	double TC4, TC4ln, TC3;
	double c0, c1, c2, c3;
	double A, B, C;
	double dVtherm;

	dVtherm = (double)V_therm;

#ifdef NOCODE
	float c0 = 340.9819863;
	float c1 = -9.10257E-05;
	float c2 = -95.08806667;
	float c3 = 0.965370274;
#endif

	//if(quadratic)
	// Thermistor coefficients, Steinhart-Hart coefficients
    c0 = sys_data.quadTherm_c0;      //340.9819863;
    c1 = sys_data.quadTherm_c1;      //-9.10257E-05;
    c2 = sys_data.quadTherm_c2;      //-95.08806667;
    c3 = sys_data.quadTherm_c3;      //0.965370274;

    //A = sys_data.shTherm_A;
    //B = sys_data.shTherm_B;
    //C = sys_data.shTherm_C;


    A = sys_data.quadTherm_c0;
    B = sys_data.quadTherm_c2;
    C = sys_data.quadTherm_c3;

#define TEMP_ABS    273.15
	// Calculate TC
	Rtherm = 20000 / ((3.3 / dVtherm) - 1);

	//This code came from Scripps
	TC4 = c0 + c1*Rtherm + c2*(log10(Rtherm)) + c3*(pow(log10(Rtherm), 3));   // I suspect conversion to Celsius is built into c0 coefficient.

	TC4ln = c0 + c1*Rtherm + c2*(log(Rtherm)) + c3*(pow(log(Rtherm), 3));

	//1/T = A + B(LnR) + C(LnR)^3  (Kelvin) - This Thom has coded from an AVX appnote on NTC thermistors, plus some other research
	TC3 = (double)1 / (double)( A + B*(log(Rtherm)) + C*(pow(log(Rtherm), 3)) );
	//TC3 -= TEMP_ABS;  // convert to Celsius

	// Apply offset to TC; TCOffset is an user input,
	// or derived during pH calibration process.
	TC = 0.0;
    if(sys_data.app_cfg[APPCFG_TEMPC_SH_ALG] == 0)
        TC = (float)TC4;
	if(sys_data.app_cfg[APPCFG_TEMPC_SH_ALG] == 1)
	    TC = (float)TC3;

//uprintf("\r\nDEBUG TC4 = %8.4lf, TC4ln = %8.4lf,  TC3 = %8.4lf\r\n;", TC4, TC4ln, TC3);

	TC = TC + TCOffset;

	//Rtherm =20000./(3.3./Vtherm-1);
	//
	//Steinhart - Hart Equation 1/T = A + B(LnR) + C(LnR)^3  (Kelvin)


	return TC;
}

/*
* Calculate pH using external reference.
* Eext refers to the voltage from the external reference, measured using isolated 24-bit ADC.
* TC should be calculated using fucntion getDurafettemp.
* Salt refers to salinity, extracted from SBE 37.
* RCG 5/14
*/
float calc_pHext(float Eext, float TC, float salt)
{
	float TK;				// Temperature in Kelvin
	float S_T;				// Nernst Slope
	float Eoext;			// Calibration coefficient corrected to in situ temperature
	float Z; 				// Ionic Strength; Dickson 2007
	float SO4_tot; 			// Total sulfate concentration; Dickson 2007
	float mCl; 				// Molality of Chloride; Dickson 2007;
	float K_HSO4; 			// Bisulfate acidity constant; Dickson 1990.
	float DHconst;			// Debye-Huckel; Khoo et al. 1997
	float log10gamma_HCl;	// log10 of mean activity coefficient of HCl in seawater
	float pHext_free;		// pH on free scale calculated from external reference
	float pHext_tot;		// pH on total scale calculated from external reference

	// Start calculations
	TK = TC + 273.15;
	S_T = (R_ * TK) / F_ * LN10;
	//Eoext = sys_data.Eo_ext_25C + dEoEXT_dt * (TC - 25);
	Eoext = sys_data.k0ext + dEoEXT_dt * (TC - 25);

	Z = 19.924 * salt / (1000 - 1.005 * salt); // Ionic strength
	SO4_tot = (0.14 / 96.062) * (salt / 1.80655); // molality sulfate from conservative relationship.
	mCl = 0.99889 / 35.453 * salt / 1.80655; // moallity chloride from conservative relationship.
	K_HSO4 =  exp(-4276.1/(TK)+141.328-23.093*log(TK)+(-13856/(TK)+324.57-47.986*log(TK))*sqrt(Z)+(35474/(TK)-771.54+114.723*log(TK))*Z-2698/(TK)*pow(sqrt(Z), 3)+1776/(TK)*pow(Z, 2)+log(1-0.001005*salt));
	DHconst = 0.00000343 * (pow(TC, 2)) + 0.00067524 * TC + 0.49172143; //Debye-Huckel
	log10gamma_HCl = 2*(-DHconst * sqrt(Z) / (1 + 1.394 * sqrt(Z)) + (0.08885 - 0.000111 * TC) * Z);

	pHext_free =  -( (Eoext - Eext) - S_T * (log10(mCl) + log10gamma_HCl) ) / S_T;
	pHext_tot = pHext_free - log10(1 + SO4_tot / K_HSO4); // pH from external reference electrode on total scale.
	return pHext_tot;

}

/*
* calc_pHint()
* Function to calculate pH using internal reference.
* Eint refers to the voltage from the internal reference, measured using the isolated 24-bit ADC.
* TC should be calculated using function getDurafettemp.
* RCG 5/14
*/
float calc_pHint(float Eint, float TC)
{
	float TK; 		// Temperature in Kelvin
	float S_T; 		// Nernest Slope
	float Eoint;  	// Calibration coefficient corrected to in situ temperature.
	float pHint;

	TK = TC + 273.15;
	S_T = (R_ * TK) / F_ * LN10;

	//Eoint = sys_data.Eo_int_25C + dEoINT_dt * (TC - 25);
	Eoint = sys_data.k0int + dEoINT_dt * (TC - 25);

	pHint = (Eint - Eoint) / S_T;

	return pHint;
}

/*
 * ph_calib()
 * Calculates DuraFET pH sensorcalibration values
 * using either user entered values, or automatic
 * calibration using temperature and salinity derived
 * from a MicroCAT CTD.
 * RCG 5/14
 */
void ph_calib(void)
{
	int response, i, j, samp, lines;
	char buff[100];
	static float Vint=0, Vext=0, pHcalpt=0, tempC, salt;
	float ftemp, tempK, E0int, S_T, Z, SO4_tot, mCl, K_HSO4, pHint_free, dummy, Vtherm, TCOffset;
	float DHconst, log10gamma_HCl, mHfree, aHfree_aCl, E0ext, sqrt_Z, E0int25, E0ext25;	// beta_SO4,
	float StdDev[SD_VALUES][SD_DIFF_SQ+1], diff, sum;
	float Vint_SD, Vext_SD, Vtherm_SD, tempC_SD, salt_SD;

	float   conductivity, density, speedSound;
	unsigned int model, sernum;
	unsigned char charInput;


	uprintf("\r\nph_calib() not supported in this version\r\n");
	//return;

	// pH Calibration point
	while(1)
	{
		sprintf(buff, "\r\n\r\nEnter pH calibration point [%.3f]: ", pHcalpt);
		uprintf("%s", buff);
		if(getUserInput(buff, strlen(buff)))
		{
			if(sscanf(buff, "%f", &ftemp) == 1)
			{
				if(ftemp >= 0 && ftemp <= 14)
				{
					pHcalpt = ftemp;
					uprintf("pH cal pt = %.3f\r\n", pHcalpt);
					break;
				}
				else uprintf("\r\nEnter between 0 and 14");
				continue;
			}
			else
			{
			    uprintf("DEBUG: sscanf fails to return 1");
			    break;   // if sscanf fails, exit?
			}
		}
		else
		{
		    uprintf("DEBUG: getUserInput fails to return 1");
		    break;         // if
		}
	}

	// Automatic or manual calibration?
	response = yesOrNoMenuChoice("\r\n\r\nPerform automatic DuraFET calibration (Y/N) [N]? ", NO);

	// Manual calibration
	if(response == NO)
	{
		// Vint
		while(1)
		{
			sprintf(buff, "\r\n\r\nEnter Vrsi [%f]: ", Vint);
			uprintf("%s", buff);
			if(getUserInput(buff, strlen(buff)))
			{
				if(sscanf(buff, "%f", &ftemp) == 1)
				{
					if(ftemp >= (-2) && ftemp <= 2)
					{
						Vint = ftemp;
						break;
					}
					else uprintf("Enter number between -2 and 2\r\n\r\n");
					continue;
				}
				else break;
			}
			else break;
		}

		// Vext
		while(1)
		{
			sprintf(buff, "\r\n\r\nEnter Vrse [%f]: ", Vext);
			uprintf("%s", buff);
			if(getUserInput(buff, strlen(buff)))
			{
				if(sscanf(buff, "%f", &ftemp) == 1)
				{
					if(ftemp >= (-2) && ftemp <= 2)
					{
						Vext = ftemp;
						break;
					}
					else uprintf("Enter number between -2 and 2\r\n\r\n");
					continue;
				}
				else break;
			}
			else break;
		}

		// Temperature
		while(1)
		{
			sprintf(buff, "\r\nEnter bath temperature [%f]: ", tempC);
			uprintf("%s", buff);
			if(getUserInput(buff, strlen(buff)))
			{
				if(sscanf(buff, "%f", &ftemp) == 1)
				{
					if(ftemp >= 0 && ftemp <= 100)
					{
						tempC = ftemp;
						break;
					}
					else uprintf("\r\nEnter between 0 and 100");
					continue;
				}
				else break;
			}
			else break;
		}

		// Salinity
		while(1)
		{
			sprintf(buff, "\r\nEnter bath salinity [%f]: ", salt);
			uprintf("%s", buff);
			if(getUserInput(buff, strlen(buff)))
			{
				if(sscanf(buff, "%f", &ftemp) == 1)
				{
					if(ftemp >= 0 && ftemp <= 100)
					{
						salt = ftemp;
						break;
					}
					else uprintf("\r\nEnter between 0 and 100");
					continue;
				}
				else break;
			}
			else break;
		}
	}

	// Automatic calibration
	else
	{
		// Clear standard deviation array
		for(j=0; j<SD_AVG; j++)
		{
			for(i=0; i<5; i++) StdDev[i][j] = 0;
		}

		j = 0;				// Reset standard deviation array counter
		lines = 20; 		// Force program to write column labels before first data line

		//ctd_open();
		openADS1248_iso();
		ROM_SysCtlDelay(ONESEC);	// Let instruments and sensors settle
		uprintf("\r\n\r\nPlace DuraFET and MicroCAT in calibration bath.");
		uprintf("\r\nHit any key when values have stabilized...");
		UARTFlushRx();

		while(1)
		{
			Vint = pollADS1248_iso(1, 6, sys_data.Vrsi_trials, 1, 5);
			Vext = pollADS1248_iso(4, 6, sys_data.Vrse_trials, 1, 5);
			Vtherm = pollADS1248_iso(0, 6, sys_data.Vtherm_trials, 1, 5);	// Chan 0-6, trials = user, gain = 1, sps = 5 Hz
			tempC = DuraFET_temp(Vtherm, sys_data.TCOffset);   // Thom, uncommented this line, future, allow entry of TCOffset as difference between MicroCat temp

			int ctdState;
			ctdState = 1;
			//uprintf("DEBUG: CTD statemachine = 1\r\n");
			while(1)
	        {
			    // ctd will open and close in the loop, might want to mod statemachine for ctd always on operation
	            if(ctdState == 0)            // makes sure ctd statemachine is finished
	                break;                  //ctd.salt and ctd.tempC returned on success
	            //ctdState = ctd_stateMachine(ctdState);

	            if((sys_data.data_cfg[CFG_UART4_INST]) == INST_SBE37_MICROCAT)
	            {
	                ctdState = ctd_sbe37_stateMachine(ctdState);     //defd in ctd_sbe37.c

	            }

	            if((sys_data.data_cfg[CFG_UART4_INST]) == INST_AANDERAA_5860)
	            {
	                ctdState = ctd_aand5860_stateMachine(ctdState);     //defd in ctd_aand5860.c

	            }



                if(UARTRxBytesAvail())
                {
                    charInput = UARTgetc();

                    if(charInput == CTRL_X)  //24
                    {
                        ctd.tempC = 0.0;
                        ctd.salt = 0.0;
                        ctd_close();
                        //uprintf("Debug: reading of ctd terminated by ctrl-x\r\n");
                        break;
                    }

                }

	            // allow user to exit with Ctrl-X

	        }

#ifdef OLDCODE
			ctd_microCat_poll();        //pollMicroCAT();
			ROM_SysCtlDelay(5*ONESEC);	// Wait for instruments to respond
			ctd_microCat_parseData();	// Extract the data from response strings
#endif

			//uprintf("Debug:  tempC = %f, salt = %f", ctd.tempC, ctd.salt);
			tempC = ctd.tempC;
			salt = ctd.salt;

			// Store current sample values
			if(samp < SD_AVG) samp++;
			else samp = 0;
			StdDev[0][samp] = Vint;
			StdDev[1][samp] = Vext;
			StdDev[2][samp] = Vtherm;
			StdDev[3][samp] = tempC;
			StdDev[4][samp] = salt;


			// Find the mean of the last SD_AVG samples for each sensor
			for(i=0; i<SD_VALUES; i++)
			{
				sum = 0;

				for(j=0; j<SD_AVG; j++)
				{
					sum += StdDev[i][j];
				}

				StdDev[i][SD_MEAN] = sum / SD_AVG;	// Current mean for each sensor
			}

			// Find the difference squared for each of the last SD_AVG samples
			// Then find the sum of the squared differences
			for(i=0; i<SD_VALUES; i++)
			{
				sum = 0;

				for(j=0; j<SD_AVG; j++)
				{
					 diff = (StdDev[i][j] - StdDev[i][SD_MEAN]) ;	// Difference for each sample
					 sum += diff * diff;							// Sum of differences squared
				}

				StdDev[i][SD_DIFF_SQ] = sum;
			}

			// Take square root for each sensor
			Vint_SD = sqrt(StdDev[0][SD_DIFF_SQ]);
			Vext_SD = sqrt(StdDev[1][SD_DIFF_SQ]);
			Vtherm_SD = sqrt(StdDev[2][SD_DIFF_SQ]);
			tempC_SD = sqrt(StdDev[3][SD_DIFF_SQ]);
			salt_SD = sqrt(StdDev[4][SD_DIFF_SQ]);

			// Write column headers every 20 lines
			if(lines >= 20)
			{
#ifdef OLDCODE
				uprintf("\r\n\r\nVint\t\tVint-SD\t"
						"Vext\t\tVext-SD\t"
						"Vtherm\tVtherm-SD\t"
						"Temp\t\tTemp-SD\t"
						"Salinity\tSal-SD");
#endif
                uprintf("\r\n\r\n    Vrsi\t Vrsi-SD\t"
                        "    Vrse\t Vrse-SD\t"
                        "  Vtherm\tVthermSD\t"
                        "   TempC\tTempC-SD\t"
                        "Salinity\tSal-SD");

				lines = 1;		// Reset line counter
			}
			else lines++;

			// Write data line
			uprintf("\r\n%8.5f\t%8.5f\t"
					"%8.5f\t%8.5f\t"
					"%8.5f\t%8.5f\t"
					"%8.5f\t%8.5f\t"
					"%8.5f\t%8.5f",
					Vint, Vint_SD,
					Vext, Vext_SD,
					Vtherm, Vtherm_SD,
					tempC, tempC_SD,
					salt, salt_SD);

			// Key hit, so display current averaged values
			if(kbhit())
			{
				uprintf("\r\n\r\nAverage of last %d values", SD_AVG);

				Vint = StdDev[0][SD_MEAN];
				uprintf("\r\nVint = %f V  SD = %f", Vint, Vint_SD);

				Vext = StdDev[1][SD_MEAN];
				uprintf("\r\nVext = %f V  SD = %f", Vext, Vext_SD);

				Vtherm = StdDev[2][SD_MEAN];
				uprintf("\r\nVtherm = %f C  SD = %f", Vtherm, Vtherm_SD);

				tempC = StdDev[3][SD_MEAN];
				uprintf("\r\nMicroCAT Temperature = %f C  SD = %f", tempC, tempC_SD);

				salt = StdDev[4][SD_MEAN];
				uprintf("\r\nMicroCAT Salinity = %f  SD = %f", salt, salt_SD);

				response = yesOrNoMenuChoice("\r\n\r\nValues acceptable (Y/N) [N]? ", NO);
				if(response == NO) continue;
				else break;
			}
		}

		closeADS1248_iso();
		ctd_close(); 	//closeMicroCAT();
	}

	// Calculate E0int25 and E0ext25 using either manual or automatic values
	tempK = tempC + 273.15;  					// Convert temp from C to K
	S_T = (R_ * tempK) / F_ * log(10); 			// Nernst temp dependence
	E0int = Vint - S_T * pHcalpt; 				// Calc E0int from Nernst & pH @ calibration point
	E0int25 = E0int + dEoINT_dt * (25 - tempC);

	Z = 19.924 * salt / (1000 - 1.005 * salt); 			// Ionic strength, Dickson et al. 2007
	sqrt_Z = sqrt(Z);

	SO4_tot = (0.14 / 96.062) * (salt / 1.80655);  	// Total conservative sulfate
	mCl = 0.99889/35.453*salt/1.80655; 				// Conservative chloride

	// Bisulfate equilibrium const., Dickson et al. 2007
	K_HSO4 = exp( -4276.1 / tempK + 141.328 - 23.093 * log(tempK) \
	          + ( -13856 / tempK + 324.57 - 47.986 * log(tempK) ) * sqrt_Z \
	          + ( 35474 / tempK - 771.54 + 114.723 * log(tempK) ) * Z - 2698 / tempK * pow(Z, 1.5) \
	          + 1776 / tempK * Z * Z + log(1 - 0.001005 * salt) );

	pHint_free = pHcalpt + log10( 1 + SO4_tot / K_HSO4);
	DHconst = 0.00000343 * tempC * tempC + 0.00067524 * tempC + 0.49172143; //Debye-Huckel, Khoo et al. 1977
	log10gamma_HCl = 2 * (-DHconst * sqrt_Z / ( 1 + 1.394 * sqrt_Z ) + (0.08885 - 0.000111 * tempC) * Z);
	mHfree = pow(10, (-pHint_free) );
	aHfree_aCl = mHfree * mCl * pow( 10, (log10gamma_HCl) );
	E0ext = Vext + S_T * log10(aHfree_aCl);
	E0ext25 = E0ext + dEoEXT_dt * (25-tempC);

	TCOffset =  tempC - DuraFET_temp(Vtherm, 0);

	uprintf("\r\n\r\nEo Int @ 25C = %f", E0int25);
	uprintf("\r\nEo Ext @ 25C = %f", E0ext25);
	uprintf("\r\nTCOffset = %f", sys_data.TCOffset);

	response = yesOrNoMenuChoice("\r\n\r\nAccept and store calibration values(Y/N) [N]? ", NO);
	if(response == YES)
	{
		//sys_data.Eo_int_25C = E0int25;
		sys_data.k0int = E0int25;
		
		//sys_data.Eo_ext_25C = E0ext25;
		sys_data.k0ext = E0ext25;			// variable rename 2 Apr 2021  Eo_ext_25C to k0ext

		sys_data.TCOffset = TCOffset;

		uprintf("\r\nCalibration values stored");
	}

}



/*
 *  send last sample, then take new sample and store to SD card
 * Take measurements and write them to SD card.
 */
void sendlast_takesample(void)
{
    FIL fileObject;
    FRESULT fresult;
#define MAX_DATASAMPSIZE    240     // this is oversized by over 20 bytes
    unsigned char buf[MAX_DATASAMPSIZE];
    unsigned int readSize;

    if(sys_data.app_cfg[APPCFG_MICROSD_ENABLE] == 0)        // fix 6 Aug 2021
    {
        uprintf("void sendlast_takesample(void) is not supported with microSD disabled\r\n");
        return;

    }

    uprintf("THOM TODO:  Sendlast_takesample is not done yet\r\n");

    // open snapshot.txt, send all until /n
    fresult = f_open(&fileObject, "snapshot.txt", FA_READ);  // Creates a new file. If the file is existing, it will be truncated and overwritten.
    if(fresult != FR_OK)
    {
        // file does not exist, first time reading so previous data not available
        //get_sample(0);      // arg=0 says 'dont tx the result', this will create the snapshot.txt file (after a delay)
        get_sample(0,1);   // THOM 14 May 2021
        fresult = f_open(&fileObject, "snapshot.txt", FA_READ);  // Creates a new file. If the file is existing, it will be truncated and overwritten.
        if(fresult != FR_OK)
        {
            uprintf("f_open error snapshot.txt: %s\r\n", StringFromFresult(fresult));
            error_store("f_open error on snapshot.txt");
            return;
        }

    }

    fresult = f_read(&fileObject, &buf[0], MAX_DATASAMPSIZE-1, &readSize);
    if(fresult != FR_OK)
    {
        uprintf("f_read error snapshot.txt\r\n");
    }
    else
    {

        if(readSize > 4)
        {
            if(readSize >= MAX_DATASAMPSIZE)        // in the odd chance of an error
                readSize = MAX_DATASAMPSIZE-1;
            buf[readSize] = 0x00;       // null terminate

            uprintf("%s", buf);       //uprintf("%s\r\n", buf); print the sample

        }
        else
        {
            uprintf("bad read size (less than 5)\r\n");
        }
    }

    // Close the file
    fresult = f_close( &fileObject );
    if(fresult != FR_OK)
    {
        //uprintf("8\r\n");
        uprintf("f_close error snapshot.txt: %s\r\n", StringFromFresult(fresult));
        error_store("f_close error");
    }

    //get_sample(0);          // get sample for reading with next 'sl'
    get_sample(0,1);
}



/****************************************************************
 * Get the current time according to the RTC.
 * returns in time-strcut
 ****************************************************************/
struct tm *get_RTC_time(void)
{
    //char timeStamp[TIMESTAMPLENGTH];
    uint32_t ticks;
    struct tm *time_struct;

    //get the time from the from the RTC so we can print it
    ticks = ROM_HibernateRTCGet();

    time_struct = localtime((const time_t*)&ticks);

    // DEBUG to print the time
    //strftime(timeStamp, sizeof(timeStamp),"%m/%d/%y %H:%M:%S", time_struct);
    //uprintf("%s", timeStamp);

    return(time_struct);
}






/*
 * error_store()
 * Stores error messages with timestamp.
 * Appends a newline character to message.
 * Function is useful during deployment when console is disconnected
 * RCG 5/14
 */
void error_store(const char *error_buff)
{
	char timestamp[TIMESTAMPLENGTH];
	uint32_t ticks;
	struct tm *time_struct;
	FIL fil;		// File object
	FRESULT fresult;
	UINT bw;

	if(sys_data.app_cfg[APPCFG_MICROSD_ENABLE] == 0)        // 20 Jan 2021 TGM
	{
	    uprintf("error_stor() not supported with microSD_flg=0 disabled\r\n");
	    return;
	}

	// Open a file
	fresult = f_open(&fil, "Error.txt", FA_WRITE |FA_OPEN_ALWAYS);
	if(fresult != FR_OK)
	{
		uprintf("Error.txt f_open error: %s\r\n", StringFromFresult(fresult));
	}

	// Seek to the end, to append our file
	fresult = f_lseek(&fil, fil.fsize);
	if(fresult != FR_OK)
	{
		uprintf("Error.txt f_lseek error: %s\r\n", StringFromFresult(fresult));
	}

	// Write timestamp to file
	ticks = ROM_HibernateRTCGet();
	time_struct = localtime(&ticks);
	strftime(timestamp, sizeof(timestamp),"\r\n%Y/%m/%d %H:%M:%S ", time_struct);

	fresult = f_write( &fil, timestamp, strlen(timestamp), &bw );
	if(fresult != FR_OK)
	{
		uprintf("Error.txt f_write error: %s\r\n", StringFromFresult(fresult));
	}

	// Write error message to file
	fresult = f_write( &fil, error_buff, strlen(error_buff), &bw );
	if(fresult != FR_OK)
	{
		uprintf("Error.txt f_write error: %s\r\n", StringFromFresult(fresult));
	}

	// Close the file
	fresult = f_close( &fil );
	if(fresult != FR_OK)
	{
		uprintf("Error.txt f_close error: %s\r\n", StringFromFresult(fresult));
	}

}




void ms_delay(unsigned int msec)
{
    ROM_SysCtlDelay(MILLISECOND*msec);
}

void delay_msec(unsigned int msec)
{
    ROM_SysCtlDelay(MILLISECOND*msec);
}

//*****************************************************************************
//
// The error routine that is called if the driver library encounters an error.
//
//*****************************************************************************
#ifdef DEBUG
void
__error__(char *pcFilename, uint32_t ui32Line)
{
}
#endif



FRESULT open_append (
    FIL* fp,            /* [OUT] File object to create */
    const char* path    /* [IN]  File name to be opened */
)
{
    FRESULT fr;

    /* Opens an existing file. If not exist, creates a new file. */
    fr = f_open(fp, path, FA_WRITE | FA_OPEN_ALWAYS);
    if (fr == FR_OK) {
        /* Seek to end of the file to append data */
        fr = f_lseek(fp, f_size(fp));
        if (fr != FR_OK)
            f_close(fp);
    }
    return fr;
}




