
#include <stdlib.h>
#include <stdio.h>
#include "nativebcd.h"
#include "prsf2.h"
#include "parity.h"

unsigned char buf[16];
unsigned char old[16];

int length;


main(argc, argv)
   int   argc;
   char   **argv;
{
   FILE   *f;
   unsigned long   a;
   int   n;
   int   i;
   int   skip;
   int even;
   int odd;
   int rm;

   if (argc != 2 && argc != 3)
   {
      fprintf(stderr, "Usage: bcddump <file> [<length>]\n");
      exit(1);
   }
   f = fopen(argv[1], "rb");
   if (f == NULL)
   {
      perror(argv[1]);
      exit(1);
   }
   if (argc == 3)
   {
      length = atoi(argv[2]);
   }
   else
   {
      length = -1;
   }

   a = 0;
   for (i = 0; i < 16; i++)
   {
      old[i] = 0;
   }
   skip = 0;
   for (;;)
   {
      if (length == 0)
      {
         break;
      }
      n = fread(buf, 1, sizeof(buf), f);
      if (n == 0)
      {
         break;
      }
      if (length > 0)
      {
         if (length > n)
	 {
            length -= n;
         }
	 else
	 {
            n = length;
            length = 0;
         }
      }

      for (i = 0; i < n; i++)
      {
         if (buf[i] != old[i])
	 {
            break;
         }
      }
      if (i == 16)
      {
         if (!skip)
	 {
            printf("\n");
            skip = 1;
         }
         a += n;
         continue;
      }
      skip = 0;

      printf("%08X ", a);

      for (i = 0; i < n; i++)
      {
         if (i == 8)
	 {
            printf(" ");
         }
         printf(" %02X", buf[i]);
         old[i] = buf[i];
      }
      for (; i < 16; i++)
      {
         if (i == 8)
	 {
            printf(" ");
         }
         printf("   ");
      }

      even = 0;
      odd = 0;
      rm = 0;
      for (i = 0; i < n; i++)
      {
         if (parity[buf[i]])
	 {
            odd++;
         }
	 else
	 {
            even++;
         }
         if (buf[i] & 0x80)
	 {
            rm++;
         }
      }

      if (odd > even)
      {
         printf(" *");
      }
      else
      {
         printf(" :");
      }
      for (i = 0; i < n; i++)
      {
         printf("%c", tonative[buf[i] & 077]);
      }
      if (odd > even)
      {
         printf("*");
      }
      else
      {
         printf(":");
      }
      if (rm)
      {
         printf(" R");
      }
      printf("\n");

      a += n;
   }
}
