#!/bin/sh
# Copyright 2002 Daniel Egnor.  See LICENSE file.
#
# This shell script knows about all the weird little stages involved in
# building an "address map" from TIGER/Line and FIPS-55 input data.
# It keeps temporary files in a "tmp.<pid>" subdirectory of the current dir.

fips="$1"
alias="$2"
map="$3"

LC_COLLATE=C
LC_ALL=C
export LC_COLLATE LC_ALL

if [ -z "$map" ]; then
	printf 'usage: find ... -name \*.zip | %s <fips-in> <alias-in> <map-out>\n' "$0" >&2
	exit 2
fi

tmp="`dirname $map`/tmp.$$"
rm -rf "$tmp"
mkdir -p "$tmp" || exit 1
dir="`dirname $0`"

while read zip; do
	name="`basename $zip`"
    (   unzip -p "$zip" 'TGR*.RT6'   # order matters!
	unzip -p "$zip" 'TGR*.RT5'
	unzip -p "$zip" 'TGR*.RT4'
	unzip -p "$zip" 'TGR*.RT1'
    ) | "$dir/geo-tiger-to-1" | sort -f > "$tmp/$name.step1"
done

(   sort -mf "$tmp"/*.step1 | "$dir/geo-1-to-2" "$map"
    "$dir/geo-fips-to-2" < "$fips"
) | "$dir/geo-2-to-2a" "$alias" | sort -f > "$tmp/all.step2a"

"$dir/geo-2-to-3" "$map" < "$tmp/all.step2a" > "$tmp/all.step3"
"$dir/geo-3-to-map" "$map" < "$tmp/all.step3"

