/*----------------------------------------------------------------------*\
 | Modified run-length encoding: read (Unix version)					|
 |																		|
 | This program converts an SST file from MRLE format to the unpacked	|
 | format of the original data from NOAA.								|
 |																		|
 | Peter N. Schweitzer (U.S. Geological Survey, Reston, VA 22092)		|
\*----------------------------------------------------------------------*/

#include <stdio.h>
#include <stdlib.h>

#define IMAGESIZE 522*512
#define MAXLEN 128

main (int argc, char *argv[]) {
	int i,n,m;
	FILE *in, *out;
	char input_file[MAXLEN], output_file[MAXLEN];
	char src[IMAGESIZE],dst[IMAGESIZE];

	if (argc > 1) {
		strcpy (input_file,argv[1]);
		if (in = fopen (input_file,"r")) {
			if (argc > 2) {
				strcpy (output_file,argv[2]);
				if (out = fopen (output_file,"w")) {
					n = fread (src,1,522*512,in);
					printf ("%d bytes read from %s\n",n,input_file);
					m = decode (dst,src,n);
					fwrite (dst,1,m,out);
					printf ("%d bytes written to %s\n",m,output_file);
					fclose (out);
					}
				else
					printf ("Error: could not open output file %s\n",output_file);
				}
			else
				printf ("Usage: %s infile outfile\n",argv[0]);
			fclose (in);
			}
		else
			printf ("Error: could not open input file %s\n",input_file);
		}
	else
		printf ("Usage: %s infile outfile\n",argv[0]);
	}

int decode (char *dst, char *src, int len) {
	int c,n;
	char *d,*s,*end;

	d = dst;
	s = src;
	end = src + len;
	while (src < end) {

		/*--------------------------------------------------------------*\
		 | Get character count											|
		\*--------------------------------------------------------------*/

		n = *src++;
		if (n >= 0) {

			/*----------------------------------------------------------*\
			 | If character count is positive repeat next src byte.		|
			\*----------------------------------------------------------*/

			n++;
			c = *src++;
			while (n-- > 0) *d++ = c;
			}
		else {

			/*----------------------------------------------------------*\
			 | If character count is negative, copy count src bytes.	|
			\*----------------------------------------------------------*/

			n = -n;
			while (n-- > 0) *d++ = *src++;
			}
		}
	return (d - dst);
	}

/*----------------------------------------------------------------------*\
\*----------------------------------------------------------------------*/
