/* unsetdru -- remove installation of setdru2                               */

#define NULL    0
#define TRUE    1
#define FALSE   0

/* declaration of structure for fcb            */
struct fcb_ {
            struct {
                   char drive;        /* drive number */
                   char fname[8];     /* file name */
                   char ftype[3];     /* file type */
                   char fext;         /* file extent */
                   char filler[3];
                   } name1, name2;
            char crec;                /* current record */
            int rrec;                 /* random record */
            char rovf;                /* random record overflow */
            };

#define FCB struct fcb_

#define BUFSIZE         (16*1024)

struct sdr {            char        s_fil1[3];      /* jp instruction */
                        int         s_len;          /* length of module */
                        unsigned    s_plen;         /* length of pgm */
                        struct {    char    s_drive, s_user;
                                    char    s_fname[8];
                                    char    s_ftype[3];
                               }    s_file[9];
                        char        s_id[13];
           };

extern FCB              dfcb_;
extern struct sdr       dbuff_;

main()
{
  char                  buffer[BUFSIZE];
  FCB                   outfcb;
  static int            i;
  static int            n;
  static char           holdtype[3];
  static char           *p, *q;
  static int            eof;

  if (dfcb_.name1.fname[0] == ' ')
    error("Syntax: unsetdru <filename>");

  for (i = 0; i < 11; ++i)
    if (dfcb_.name1.fname[i] == '?')
      error("ERROR: ambiguous file name not allowed.");

  strncpy(&outfcb, &dfcb_, sizeof(FCB));
  strncpy(outfcb.name1.ftype, "$$$", 3);
  strncpy(holdtype, dfcb_.name1.ftype, 3);

  if (open(&dfcb_) == 0xff)
    error("ERROR: cannot open input file.");
  setdma(&dbuff_);
  if (rdseq(&dfcb_) || strncmp(dbuff_.s_id, "***SETDRU2***", 13) != 0)
    error("ERROR: setdru not applied to input file.");
  n = dbuff_.s_len;
  for (i = 128; i < n; i += 128)
    if (rdseq(&dfcb_))
      error("ERROR: unexpected EOF on input");

  delete(&outfcb);
  if (make(&outfcb) == 0xff)
    error("ERROR: cannot create output file.");

  do
  {
    for (p = buffer; p < buffer + BUFSIZE; p += 128)
    {
      setdma(p);
      if (eof = rdseq(&dfcb_))
        break;
    }
    for (q = buffer; q < p; q += 128)
    {
      setdma(q);
      if (wrseq(&outfcb))
        error("ERROR: output error.");
    }
  } while (!eof);

  close(&dfcb_);
  close(&outfcb);
  strncpy(outfcb.name2.fname, outfcb.name1.fname, 8);
  strncpy(outfcb.name2.ftype, holdtype, 3);
  for (i = 0; i < 11; ++i)
  {
    outfcb.name1.fname[i] &=0x7f;
    outfcb.name2.fname[i] &=0x7f;
  }
  delete(&dfcb_);
  if (rename(&outfcb) == 0xff)
    error("ERROR: cannot rename output.");
}
