/*
 * $Id: bin2flash.c,v 1.2 2006/03/25 02:50:45 orest Exp $
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#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.
 */

/*
 * write_bytes
 *
 * Write out a thirty-two bit word as bytes.
 */
void
write_bytes (FILE *outfile, int value)
{
    static int comma = 0;
    if (comma)
        fprintf (outfile, ",0x%02x\n", (value & 0x000000ff));
    else {
        comma = 1;
        fprintf (outfile, "0x%02x\n", (value & 0x000000ff));
    }

    fprintf (outfile, ",0x%02x\n", (value & 0x0000ff00) >> 8);
    fprintf (outfile, ",0x%02x\n", (value & 0x00ff0000) >> 16);
    fprintf (outfile, ",0x%02x\n", (value & 0xff000000) >> 24);
}

/*
 * usage
 */
void 
usage (char **argv)
{
    fprintf (stderr, "usage: %s -v NN.MM -s 64|128 block0.flash block1.flash block2.flash block3.flash block4.flash fb64|128.c\n",
             argv[0]);
    exit (1);
}

int
main (int argc, char **argv)
{
    char *infilename = "", *ver = NULL, *outfn,
         ln[80];
    FILE *infile, *outfile;
    unsigned int value, status, i, size = 0;

    if (argc != 11) {
        usage (argv);
        exit (1);
    }

    for (i = 1; i < 5; i++) {

        if (!strcmp(argv[i], "-v")) {
            i++;
            ver = argv[i];
        }
        else
        if (!strcmp(argv[i], "-s")) {
            i++;
            size = strtol (argv[i], NULL, 10);

            if (size != 64 && size != 128) {
                printf("Invalid memory size: 64 | 128\n");
                exit (1);
            }
        }
    }
    if (!ver) {
        printf("No version string specified (-v N.M)\n");
        exit (1);
    }

    outfn = argv[argc - 1];
    printf("Output file: %s\n", outfn);
    if ((outfile = fopen (outfn, "w")) == NULL) {
        perror ("open");
        exit (1);
    }
    printf("Input files:\n");

    fprintf (outfile, "#include <revolution/os.h>\n");

    snprintf(ln, sizeof(ln), "char __ver%d[] = \"%s\";\n", size, ver);
    fprintf (outfile, ln);

    sprintf(ln, "u8 __db%d[] __attribute__ ((aligned(32))) = {\n", size);
    fprintf (outfile, ln);

    for (i = 5; i < argc - 1; i++) {

        infilename = argv[i];
        printf ("%s\n", infilename);
        if ((infile = fopen (infilename, "r")) == NULL) {
            perror ("open");
            exit (1);
        }

        do {
            status = fread (&value, sizeof (value), 1, infile);
            if (status != 1) break;
            write_bytes (outfile, value);
        } while (1);
        fclose(infile);
    }
    fprintf (outfile, "};\n"); 
    fclose(outfile);
    exit (0);
}

/* eof */
