/*
 *		makecold.cpp
 *		Copyright (C) Z-World (jjb)
 *		This program builds a coldloader file from
 *		a *.bin file.
 *
 *
 *		To make this work you have to change a couple of the compiler
 *		options.  You should turn pointer checking off, Restrict watch
 *		expressions, and exclude the bios.
 *
 *		Your program should use the following format:
 *
 *		#rcodorg rootcode2 0x0 0x0 0x6000 apply
 *
 *		#asm
 *		main::
 *		premain::
 *				ld		a,0x84
 *		ioi	ld		(SPCR),a
 *				ld		a,0xff
 *
 *				ld		a,0xa5
 *		ioi	ld		(PADR),a
 *
 *		loop:
 *				jr		loop
 *		#endasm
 *
 *		Notice both the main and premain.  This is necessary to cause
 *		the compiler to not bring in the functions called from premain.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <io.h>
#include <sys/stat.h>

/*
 *	This is the first eight bytes of the coldload sequence.  It is
 *	used to set up a could of of the configuration registers.
 */

const char start_sequence[] =
	"\x80\x00\x08"  // GCSR: no periodic int, main osc no div
   "\x80\x10\x00"  // MMIDR: normal operation
   "\x80\x14\x45"  // MB0CR: 2 ws, OE1, CS1 active
   "\x80\x15\x45"  // MB1CR: 2 ws, OE1, CS1 active
   "\x80\x16\x40"  // MB2CR: 2 ws, OE0, WE0, CS0 active
   "\x80\x17\x40"  // MB3CR: 2 ws, OE0, WE0, CS0 active
   "\x80\x13\xc6"  // SEGSIZE
   "\x80\x11\x74"  // STACKSEG
   "\x80\x12\x3a"; // DATASEG

int main(int argc, char* argv[])
{
	int h_in, h_out;
   unsigned int x;
   char ch;
   char seq[3];

   if(argc!=3) {
   	printf("usage:  makecold <source filename> <destination file>\n");
      return 1;
   }

   printf("source=%s, destination=%s\n",argv[1],argv[2]);

   if((h_in=open(argv[1],O_BINARY|O_RDONLY))<0) {
   	perror("error opening source file");
      return 1;
   }

   if((h_out=open(argv[2],O_BINARY|O_CREAT|O_EXCL|O_RDWR,
   	S_IREAD|S_IWRITE))<0) {
   	perror("error creating destination file");
      return 1;
   }

   if(write(h_out,start_sequence,sizeof(start_sequence)-1)<0) {
   	printf("error writing start sequence\n");
   }

   for(x=0;x<32768&&!eof(h_in);x++) {
   	if(read(h_in,&ch,1)<0) {
      	printf("error reading input file\n");
         return 1;
      }

      seq[0]=(x>>8)&0xff;
      seq[1]=x&0xff;
      seq[2]=ch;

      if(write(h_out,seq,3)<0) {
      	printf("error writing output file\n");
         return 1;
      }
   }

   seq[0]=0x80;
   seq[1]=0x24;
   seq[2]=0x80;

   if(write(h_out,seq,3)<0) {
    	printf("error writing 0x80 0x24 0x80\n");
      return 1;
   }

   if(x>=32768)
   	printf("warning:  input file may have been too long\n");

   printf("output file succefully created %d bytes\n",
   	x*3+sizeof(start_sequence)-1);
   return 0;
}
