/* Copyright 2002 Daniel Egnor.  See LICENSE file.
 * 
 * This program is part of the processing chain to convert TIGER/Line data
 * into an index ("map") for fast address lookup.  It reads "step3" data
 * as generated by "geo-2-to-3" and finishes the map file by writing a
 * geographical name table.
 *
 * The input format contains one line per unique name, in sorted order:
 * 
 * REMain Street //      454545
 * |<-----name---//-><-offset->
 * type/parity
 *
 * The names are simply written to the map file, in a format suitable for
 * binary searching. */

#include "io.h"

#include <stdio.h>
#include <string.h>

int main(int argc,char *argv[]) {
	char line[256],prev[256] = "";
	struct io_file *index;
	int end,zip_end,name_offset;
	int end_pointer,end_offset;

	if (2 != argc) {
		fprintf(stderr,"usage: %s map-file < test3-data\n",argv[0]);
		return 2;
	}

	index = io_open(argv[1]);
	if (NULL == index) return 1;

	end = 0;
	end = io_in_i4(index,end,&zip_end);
	end = io_in_i4(index,end,&name_offset);
	end = io_in_i4(index,end_pointer = end,&end_offset);
	if (end < 0) return 1;

	if (name_offset != end_offset)
		fputs("warning: overwriting previous name data\n",stderr);

	zip_end = zip_end + 4*100000;
	end = name_offset;

	while (NULL != fgets(line,sizeof line,stdin)) {
		int range;

		if (strlen(line) < 64) {
			fputs("warning: truncated input line\n",stderr);
			continue;
		}

		if ('R' != line[0]) {
			fputs("warning: invalid input record\n",stderr);
			continue;
		}

		if (strncasecmp(line,prev,64) < 0) {
			fputs("warning: input line out of order\n",stderr);
			continue;
		}

		range = io_strntoi(line + 54,10);
		if (range < zip_end || range > name_offset) {
			fputs("warning: invalid address\n",stderr);
			continue;
		}

		strcpy(prev,line);
		end = io_out(index,end,line + 1,41); /* 53? */
		end = io_out_i4(index,end,range);
		if (end < 0) return 1;
	}

	if (io_out_i4(index,end_pointer,end) < 0) return 1;
	io_close(index);
	return 0;
}

