/*----------------------------------------------------------------------*\
 | Program to read a 5-minute etopo5 grid containing 16-bit integer		|
 | elevation and bathymetry, and from it calculate a 1-degree grid		|
 | containing percent land cover.										|
 |																		|
 | Peter N. Schweitzer (U.S. Geological Survey, Reston, VA 22092)		|
\*----------------------------------------------------------------------*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define WIDTH	360*12
#define HEIGHT	180*12
#define DX	12
#define DY	12

enum byte_order_t {
	LITTLE_ENDIAN,
	BIG_ENDIAN
	} byte_order;

static enum byte_order_t get_byte_order (void) {
	short w = 255;

	unsigned char *s = (unsigned char *) &w;
	if (*s) return (LITTLE_ENDIAN);
	else return (BIG_ENDIAN);
	}

main (int argc, char *argv[]) {
	int i,j,k,m,n;
	long size;
	char *input_file;
	FILE *in;
	short *etopo5[DY];
	short *e[DY];
	char *scratch;
	enum byte_order_t byte_order = get_byte_order();
	short sum;

	if (argc > 1) {
		input_file = argv[1];
		if (in = fopen (input_file,"rb")) {

			/*----------------------------------------------------------*\
			 | Allocate DY rows of ETOPO5 grid cells and a scratch array|
			\*----------------------------------------------------------*/

			size = WIDTH * sizeof(short);
			for (j=0; j < DY; j++)
				if (etopo5[j] = (short *) malloc (size)) memset (etopo5[j],0,size);
				else {
					fprintf (stderr,"Error: could not allocate space for results\n");
					exit (1);
					}

			if (!(scratch = (char *) malloc (size))) {
				fprintf (stderr,"Error: could not allocate scratch space\n");
				exit (1);
				}

			/*----------------------------------------------------------*\
			\*----------------------------------------------------------*/

			for (j=0; j < 180; j++) {
				for (k=0; k < DY; k++) {
					size = WIDTH * sizeof(short);
					if ((n = fread (scratch,sizeof(short),WIDTH,in)) != WIDTH) {
						fprintf (stderr,"Error: only %ld of %ld words read from input file %s\n",n,WIDTH,input_file);
						exit (1);
						}
					if (byte_order == BIG_ENDIAN)
						swab (scratch,(char *)etopo5[k],n*sizeof(short));
					else
						memcpy (etopo5[k],scratch,n*sizeof(short));
					e[k] = etopo5[k];
					}
				for (i=0; i < 360; i++) {
					sum = 0;
					for (k=0; k < DY; k++)
						for (m=0; m < DX; m++)
							sum += (*e[k]++ >= 0);
					sum *= 100;
					sum /= DX*DY;
					printf ("%d",sum);
					if (i < 359) printf ("\t");
					else printf ("\n");
					}
				}
			fclose (in);
			}
		else {
			fprintf (stderr,"Error: could not open input file %s\n",input_file);
			exit (1);
			}
		}
	else {
		fprintf (stderr,"Usage: %s input_file\n",argv[0]);
		exit (0);
		}
	}

/*----------------------------------------------------------------------*\
\*----------------------------------------------------------------------*/
