# scale an image for google maps at any given zoom level using python image library
# googletilecutter-0.11.sh downloaded from 
# the math used was taken from http://facstaff.unca.edu/mcmcclur/GoogleMaps/Projections/GoogleCoords.html
# python image library code taken from http://www.daniweb.com/code/snippet216637.html
# python image library downloaded with "sudo apt-get install python-imaging"
# usage python tile.py {imagefile} {lat1,lon1} {lat2,lon2} {zoom}

import sys
import Image
import os
import math

def latlon2xy(z,lat,lon):
    x,y = latlon2px(z,lat,lon)
    x = int(x/256),int(x%256)
    y = int(y/256),int(y%256)
    return x,y

def latlon2px(z,lat,lon):
    x = 2**z*(lon+180)/360*256
    y = -(.5*math.log((1+math.sin(math.radians(lat)))/(1-math.sin(math.radians(lat))))/math.pi-1)*256*2**(z-1)     #hyper complex Mercator projection super trig... blech!
    return x,y

imageFile = sys.argv[1]
imageName = imageFile.split('/')[-1]
imageDir = '/'.join(imageFile.split('/')[:-1])
latlon1 = eval(sys.argv[2])
latlon2 = eval(sys.argv[3])
img = Image.open(imageFile)
size = img.size
prev = (1,2)
newImage = 'arst'
cutter = '/home/fish/utils/googletilecutter-0.11.sh'

for z in range(5,12):    #zoom levels 5-12
    px1 = latlon2px(z,*latlon1)
    px2 = latlon2px(z,*latlon2)
    width = int(px2[0]-px1[0])
    height = int(px2[1]-px1[1])
    x,y = latlon2xy(z,*latlon1)
    tile = '%s,%s'%(x[0],y[0])
    padding = '%s,%s'%(x[1],y[1])
    try:
        os.mkdir(os.path.join(imageDir,str(z)))
    except:
        pass
    os.chdir(os.path.join(imageDir,str(z)))
    if size[0]*1.5<width or size[1]*1.5<height:
        img5 = img
    else:
        img5 = img.resize((width, height), Image.NEAREST)
    newImage = os.path.join(os.getcwd(),imageName[:-4]+"-%s"%z+imageName[-4:])
    img5.save(imageName[:-4]+"-%s"%z+imageName[-4:])
    print 'cd '+os.getcwd()
    print '%s -o %s -t %s -z %s -p %s %s'%(cutter,z,tile,z,padding,newImage)
    prev = tile,padding

