#include "system.h"
#include "uart.h"

#if (ENABLE_HAPTICS)
  #include "haptics.h"
#endif

static void gpio_init(void);
static void sysclk_init(void);

uint8 flash_read_byte(uint8 index)
{
  uint8 *flash_ptr = ((uint8 *)SEGMENT_START) + index;
  
  return *flash_ptr;
}

void flash_write_array(uint8 *value,uint8 size,uint8 index)
{
  uint8 buffer[SEGMENT_SIZE];
  uint8 i=0;
  
  uint8 *flash_ptr = (uint8 *)SEGMENT_START;
  
  for(i = 0;i < SEGMENT_SIZE; i++)
  {
    buffer[i] = flash_read_byte(i);
  }
  
  FCTL1 = FWKEY + ERASE;                    // Set Erase bit
  FCTL3 = FWKEY;                            // Clear Lock bit
  *flash_ptr = 0;                           // Dummy write to erase Flash segment
  
  FCTL1 = FWKEY + WRT;                      // Set WRT bit for write operation
  
  for(i = 0;i < size;i++)
  {
    buffer[index + i] = value[i];
  }
  
  for(i=0; i < SEGMENT_SIZE; i++)
  {
    *(flash_ptr++) = buffer[i];                   
  }
  
  FCTL1 = FWKEY;                            // Clear WRT bit
  FCTL3 = FWKEY + LOCK;                     // Set LOCK bit
}

void sysclk_init(void)
{
  WDTCTL = WDTPW + WDTHOLD;   //stop WDT 
  
  DCOCTL = 0;                 // Select lowest DCOx and MODx settings
  
  //set clock source to 11.0592MHZ XT
  BCSCTL1 = (0xC0 | CALBC1_1MHZ);  //XT2-off, XTS-High frequency mode, ACLK=1/1 division
  
  DCOCTL = CALDCO_1MHZ; 
  
  /*
  SELMx : 11 : LFXT1CLK or VLOCLK  //Select MCLK
  DIVMx : 00 : /1                  //Divider for MCLK   
  SELS  : 0  : DCOCLK              //Select SMCLK
  DIVSx : 00 : /1                  //Divider for SMCLK
  DCOR  : 0  : Internal resistor   //DCO resistor select
  */
  BCSCTL2 = 0xC0;  //SELM-LFXT1CLK, DIVM1-1/1 division, 
                   //SMCLK-DCO, DIVS-1/1 division, 
                   //DCOR-internal resistor
  
  BCSCTL3 = 0x20;  //XT2S-xx, LFXT1S-3~16M crystal, XCAP-xx
}

void flash_init(void)
{
  //fFTG : 257kHz - 476 kHz 
  /*
  FSSELx : 10 : SMCLK  //1MHz
  */
  FCTL2 = FWKEY + FSSEL1 + FN1;             // SMCLK/3 for Flash Timing Generator
}

void gpio_init(void)
{
//  P3.0 - TSC2013_RST     OUTPUT
//  P3.1 - SDA
//  P3.2 - SCL
//  P3.3 - UART0_RST       INPUT     Disconnected
//  P3.4 - UART0_TXD   
//  P3.5 - UART0_RXD 
//  P3.6 - UART1_TXD
//  P3.7 - UART1_RXD
  P3DIR = 0x57;         //01010111
  P3SEL = 0xF6;         //Enable UART and I2C
  //P3REN = 0x06;       //I2C set pull up or down
  P3OUT = 0x00;         //I2C and UART not affected, and reset uart0, reset tsc2013 

//  P6.0 - CALIBRATION_ENABLE   INPUT
  P6DIR &= (~PIN_CAL);
  P6SEL &= (~PIN_CAL);
}

void board_init(void)
{  
  sysclk_init();
  
  gpio_init();
  
#if (ENABLE_DEBUG_UART_GUI)  
  uart0_init();
#endif
  
#if (ENABLE_DEBUG_UART)   
  uart1_init();
#endif  

#if (ENABLE_HAPTICS & ENABLE_HAPTICS_DRV2603)
  haptics_init();
#endif  
  
  flash_init();
}
