#include <stdio.h>
#include <string.h> // memset
#include <stdlib.h> // atoi

int i,j,k,load_addr=0x100,boot_addr=0;
FILE *f;
unsigned char buff[1<<16];
unsigned char amsdos[1<<7];

int pascal_atoi(char *s)
{
	if (*s=='$')
		return strtol(&s[1],NULL,16);
	return strtol(s,NULL,0);
}

int main(int argc,char *argv[])
{
	if ((argc<3)||(argc>5))
		return puts("Usage: RAW2CPC infile outfile [load_address] [boot_address]"),1;
	if (argc>3)
	{
		load_addr=pascal_atoi(argv[3]);
		if (argc>4)
			boot_addr=pascal_atoi(argv[4]);
	}
	if (!(f=fopen(argv[1],"rb")))
		return puts("Error: cannot open source!"),1;
	i=fread(buff,1,1<<16,f);
	fclose(f);
	if (!(f=fopen(argv[2],"wb")))
		return puts("Error: cannot create target!"),1;
	memset(amsdos,0,1<<7);
	amsdos[0x12]=2; // BINARY TYPE
	amsdos[0x15]=load_addr;
	amsdos[0x16]=load_addr>>8;
	amsdos[0x18]=i;
	amsdos[0x19]=i>>8;
	amsdos[0x1A]=boot_addr;
	amsdos[0x1B]=boot_addr>>8;
	amsdos[0x40]=i;
	amsdos[0x41]=i>>8;
	for (k=j=0;k<0x42;k++)
		j+=amsdos[k];
	amsdos[0x43]=j;
	amsdos[0x44]=j>>8;
	fwrite(amsdos,1,1<<7,f);
	fwrite(buff,1,i,f);
	return fclose(f),0;
}
