// as2md - convert octal to drum image

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


unsigned long long md[4*4096];

main () {

  FILE *fid;

  char line[80];
  unsigned int addr, op, u, v;
  unsigned long long word;
  unsigned int baseaddr = 040000;
  char junk[40];
  int addr_delta = 0; // address offset
  int addr_delta_prev = 0; // address offset

  fid = fopen("cpu_diag.txt","r");
  while (fgets(line,80,fid) != NULL) {
    //    printf("%s",line);
    if (strncmp("START",line,5) == 0) {
      sscanf(line,"%s %o",junk,&baseaddr);
      printf("baseaddr: %05o\n",baseaddr);
    } else if (isdigit(line[0])) {
      sscanf(line,"%o %o %o %o", &addr, &op, &u, &v);
      word = (((unsigned long long) op) << 30)
	| (((unsigned long long) u) << 15)
	| ((unsigned long long) v);
      addr_delta = baseaddr-addr;
      if (addr_delta != addr_delta_prev) {
	printf("WARNING: address jump: %d\n",addr_delta);
      }
      addr_delta_prev = addr_delta;
      printf("%05o %05o %02o %05o %05o ",
	     baseaddr,addr,op,u,v);
      printf("%012llo\n",word);
      md[baseaddr-040000] = word;
      baseaddr++;
    } else {
      printf("%s",line);
    }
  }
  fclose(fid);

  // clean up
  fid = fopen("md","w");
  fwrite(md,sizeof(md[0]),4*4096,fid);
  fclose(fid);
}
  
  
