/*
===============================================================================
 Name        : bootloader.c
 Author      : $(author)
 Version     :
 Copyright   : $(copyright)
 Description : main definition
===============================================================================
*/

#ifdef __USE_CMSIS
#include "LPC17xx.h"
#endif

#include <cr_section_macros.h>

#include <stdio.h>
#include <string.h>

#include "uart_commands.h"

error_code status;

char okk[4] = "OK\r\n";
char errr[5] = "ERR\r\n";



char* argvs[3][10];

cmd_t cmd;


uint32_t offset, total_size, offset_pointer;

crc_t crc_prog, crc_data;


// TODO: insert other include files here

// TODO: insert other definitions and declarations here

char buff[256];

int main(void) {
	cmd.argv = argvs;
    uart_init(115200);
    while(1){
		uart_receive_command(buff);
		uart_parse_command(buff, &cmd);
		if (strncmp("GETID", cmd.argv[0], 5)==0){
			uart_commands_getid(&status);

		}else if(strncmp("GETSE", cmd.argv[0], 5)==0){
			uart_commands_getserial(&status);

		}else if(strncmp("PROG", cmd.argv[0], 4)==0){
			crc_prog = uart_string_to_int(cmd.argv[3]);
			total_size = uart_string_to_int(cmd.argv[2]);
			offset = uart_string_to_int(cmd.argv[1]);
			crc_data = uart_commands_prog(&status, total_size);
			offset_pointer = offset;

		}else if(strcmp("DATA", cmd.argv[0])==0){
			int size = uart_string_to_int(cmd.argv[1]);
			crc_t local_checksum = uart_string_to_int(cmd.argv[2]);
			uart_commands_data(&status, size, &crc_data, local_checksum, offset_pointer);
			//uart_commands_data(&status, size, &crc_data, crc_data, offset_pointer);
			if(status == 0) offset_pointer += size;

		}else if(strncmp("CHECK", cmd.argv[0], 5)==0){
			error_code is_error = uart_commands_check(crc_prog, crc_data);
			if(is_error == ok){
				uart_send_ok();
			}else{
				uart_send_err();
			}

		}
    }
    while(1);
    return 0 ;
}
