#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <time.h>

#define TRUE (1==1)
#define FALSE (!TRUE)

void usage(char *err)
{
  puts("bin2s -- convert binary files into assembler source\n");
  puts("Usage:\n");
  puts("  bin2s <input> <global name> [<output>]");
  if (err != NULL)
    printf("\n\nError: %s\n");
  exit(1);
}

char *timestr(void)
{
  struct tm *lt;
  time_t    t;

  t = time(NULL);
  lt = localtime(&t);
  return asctime(lt);
}

long filesize(FILE *f)
{
  long posi, res;

  posi = ftell(f);
  fseek(f, 0, SEEK_END);
  res = ftell(f);
  fseek(f, posi, SEEK_SET);
  return res;
}

void main(int argc, char *argv[])
{
  FILE *inp, *outp;
  char name[1000];
  long length, count;
  unsigned char *buffer;

  if (argc < 3 || argc > 4) usage("Incorrect command line");

  strcpy(name,"binary_data_field");
  inp = fopen( argv[1], "rb");
  if (inp == NULL) usage("Couldn't opem input file");

  strcpy( name, argv[2]);
  if (argc > 3) {
    outp = fopen(argv[3], "w");
    if (outp == NULL) usage("Couldn't open output file");
  } else
    outp = stdout;

  length = filesize(inp);
  buffer = malloc( length);
  if (buffer == 0) usage("Out of memory");
  if (fread( buffer, length, 1, inp) != 1) usage("read error");
  fclose(inp);

  fprintf(outp, ".globl _%s\n.text\n_%s:\n", name, name);
  count = 0;
  while (count != length) {
    if (((count++)&15) == 0) fprintf(outp, "\n .byte %d", *(buffer++));
			else fprintf(outp, ",%d", *(buffer++));
  }
  fprintf(outp, "\n");
  fclose( outp);
}


