#!/bin/bash

IFS=,
while read city airport ; do
  f="cache/$city.geonames"
  if [ ! -f "$f" ] ; then
    curl 'http://www.geonames.org/search.html?q='$city'&country=IE' 2>/dev/null > "$f"
  fi
  lat=$(cat "$f" | grep latitude | head -1 | awk -F '>' '{print $20}' | sed 's/<\/span//')
  long=$(cat "$f" | grep latitude | head -1 | awk -F '>' '{print $22}' | sed 's/<\/span//')
  if [ "$long" = "<td" ] ; then
    lat=$(cat "$f" | grep latitude | head -1 | awk -F '>' '{print $17}' | sed 's/<\/span//')
    long=$(cat "$f" | grep latitude | head -1 | awk -F '>' '{print $19}' | sed 's/<\/span//')
  fi
  #echo $city $lat $long
  echo '<city>'
  echo '  <name>'$city'</name>'
  echo '  <coordinates>'$lat $long'</coordinates>'
  echo '  <location>'

  ad=cache/$airport.data 
  if [ ! -f "$ad" ] ; then
    IFS=,
    grep -n $airport airports.list > $ad
  fi
  read airport1 apn apc < $ad

  echo '    <name>'$apn'</name>'
  echo '    <code>'$airport'</code>'
  echo '    <coordinates>'$apc'</coordinates>'

  echo '  </location>'
  echo '</city>'

done < towns.list
