# Create KML files from the <filename>.places file
doitfile="kmldoit.places"
outfile="kmldoit.work"
gotmyfile="kmldoit.gotmy"
gotusfile="kmldoit.gotus"
notfile="kmldoit.notfound"
tmpfile="kmldoit.tmp"
parm="$1"
if [ "$parm" = "" ] ; then
   infile="$doitfile"
else
   infile="$parm"
fi
if [ ! -f $infile ] ; then
   echo "Cannot find $infile, aborting"
   exit 1
fi
echo "Checking file: $infile"
rm -f $outfile
rm -f $notfile
rm -f $gotmyfile
rm -f $gotusfile
f=0
n=0
while read line ; do
        gotp=0
        f1=`echo "$line" | cut -d ":" -f 1`
        key=`echo "$f1" | cut -d " " -f 1`
        type=`echo "$f1" | cut -d " " -f 2`
        dat=`echo "$f1" | cut -d " " -f 3-`
        plac=`echo "$line" | cut -d ":" -f 2`
#        echo "key=$key"
#        echo "type=$type"
#        echo "dat=$dat"
#        echo "plac=$plac"
#        echo "reading $plac"
        gotline=`grep "$plac" mylatlong.txt | head -1`
	if [ "$gotline" != "" ] ; then
#	    echo "found MY $line"
           echo "$gotline" >>$gotmyfile
           f=`expr $f + 1`
           gotp=1
        else
           u=`echo "$plac" | grep "United States"`
           if [ "$u" != "" ] ; then 
#              echo "reading $plac"
              city=`echo "$plac" | cut -c 1-2`
              if [ $city != "#," ] ; then
#                 echo "checking $city"
                 gotline=`grep "$plac" uslatlong.txt | head -1`
	         if [ "$gotline" != "" ] ; then
# 	             echo "found US $line"
                    echo "$gotline" >>$gotusfile
                    f=`expr $f + 1`
                    gotp=1
                 else
                    n=`expr $n + 1`
                    echo "Ignoring NOT found $line"
                    echo "$line" >>$notfile
                 fi
              else
                 n=`expr $n + 1`
                 echo "Ignoring NOT found $line"
                 echo "$line" >>$notfile
              fi
           else
              n=`expr $n + 1`
              echo "Ignoring NOT found $line"
              echo "$line" >>$notfile
           fi
	fi
        if [ $gotp = 1 ] ; then
           echo "$key $type $dat :$gotline" >>$outfile
        fi
done < $infile
echo "$f places found"
echo "$n places not found"
sort -u $gotmyfile >$tmpfile
rm $gotmyfile
mv $tmpfile $gotmyfile
sort -u $gotusfile >$tmpfile
rm $gotusfile
mv $tmpfile $gotusfile
cnt=`cat $outfile | wc -l`
echo "File $outfile has $cnt entries"
./kmlgen.pl