#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
//
#include "proto.h"
#include "bucket.h"
#include "flash.h"


void usage() {

  fprintf(stderr, "readflash 0.06\n");
  fprintf(stderr, "syntax:   readflash [switches] <flashfile>\n");
  fprintf(stderr, "\n");
  fprintf(stderr, "switches:   -t               display tags only\n");
  exit(-1);
}


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

  U8 *flashfile;
  U32 flashfilesize;
  FILE *fh;
  int info, arg;

  // check for the correct number of arguments
  if ((argc < 2) || (argc > 3))  usage();

  info = TAG_BODY;

  arg = 1;
  while (argv[arg][0] == '-') {
    if (strcmp(argv[arg], "-t") == 0)
      info &= ~TAG_BODY;
    else
      usage();
    arg++;
  }

  fh = fopen(argv[arg], "rb");
  if (!fh) {
    fprintf(stderr, "Failed to open file %s\n", argv[arg]);
    exit(0);
  }
  fseek(fh, 0, SEEK_END);
  flashfilesize = (U32)ftell(fh);
  if (flashfilesize == 0) {
    fclose(fh);
    fprintf(stderr, "File is empty!\n");
    exit(-1);
  }
  fseek(fh, 0, SEEK_SET);

  flashfile = malloc(flashfilesize);
  if (!flashfile) {
    fclose(fh);
    fprintf(stderr, "malloc(%d) failed\n", flashfilesize);
    exit(-1);
  }

  fread(flashfile, 1, flashfilesize, fh);
  fclose(fh);

  init_bucket(flashfile, flashfilesize);

  if (flash_read_header())  exit(-1);

  while (flash_read_object(info) == 0) ;

  free(flashfile);
}
