/*
 * 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.
 */
/* 
 * rletoqrt.c - Converts an RLE file into a qrt file.
 * 
 * Author:	Kriton Kyrimis
 * Based on rletogray.c by Michael J. Banks
 */

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

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

#ifdef USE_STRING_H
#include <string.h>
#else
#include <strings.h>
#endif

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

#endif /* USE_STDLIB_H */

/*
 * usage : rletoqrt [-o outfile] [infile]
 *
 *	-o outfile		Specifies ouput file name.
 *	infile			File to split.  If none, uses stdin.
 */

void
out(int x, FILE* f)
{
  unsigned char l, h;

  l = x & 0xff;
  h = ((x & 0xff00) >> 8) & 0xff;
  fwrite(&l, sizeof(l), 1, f);
  fwrite(&h, sizeof(h), 1, f);
}

void
main(argc, argv)
int  argc;
char *argv[];
{
    char       *inpnam = NULL;	/* Input file name. */
    char       *outnam = NULL;	/* Output file name. */
    int 	oflag = 0;	/* Output file name prefix flag. */
    register char * cp, * slashp;
    FILE       *outfil;		/* Output file pointer. */
    int 	scans, rasts;	/* Number of scan lines. */
    rle_pixel **inprow;		/* Input buffer. */
    int 	i, row;

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

    /* If an input file is specified, open it. Otherwise use stdin. */

    rle_dflt_hdr.rle_file = rle_open_f("rletogray", inpnam, "r");
    /* Read header information. */

    rle_get_setup( &rle_dflt_hdr );
    scans = rle_dflt_hdr.ymax - rle_dflt_hdr.ymin + 1;
    rasts = rle_dflt_hdr.xmax - rle_dflt_hdr.xmin + 1;

    if (!oflag) {
        outfil = stdout;
    }else{
        if (( outfil = fopen(outnam, "w")) == NULL) {
            perror(outnam);
            exit(-1);
        }
    }

    /* Allocate input buffer. */

    if (rle_row_alloc( &rle_dflt_hdr, &inprow ))
    {
	fprintf(stderr, "rletoqrt: Out of memory.\n");
	exit(-2);
    }

    /* Read .rle file, and convert to qrt. */

    out(rasts, outfil);
    out(scans, outfil);

    for (row=0; (row<scans); row++)
    {
        out(row, outfil);
	rle_getrow( &rle_dflt_hdr, inprow );
	for ( i = 0; i<3; i++ )
	    fwrite( inprow[i], 1, rasts, outfil );
    }
    exit(0);
}
