/*****************************************************************
 *
 *  FILE: MEMAKEOV.C
 *
 *  Make large main overlay file from several smaller ones..
 *
 *  For Metal/Z-Msg
 *  Copyright (c) 1985 Tim Gary
 *
 *****************************************************************
 *
 * 1.31a   10/13/85 Release version (use only with 1.31a or above)
 * 1.31xx  08/18/85 Started..
 *
 *****************************************************************/

#define CON_IO	1	/* make this so we get getchar/putchar/etc */
#define OK	1
#include "xpmio.c"

unsigned ov_seek[64];	/* assumes 16 bit word */
int ov_ind;		/* index to above array */

FILE *outfile,*infile,*ovfile;
char inname[128],outname[128],ovname[128];


main(argc,argv)
 int argc;
 char *argv[];
{

puts("\nMake Main Overlay file utility for Metal/Z-Msg\n\r");

outfile=infile=ovfile=NULL;

if (argc<=1)
	{
	puts("\n\rEnter name of file with list of overlays (in order!) ->");
	gets(inname);
	}
	else strcpy(inname,argv[1]);
if (*inname=='\0' || !(infile=open(inname,0))) quit();

if (argc<=2)
	{
	puts("\n\rEnter name of main overlay file to be created ->");
	gets(outname);
	}
	else strcpy(outname,argv[2]);
if (*outname=='\0') quit();
unlink(outname);
if (*outname=='\0' || !(outfile=open(outname,1))) quit();

setmem(bufloc(outfile),128,0);	/* reserve for later */
write(outfile,1);		

read(infile,1);

do {
   fgets(ovname,infile);
   if (*ovname=='\n') strcpy(ovname,ovname+1);
   if (*ovname<' ') break;
   if (copyov(ovname)==ERROR) quit();
   } while (1);

/* normal end falls through to here */

setarec(outfile,0);	/* go to start of file */
movmem(ov_seek,bufloc(outfile),128);	/* copy seek table */
write(outfile,0);
close(outfile);
close(infile);

puts("\n[All Done!!!]\n");
exit(0);
}

copyov(name)
 char *name;
{
char *ov_mem,*cp;
int sec_count=0;

ov_mem=cp=alloc(0x4000);

if ( !ov_mem || (ovfile=open(name,0))==NULL)
	{
	free(cp);
	return ERROR;
	}

ov_seek[ov_ind++]=getrec(outfile);

printf("\nLoading %s, ",name);

while (read(ovfile,1)==128)
	{
	movmem(bufloc(ovfile),cp,128);
	cp+=128;
	}
sec_count=getrec(ovfile);
close(ovfile);

printf("saving (to rec %u), ",getrec(outfile));

for (cp=ov_mem; sec_count--; cp+=128)
	{
	movmem(cp,bufloc(outfile),128);
	if (write(outfile,1)!=128)
		{
		free(ov_mem);
		return ERROR;
		}
	}

puts("done.");

free(ov_mem);

return OK;
}


quit()
{
puts("\n\r[  ERROR:  Bad file name or out of disk space !! ]\n\r");
unlink(outname);	/* Close this file */
exit(1);
}

