/*
 * $Id: bin2hex.c,v 1.2 2006/02/28 02:13:04 jlivesey Exp $
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
 * If intelHex is zero, we write the hex output as an ascii file with
 * one line per byte.  This is the appropriate format for back-door
 * loading the flash in the ATI DV environment.
 *
 * If intelHex is non-zero, we write the hex output as an ascii file
 * in the Intel format defined as follows:
 *
 * An Intel HEX file is composed of any number of HEX records. Each 
 * record is made up of five fields that are arranged in the following 
 * format:
 * 
 * :llaaaatt[dd...]cc
 * 
 * Each group of letters corresponds to a different field, and each
 * letter represents a single hexadecimal digit. Each field is
 * composed of at least two hexadecimal digits-which make up a byte-as
 * described below:
 * 
 *     * : is the colon that starts every Intel HEX record.
 *
 *     * ll is the record-length field that represents the number 
 *            of data bytes (dd) in the record.
 *
 *     * aaaa is the address field that represents the starting 
 *            address for subsequent data in the record.
 *
 *     * tt is the field that represents the HEX record type, which 
 *            may be one of the following:
 *       00 - data record
 *       01 - end-of-file record
 *       02 - extended segment address record
 *       04 - extended linear address record
 *
 *     * dd is a data field that represents one byte of data. A record may 
 *            have multiple data bytes. The number of data bytes in the 
 *            record must match the number specified by the ll field.
 *
 *     * cc is the checksum field that represents the checksum of the
 *            record. The checksum is calculated by summing the values 
 *            of all hexadecimal digit pairs in the record modulo 256 
 *            and taking the two's complement.
 * 
 * Example:
 * :10246200464C5549442050524F46494C4500464C33
 * 
 * This record is decoded as follows:
 * 
 * :10246200464C5549442050524F46494C4500464C33
 * |||||||||||                              CC->Checksum
 * |||||||||DD->Data
 * |||||||TT->Record Type
 * |||AAAA->Address
 * |LL->Record Length
 * :->Colon
 * 
 * where:
 * 
 *     * 10 is the number of data bytes in the record.
 *     * 2462 is the address where the data are to be located in memory.
 *     * 00 is the record type 00 (a data record).
 *     * 464C...464C is the data.
 *     * 33 is the checksum of the record.
 * 
 */
int intelHex = 0;

#define DATA_LEN 32
#define HDR_LEN  9
#define CC_LEN   2
#define LF_LEN   1
/*
 * There are two printable characters for each data byte.
 */
#define BUF_LEN  (HDR_LEN + (2 * DATA_LEN) + CC_LEN + LF_LEN)

typedef struct _intel {
    int bytecount;
    char buffer[BUF_LEN];
} intel_t;
intel_t intel_line;

unsigned int flash_address = 0;
unsigned int checksum = 0;

/*
 * intelTrailer
 *
 * Write the terminating record
 */
void
intelTrailer (FILE *outfile)
{
    fprintf (outfile, ":00000001FF\n");

    return;
}

/*
 * intelHdr
 *
 * Write an intel record header.
 */
void
intelHdr (unsigned int address, unsigned short tp, unsigned short cc)
{

    /* 
     * write the intitial ':'.
     */
    intel_line.buffer[0] = ':';

    /*
     * write the data length
     */
    sprintf (&intel_line.buffer[1], "%02X", DATA_LEN);

    /*
     * Write the address.
     */
    sprintf (&intel_line.buffer[3], "%04X", address);

    /* 
     *  Write the record type
     */
    sprintf (&intel_line.buffer[7], "%02X", tp);

    /*
     * Write the CC
     */
    sprintf (&intel_line.buffer[HDR_LEN + (2 * DATA_LEN)], "%02X ", cc);

    /*
     * Add these values to the checksum
     */
    checksum += DATA_LEN + ((address >> 8) & 0xff) + (address & 0xff);

    return;
}

/*
 * intelInit
 *
 * Initialise an intel record.
 */
void
intelInit (void)
{
    int i;
    unsigned short cc = 0, tp = 0;

    intel_line.bytecount = 0;
    memset (&intel_line.buffer[0], 0, BUF_LEN);
    for (i = 0; i < BUF_LEN; i++) {
        intel_line.buffer[i] = '0';
    }

    checksum = 0;

    intelHdr (flash_address, tp, cc);

    intel_line.buffer[BUF_LEN] = '\0';

    return;
}

/*
 * intelFlush
 *
 * Write the current line whether or not it is filled.
 */
void
intelFlush (FILE *outfile)
{

    /*
     * Take the two's complement of the checksum
     */
    checksum = -checksum & 0xff;

    /*
     * Write the checksum in the final two character positions.
     */
    sprintf (&intel_line.buffer[HDR_LEN+(2 *DATA_LEN)],
             "%02X", checksum & 0xff);

    /*
     * Output the final line.
     */
    fprintf (outfile, "%s\n", &intel_line.buffer[0]);

    return;
}

/*
 * intelWrite
 *
 * Called with a byte of data.   Adds it to the intel line and
 * physically writes the line when it is filled.
 */
void
intelWrite (FILE *outfile, char data)
{

    sprintf (&intel_line.buffer[HDR_LEN+intel_line.bytecount], 
             "%02X", data & 0xff);
    /*
     * Add the data to the checksum modulo 256
     */
    checksum += data & 0xff;

    intel_line.bytecount += 2;
    if (intel_line.bytecount == (2 * DATA_LEN)) {
        intelFlush (outfile);
        flash_address += DATA_LEN;
        intelInit ();
    }

    return;
}

/*
 * write_bytes
 *
 * Write out a thirty-two bit word as bytes.
 */
void
write_bytes (FILE *outfile, int value, int swap, int intel)
{
    if (swap) {
        if (intel) {
            intelWrite (outfile, (value & 0x0000ff00) >> 8);
            intelWrite (outfile, (value & 0x000000ff));
            intelWrite (outfile, (value & 0xff000000) >> 24);
            intelWrite (outfile, (value & 0x00ff0000) >> 16);
        } else {
            fprintf (outfile, "%02x\n", (value & 0x0000ff00) >> 8);
            fprintf (outfile, "%02x\n", (value & 0x000000ff));
            fprintf (outfile, "%02x\n", (value & 0xff000000) >> 24);
            fprintf (outfile, "%02x\n", (value & 0x00ff0000) >> 16);
        }
    } else {
        if (intel) {
            intelWrite (outfile, (value & 0xff000000) >> 24);
            intelWrite (outfile, (value & 0x00ff0000) >> 16);
            intelWrite (outfile, (value & 0x0000ff00) >> 8);
            intelWrite (outfile, (value & 0x000000ff));
        } else {
            fprintf (outfile, "%02x\n", (value & 0xff000000) >> 24);
            fprintf (outfile, "%02x\n", (value & 0x00ff0000) >> 16);
            fprintf (outfile, "%02x\n", (value & 0x0000ff00) >> 8);
            fprintf (outfile, "%02x\n", (value & 0x000000ff));
        }
    }
}

/*
 * usage
 */
void 
usage (char **argv)
{
    fprintf (stderr, "usage: %s infilename outfilename [-b|-B|-i]\n",
             argv[0]);
    fprintf (stderr, "          -b: output bytes for flash\n");
    fprintf (stderr, "          -B: output bytes for flash, swapped\n");
    fprintf (stderr, "          -b -i: output intel hex for flash\n");
    fprintf (stderr, "          -B -i: output intel hex for flash\n");
    fprintf (stderr, "          -m nn: pad out to length nn with zeros\n");
    exit (1);
}

int
main (int argc, char **argv)
{
    char *infilename = "", *outfilename = "";
    FILE *infile, *outfile;
    unsigned int value, status;
    int bytes = 0, Bytes = 0, i, valid;
    int maxbytes = 0, byteswritten = 0;

    if (argc > 2) {
        if (argc > 3) {
            for (i = 3; i < argc; i++) {
                valid = 0;
                if (!strcmp(argv[i], "-b")) {
                    bytes = 1;
                    valid = 1;
                }
                if (!strcmp(argv[i], "-B")) {
                    Bytes = 1;
                    valid = 1;
                }
                if (!strcmp(argv[i], "-i")) {
                    intelHex = 1;
                    valid = 1;
                }
                if (!strcmp(argv[i], "-m")) {
                    if (argc < (i + 2)) {
                        usage(argv);
                    } else {
                        i++;
                        maxbytes = strtol (argv[i], NULL, 10);
                    }
                    valid = 1;
                }
                if (!strcmp(argv[i], "-h")) {
                    usage (argv);
                    exit (0);
                }
                if (!valid) {
                    fprintf (stderr, "%s: bad arg %s\n", argv[0], argv[3]);
                    exit (1);
                }
            }
        }
        infilename = argv[1];
        printf ("%s\n", infilename);
        if ((infile = fopen (infilename, "r")) == NULL) {
            perror ("open");
            exit (1);
        }
        outfilename = argv[2];
        printf ("%s\n", outfilename);
        if ((outfile = fopen (outfilename, "w")) == NULL) {
            perror ("open");
            exit (1);
        }
    } else {
        usage (argv);
        exit (1);
    }

    if (intelHex) {
        intelInit ();
    }
    
    do {
        status = fread (&value, sizeof (value), 1, infile);
        if (status != 1) break;
        printf ("%08x\n", value);
        if (bytes) {
            write_bytes (outfile, value, 0, intelHex);
        } else {
            if (Bytes) {
                write_bytes (outfile, value, 1, intelHex);
            } else {
                fprintf (outfile, "%08x\n", value);
            }
        }
        byteswritten += 4;
    } while (status == 1);

    if (byteswritten < maxbytes) {
        value = 0;
        for (i = byteswritten; i < maxbytes; i += 4) {
            if (bytes) {
                write_bytes (outfile, value, 0, intelHex);
            } else {
                if (Bytes) {
                    write_bytes (outfile, value, 1, intelHex);
                } else {
                    fprintf (outfile, "%08x\n", value);
                }
            }
        }
    }

    if (intelHex) {
        intelFlush (outfile);
        intelTrailer (outfile);
    }

    exit (0);
}

/* eof */
