#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <iostream>

using namespace std;

int
main(int argc,
     char ** argv)
{
   int i,size,k=2,ftab,sect=3;
   int j;

   char buf[512];
   char vbuf;
   int dev,fil_descr,off=0;

   fil_descr=open(argv[2],O_RDONLY);
   assert(fil_descr>0);
   read(fil_descr,buf,512);
   close(fil_descr);

   printf("Bootsector file: %s\n",argv[2]);
   

        cout << "open: " << argv[1] << endl;
        
   dev=open(argv[1],O_RDWR|O_CREAT);
   assert(dev>0);
   write(dev,buf,512);


   ftab = open("filetable",O_CREAT|O_RDWR);
   sprintf(buf,"{");
   write(ftab,buf,1);
   
   for(i=3;i<argc;i++)
   {   
      

      off = off + (k * 512);
      lseek(dev,off,SEEK_SET);
                cout << "open: "  << argv[i] << endl;
      fil_descr=open(argv[i],O_RDONLY);
                if(fil_descr != 0) printf("argv[%d] == \"%s\"\n", i, argv[i]);
      if(fil_descr == 0) exit(1);
      size=0;      
      while((read(fil_descr,&vbuf,1))!=0) 
      {
         size++;
         write(dev,&vbuf,1);
      }

      k = size / 512;

      if((size - (k * 512)) > 0) {
         k++;
      }

      vbuf = '\0';
      for(j = size; j < (k * 512); j++) {
         write(dev,&vbuf,1);
      }

      sprintf(buf,"%s-%d,",argv[i],sect);
      write(ftab,buf,strlen(buf));
      printf("Input file \'%s\' written at offset %d\n",argv[i],off);
      printf("ACTUAL(%d) -> REAL(%d)\n", size, k * 512);
                printf("k -> %d\n", k);
      close(fil_descr);
   
      sect = sect + k;
   }
   sprintf(buf,"}");
   write(ftab,buf,1);

   lseek(ftab,0,SEEK_SET);
   read(ftab,buf,512);

   lseek(dev,512,SEEK_SET);
   write(dev,buf,512);   

   close(dev);
   close(ftab);   
}
