#!/usr/bin/python
#
# Download "Bett & Bike" POI from the Web 
# and write in CSV Format for Garmin PoiLoader
#
import urllib
import sys
import time

MINlon=47.25
MAXlon=55.25
INC=0.25
BaseURL='http://www.adfc-tourenportal.de/poi.php?cmd=bettbike&bbox='
BBox='%.2f,5.86,%.2f,15.04'
Outfile='Bett & Bike.csv'

# Alle keys of "Bett & Bike" data
knr='knr'
bild='bild'
name='name'
str='str'
plz='plz'
ort='ort'
buland='buland'
sterne='sterne'
vorwahl='vorwahl'
tel='tel'
internet='internet'
lat='lat'
lng='lng'

# open output file line buffered
ofd = open(Outfile,'w+',1)

# Iteration over germany in stripes of 0.25 degrees longitude
lon1=MINlon
while lon1 < MAXlon:
  lon2 = lon1 + INC

  curBox = BBox % (lon1,lon2)
  URL = BaseURL + curBox
  sys.stdout.write("download BBox: %s... " % curBox)
  sys.stdout.flush()

  data = ""  
  while data == "":
    data = urllib.urlopen(URL).read()
    if (data == ""):
      sys.stderr.write("\nFehler beim download, wiederhole: %s... " % curBox)
      time.sleep(1)

  # das Ergebnis sieht fast aus wie ein dictionary,
  # der folgende Befehl macht eines draus
  lall=eval('['+data.partition('[')[2].partition(']')[0]+']')

  for poi in lall:
    poi[name] = poi[name].replace('&amp;','&')
    poi[name] = poi[name].replace('&quot;','\"')

    addr="\""

    nsterne = int(poi[sterne])    
    for x in range(0,nsterne):
      addr = addr + '*'    
      
    if (nsterne >0):
      addr = addr + '\n'
    
    if (poi[str] != ""):
      addr = addr+'%s\n%s %s\n%s/%s\"\n' % (poi[str],poi[plz],poi[ort],poi[vorwahl],poi[tel])
    else:
      addr = addr+'%s %s\n%s/%s\"\n' % (poi[plz],poi[ort],poi[vorwahl],poi[tel])

    out='%s,%s,\"%s\",%s' % (poi[lng],poi[lat],poi[name],addr)
    # bytestring to unicode (input is utf-8)
    out = out.decode('utf-8')
    # unicode to latin-1 (neded by
    ofd.write(out.encode('latin1'))

  time.sleep(1)
  sys.stdout.write("OK.\n")
  sys.stdout.flush()
  lon1 = lon2

ofd.close()

