
#include "eeprom.h"
#include <xc.h>
#include "HardwareProfile.h"
#include "timer.h"
#include <stdio.h>

int __attribute__ ((space(eedata))) eeData = 0x1234;

void eeWrite (int newData,int tableno)
{
    unsigned int offset;
    
    if ( (tableno < 0) || (tableno>=eMAX) )
    {
        printf("Error, invalad eeprom address\n");
        return;
    }
    
    // Set up NVMCON to erase one word of data EEPROM
    NVMCON = 0x4004;
    // Set up a pointer to the EEPROM location to be erased
    TBLPAG = __builtin_tblpage(&eeData); // Initialize EE Data page pointer
    offset = __builtin_tbloffset(&eeData)+tableno; // Initizlize lower word of address
    __builtin_tblwtl(offset, newData); // Write EEPROM data to write latch
    asm volatile ("disi #5"); // Disable Interrupts For 5 Instructions
    __builtin_write_NVM(); // Issue Unlock Sequence & Start Write Cycle
    //while(NVMCONbits.WR=1); // Optional: Poll WR bit to wait for
    // write sequence to complete   
    msWait(500);
    return;
}

int eeRead (int tableno)
{
    int data=-99;
    unsigned int offset;
    
    if ( (tableno < 0) || (tableno>=eMAX) )
    {
        printf("Error, invalad eeprom address\n");
        return(0);
    }
    // Set up a pointer to the EEPROM location to be erased
    TBLPAG = __builtin_tblpage(&eeData); // Initialize EE Data page pointer
    offset = __builtin_tbloffset(&eeData)+tableno; // Initizlize lower word of address
    data = __builtin_tblrdl(offset); // Write EEPROM data to write latch  
    return(data);
}