#include <stdio.h>
#include "i2c.h"
#include "br24t_eeprom_driver.h"

#define EEPROM_ADDR       0x57
#define EEPROM_PAGE_SIZE  64

//for burning eeprom
#define MAGIC_SYN         0xdeadbeef
#define MAGIC_ACK         0xf00dd00d

#define PAGE_WRITE_OK                 0x00
#define PAGE_WRITE_CORRUPTED          0x01
#define PAGE_WRITE_UNKNOWN_ERROR      0xff

//we need another function cause it's got a 16 bit register address

#ifdef FLASH_EEPROM
void flash_eeprom() {
  uint16_t data_len;
  uint32_t syn = 0;
  uint8_t on_byte;
  uint8_t eeprom_buffer_out[EEPROM_PAGE_SIZE]; 
  uint8_t eeprom_buffer_in[EEPROM_PAGE_SIZE];

  while(syn != MAGIC_SYN) fread(&syn, 4, 1, stdin); //not sure we _really_ need to do this?
  
  //this feels ugly
  syn = MAGIC_ACK;
  fwrite(&syn, 4, 1, stdout);
  
  //get amount of data we'll be using
  data_len = uart_recvbyte();
  data_len |= (uart_recvbyte() >> 8);

  for(int page = 0; page < (data_len / EEPROM_PAGE_SIZE); data_len -= EEPROM_PAGE_SIZE) {

    fread(eeprom_buffer_out, EEPROM_PAGE_SIZE, 1, stdin);

    i2c_start(EEPROM_I2C_ADDR, I2C_READ);
    i2c_send((uint8_t)(page * EEPROM_PAGE_SIZE) & 0xff);
    i2c_send((uint8_t)(page * EEPROM_PAGE_SIZE) >> 8);
    for(on_byte = 0; on_byte < EEPROM_PAGE_SIZE; on_byte++) 
      i2c_send(eeprom_buffer_out[on_byte]); 
    i2c_stop();

    //verify
    eeprom_buffer_in[0] = EEPROM_READBYTE(page * EEPROM_PAGE_SIZE);
    //eeprom_buffer_in[0] = i2c_read_reg_addr16(EEPROM_I2C_ADDR, page * EEPROM_PAGE_SIZE);
    i2c_start(EEPROM_I2C_ADDR, I2C_READ);
    for(on_byte = 1; on_byte < EEPROM_PAGE_SIZE; on_byte++)
      eeprom_buffer_in[on_byte] = i2c_recv();
    i2c_stop();

    if(memcmp(eeprom_buffer_in, eeprom_buffer_out, EEPROM_PAGE_SIZE)) {
      fputc(PAGE_WRITE_CORRUPTED, stdout);
      error();
    }
    fputc(PAGE_WRITE_OK, stdout);
  }
}
#endif
