#/usr/local/bin/perl

#----------------------------------------------------------------------
# variables you should change:

$geo_server    = "geoserver.eecs.umich.edu";
$geo_port      = 3000;

#----------------------------------------------------------------------

# gateway from gopher to the geographic name server
# this is the "brute force" kind of approach; a tidier solution
# would speak the prospero protocols directly.

sub geo_main {
    
    local($_) = @_;
    
    if (/^$/) {
	&Greply("7Search Geographic Name Server by City or ZIP code\t$Ggw search\t$Ghost\t$Gport");
	&Greply(".");
	exit;
    }
    
    ($action, $query, $gplus) = split('\t');

    if ($action =~ /^city/) {
	$city = $action;
	$city =~ s/^city//;
	&GopenServer($geo_server, $geo_port);

	# remove banner
	while ($_ ne ".") {
	    $_ = &Grecv;
	}
	&Gsend($city);

	$_ = "";

      LOOP:
	while ($_ ne "." || $_ eq "") {

	    $_ = &Grecv;
	    
	    s/^R /Note            : /;
	    s/^0 /City            : /;
	    if (/^1 /) {
		s/^1 //;
		s/(\d+)/[$1]/;
		push(@Counties,$_);
		next LOOP;
            }
	    s/^3 /Nation          : /;
	    s/^A /Area-Code       : /;
	    s/^2 /State\/Province  : /;
	    s/^F /Feature Code    : /;

	    if (/^E /) {
	        s/^E /Elevation       : /;
		$_ = $_ . " feet";
	    }
	    if (/^L /) {
		($L, $latdeg, $latmin, $latsec, $NS,
		     $londeg, $lonmin, $lonsec, $EW) =
			 split;
		&Greply("");
	        &Greply("Latitude        : $latdeg degrees, $latmin minutes, $latsec seconds $NS");
		&Greply("Longitude       : $londeg degrees, $lonmin minutes, $lonsec seconds $EW");
		&Greply("");
		next LOOP;
	    }

	    if (/^P /) {
		s/^P /1980 Population : /;
	    }

	    if (/^Z /) {
		s/^Z //;
		push(@Zips, $_);
		next LOOP;
	    }

	    &Greply($_) unless ($_ eq "." || $_ eq "");
	}

	&Greply("");
	$line = "ZIP Codes       : ";
	foreach $i (@Zips) {
	    if (length($line) <70) {
		$line = "$line $i";
	    } else {
		&Greply($line);
		$line = "                : ";
	    }
	}
	&Greply($line);

	&Greply("");
	$line = "Counties        : ";
	foreach $i (@Counties) {
	    if (length($line) <70) {
		$line = "$line $i";
	    } else {
		&Greply($line);
		$line = "                : ";
	    }
	}

	&Greply($line);

	if ($_ eq "") {
	    @Zips = ();
	    @Counties = ();
	    &Greply("");
	    next LOOP;
	}
    }



    elsif ($action eq "search") {
	&GopenServer($geo_server,$geo_port);
	# remove banner
	while ($_ ne ".") {
	    $_ = &Grecv;
	}
	&Gsend($query);

	$_ = "";	
	while ($_ ne ".") {
	    $_ = &Grecv;
	    
	    if (/^0 (.*)$/) {
		$City = $1;
	    }
	    if (/^2 (\S+) (.*)$/) {
		$States{$1} = $City;
	    }
	}
	
	foreach $i (keys(%States)) {
		&Greply("0$States{$i}, $i\tgeo city $States{$i}, $i\t$Ghost\t$Gport");
	    }
    }


    &Greply(".");
    exit;
    
}

1;