/* MTV raytracer to HamLab filter
 * (c) Copyright 1990 James Edward Hanway
 * All rights reserved.
 *
 * $Id: mtv2hl.c,v 1.4 90/07/30 13:22:16 jeh Exp $
 *
 * $Log:	mtv2hl.c,v $
 * Revision 1.4  90/07/30  13:22:16  jeh
 * Added includes needed for compilation without CHEAPIO library
 * 
 * Revision 1.3  90/07/19  19:36:39  jeh
 * Cleaned up some comments for source code release.
 * 
 * Revision 1.2  90/07/19  19:12:49  jeh
 * First Release Version (HamLab 1.0)
 * 
 * Revision 1.1  90/07/11  20:33:50  jeh
 * Initial revision
 * 
 * NOTE:
 *
 * Filters for files like MTV images must be extremely careful, since HamLab
 * can't identify them using its simple pattern matching.  Any invalidity should
 * be detected ASAP and gracefully recovered from.
 */

#ifdef CHEAP
#include <cheapio.h>
#else
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#endif
#include <string.h>

#include "hl_filter.h"

static int
break_handler(void)
{
	return EXIT_ABORTED;
}

static void
putword(unsigned short uw)
{
	putchar(uw >> 8);
	putchar(uw);
}

main(int argc, char *argv[])
{
	char line[80], *s;
	unsigned short	width, height;
	long	size;
	int	c;

	/* It's important to set up a break handler so that it'll return the right
	 * error code to HamLab and so that it won't print anything to stderr.
	 */
	(void) onbreak(break_handler);

	if(!fgets(line, sizeof(line), stdin))
		exit(EXIT_WRONGTYPE);

	s = line;
	width = (unsigned short) strtol(s, &s, 10);
	height = (unsigned short) strtol(s, &s, 10);

	/* Normally the thing to do here would be to double-check the characteristic
	 * signature at the beginning of the file, but MTV files have no such thing,
	 * so we'll have to be satisfied if everything seems like it makes sense.
	 */
	if(width == 0 || height == 0 || width > 2000 || height > 2000 || *s != '\n')
		exit(EXIT_WRONGTYPE);

	fputs(HL_24BITHEADER, stdout);
	putword(width);
	putword(height);
		
	/* MTV files have no specified "background color."
	 * I could just always use black for the background, but instead
	 * I sleaze the first color from the picture (the upper left corner)
	 * and call that the background.
	 */

	putchar(0);	/* background color a 24 bit RGB triple, padded to a long
			 * with zeros (it is the ONLY RGB triple so padded)
			 */

	line[0] = getchar();
	putchar(line[0]);
	line[1] = getchar();
	putchar(line[1]);
	line[2] = getchar();
	putchar(line[2]); 

	/* output the pixel that we just read */
	putchar(line[0]);
	putchar(line[1]);
	putchar(line[2]); 
	
	size = (long) width * (long) height;

	/* This part is really easy -- read 24 bit RGB triples, write 24 bit
	 * RGB triples. It's usually harder than this.
	 */
	while(--size) {	/* Pre-decrement to account for first pixel already written */
		c = getchar(); putchar(c);	/* R */
		c = getchar(); putchar(c);	/* G */
		c = getchar(); putchar(c);	/* B */
		if(feof(stdin))
			exit(EXIT_PARTIAL);
	}

	exit(EXIT_SUCCESS);
}
