#!/bin/bash
# $Id: getPlaceNamesByZip.sh 175 2007-04-17 18:33:45Z mark $
# Author: Mark Thomas
# Description: Simple shell script that takes a 5-digit zip code as an input
#   then searches the USPS for the city and state associated with that zip.
#   The script outputs the actual city name associated with the specified
#   zip according to the USPS.  "Acceptable" names are not returned.

URL="http://zip4.usps.com/zip4/zcl_3_results.jsp"
PARAM_NAME="zip5"

cat > t.conf << EOF
output-xml: yes
add-xml-decl: no
doctype: omit
char-encoding: ascii
indent: auto
wrap: 120
bare: yes
clean: yes
word-2000: yes
repeated-attributes: keep-last
error-file: errs.txt
drop-empty-paras: yes
drop-font-tags: yes
drop-proprietary-attributes: yes
alt-text: foo
numeric-entities: yes
tab-size: 4
EOF

CITY_STATE=`curl -s -G -d "${PARAM_NAME}=${1}" $URL | \
    tidy -config t.conf | \
    xml sel -t -m "//td[@headers = 'pre'][1]" -v "b" | \
    sed 's/, /,/g'`

# Alteratively, you can use this if you don't have xmlstarlet installed,
# but do have xsltproc installed
#
# cat > t.xsl << EOF
# <?xml version="1.0" encoding="UTF-8"?>
# <xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
# <xsl:output method="text" indent="no"/>
# <xsl:strip-space elements="*"/>
# <xsl:template match="/">
# <xsl:value-of select="//td[@headers = 'pre'][1]/b"/>
# </xsl:template>
# </xsl:transform>
# EOF
#
# CITY_STATE=`curl -s -G -d "${PARAM_NAME}=${1}" $URL | \
#     tidy -config t.conf | \
#     xsltproc t.xsl - | \
#     sed 's/, /,/g'`

echo "${CITY_STATE},${1}"


