#include <stdio.h>
#include <ctype.h>
#define ZIPFILE "/afs/athena.mit.edu/contrib/watchmaker/lib/zipcode.txt"

main(argc,argv)
int        argc ;
char    *argv[] ;
{
	FILE *zipfile;
	int keynum;
	char buf[128];
	char grepbuf[128];
	char keywrd[128];
	int num1;
	int num2;
	int i;
	char city[128];
	char *City;
	char *lowercase();
	FILE *grepstream;

	if (argc != 2) {
		fprintf(stderr, "Usage: zipcode keyword\n");
		exit (1);
	}
	if (strlen(argv[1]) > 120) {
		fprintf(stderr, "keyword %s too long\n", argv[1]);
		exit (1);
	}
	if ( keynum = isnum(argv[1]) ) {
		zipfile = fopen (ZIPFILE, "r");
		if (zipfile == NULL) {
			fprintf(stderr, "%s: unable to open zipcode.txt file\n", argv[0]);
			exit(1) ;
		}
		while (fgets(buf, 128, zipfile) != NULL) {
			*(buf+strlen(buf)-2) == '\0';
			if (*(buf+5)=='-') {
				sscanf (buf, "%5d-%5d", &num1, &num2);
				City = buf+12;
		   	} else {
				sscanf (buf, "%5d", &num1);
				num2 = num1;
				City = buf+6;
			}
			if (keynum >= num1 && keynum <= num2) {
				trunc (City);
				prbuf (num1, num2, City);
				break;
			}
		}
		fclose (zipfile);
	} else {
		sprintf (grepbuf, "grep -i '%s' %s", argv[1], ZIPFILE);
		grepstream = popen (grepbuf, "r");
		if (grepstream == NULL) {
			fprintf(stderr, "%s: can't pipe to grep\n", argv[0] );
			exit( 1 );
		}

		while (fgets (buf, 128, grepstream) != NULL) {
			*(buf+strlen(buf)-2) == '\0';
			if (*(buf+5)=='-') {
				sscanf (buf, "%5d-%5d", &num1, &num2);
				City = buf+12;
		   	} else {
				sscanf (buf, "%5d", &num1);
				num2 = num1;
				City = buf+6;
			}
			trunc (City);
			prbuf (num1, num2, City);
		}
		exit( pclose( grepstream ) );
	}
}

isnum(keywrd)
char *keywrd;
{
	int i;
	int num;

	if (strlen(keywrd) != 5)
		return 0;
	for (i=0; i<5; i++)
		if (!isdigit(*(keywrd+i)))
			return 0;
	sscanf(keywrd, "%d", &num);
	return num;
}

trunc(s)
char *s;
{
	char *cp;
	cp = s + strlen(s);
	while (cp-- >= s) {
		if (!isspace(*cp)) break;
		*cp = NULL;
	}
}

prbuf (n1, n2, s)
int n1;
int n2;
char *s;
{
	if (n1 == n2)
		printf ("%05d       %s\n", n1, s);
	    else
		printf ("%05d-%05d %s\n", n1, n2, s);
}
