#!/bin/bash

# This is known to work well with the 2010 "TIGER" data and shapelib 1.3.0.
# Earlier shapelib's probably won't work; for one thing, they don't give
# much precision in the output floating point numbers.

set -eu
set -o pipefail

prev_lat=""
prev_long=""

function double
{
python -c '
import sys

prev_lat=""
prev_long=""

for line in sys.stdin:
    fields = line.split()

    if fields:
        lat=fields[0]
        long=fields[1]

        if prev_lat != "" and prev_long != "":
            print("%s %s %s %s" % (prev_lat, prev_long, lat, long))
        prev_lat=lat
        prev_long=long
'
}

shpdump "$@" | \
    (
        set -eu
        set -o pipefail

        read line
        # ensure that this is a file full of Arcs
        if echo "$line" | egrep -q '^Shapefile Type: Arc '
        then
            cat
        else
            echo "$0: This input file is not composed of Arcs: $@" 1>&2
            exit 1
        fi
    ) | \
    sed 's/[ \+]*//' | \
    egrep '^\(' | \
    sed 's/^\(.*\)Ring *$/\n\1/' | \
    sed 's/[()]//g' | \
    awk -F',' ' { print $1, $2 }' | \
    double