#include <stdio.h>
#include <stdlib.h>
//
// UNIVAC xs3 code -- '_' added for 0x2e '@' added for 0x13
//            0    1    2    3    4    5    6    7    8    9    A    B    C    D    E    F
char xs3[]={ ' ', '&', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', '<', '>',  // 00
             '+', ')', '.', '@',  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', '=', 0,   0,   // 01
              0,  '*', '$',  0,  'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',  0,  '_',  0,   // 02
              0,  '(', ',', '\'','/', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',  0,   0,   0 }; // 03

// Pierce .bdc tape images set 0x80 as a flag bit with a couple of special values
// It also retains the 7th bit for parity
// The first byte of a record has the 0x80 bit set
// File marks are signaled with a 0x99 byte preceeded by a 0x00
//

int main(){
unsigned char c;
int i;
unsigned char rec[4096];               // how long is the maximum tape record on a 1050??
int column = 0;   // record column
int state = 0;   // where we are dumping the tape, 0 looking for header, 1 header, 2 inside the record 
int recnum = 0;  // record number on the tape

 while(1){
  c = getchar();
  if(feof(stdin)){putchar('\n'); exit(0);}   //// TODO, if we hit EOF and are in state 2, dmp out the last record

// this isn't a flag byte. if we're in state 2, store the character in the buffer, and check for buffer overflow
  if((c & 0x80) == 0){
   if(state == 1) state = 2;  // first byte after the flag moves us to state 2
   if((state == 2)&&(column > 4095)){ printf("\n {record buffer overflow!}\n"); exit(1); }
   rec[column++] = c;
   continue;
  }

// we found a 0x80 marker, 
// if we've been accumulating bytes, this is the next record
// dump out what we found
// then reset the column pointer resetting the record accumulator
// if the flag is 0x99 we've hit a file mark, print the fact after
// printing the record
//
  if(c & 0x80){
// time to dump out what we've accumulated if we are in state 2
   if(state == 2){
    printf("\n%06d ", recnum); 
    for(i=0; i<column; i++){
     printf("%02x ",rec[i]); 
     if((i%32)==0) printf("\n       ");
    }
    printf("\n       ");
    for(i=1; i<column; i++){
     if((i%128)==0) printf("\n       ");
     printf("%c", xs3[rec[i]&0x3f]);
    }
   }

// we found a tape mark, after dumping the record print out the fact and go back to the flag
// search state
   if(c == 0x99)
    {column = 0; printf("\n{-- tape mark --} \n"); }   // .bcd tape mark
   else
    {column = 1; recnum++; rec[0] = c; }               // save the flag and reset
   if(state ==0) state = 1;
   continue;
  } 
 }
}
