/*
 * Init.c
 *
 *  Created on: Jan 23, 2014
 *      Author: rob
 *  Modified starting Mar 2018 by Thom Maughan (TM)
 *    Added MFET/MCAP board support
 */

#include "system.h"
#include "init.h"
#include "microsd.h"
#include "uartstdio.h"	// User local version with larger RX buffer
#include "sleep.h"
#include "i2c_fram.h"
#include "pwm.h"
#include "board_util.h"
#include "i2c_bme280.h"
#include "sample.h"
#include "apf_init.h"

int microSD_flg;



extern void AUX1_init(void);
extern void optode_init(void);
//extern void microCat_init(void);
extern void ctd_init(void);
extern void led_init(void);

extern void profile2_toggle(int target);
extern void ADS1248_gpio_init(void);

extern void init_TM4C123GH6PGE_144pin(void);
extern void init_TM4C123GH6PM_64pin(void);

/**********************************************************************************
 * Init()
 * Initialize pins and ports upon reset or wake from hybernation. Set unused pins low.
 **********************************************************************************/
void init(void)
{

    // Enable lazy stacking for interrupt handlers.  This allows floating-point
    // instructions to be used within interrupt handlers, but at the expense of2
    // extra stack usage.
    ROM_FPULazyStackingEnable();

    //enable floats
    ROM_FPUEnable();

    //set the system clock...50MHZ
    // THOM TODO, experiment with slower clock settings to balance compute vs power consumption
    ROM_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_XTAL_16MHZ | SYSCTL_OSC_MAIN);


#if BOARD_MFET >= 1 || BOARD_SEAPHOX == 1 || BOARD_MPHOX == 1  || BOARD_MSC == 2
    init_TM4C123GH6PGE_144pin();

    // PK0 = en_xcvr  (output)
    // PE0 = CTS (input)
    // PE1 = RTS (output)
#endif

#if BOARD_NANOFET >= 1 || BOARD_MSC == 3
//#define BOARD_DAG       1
    init_TM4C123GH6PM_64pin();
#endif

    // code from Thomz personal project, draft implementation
#if BOARD_TESTFIT >= 1
    init_TM4C123GH6PZ_100pin();
#endif


    /*** Configure SysTick for a 100Hz interrupt.  The FatFs driver and 10 ms timer share a 10 ms tick ***/
    /*** Configure SysTick for a 1000Hz / 1msec interrupt.  General purpose timing while maintaining the
     * The FatFs driver and 10 ms timer share a 10 ms tick ***/
    // void SysTickHandler(void) is in system.c
    //ROM_SysTickPeriodSet(ROM_SysCtlClockGet() / 100);     // 10msec tick (100 Hz)
    ROM_SysTickPeriodSet(ROM_SysCtlClockGet() / 1000);      // 1msec tick (1K Hz)
    ROM_SysTickEnable();
    ROM_SysTickIntEnable();


#if BOARD_MPHOX >= 1  || BOARD_MSC == 2
    pwm_init();
#endif


//#if BOARD_MFET == 2 || BOARD_MPHOX == 1  || BOARD_MSC == 2
    // if i2c does not have a device, the fram_probe hangs (on MFET v1)

    //while(1)
    //{
    fram_init();        // i2c0_init(TRUE);     // fast mode 400kpbs, defd in i2c_fram.c
    //}

#if BOARD_NANOFET >= 1 || BOARD_MSC == 3
    bme280_init();
#endif

//#endif

    /*** Retrieve saved sys_data variables ***/
    retrieveSysDataVariables();         // defd in system.c, moved down in init until after i2c init (in fram)

    verifySysDataVariables();

    init_apf_global_vars();         // apf_init.c

    // default is 115200 and this is set in the init() above - if sys_data.baud_rate is not 115200, then re(set) here
    if(sys_data.baud_rate == 4800L)
    {
        UARTStdioConfig(0, 4800, 16000000);       // 4800 bits per second
    }
    if(sys_data.baud_rate == 9600L)
    {
        UARTStdioConfig(0, 9600, 16000000);       // 9600 bits per second
    }
    if(sys_data.baud_rate == 19200L)
    {
        UARTStdioConfig(0, 19200, 16000000);       // 19200 bits per second
    }
    if(sys_data.baud_rate == 38400L)
    {
        UARTStdioConfig(0, 38400, 16000000);       // 38400 bits per second
    }
    if(sys_data.baud_rate == 57600L)
    {
        UARTStdioConfig(0, 57600, 16000000);       // 57600 bits per second
    }

    // Find out what woke us and decide what to do
    //sleep_handler();  Move to main after init() 25 May 2021

    microSD_flg = 0;
#if BOARD_MFET == 2 || BOARD_MPHOX == 1  || BOARD_MSC == 2
    // Initialize MicroSD card and FatFs (relies on retrieveSysDataVariables)
    if(sys_data.app_cfg[APPCFG_MICROSD_ENABLE] != 0)
    {
        // TODO: check SDpresent
        if( uSD_present() )
        {
            // uprintf("\r\nMicroSD card is Initialized....\r\n");
            Init_SDCard();
            microSD_flg = 1;
        }
        else
        {
            uprintf("\r\nError: MicroSD card is not detected\r\n");
            microSD_flg = 0;
        }
    }
    else
    {
        //uprintf("MicroSD card is Disabled, to change it: 3 -- Config, A -- App Config....\r\n");
    }

#endif

    pump_var_init();
}



#ifdef APFTODO
void InitMSC( void )
{
    short ret;

#ifdef ShowInitTimes
    ldiv_t sdiv;
    RTCTimer ElpTm;
#endif

    DS3234_Init();
    RegIO_Init();

    if( RegIO_RdWord() & SYS_POR_MON )
        sys_por_flag = FALSE;
    else
        sys_por_flag = TRUE;

    if( CFCardDetect() != TRUE ) {
        cprintf("\nNO FLASH CARD FOUND, EXITING!\n");
        BIOSResetToPicoDOS();           //return to PicoDOS Monitor
    }

    if( pdx_access("ISUS", _A_SUBDIR) != OK ) {
        ret = execstr("MKDIR C:\\ISUS");
        if( pdx_access("ISUS", _A_SUBDIR) != OK ) {
            printf("\nISUS MKDIR Failure, ret = %d!\n", ret);
            BIOSResetToPicoDOS();
        }
    }

    if( pdx_access("DURA", _A_SUBDIR) != OK ) {
        ret = execstr("MKDIR C:\\DURA");
        if( pdx_access("DURA", _A_SUBDIR) != OK ) {
            printf("\nDURA MKDIR Failure, ret = %d!\n", ret);
            BIOSResetToPicoDOS();
        }
    }

    printf("\n\n  MBARI Sensor Controller (ISUS/DURA) Initializing...\n");

    InitVars();

    IOPwrUp();

#ifdef ShowInitTimes
    RTCElapsedTimerSetup( &ElpTm );
#endif
    Zcoefs=LoadIsusZCoefs(ZeissCoefs);
#ifdef ShowInitTimes
    sdiv = ldiv(RTCElapsedTime( &ElpTm ), 1000000L);
    printf("ZcoefLoad = %ld.%.6ld\n", sdiv.quot, sdiv.rem);
#endif
    if(Zcoefs > 0) {
        InitLambdaArray(LambdaData, ZeissCoefs);
#ifdef ShowInitTimes
        sdiv = ldiv(RTCElapsedTime( &ElpTm ), 1000000L);
        printf("InitLambda = %ld.%.6ld\n", sdiv.quot, sdiv.rem);
#endif
        Ecoefs=LoadIsusECoefs(NULL, EcoefFile, ZeroData, TcompCoefs, &SwCalTemp, CalDate);
#ifdef ShowInitTimes
        sdiv = ldiv(RTCElapsedTime( &ElpTm ), 1000000L);
        printf("EcoefLoad = %ld.%.6ld\n", sdiv.quot, sdiv.rem);
#endif
        CopyEcoefs(EcoefFile, EcoefData);
#ifdef ShowInitTimes
        sdiv = ldiv(RTCElapsedTime( &ElpTm ), 1000000L);
        printf("CopyEcoefs = %ld.%.6ld\n", sdiv.quot, sdiv.rem);
#endif
    }
    else{
        Ecoefs=LoadIsusECoefs(LambdaData, EcoefFile, ZeroData, TcompCoefs, &SwCalTemp, CalDate);
        CopyEcoefs(EcoefFile, EcoefData);
    }

    //error log entry if no ZCOEF or ECOEF file

    DisplaySystemInfo();

    SyncNextSample();

    SCIRxSetBuffered( TRUE ); // enables IRQ4-

}


void InitVars( void )
{
    char ebuf[ERRBUFSIZE];
    uchar val_uchar;

    DS3234_RdSRAM(SYS_INITSRAM_PTR, sizeof(uchar), (uchar*)&val_uchar);

    if( val_uchar != SYS_INITSRAM_VAL ) {
        val_uchar = SYS_INITSRAM_VAL;
        DS3234_WrSRAM(SYS_INITSRAM_PTR, sizeof(uchar), (uchar*)&val_uchar);

        DS3234_RdSRAM(SYS_INITSRAM_PTR, sizeof(uchar), (uchar*)&val_uchar);

        if( val_uchar != SYS_INITSRAM_VAL ) {
            cprintf("\nNO DS3234 RTC FOUND, EXITING!\n");
            BIOSResetToPicoDOS();           //return to PicoDOS Monitor
        }
        else
            SetDefaultsIntoNVRAM();
    }

    GetVarsFromNVRAM();

    isus_reset_flag = dura_reset_flag = TRUE;          // flag to mark initialization for outputing header info

    sys_reset_time = DS3234_secs;   // instrument initialization time
    DS3234_WrSRAM(SYS_RESETTIME_PTR, sizeof(ulong), (ulong*)&sys_reset_time);

    ++sys_reset_ctr;
    DS3234_WrSRAM(SYS_RESETCTR_PTR, sizeof(ulong), (ulong*)&sys_reset_ctr);

    if( sys_por_flag == TRUE ) {
        ++sys_por_ctr;
        DS3234_WrSRAM(SYS_PORCTR_PTR, sizeof(ulong), (ulong*)&sys_por_ctr);
    }

    isus_fit_pixels = (isus_pixel_end - isus_pixel_beg) + 1;

    SpecData = calloc((size_t)(256*isus_scan_num), sizeof(ushort));
    if( SpecData == NULL ) {
        printf("CAN'T allocate ScanData Array memory\n");
        sprintf(ebuf, "CAN'T allocate ScanData Array memory");
        LogErrorMsg(ebuf, (int)MALLOC_FAILURE, sys_message_enable);
    }

    DarkData = calloc((size_t)(256*isus_dark_num), sizeof(ushort));
    if( DarkData == NULL ) {
        printf("CAN'T allocate DarkScanData Array memory\n");
        sprintf(ebuf, "CAN'T allocate DarkScanData Array memory");
        LogErrorMsg(ebuf, (int)MALLOC_FAILURE, sys_message_enable);
    }

    EcoefFile=dmatrix(1L,256L,1L,3L);
    if (EcoefFile != NULL )
        InitEcoefMatrix(EcoefFile);

    EcoefData=dmatrix(1L,256L,1L,3L);
    if (EcoefData != NULL )
        InitEcoefMatrix(EcoefData);

    dat_file=FNULL;
    err_file=FNULL;

}


//******************************************************************************
// SYS NV VARIABLES OCCUPY (0x0001 - 0x0064) IN THE 256 BYTE DS3234 SRAM
//******************************************************************************

//SYS UCHAR value and memory address in DS3234 SRAM (0x0000 - 0x000F)
#define SYS_INITSRAM_PTR        0x0000
#define SYS_INITSRAM_VAL        0xAA            // for detecting unitialized DS3234 SRAM
#define SYS_SYNCMODE_PTR        0x0001
#define SYS_SYNCMODE_VAL        4               // Scheduled Logging Sync Modes 1=Sync Immediate 2=Sync to Delay in Hours 3=Sync to Given Hours and Mins in LocalTime 4=Sync to Given Mins
#define SYS_DEPLMODE_PTR        0x0002
#define SYS_DEPLMODE_VAL        1               // Deployment mode 1=Scheduled 2=Continuous 3=Triggered
#define SYS_DATAMODE_PTR        0x0003
#define SYS_DATAMODE_VAL        1               // Scheduled Data Collection Mode 1=Real Data 2=Pseudo Data (TEST MODE)
#define SYS_TIMETYPE_PTR        0x0004
#define SYS_TIMETYPE_VAL        1               // Report time in WholeSecs=1 or FractionalSecs=2, using CF2 RTC
#define SYS_WDOGENABLE_PTR      0x0005
#define SYS_WDOGENABLE_VAL      0               // boolean for enabling watchdog reset
#define SYS_MSGENABLE_PTR       0x0006
#define SYS_MSGENABLE_VAL       0               // boolean for enabling the printing of error/status messages
#define SYS_PUMPENABLE_PTR      0x0007
#define SYS_PUMPENABLE_VAL      0               // boolean for enabling the flushing pump cycle
#define SYS_SENSORTYPE_PTR      0x0008
#define SYS_SENSORTYPE_VAL      4               // Sensor Type Return Values 1=No Sensors 2=ISUS Only Sensor 3=DURA Only Sensor 4=ISUS & DURA Sensors


//SYS USHORT value and memory address in DS3234 SRAM (0x0010 - 0x002F)
#define SYS_DELAYHR_PTR         0x0010
#define SYS_DELAYHR_VAL         3               // number of hours until start of data logging
#define SYS_SYNCHR_PTR          0x0012
#define SYS_SYNCHR_VAL          6               // local hour to sync start of data logging to
#define SYS_SYNCMIN_PTR         0x0014
#define SYS_SYNCMIN_VAL         0               // local minute to sync start of data logging to
#define SYS_DFLIMIT_PTR         0x0016
#define SYS_DFLIMIT_VAL         5               // max size (in Mbytes) for any datafile
#define SYS_SFLIMIT_PTR         0x0018
#define SYS_SFLIMIT_VAL         256             // max size (in kbytes) for data spool file (e.g., OASIS dat file) before removal
#define SYS_EFLIMIT_PTR         0x001A
#define SYS_EFLIMIT_VAL         256             // max size (in kbytes) for error log file (ERROR.LOG) before removal
#define SYS_LASTDOY_PTR         0x001C
#define SYS_LASTDOY_VAL         0               // last day of year value used in datafile naming
#define SYS_SERIALN_PTR         0x001E
#define SYS_SERIALN_VAL         777             // Default Serial Number
#define SYS_APFTMOUT_PTR        0x0020
#define SYS_APFTMOUT_VAL        10              // number of hours to keep system active before self-powering OFF

//SYS INT value and memory address in DS3234 SRAM (0x0010 - 0x002F)
#define SYS_TZOFFSET_PTR        0x0022
#define SYS_TZOFFSET_VAL        8               // hrs local time is offset from GMT (+) is W (-) is E
#define SYS_LASTERROR_PTR       0x0024
#define SYS_LASTERROR_VAL       0               // Clear any value

//SYS ULONG value and memory address in DS3234 SRAM (0x0030 - 0x0064)
#define SYS_ERRORCTR_PTR        0x0030
#define SYS_ERRORCTR_VAL        0               // counter indicating number of System errors
#define SYS_LASTERRTIME_PTR     0x0034
#define SYS_LASTERRTIME_VAL     0               // time of the last error event
#define SYS_RESETCTR_PTR        0x0038
#define SYS_RESETCTR_VAL        0               // counter indicating total number of system resets
#define SYS_RESETTIME_PTR       0x003C
#define SYS_RESETTIME_VAL       0               // time of the last system reset event
#define SYS_PORCTR_PTR          0x0040
#define SYS_PORCTR_VAL          0               // counter indicating total number of Power On Resets
#define SYS_FILECTR_PTR         0x0044
#define SYS_FILECTR_VAL         1               // counter indicating number of files used in current DOY
#define SYS_SLEEPPER_PTR        0x0048
#define SYS_SLEEPPER_VAL        60              // number of minutes between RTC wakeups (not used in APF firmware)
#define SYS_PUMPPER_PTR         0x004C
#define SYS_PUMPPER_VAL         60              // number of seconds to run pump prior to sampling




`

//******************************************************************************
// SYS Global Variables used and or shared in any build
//******************************************************************************

// Memory Mapped Latches
ushort WrRegVal;
ushort WhichRxd;

// UCHARs Stored in DS3234 NVRAM:
uchar  sys_slog_delay, sys_deploy_mode, sys_sensor_type;
uchar  sys_data_mode, sys_time_type, sys_watchdog_enable;
uchar  sys_message_enable, sys_pump_enable;

// UCHARs NOT Stored in DS3234 NVRAM:
uchar  sys_sensor_mode;                 // CF2 Logger Sensor Select, 0=Default 1=ISUS 2=DuraFET
uchar  sys_por_flag;
uchar  sys_pump_pwr;

// USHORTs Stored in DS3234 NVRAM:
ushort sys_delay_hour, sys_sync_hour, sys_sync_min;
ushort sys_df_limit, sys_sf_limit, sys_ef_limit;
ushort sys_last_doy, sys_serial_num, sys_apf_tmout;

// INTs Stored in DS3234 NVRAM
int  sys_tzoffset, sys_last_error;

// ULONGs Stored in DS3234 NVRAM
ulong  sys_error_ctr, sys_error_time;
ulong  sys_reset_ctr, sys_reset_time;
ulong  sys_por_ctr, sys_file_ctr;
ulong  sys_sleep_period, sys_pump_period;


// ALL RTC TIMES ARE GMT - SHOULD BE ANYWAY!
time_t DS3234_secs;     // time in secs from Dallas DS3234 RTC (batt backed)
time_t CF2_secs;        // time in secs from CF2 TPU RTC (NOT batt backed)
time_t alarm_time;      // time in secs to set the wakeup alarm time to, gets passed to PWRSuspendUntil()
time_t wake_time;       // time in secs indicating when PWRSuspendUntil() returned
time_t current_time;    // time in secs indicating the current time
time_t data_time;       // time in secs indicating when data sample was taken
float  data_time_fsecs; // time in fractional decimal secs indicating when data sample was taken (if time_type == FRACSECS)
struct tm DS3234_tm;    // DS3234 time of day as struct tm
struct tm *tp;          // scratchpad struct tm

char  logfname[64];
FILE  *dat_file;
FILE  *err_file;

long   size, avail;
ldiv_t hdiv, mdiv;

float  DataMean, DataStdDev;
float  sysTemperature, sysHumidity;
float  sysVoltage, sysCurrent;




//******************************************************************************
// ISUS NV VARIABLES OCCUPY (0x0065 - 0x00C8) IN THE 256 BYTE DS3234 SRAM
//******************************************************************************

//ISUS UCHAR value and memory address in DS3234 SRAM (0x0065 - 0x006F)
#define ISUS_TCOMPMODE_PTR      0x0065
#define ISUS_TCOMPMODE_VAL      1               // Br temperature compensation mode
#define ISUS_SALFITMODE_PTR     0x0066
#define ISUS_SALFITMODE_VAL     0               // fitting algorithim, fix/fit salinity, mode  0=fix, 1=fit
#define ISUS_WARMSHUT_PTR       0x0067
#define ISUS_WARMSHUT_VAL       1               // boolean of shutter state during warmup

//ISUS USHORT value and memory address in DS3234 SRAM (0x0070 - 0x008F)
#define ISUS_INTSCANS_PTR       0x0070
#define ISUS_INTSCANS_VAL       3               // number of intensity scans
#define ISUS_DCSCANS_PTR        0x0072
#define ISUS_DCSCANS_VAL        1               // number of dark current scans
#define ISUS_PRESCANS_PTR       0x0074
#define ISUS_PRESCANS_VAL       2               // number of spectromter 4ms pre scans (to clear PDA)
#define ISUS_PIXELBEG_PTR       0x0076
#define ISUS_PIXELBEG_VAL       17              // start  fitting pixel
#define ISUS_PIXELEND_PTR       0x0078
#define ISUS_PIXELEND_VAL       87              // ending fitting pixel
#define ISUS_FITCONCS_PTR       0x007A
#define ISUS_FITCONCS_VAL       2               // number of concentrations to fit
#define ISUS_BSLNMODL_PTR       0x007C
#define ISUS_BSLNMODL_VAL       1               // baseline model to use in curve fitting
#define ISUS_REFLIMIT_PTR       0x007E
#define ISUS_REFLIMIT_VAL       5000            // min number of spectrometer A/D counts that establishs when the DU Lamp is on
#define ISUS_REFSAMPS_PTR       0x0080
#define ISUS_REFSAMPS_VAL       15              // number of reference detector readings
#define ISUS_DATPIXELBEG_PTR    0x0082
#define ISUS_DATPIXELBEG_VAL    17              // start  reported spectra pixel (APF)
#define ISUS_DATPIXELEND_PTR    0x0084
#define ISUS_DATPIXELEND_VAL    87              // ending reported spectra pixel (APF)
#define ISUS_LAMPWARM_PTR       0x0086
#define ISUS_LAMPWARM_VAL       3               // number secs to warmup lamp after power on
#define ISUS_CLEANUV_PTR        0x0088
#define ISUS_CLEANUV_VAL        30              // number of seconds for UV "cleaning" cycle

//ISUS INT value and memory address in DS3234 SRAM (0x0070 - 0x008F)
#define ISUS_LASTERROR_PTR      0x008A
#define ISUS_LASTERROR_VAL      0               // Clear any value

//ISUS ULONG value and memory address in DS3234 SRAM (0x0090 - 0x00C8)
#define ISUS_ERRORCTR_PTR       0x0090
#define ISUS_ERRORCTR_VAL       0               // counter indicating number of ISUS errors
#define ISUS_LASTERRTIME_PTR    0x0094
#define ISUS_LASTERRTIME_VAL    0               // time of the last error event
#define ISUS_SAMPLECTR_PTR      0x0098
#define ISUS_SAMPLECTR_VAL      0               // counter indicating total number of ISUS samples
#define ISUS_LASTSAMPTIME_PTR   0x009C
#define ISUS_LASTSAMPTIME_VAL   0               // time of the last ISUS sample
#define ISUS_PERIOD_PTR         0x00A0
#define ISUS_PERIOD_VAL         1000            // number of milliseconds to integrate spectrometer
#define ISUS_SAMPSPERDC_PTR     0x00A4
#define ISUS_SAMPSPERDC_VAL     25              // number of samples per dark current reading
#define ISUS_SAMPSPERUV_PTR     0x00A8
#define ISUS_SAMPSPERUV_VAL     24              // number of samples per UV "cleaning" cycle

//ISUS FLOAT value and memory address in DS3234 SRAM
#define ISUS_NO3SPAN_PTR        0x00AC
#define ISUS_NO3SPAN_VAL        45.0
#define ISUS_NO3OFFSET_PTR      0x00B0
#define ISUS_NO3OFFSET_VAL      5.0


//******************************************************************************
// ISUS Global Variables
//******************************************************************************

#define ZCOEFS              5       // Zeiss Spectrometer Wavelength Coefs
#define TCOEFS              5       // Bromide Temperature Compensation Coefs
#define FITVALUES           10      // Returned Values from lsqfit()

// UCHARs Stored in DS3234 NVRAM:
uchar  isus_tcomp_mode, isus_salfit_mode, isus_warm_shut;

// UCHARs NOT Stored in DS3234 NVRAM:
uchar  isus_reset_flag;
uchar  isus_spec_pwr, isus_lamp_pwr, isus_ref_pwr;

// USHORTs Stored in DS3234 NVRAM:
ushort isus_scan_num, isus_dark_num, isus_pre_scans;
ushort isus_pixel_beg, isus_pixel_end, isus_fit_concs;
ushort isus_bsl_model, isus_ref_limit, isus_ref_samples;
ushort isus_warm_lamp, isus_clean_lamp;
ushort isus_datpixel_beg, isus_datpixel_end;

// USHORTs NOT Stored in DS3234 NVRAM:
ushort isus_fit_pixels;
ushort isus_lamp_evt;               // value comes from DS1683

// INTs Stored in DS3234 NVRAM
int    isus_last_error;

// INTs NOT Stored in DS3234 NVRAM
int    Zcoefs, Ecoefs, Zeros;

// ULONGs Stored in DS3234 NVRAM
ulong  isus_error_ctr, isus_error_time;
ulong  isus_sample_ctr, isus_sample_time;
ulong  isus_spec_period, isus_scans_per_dc, isus_samps_per_clean;

// ULONGs NOT Stored in DS3234 NVRAM
ulong  isus_lamp_elp;               // value comes from DS1683

// FLOATs Stored in DS3234 NVRAM
float  no3_span, no3_offset;

ushort *SpecData, *DarkData, *RefData;

static TUPort *SpecPort;
static TUPort *RefPort;

char   CalDate[25];
double SwCalTemp;
double ZeissCoefs[ZCOEFS];
double TcompCoefs[TCOEFS];
double FitData[FITVALUES];
double ZeroData[260];
double LambdaData[260];
double AbsData[260];
double AbsFitData[260];
double ResidualsData[260];
double **EcoefData, **EcoefFile;



//******************************************************************************
// DURA NV VARIABLES OCCUPY (0x00C9 - 0x00FF) IN THE 256 BYTE DS3234 SRAM
//******************************************************************************

//DURA UCHAR value and memory address in DS3234 SRAM (0x00C9 - 0x00CF)
#define DURA_LEDENABLE_PTR      0x00C9
#define DURA_LEDENABLE_VAL      1               // boolean for enabling LED status during AtoD sampling

//DURA USHORT value and memory address in DS3234 SRAM (0x00D0 - 0x00DF)
#define DURA_ATODREADINGS_PTR   0x00D0
#define DURA_ATODREADINGS_VAL   10              // number of AtoD readings to average per sample reading
#define DURA_ATODDELAY_PTR      0x00D2
#define DURA_ATODDELAY_VAL      100             // number of mSecs to delay from AtoD mux change to the starting of AtoD reading(s)

//DURA INT value and memory address in DS3234 SRAM (0x00D0 - 0x00DF)
#define DURA_LASTERROR_PTR      0x00D4
#define DURA_LASTERROR_VAL      0               // Clear any value

//DURA ULONG value and memory address in DS3234 SRAM (0x00E0 - 0x00FF)
#define DURA_ERRORCTR_PTR       0x00E0
#define DURA_ERRORCTR_VAL       0               // counter indicating number of DuraFET errors
#define DURA_LASTERRTIME_PTR    0x00E4
#define DURA_LASTERRTIME_VAL    0               // time of the last error event
#define DURA_SAMPLECTR_PTR      0x00E8
#define DURA_SAMPLECTR_VAL      0               // counter indicating total number of DuraFET samples
#define DURA_LASTSAMPTIME_PTR   0x00EC
#define DURA_LASTSAMPTIME_VAL   0               // time of the last DuraFET sample
#define DURA_SAMPSPERCAL_PTR    0x00F0
#define DURA_SAMPSPERCAL_VAL    250             // number of AtoD samples per AtoD (re)calibration


/******************************************************************************/
/* DURA Global Variables                                                      */
/******************************************************************************/

// UCHARs Stored in DS3234 NVRAM:
uchar  dura_led_enable;

// UCHARs NOT Stored in DS3234 NVRAM:
uchar  dura_reset_flag, dura_atod_pwr;

// USHORTs Stored in DS3234 NVRAM:
ushort dura_atod_readings, dura_atod_delay;

// INTs Stored in DS3234 NVRAM
int    dura_last_error;

// ULONGs Stored in DS3234 NVRAM
ulong  dura_error_ctr, dura_error_time;
ulong  dura_sample_ctr, dura_sample_time;
ulong  dura_samps_per_cal;


// Values from DuraFET III One-Wire EEPROM (not used in APF build)
//char   DURASN[32];         // DuraFET Sensor Serial Number
//float  K0;                 // Iso-Potential EMF which is the zero Kelvin Standard Potential (y intercept of K2 at zero Kelvin)
//float  K1;                 // Nerst Factor
//float  K2;                 // Standard Potenial TempCo of Sensor (non-pH dependent temperature coef of sensor)
//float  PTS;                // Percent Theoretical Slope
//float  IsopH;              // Iso-Potential pH which is the pH value where the EMF of the electrode pair is temperature invariant and occurs when Vrs and K0 are equal
//float  IsopH_2;            // Second (???) Iso-Potential pH Value

// Misc DuraFET III Variables (not used in APF build)
//int    Tcoefs, CalVals;
//char   CalDate[25];
double SHHCoefs[5];
//float  temp_cal_offset;    // temperature calibration offset
//float  pH_cal_offset;      // pH calibration offset

#endif
