#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <util/delay.h>
#include <avr/pgmspace.h>

#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <avr/iocan128.h>


#include "api.h"
#include "api_define.h"
#include "api_global.h"
#include "api_constants.h"

#include "api_show.h"
#include "delay.h"
#include "twi_master.h"


char currentCommandKeyword[MAX_LENGTH_KEYWORD];/*variable to store command keyword e.g. "SEND"*/
char currentResponseKeyword[MAX_LENGTH_KEYWORD];/*variable to store response keyword e.g. "RECV"*/

uint8_t debug = 0;
uint32_t debugMask = 0x0;


char* ptr_setParameter[MAX_PARAMETER];

volatile unsigned char uartReady;/*variable for Uart interrupt*/

char uartString[BUFFER_SIZE]; /* variable for storage received a complete string via UART */
char decrypt_uartString[BUFFER_SIZE];

uint8_t twiData[8];
char temp_twiString[BUFFER_SIZE];/*temporary variable for storage received TWIS data*/
char twiString[BUFFER_SIZE];/*variable for storage received TWIS data*/
char store_twiData[BUFFER_SIZE];
 
char uart_message_string[BUFFER_SIZE];
char message[BUFFER_SIZE];

char setParameter[MAX_PARAMETER][MAX_LENGTH_PARAMETER];

unsigned char nextCharPos; /*pointer of the variable uartString  */
uint8_t uart_errorCode; /* error code for UART-communication */
uint8_t general_errorCode; /*  general error code */
uint8_t twi_errorCode; /* error code for I2C-communication */



/*define UART-structure */
struct uartStruct uartFrame;
struct uartStruct *ptr_uartStruct;

unsigned short unusedMemoryStart;

#warning check if done remove pgm_read_byte from all CommunicationErrors and set the corresponding arrays back from PROGMEM, also printout pointers
int main( void )
{

   debug = noDebug;
   debugMask = 0xFFFFFFFF;

   ptr_uartStruct = &uartFrame; /* initialize pointer for CPU-structure */
   //	initUartStruct(ptr_uartStruct); /*initialize basic properties of uartStruct

   /* initialize flag */
   nextCharPos = 0;
   uartReady = 0; 
   Initialization();

   snprintf_P(uart_message_string, BUFFER_SIZE - 1, PSTR("SYST system (re)started"));
   UART0_Send_Message_String(NULL,0);

   // main endless loop
   int16_t indi = 0;

   while ( 1 )
   {
      indi++;

      // UART has received a string

      if ( 1 == uartReady )/* of the ISR was completely receive a string */
      {
         cli();
         // disable interrupts

         /* TODO:
          * can those to lines be moved into Process_Uart_Event ?
          */
         strncpy(decrypt_uartString, uartString, BUFFER_SIZE - 1);
         /* clear uartString, avoiding memset*/
         clearString(uartString, BUFFER_SIZE);

         Process_Uart_Event();

         uartReady = 0; /* restore flag */

         sei();
         // (re)enable interrupts
      }

   }// END of while

} // END of main
