/* Extracts a tar archive from a tape in SIMH format */

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

int main(int argc, char **argv)
{
       int f1, f2, n, recbytes, rootlen;
       int err = 0;
       char tapefile[512], tarfile[512];
       char buf[512], *p;

       if (argc < 2) {
               fprintf(stderr, "usage: extar <tapefile> [<tarfile>]\n");
               exit(0);
       }

       strcpy(tapefile, argv[1]);
       if (argc > 2)
               strcpy(tarfile, argv[2]);
       else {
               p = strchr(tapefile, '.');
               if (! p)
                       rootlen = strlen(tapefile);
               else
                       rootlen = p - tapefile;
               memset(tarfile, 0, 512);
               strncpy(tarfile, tapefile, rootlen);
               strcat(tarfile, ".tar");
       }

       if ((f1 = open(tapefile, O_RDONLY)) == -1) {
               perror("open");
               exit(1);
       }
       if ((f2 = open(tarfile, O_CREAT | O_WRONLY)) == -1) {
               perror("open");
               exit(1);
       }
       fchmod(f2, 0666);

       while (1) {
               if ((n = read(f1, &recbytes, 4)) == 0)
                       break;
               if (n == -1) {
                       perror("read");
                       err++;
                       break;
               }
               if (n != sizeof(recbytes)) {
                       fprintf(stderr, "Error: read too few bytes\n");
                       err++;
                       break;
               }
               if ((n = read(f1, buf, recbytes)) == -1) {
                       perror("read");
                       err++;
                       break;
               }
               if ((n != 0) && (n != sizeof(buf))) {
                       fprintf(stderr, "Error: read too few bytes\n");
                       err++;
                       break;
               }
               if ((n = read(f1, &recbytes, 4)) == -1) {
                       perror("read");
                       err++;
                       break;
               }
               if (n != sizeof(recbytes)) {
                       fprintf(stderr, "Error: read too few bytes\n");
                       err++;
                       break;
               }
               if ((write(f2, buf, recbytes)) == -1) {
                       perror("write");
                       err++;
                       break;
               }
       }

       close(f1);
       close(f2);
       if (err) {
               unlink(tarfile);
               exit(1);
       }
       exit(0);
}