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

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

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

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

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

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

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

       n = 0;
       if ((write(f2, &n, sizeof(n))) == -1) {
               perror("write");
               err++;
               goto error;
       }
       if ((write(f2, &n, sizeof(n))) == -1) {
               perror("write");
               err++;
       }

error:
       close(f1);
       close(f2);
       if (err) {
               unlink(tapefile);
               exit(1);
       }
       exit(0);
}