// Main.cpp
// Bootloader Interface
// V1.0
//
// Daniel Mckenna
// 31/8/06
//
// Interface for Martyn Gallop's S12X primary bootloader.
// 1. Transmits an s-record of a secondary LFAE bootloader to the primary LRAE bootloader via either SCI or CAN.
// 2. Transmits an s-record to the secondary bootloader via SCI or CAN.
//
// Contains the open source CSerial class along with
// Vector's CANalyzer drivers
//
// Notes:
// The s-record of the secondary bootloader should be made up of consecutive S1 lines. 
// The code will be loaded STRICTLY SEQUENTIALLY.
//
// The s-record of the application to be loaded to flash should contain only S2 lines and does not need to be sequential.
//
// The start address of the secondary bootloader and the speed settings of the SCI and CAN must be set
// via the global variable before execution.


#include <windows.h>
#include <string>
#include "main.h"
#include "SCI Functions.h"
#include "CAN Functions.h"
#include "LFAE SCI Functions.h"
#include "interface.h"


//*******************************************
// function to convert BCD number to unsigned integer value
//*******************************************
unsigned int hex2dec(char lineData[], int byteNumber) 
{
	unsigned int i,result;
	int charvalue;
	result=0;
	for (i=0;i<2;i++) 
	{
		charvalue=lineData[byteNumber]-'0';
		if (charvalue>9) charvalue-='A'-'0'-10;
		if (charvalue>15) charvalue-='a'-'A';
		if ((charvalue>15) || (charvalue<0)) 
		{
			printf("Hex2dec conversion error \n");
			return (0);
		}
		byteNumber++;
		result*=16;
		result+=charvalue;
	}
	return (result);
}



//*******************************************
// global variables
//*******************************************
// Setting up S-Record
char* SRecordFilename = "Secondary Bootloader.sx"; //filename of s-record of secondary bootlader
char* SecondarySRecordFilename = "application.abs.glo"; //filename of s-record to be loaded to flash
unsigned char StartAddressMSB = 0x20; //address to which application will be loaded (in hex), 
unsigned char StartAddressLSB = 0x00; //also the line from which the program will execute

//setting up SCI
int BaudRate = 57600; //SCI Baud Rate

// Selecting port to use
int CANPort = 0;
int SCIPort = 1;

//setting up CAN channel
int ChannelBitrate = 500000; //channel bitrate in b/s
int DataField = 0; //current data field in packet

// Selecting interface
int iFace = 1; //0: SCI, 1: CAN




//*******************************************
// main function
//*******************************************
int main(void)
{
	MainMenu(); // display user interface
	if (iFace)
	{
		if(!CAN_interface())
			return 0;
		else
			return 1;
	}
	else
	{
		if(!SCI_interface())
			return 0;
		else
			return 1;
	}
}