#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <autoboot.h>

unsigned char buffer[BUFSIZE]; // The "stack" buffer

#define MAXLINESIZE 256 
/* The maximum length of any line in the text file (255 is the maximum 
   length of arguments which a linux kernel can handle
   
   If line does not start with # and is non-empty entire line taken as
   as an image name with arguments.
   
   Expects 1 or 2 arguments. First argument is the name of the output file. 
   If second argument given, then 
      prints debugging messages.
      Create output file anew, and writes the STACK.
   If second argument not given, then
      no debugging messages and writes to appropriate portion of output file.
*/

int main(int argc, char **argv)
{
  FILE *ifd;
  char line[MAXLINESIZE+2];
  unsigned int ctr,i,cnt;
  int ofd,debug;

  debug = (argc > 2); // Should we run in debug mode
  ifd = stdin; // Read from standard input
  for (i=0; i < BUFSIZE; i++) buffer[i]=0; // Initialise
  ctr = GAPSIZE+2;
  buffer[0]=ctr>>8; buffer[1]=ctr&255;
  if (debug) printf("Processing Images...\n");
  cnt = 0;
  if (debug) printf("First offset = %3d\n",ctr);
  while (fgets(line,MAXLINESIZE,ifd)) 
    {
      // line can't be empty, atleast \n. if EOF encountered it wont be here
      if (line[strlen(line)-1] == '\n') {
	line[strlen(line)-1] = 0; // Replace \n with Null Char
	  }
      if (line[0] == '#' || line[0] == 0) continue; // Comment or empty line
      i = ctr+2+strlen(line)+GAPSIZE;
      buffer[ctr]=i>>8;
      buffer[ctr+1]=i&255;
      strcpy(buffer+ctr+2,line);
      ctr = i; ++cnt;
      if (debug) printf("Next offset = %4d, image name = [%s]\n",ctr,line);
      if (ctr > BUFSIZE - GAPSIZE) {
	printf("Sorry: Too many images. If you really need it, \n");
	printf("Consider modifying the source code\n");
	exit(1);
      }
    }
  fclose(ifd);
  if (cnt <= 1) {
    printf("No substantial input...Ignoring...");
    exit(1);
  }
  if (debug) {
    ofd = open(argv[1],O_CREAT|O_TRUNC|O_WRONLY,S_IRWXU); // New file
  }
  else {
    ofd = open(argv[1],O_RDWR); // Existing file
  }
  if (ofd == -1) {
    printf("Sorry could not open %s.\n",argv[1]);
    exit(2);
  }
  if (! debug) {
    // Move to beginning of SECT_START sector
    // The -1 is bcos here it starts at 0'th sector based while
    // in the BIOS it is 1'st sector
    lseek(ofd,(SECT_START-1)*SECT_SIZE,SEEK_SET);
  }
  // Write our data
  write(ofd,buffer,BUFSIZE);
  close(ofd);
  return 0;
}
