/*********************************************************

  QRTRaw is a post processor for QRT for the IBM PC/AT,
  etc.  It reads in the QRT .RAW file, and spits out three
  RAW 16 million color pixel bitmap planes which can be
  then be further postprocessed by another program, such as
  the Stone Soup Group's PICLAB, which uses this format.

  QRTRaw is based upon the original QRTPost program by
  Steve Koren (I think...).

  Adapted for RAW output and ported to the IBM PC World
  (Turbo-C) from Amiga-Land by Aaron A. Collins, 1/30/90.

 *********************************************************/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAXXRES 640      /* max x resolution */

void main(argc,argv)
int argc;
char *argv[];
{
	int xres, yres, line;
	register int x;
	char rname[80], gname[80], bname[80];
	FILE *in, *rout, *gout, *bout;

	if (argc != 3 || strchr(argv[2], '.') != NULL)
	{
		printf("Usage: %s InFile.Ext OutFile (No .Ext on OutFile)\n",argv[0]);
		exit(1);
	}

	/** open files **/

	strcpy(rname, argv[2]);
	strcpy(gname, argv[2]);
	strcpy(bname, argv[2]);
	strcat(rname, ".R8");
	strcat(gname, ".G8");
	strcat(bname, ".B8");

	if ((in = fopen(argv[1], "rb")) == NULL)
	{
		printf("Couldn't open file %s\n",argv[1]);
		exit(1);
	}

	if ((rout = fopen(rname, "wb")) == NULL)
	{
		printf("Couldn't open file %s\n", rname);
		fclose(in);
		exit(1);
	}

	if ((gout = fopen(gname, "wb")) == NULL)
	{
		printf("Couldn't open file %s\n", gname);
		fclose(in);
		fclose(rout);
		exit(1);
	}

	if ((bout = fopen(bname, "wb")) == NULL)
	{
		printf("Couldn't open file %s\n", bname);
		fclose(in);
		fclose(rout);
		fclose(gout);
		exit(1);
	}

	/** load x and y resolution **/

	xres  = ((unsigned int)fgetc(in));
	xres += ((unsigned int)(fgetc(in) << 8));

	yres  = ((unsigned int)fgetc(in));
	yres += ((unsigned int)(fgetc(in) << 8));

	/** print info **/

	printf("\nInput  file  = %s\n", argv[1]);
	printf("Output  files  = %s, %s, %s\n\n", rname, gname, bname);
	printf("X  resolution  = %d\n", xres);
	printf("Y  resolution  = %d\n\n", yres);

	printf("Processing Line:   0");

	while (!feof(in))
	{
		line  = ((int)fgetc(in));	/* read scan line number */
		line |= ((int)(fgetc(in) << 8));

		if (feof(in))
		break;

		if (line >= yres)
		{
			printf("Corrupt data file at line: %d.\n",line);
			break;
		}

		printf("\b\b\b%3d", line);	/* disp. current line # */

		for (x=0; x<xres; x++)		/* do red color data */
			fputc(((int)fgetc(in)) & 0xff, rout);

		for (x=0; x<xres; x++)		/* do green color data */
			fputc(((int)fgetc(in)) & 0xff, gout);

		for (x=0; x<xres; x++)		/* do blue color data */
			fputc(((int)fgetc(in)) & 0xff, bout);

	}
	printf("\n");
	fclose(in);                                 /* close files */
	fclose(rout);
	fclose(gout);
	fclose(bout);
}
