#include "libc.h"

#define         ASCII   1
#define         BINARY  0
#define         CTLZ    26
#define         END     -3

/*  a program to dump a file in hex and ASCII  */

main(argc, argv)
int argc;
char *argv[];
  {
  FILE *fopen();
  static FILE *ptr;
  static int addr, i, j, type;
  int fgetc();
  static char c, line[73], buf[16];
  register char *pa, *ph, *pi;
  static char hex[] = "0123456789ABCDEF";
  static char cant[] = "cannot open ";
  char *cpt;

  i = 1;

/*  open file to be dumped  */

  if ((ptr = fopen(argv[i], "r")) == 0)  {
    for (cpt = cant; *cpt != 0;)
      putchar(*cpt++);
    for (cpt = argv[i]; *cpt != 0;)
      putchar(*cpt++);
    putchar('\n');
    return;
    }

/*  dump file  */

  addr = 0;
  ph = line + 72;

  for (pa = line; pa < ph; )            /*  blank line and  */
    *pa++ = ' ';
  *pa = '\0';                           /*     null terminate it  */

  for (;;)  {

/*  fill in each line (16 bytes) to be dumped  */

    ph = buf + 16;
    for (pi = buf; pi < ph; )  {

     if ((i = fgetc(ptr)) == EOF)  {    /*  check for EOF  */
        type = END;
        break;
        }

      *pi++ = i & 0377;
      }

    if (type == END)
      break;

    pi = buf;                           /*  address position  */
    ph = line + 6;                      /*  hex position  */
    pa = ph + 50;                       /*  ASCII position  */
    j = addr;
    addr += 16;

    for (i = 3; i >= 0; i--)  {         /*  fill in address  */
      line[i] = hex[j & 017];
      j >>= 4;
      }

    for (i = 0; i < 16; i++)  {         /*  fill in file contents  */
      c = *pi;
      *ph++ = hex[(c >> 4) & 017];      /*  first hex char  */
      *ph++ = hex[c & 017];             /*  second hex char  */
      *ph++;
      if (c < ' ' || c > '\0177')       /*  check if printing char  */
        *pi = '.';                      /*  put in "." if not  */
      *pa++ = *pi++;                    /*  ASCII char  */
      }
    for (cpt = line; *cpt != 0;)        /*  write line  */
      putchar(*cpt++);
    putchar('\n');
    }
  }


