
#include <bios.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char filename[255];
char Savefile[255];
char tmpbuf[1024];
char mode = 0;
char cDrive = 0x80;

const char boothead[] = {0xeb,0x65,'B','o','o','t','M','a','n'};
const char boottail[] = {0x55,0xaa};

#pragma argsused
void main(int argc, char **argv)
{
	FILE *fin, *fout;
	char *zptr;

	/************************************************************/
	/* If we didn't get an arguement then prompt for a filename */
   if((--argc == 3) && (strncmp("/r", argv[1], 2) == NULL)) {
		mode = 1;
   } else if(argc != 2) {
      printf("\nUsage: Install [/r] <Drive> <Filename>\n");
      printf("\t\t/r = restore saved boot sector (usually boot(x).sav)\n");
      printf("\t\t<Drive> = 0, 1, 2, 3, etc...\n\n");
      exit(1);
	}
   strcpy(filename, argv[argc]);
   cDrive += (char) atoi(argv[argc-1]);
	sprintf(Savefile,"Boot%d.sav",atoi(argv[argc-1]));

	/***************************************************/
	/* Strip off trailing line feed or carriage return */
	for(zptr=filename;*zptr > 32;zptr++);
	*zptr=0;

	/*************************/
	/* Try and open the file */
	if((fin = fopen(filename, "rb")) == NULL) {
		perror(filename);
		exit(1);
	}

	if(mode == 1) {
		fread(tmpbuf, 1, 512, fin);
	} else if((biosdisk(2,cDrive,0,0,1,1,tmpbuf))) {
		perror("Reading Boot Sector");
		exit(1);
	} else if(!(fout = fopen(Savefile, "wb"))) {
		perror(Savefile);
		exit(1);
	} else if(fwrite(tmpbuf,1,512,fout) != 512) {
		perror("Incorrect bytes written to 'boot.sav'");
		exit(1);
	} else {
		fclose(fout);
		fread(tmpbuf, 1, 446, fin);
		strncpy(tmpbuf+510, boottail, 2);
	}

	fclose(fin);

	if(biosdisk(3,cDrive,0,0,1,1,tmpbuf)) {
		perror("Writing Boot Sector");
	} else {
		printf("Boot sector updated OK\n");
	}
}


