/* GRABKICK  Copy Kickstart ROM into a file                         ***RGR***
   MANX Aztec C 5.2: cc GrabKick; ln GrabKick -lm -lc               23-dec-92
   Author:   Ralf Gruner, An der Sense 5a, D-02779 Großschönau, Germany.
*/

#include <stdio.h>
#include <libraries/dos.h>

main(int argc, char *argv[])
{
	void grab(char *kickfile);
	char *msg="\n GrabKick Version 1.1 - 1992 by Ralf Gruner, Großschönau, Germany.\n";

	if(argc == 0)
	{
		/* Start from WorkBench */
		printf(msg);
		grab("Kickfile");
		Delay(500L);
	}

	if((argc != 2)&&(argc != 1)||(*argv[1]=='?'))
	{
		printf("\n Copy Kickstart ROM to file.");
		printf(msg);
		printf(" Usage: GrabKick [<destination file name>]\n\n");
	}
	else
		if(argc == 2)
		{
			grab(argv[1]);
		}
		else
			grab("Kickfile");
}

void grab(char *kickfile)
{
	FILE *ausgabe, *fopen();
	long anzahl = 0;
	unsigned short *version;
	char c, *romptr, *romstart, *romend=(char *)0x00ffffff;

	if(!(ausgabe = fopen(kickfile, "w")))
		{
			printf("cannot open: %s\n",kickfile);
			return;
		}
	romstart= (char *) (romend- *(unsigned long *)(romend - 0x13) +1);
	printf("\nROMstart: %lX\n",romstart);
	printf("ROMend :  %lX\n",romend);

	version=(unsigned short*)(romstart+12);
	printf("Copying Kickstart version %u.%u to file %s\n",*version,*(version+1),kickfile);

	for(romptr= romstart; romptr< (char *)(romend +1); ++romptr)
	{
		c=*romptr;
		if(fputc( c, ausgabe)==EOF)
		{
			printf("\nError while writing.");
			fclose(ausgabe);
			if(remove(kickfile)==0)
				printf(" File %s removed.",kickfile);
			printf("\n\n");
			anzahl=-1;
			break;
		}
		anzahl++;
	}
	if(anzahl>=0L)
	{
		fclose(ausgabe);
		printf("%ld bytes (%ld KB).\n\n", anzahl,anzahl/1024);
	}
}

