/*
 * David Muller; German Alfaro
 * davehmuller@gmail.com; alfaro.germanevera@gmail.com
 *
 * 2/2014 Robert Glatts, rglatts@ucsd.edu
 *
 * 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_microcat.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);

//void get_header(void);

//void print_data_header(void);

//int write_metadata_header(const time_t currentTime);
//void print_metadata_header(const time_t currentTime);




// Global variables
//extern char uart3_buff[];       // Optode
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;

//#define SIZEOF_SAMPBUF  160                 // Thom TODO BUG due to max data config sampBuf size
//char sampBuf[SIZEOF_SAMPBUF+4];     // for sl command


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

//V=I*R => V=I*15K => I=V/15K amps => I=V*10^9/15K nano-Amps => I=V*66.6k nA => 15uV/nA.
//#define COUNTERELECTRODE_IK_SCALE       66666.667   // 10^9/15K MCAP has 15K resistor, Ik
//
//#define SUBSTRATECURRENT_IB_SCALING     1000        // 10^9/1M = 1000   MCAP has 1M resistor for Ib, substrate current





/*****************************************************************************
*
* 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("\nWarning: Initialized volatile sys data variables\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()
{
	uint32_t ulStatus;

	//enable the EEPROM
	ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_EEPROM0);

	ulStatus = EEPROMInit();
	if( ulStatus != EEPROM_INIT_OK)
	{
		uprintf("EEPROM Initialization error.\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 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)
    {
        config_sys_data_default_init();
    }


}

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("\nwrite_nonvol_ram() st=%u, nwup=%u, ngfptr=%u, cursam=%u, std=%u\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("\nread_nonvol_ram() st=%u, nwup=%u, ngfptr=%u, cursam=%u, std=%u\n");
}

uint32_t storeSysDataVariables(void)
{

    storeSysSampFRAMVariables();

    // 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();

}


void storeSysSampFRAMVariables(void)
{

    if(sys_samp.initNum != 0x55AA55AA)
    {
        uprintf("FRAM sys_samp.initNum is not 0x55AA55AA\n");
        //initSysSampFRAMVariables();
        sys_samp.initNum= 0x55AA55AA;
    }


    fram_sys_samp_store();  // defd in i2c_fram.c

}

void retrieveSysSampFRAMVariables(void)
{


    fram_sys_samp_retrieve();  // defd in i2c_fram.c

    if(sys_samp.initNum != 0x55AA55AA)
    {
        uprintf("FRAM sys_samp.initNum is not 0x55AA55AA\n");
        initSysSampFRAMVariables();
        sys_samp.initNum= 0x55AA55AA;
    }


}

void initSysDataVariables(void)
{
    config_sys_data_default_init();     // defd in config.c
}





/*
 * batt_volt()
 * Returns main battery voltage on controller side of isolation diodes
 * RCG 4/14
 * TM 4/18  Added support for new MFET board
 *
 */
float batt_volt()
{
	float batt_volt;

#if BOARD_MFET >= 1 || BOARD_MPHOX == 1
	batt_volt = read_env_sensors();
#endif

	return batt_volt;
}

/*
 * batt_volt_iso()
 * Returns isolated battery voltage
 * RCG 4/14
 * TM  8/2019 added support for MFET v2 (revB)
 * assumes that iso power is on
 */
float batt_volt_iso()
{
	float ADC_volts, batt_volt;

#if BOARD_MFET == 1
	batt_volt = 0.0;
#endif

#if BOARD_MFET == 2  || BOARD_MPHOX == 1
	// GPIO3 on ADS1248
	//    float is gnd
	//    0 = bias-
	//    1 = bias+
	ADS1248_gpio3(1);
	ADC_volts = pollADS1248_iso(7, 6, 5, 1, 20);
	batt_volt = ADC_volts*2.0;
#endif
	return(batt_volt);
}

// NOT TESTED YET 14 Apr 2021 - issue with iso power turn on and init should be resolved
void read_bias_bat(void)
{
    float biasplus, biasneg, ADC_volts;
    //unsigned int indx;

    // GPIO3 on ADS1248
    //    float is gnd
    //    0 = bias-
    //    1 = bias+


    openADS1248_iso();
    ROM_SysCtlDelay(MILLISECOND * 100);
    ADS1248_gpio_init();

    ADS1248_gpio3(0);
    ROM_SysCtlDelay(MILLISECOND * 10);
    ADC_volts = pollADS1248_iso(7, 6, 5, 1, 20);    // throw away first reading
    ROM_SysCtlDelay(MILLISECOND * 100);
    ADC_volts = pollADS1248_iso(7, 6, 5, 1, 20);
    biasneg = ADC_volts*2.0;

    ADS1248_gpio3(1);
    ROM_SysCtlDelay(MILLISECOND * 10);
    ADC_volts = pollADS1248_iso(7, 6, 5, 1, 20);    // throw away first reading
    ROM_SysCtlDelay(MILLISECOND * 100);
    ADC_volts = pollADS1248_iso(7, 6, 5, 1, 20);
    biasplus = ADC_volts*2.0;

    fBiasPos = biasplus;   // update global var
    fBiasNeg = biasneg;     // update global var

    //uprintf("Iso Bat Bias- %7.3F,  Bias+ %7.3F\n", biasneg, biasplus);
    //ROM_SysCtlDelay(MILLISECOND * 500);


    closeADS1248_iso();
}

void print_bias_volt_iso(void)
{
    float biasplus, biasneg, ADC_volts;
    unsigned int indx;

    // GPIO3 on ADS1248
    //    float is gnd
    //    0 = bias-
    //    1 = bias+


    openADS1248_iso();
    ROM_SysCtlDelay(MILLISECOND * 100);
    ADS1248_gpio_init();

    for(indx=0; indx<5; indx++)
    {
        ADS1248_gpio3(0);
        ROM_SysCtlDelay(MILLISECOND * 10);
        ADC_volts = pollADS1248_iso(7, 6, 5, 1, 20);
        biasneg = ADC_volts*2.0;

        ADS1248_gpio3(1);
        ROM_SysCtlDelay(MILLISECOND * 10);
        ADC_volts = pollADS1248_iso(7, 6, 5, 1, 20);
        biasplus = ADC_volts*2.0;

        uprintf("Iso Bat Bias- %7.3F,  Bias+ %7.3F\n", biasneg, biasplus);
        ROM_SysCtlDelay(MILLISECOND * 500);
    }

    closeADS1248_iso();
}

/*
 * temp_int()
 * Returns internal temperature
 * RCG 4/14
 */
float controller_temp()
{
	float ADC_volts, temp;

	ADC_volts = pollADS1248_noniso(2, 7, 1); // Chan 2-7, 1 trial
	temp = (ADC_volts * 1000 - 480) / 15.6;
	return temp;
}


/*
 * depth()
 * Returns depth in meters from Honeywell MLH100PGB 100 psi pressure sensor
 * RCG 4/14
 */
float pressure(void)
{
#ifdef GETRIDOFPRESSURE_7May2019
	float ADCvolts, pressure;


	ADCvolts = pollADS1248_noniso(3, 7, 1);	// Result in volts

	pressure = ((ADCvolts * 3.2) - 0.5) * (100 / 4 / 1.45);	// 3.2-to-1 divider, 0.5-4.5 V span, 1.45 dBar/psi
	return pressure; 	// Pressure in dBar
#endif
	return(0.0);
}

#if BOARD_MFET >= 1  || BOARD_MPHOX == 1
// This function applies only to the MFET
float read_env_sensors(void)
{
    float fVbat, fOnChipTemp, fExtTemp;
    uint32_t  uiHumidity, uiWater;
    uint32_t indx = 0;

    pwr_env_mon_on();    // Turn on Load switch for ENV monitoring
    ROM_GPIOPinWrite(GPIO_PORTM_BASE, GPIO_PIN_6, 0xFF);   // Turn on VBat monitoring

    pwr_iso_on();        // Iso-power On
    dbg_printf("iso power on\n");

    adc_onchip_init();

    // delay to allow voltage divider circuit to charge up
    ROM_SysCtlDelay(MILLISECOND*150);    // 150msec reads 12.26, s100 works (12.31 reads 12.18), 25 does not (12.31 reads 8.99, 9.09, 9.20, 9.29)v), 50msec is weak (11.28, 11.31, 11.35, 11.37)

    read_all_adc();

    fVbat = (float)(adc_data[0]*100);
    //fVbat /= 18687.707;  // Thom 30 Sep 2019 reading 11.75 when actual is 12.069v
    fVbat /= 18193.77;

    // onchip temperature (formulae from TI example code)
    //TempValueC = (uint32_t)(147.5 - ((75.0*3.3 *(float)adc_data[7])) / 4096.0);
    fOnChipTemp = (147.5 - ((75.0*3.3 *(float)adc_data[7])) / 4096.0);

    // LM60 temperature sensor - formula from datasheet / schematic (good job Scott)
    // Vout = (+6.25 mV/C * T) + 424mV   =>  T = ((ADCcnt * 0.80566) - 424) / 6.25
    fExtTemp = ((((float)adc_data[4])*0.80566) - 424) / 6.25;

    // Water sensor - convert to percent
    uiWater = (adc_data[3] * 100) / 2596;    // NOTE: Water voltage adc cnts is 2622 when pulled to 3.3v  (measured at 2.1092v on test point with agilent u1272a meter)
    if(uiWater > 100)
        uiWater = 100;

    // Humidity
    uiHumidity = (adc_data[2] * 100) / 3284;

    // Pressure

    //uprintf("Bat = %6.2fV VBAT=%u VPRESS=%3u  VHUM=%3u  VWATER=%3u   VXTEMP=%3u   VBAT=%3u, VBAT=%u, VTEMP=%u  i=%u\r", fVbat, adc_data[0], adc_data[1], adc_data[2], adc_data[3], adc_data[4], adc_data[5], adc_data[6], TempValueC, indx++);
    dbg_printf("Bat = %6.2fV Pressure = %4u  Humidity = %3u  Water = %3u  Temperature = %5.1fC (%4u)   ChipTemp = %5.1fC  i=%u\n\r", fVbat, adc_data[1], uiHumidity, uiWater, fExtTemp, adc_data[4], fOnChipTemp, indx++);


    pwr_vbat_mon_off();   // Turn off VBat monitoring
    pwr_iso_off();        // Iso-power Off
    dbg_printf("iso power off, vbat monitoring off\n");

    return(fVbat);
 }
#endif






// 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("\nDEBUG TC4 = %8.4lf, TC4ln = %8.4lf,  TC3 = %8.4lf\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("\nph_calib() not supported in this version\n");
	//return;

	// pH Calibration point
	while(1)
	{
		sprintf(buff, "\n\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\n", pHcalpt);
					break;
				}
				else uprintf("\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("\n\nPerform automatic DuraFET calibration (Y/N) [N]? ", NO);

	// Manual calibration
	if(response == NO)
	{
		// Vint
		while(1)
		{
			sprintf(buff, "\n\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\n\n");
					continue;
				}
				else break;
			}
			else break;
		}

		// Vext
		while(1)
		{
			sprintf(buff, "\n\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\n\n");
					continue;
				}
				else break;
			}
			else break;
		}

		// Temperature
		while(1)
		{
			sprintf(buff, "\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("\nEnter between 0 and 100");
					continue;
				}
				else break;
			}
			else break;
		}

		// Salinity
		while(1)
		{
			sprintf(buff, "\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("\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("\n\nPlace DuraFET and MicroCAT in calibration bath.");
		uprintf("\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\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(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\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("\n\nVint\t\tVint-SD\t"
						"Vext\t\tVext-SD\t"
						"Vtherm\tVtherm-SD\t"
						"Temp\t\tTemp-SD\t"
						"Salinity\tSal-SD");
#endif
                uprintf("\n\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("\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("\n\nAverage of last %d values", SD_AVG);

				Vint = StdDev[0][SD_MEAN];
				uprintf("\nVint = %f V  SD = %f", Vint, Vint_SD);

				Vext = StdDev[1][SD_MEAN];
				uprintf("\nVext = %f V  SD = %f", Vext, Vext_SD);

				Vtherm = StdDev[2][SD_MEAN];
				uprintf("\nVtherm = %f C  SD = %f", Vtherm, Vtherm_SD);

				tempC = StdDev[3][SD_MEAN];
				uprintf("\nMicroCAT Temperature = %f C  SD = %f", tempC, tempC_SD);

				salt = StdDev[4][SD_MEAN];
				uprintf("\nMicroCAT Salinity = %f  SD = %f", salt, salt_SD);

				response = yesOrNoMenuChoice("\n\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("\n\nEo Int @ 25C = %f", E0int25);
	uprintf("\nEo Ext @ 25C = %f", E0ext25);
	uprintf("\nTCOffset = %f", sys_data.TCOffset);

	response = yesOrNoMenuChoice("\n\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("\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\n");
        return;

    }

    uprintf("THOM TODO:  Sendlast_takesample is not done yet\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)
        fast_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\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\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\n", buf); print the sample

        }
        else
        {
            uprintf("bad read size (less than 5)\n");
        }
    }

    // Close the file
    fresult = f_close( &fileObject );
    if(fresult != FR_OK)
    {
        //uprintf("8\n");
        uprintf("f_close error snapshot.txt: %s\n", StringFromFresult(fresult));
        error_store("f_close error");
    }

    //get_sample(0);          // get sample for reading with next 'sl'
    fast_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\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\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\n", StringFromFresult(fresult));
	}

	// Write timestamp to file
	ticks = ROM_HibernateRTCGet();
	time_struct = localtime(&ticks);
	strftime(timestamp, sizeof(timestamp),"\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\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\n", StringFromFresult(fresult));
	}

	// Close the file
	fresult = f_close( &fil );
	if(fresult != FR_OK)
	{
		uprintf("Error.txt f_close error: %s\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;
}




