#!/bin/sh

# This script is for downloading Openstreetmap tiles.

# example url of the tile in the topleft corner:
# http://c.tile.openstreetmap.org/17/66370/45082.png
# we need 5 tiles horizontally and 4 tiles vertically
# 
# ./osm-dl.sh 17 66370 66374 45082 45085

[ $# -lt 5 ] && exit 1

zoom=$1
x1=$2
x2=$3
y1=$4
y2=$5


xtiles=`echo $x2-$x1|bc`
ytiles=`echo $y2-$y1|bc`
tilecount=`echo $ytiles*$xtiles|bc`

echo "Settings for TTOPM:"
echo
echo "xtiles = $xtiles"
echo "ytiles = $ytiles"
echo "Tiles: $tilecount"

for y in `seq -s" " $y1 $y2`
do
  for x in `seq -s" " $x1 $x2`
  do
     mkdir -p ${zoom}/${x} 2>/dev/null
     filename=`echo ${zoom}/${x}/${y}.png`
     curlget="http://a.tile.openstreetmap.org/${zoom}/${x}/${y}.png -o ${filename}"
     echo -n "check for $filename"

     identify $filename 2>/dev/null |grep -s -q " PNG 256x256 " 
     if [ $? != 0 ]
     then
       echo " error"
       echo "  Lade $curlget"
       echo "    curl $curlget"
       curl --limit-rate 50K $curlget
     else 
       echo " ok"
     fi
  done
done

echo "Settings for TTOPM:"
echo
echo "xtiles = $xtiles"
echo "ytiles = $ytiles"
echo "zoom = $zoom"
echo "toplefttile_x = $x1"
echo "toplefttile_y = $y1"
