/**************************************************************************************
 * FILE PURPOSE: Merge multiple boot tables into one boot table
 **************************************************************************************
 * FILE NAME: mergebtbl.c
 *
 *   Usage: mergebtbl inputfile1 inputfile2 ... outputfile
 *          Note: may not support single line boot table(hardly possible)
 *
 **************************************************************************************/
#include <stdio.h>
#include <string.h>


int asciiByte (unsigned char c)
{
  if ((c >= '0') && (c <= '9'))
    return (1);

  if ((c >= 'A') && (c <= 'F'))
    return (1);

  return (0);
}


int main (int argc, char *argv[])
{
  FILE *strin;
  FILE *strout;
  int i,j,k;
  int line;
  int start;
 
  char iline[132];
  char iline2nd[132];

  /* Verify the number of args */
   if (argc < 3)  {
    printf ("usage: %s inpfile[1] ... infile[n] outfile\n", argv[0]);
    return (-1);
  }

  strout = fopen (argv[argc-1], "w");
  if (strout == NULL)  {
    printf ("could not open file %s to write\n",argv[argc-1]);
    return (-1);
  }

  fputs("first line\n",strout);
  fputs("second line\n",strout);

  for(i=1; i<argc-1;i++) {
	
        strin = fopen (argv[i], "r");
		if (strin == NULL)  {
			printf ("could not open input file %s\n", argv[i]);
			return (-1);
		}

		line = 0;

		/* skip the next two lines */
		fgets (iline, 132, strin);
		fgets (iline, 132, strin);

		if(fgets(iline2nd, 132, strin)==NULL) {
			printf("error in boot table\n");
		}

		while(1) {
			fgets(iline, 132, strin);
			if(!asciiByte(iline[0])) break;
			line++;

			if(i!=1 && line==1) { /* if not the first file, get rid of entry point */
				for(j=12; j<132; j++) {
					if(iline2nd[j]=='\0') break;
					fputc(iline2nd[j],strout);
				}
			} else {
				fputs(iline2nd,strout);
			}
      		strcpy(iline2nd,iline);
		} /* while */
		
		if(i!=argc-2) { /* If not the last file, get rid of ending 00 00 00 00 */
			for(j=0,start=0;j<132;j+=2){
				if((iline2nd[j]=='0')&&(iline2nd[j+1]=='0')) {
					if(start) k++;
					else if((j-j/4*4)==0) {
						start = 1; /* not count from any 00 */
						k=1;
					}
				}
				else { 
					start = 0;
					k=0;
				}
		
				if(k==4) {  // when 00 00 00 00 reached
					if(asciiByte(iline2nd[j+3])) { //if the next char is still ASCII
						start = 0;
					} else break; /* Ending 00 00 00 00 reach */
				}
				j++;            /* skip the space */
			}

			if((k==4) && (j>10)) {
     			for(k=0;k<j-10;k++){
	    			fputc(iline2nd[k],strout);
				}
				fputc('\n',strout);
			}
		} else {
			fputs(iline2nd,strout);
		}

		fclose(strin);
  } /* for */

  fputc(0x04,strout); /* any non-ASCII character */

  fclose(strout);

  return (0);
}

