#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define WIDTH	360
#define HEIGHT	180
#define OFFSET	10000

#define MAINTAIN_OFFSET			1
#define LITTLE_ENDIAN_OUTPUT	1

short *read_topo_file (char *name) {
	int i,x,y;
	short *data = NULL;
	short *d;
	FILE *in;
	long size;
	char *scratch;
	char *s;

	if (in = fopen (name,"r")) {
		size = WIDTH*HEIGHT;
		if (data = (short *) malloc (size*sizeof(short))) {
			if (scratch = (char *) malloc (WIDTH*sizeof(short))) {
				s = (char *) data;
				for (y=0; y < HEIGHT; y++)
					if (fread (scratch,sizeof(short),WIDTH,in) == WIDTH) {
						swab (scratch,s,WIDTH*sizeof(short));
						d = (short *) s;
						for (i=0; i < WIDTH; i++) *d++ -= OFFSET;
						s += WIDTH*sizeof(short);
						}
					else {
						fprintf (stderr,"Error: unexpected EOF at y = %d in %s\n",y,name);
						free (data);
						data = NULL;
						break;
						}
				if (data) fprintf (stderr,"%s ok\n",name);
				free (scratch);
				}
			else
				fprintf (stderr,"Error: could not allocate scratch array\n");
			}
		else
			fprintf (stderr,"Error: could not allocate %d bytes\n",size*sizeof(short));
		}
	else
		fprintf (stderr,"Error: could not open input file %s\n",name);
	return (data);
	}

main (int argc, char *argv[]) {
	int i;
	short *data1,*data2,*d,*e;

	if (argc < 3) {
		fprintf (stderr,"Usage: %s file1 file2 >result\n",argv[0]);
		fprintf (stderr,"       Output redirection is required because result is binary\n");
		exit(0);
		}

	if (data1 = read_topo_file (argv[1])) {
		if (data2 = read_topo_file (argv[2])) {
			d = data1;
			e = data2;
			for (i=0; i < WIDTH*HEIGHT; i++) *d++ -= *e++;

			#ifdef DEBUG
			{
				short dmin,dmax;

				d = data1;
				dmin = dmax = *d;
				for (i=0; i < WIDTH*HEIGHT; i++) {
					if (*d < dmin) dmin = *d;
					if (*d > dmax) dmax = *d;
					d++;
					}
				fprintf (stderr,"Difference  Min: %d  Max: %d\n",dmin,dmax);
				}
			#endif

			#ifdef MAINTAIN_OFFSET
				for (i=0,d=data1; i < WIDTH*HEIGHT; i++) *d++ += OFFSET;
			#endif

			#ifdef LITTLE_ENDIAN_OUTPUT
				swab ((char *)data1,(char *)data2,WIDTH*HEIGHT*sizeof(short));
				fwrite (data2,sizeof(short),WIDTH*HEIGHT,stdout);
			#else
				fwrite (data1,sizeof(short),WIDTH*HEIGHT,stdout);
			#endif

			free (data2);
			}
		free (data1);
		}
	}

