/*
*  bin2c v1.0  Converts binary data to C source
*
*  Copyright (C) 2000 Mats Peterson
*
*  This program is free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  You should have received a copy of the GNU General Public License
*  along with this program; see the file COPYING.  If not, write to
*  the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
*  Boston, MA 02111-1307, USA.
*
*  Please send any comments/bug reports to
*  [email protected]  (Mats Peterson)
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>


void usage(void)
{
   fprintf(stderr, "usage: bin2c <binfile> <cfile> <varname>\n");
   exit(0);
}

int main(int argc, char **argv)
{
   FILE *f_in, *f_out;
   struct stat st;
   off_t len;
   int cnt = 0;
   u_char inbyte;
   char varname[80], o_fname[80];

   if (argc == 1)
       usage();

   if (! (f_in = fopen(argv[1], "r"))) {
       perror("open");
       exit(1);
   }

   if (stat(argv[1], &st) == -1) {
       perror("stat");
       exit(1);
   }
   len = st.st_size;

   if (argc > 2)
       strcpy(o_fname, argv[2]);
   else
       strcpy(o_fname, "bin2c.c");

   f_out = fopen(o_fname, "w");

   if (argc > 3)
       strcpy(varname, argv[3]);
   else
       strcpy(varname, "varname");

   fprintf(f_out, "unsigned char %s[%ld] = {\n", varname, len);

   inbyte = (u_char)fgetc(f_in);
   while (1) {
       fprintf(f_out, "0x%02x", inbyte);
       inbyte = (u_char)fgetc(f_in);
       if(feof(f_in)) break;
       fprintf(f_out, ",");
       if (++cnt > 30) {
           fprintf(f_out, "\n");
           cnt = 0;
       }
   }

   fprintf(f_out,"};\n");
   fclose(f_in);
   fclose(f_out);
   exit(0);
}