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

int main ( int argc, char *argv[]  ) {

    char *temp;
    FILE *fp = 0;

    if ( !strcmp(argv[1], "-p" ) ) {
        convert_atari800_palette(argv[2]);
        return 0;
    }

    fp = fopen(argv[1], "rb");

    if ( !fp ) {
        printf ( "Could not open input file" );
    }

    printf ( "colors = [ \n  " );
    char line [1000];
    int number = 0;
    while(fgets(line,sizeof line,fp)!= NULL)  {

      if (line[0] == ',') {
          if (number == 8) {
              number = 0;
              printf("\n  ");
          }
          temp = line+1;
          if ( number == 7 )
               printf ( "0x%06x,", atoi(temp));
          else
               printf ( "0x%06x, ", atoi(temp));
          number++;
      }
    }

    printf ( "\n  ]\n" );

    fclose(fp);
}

int convert_atari800_palette ( char *pal_file ) {

    int pal[256];
    int i,j,c;
    FILE *fp;

    /*
     * Open the atari800 palette and get values
     */
    if ((fp = fopen(pal_file,"rb")) == NULL) {
        printf ( "Could not open Atari800 Pallete file: %s", pal_file );
        return -1;
    }
    for (i = 0; i < 256; ++i ) {
        pal[i] = 0;
        for (j = 16; j >= 0; j -= 8) {
            c = fgetc(fp);
            if (c == EOF) {
                fclose(fp);
                return -1;
            }
            pal[i] |= c << j;
        }
    }
    fclose(fp);

    /*
     * Now print as config array
     */
    printf ( "colors = [" );
    for (i = 0; i < 256; ++i ) {
          if (i % 8 == 0) {
              printf("\n  ");
          }
          if ( i % 8 == 7 )
               printf ( "0x%06x,", pal[i]);
          else
               printf ( "0x%06x, ", pal[i]);
    }
    printf ( "\n  ]\n" );

    return 0;

} /* end convert_palette */
