#!/bin/bash

cat > $2 << ENDL
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Document>
    <name>Portland Bike Parking</name>
    <Style id="icon">
      <IconStyle>
        <Icon>
          <href>dot.png</href>
        </Icon>
        <hotSpot x="15" y="17" xunits="pixels" yunits="pixels"/>
      </IconStyle>
    </Style>
ENDL

cat $1 | while IFS=: read lineno lat lng; do
	STATS=$(grep "^${lineno}:" $3)
	NUM_SPACES=$(echo $STATS | cut -d : -f 2)
	NUM_UNITS=$(echo $STATS | cut -d : -f 3)
	STYLE=$(echo $STATS | cut -d : -f 4 | sed -e 's/.* - //g')
	COVERED=$(echo $STATS | cut -d : -f 5 | sed -e 's/.* - //g')
	if [ -z "$NUM_SPACES" ]; then
		NUM_SPACES=1
	fi
	if [ -z "$NUM_UNITS" ]; then
		NUM_UNITS=1
	fi
	HASH=$(echo -n "$lat:$lng" | md5sum | cut -d ' ' -f 1)
	ADDR=$(grep formatted_address "cache/$HASH.geo" | head -1 | sed -e 's/^.*": "//g' -e 's/",$//g')
	cat >> $2 << ENDL
    <Placemark>
      <name>$ADDR</name>
      <description><![CDATA[<br />
<b># of Spaces:</b> $NUM_SPACES<br />
<b># of Units:</b> $NUM_UNITS<br />
<b>Style:</b> $STYLE<br />
<b>Covered:</b> $COVERED<br />
<b>Location:</b> $lat, $lng<br />
]]></description>
      <Point>
        <coordinates>$lng,$lat,0</coordinates>
      </Point>
      <styleUrl>#icon</styleUrl>
    </Placemark>
ENDL
done

cat >> $2 << ENDL
  </Document>
</kml>
ENDL
