/*
 * This software is copyrighted as noted below.  It may be freely copied,
 * modified, and redistributed, provided that the copyright notices are 
 * preserved on all copies.
 * 
 * There is no warranty or other guarantee of fitness for this software,
 * it is provided solely "as is".  Bug reports or fixes may be sent
 * to the author, who may or may not act on them as he desires.
 *
 * You may not include this software in a program or other software product
 * without supplying the source, or without informing the end-user that the 
 * source is available for no extra charge.
 *
 * If you modify this software, you should include a notice giving the
 * name of the person performing the modification, the date of modification,
 * and the reason for such modification.
 */
/* 
 * qrttorle.c - Convert a QRT file to an RLE image.
 * 
 * Author:      Kriton Kyrimis
 * Based on graytorle.c by Michael J. Banks
 */

#include <stdio.h>
#include "rle.h"

#ifdef USE_STDLIB_H
#include <stdlib.h>
#else

#ifdef VOID_STAR
extern void *malloc();
#else
extern char *malloc();
#endif
extern void free();

#endif /* USE_STDLIB_H */

typedef FILE	*FILPTR;

/*
 * usage : qrttorle [-o outfile] [file]
 *
 *    -o outfile	Output file name.
 */

int
in(FILE *f)
{
  int n, l , h;
  unsigned char c;

  fread((char *)&c, sizeof(c), 1, f);
  l = c;
  fread((char *)&c, sizeof(c), 1, f);
  h = c;
  n = (h << 8) + l;
  return n;
}

void
main(int argc, char *argv[])
{
    char *oname = NULL;		/* Output file name. */
    FILE *inpfil;		/* Input file pointer. */
    int xsize, ysize;		/* Image size. */
    int oflag;	        	/* Output file flag. */
    char *fname = NULL;		/* Input file name. */
    rle_pixel **outrow;		/* Output buffer. */
    int i, row;

    if (! scanargs( argc,argv,
        "% o%-outfile!s infile%s", &oflag, &oname, &fname ))
        exit( -1 );

    /* 
     * Open input file.
     */

    inpfil = rle_open_f( "qrttorle", fname, "r" );
    xsize = in(inpfil);
    ysize = in(inpfil);

    /* Initialize the_hdr and allocate image row storage. */

    rle_dflt_hdr.alpha = 0;
    rle_dflt_hdr.ncolors = 3;
    rle_dflt_hdr.xmax = xsize - 1;
    rle_dflt_hdr.ymax = ysize - 1;
    rle_dflt_hdr.rle_file = rle_open_f("qrttorle", oname, "w");
    for ( i = 0; i<rle_dflt_hdr.ncolors; i++)
	RLE_SET_BIT( rle_dflt_hdr, i );
    rle_addhist( argv, (rle_hdr *)NULL, &rle_dflt_hdr );
    rle_put_setup( &rle_dflt_hdr );

    if (rle_row_alloc( &rle_dflt_hdr, &outrow ))
    {
	fprintf(stderr, "Ran out of heap space!!\n");
	exit(-2);
    }

    /* Combine rows and write to output file. */

    for ( row=0; row<ysize; row++)
    {
	(void)in(inpfil);	/* Discard scan line number */
	for ( i = 0; i<3; i++ )
	    fread( outrow[i], 1, xsize, inpfil );
	rle_putrow( outrow, xsize, &rle_dflt_hdr );
    }
    exit(0);
}
