/*
 * isdk_image.c
 *
 * Copyright (c) 2012 Texas Instruments Incorporated ALL RIGHTS RESERVED
 * 
 */

/*
 * \brief  Generates an image bootable by the ROM code
 *
 */ 
 
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAGIC_NUM_MMC				0xEE3355CC

typedef struct _gd_header_appl
{
	unsigned int magic_number;
	char			board_name[32];
	char			software_revision[32];
    unsigned int image_size;
    unsigned int load_addr;
	unsigned int run_addr;

}gd_header_appl;


int main (int argc, char *argv[])
{
    FILE *in_fp, *out_fp;
    long image_size = 0;
	gd_header_appl	gd_appl;
	
    int i = 0;
	char *applName = NULL;
	char outFileName[128];

	unsigned long load_addr = 0;
	unsigned long run_addr = 0;
	unsigned long magicNumber = 0;

    if (argc != 7 )
    {
        /* expect : isdk_image </path/to/boot.bin> <path/to/place/modified/boot.bin> */
        printf("Usage : \n");
        printf("gd_image takes the input image and adds the image header \n");
        printf("The resulting output is placed in the output image path\n");
        printf("Syntax: gd_image <input image path/name> <output image path/name> <load address in hex> <run address in hex> <board_name> <software_revision>\n");
       return -1;
    }

    printf ("gd_image Heater Tool versione 2015.11.13\n");
	printf("Input File  \t- %s \n",argv[1]);
	printf("Output File \t- %s \n",argv[2]);
	printf("Load address \t- %s \n",argv[3]);
	printf("Run address \t- %s \n",argv[4]);
	printf("Board name  \t- %s \n",argv[5]);
	printf("Firmware rev\t- %s \n",argv[6]);

    in_fp = fopen(argv[1], "rb");
    if(!in_fp) {
        printf("Error opening input image file!\n");
        return -1;
    }

	magicNumber = MAGIC_NUM_MMC;
	
    out_fp = fopen(argv[2], "wb+");
    if(!out_fp) {
        printf("Error opening/creating out image file!\n");
        return -1;
    }

	sscanf(argv[3],"%x",&load_addr);
	sscanf(argv[4],"%x",&run_addr);

	
    /* Calcualte the size of the input image and rewind to the begin of file */
    fseek(in_fp, 0, SEEK_END);
    image_size = ftell(in_fp);
    rewind(in_fp);


	/* Binary Type - GD Application */
	gd_appl.magic_number = magicNumber;
	/* Size of  new image is actual bin image size + header */
	gd_appl.image_size = image_size + sizeof(gd_appl);
	strcpy(gd_appl.board_name,argv[5]);
	strcpy(gd_appl.software_revision ,argv[6]);
	gd_appl.load_addr = load_addr;
	gd_appl.run_addr = run_addr;

	/* Insert the header first */
	fwrite(&gd_appl, sizeof(gd_header_appl), 1, out_fp);

    /* Insert the actual image */
    for (i = 0; i <= (image_size / 4); i++) 
	{
        unsigned int temp;
        fread(&temp, sizeof(temp), 1, in_fp);

        fwrite(&temp, sizeof(temp), 1, out_fp);
    }

    printf("Out binary size\t- %d [%d Kbytes]\n",
    		image_size+sizeof(gd_header_appl),
    		(image_size+sizeof(gd_header_appl))/1024 );
    printf("\n");

    return 0;
}
