"""
   ulmo.util.raster
   ~~~~~~~~~~~~~~~~

   Collection of useful functions for raster manipulation
"""

import hashlib
from .misc import download_if_new
import os
import zipfile


def mosaic_and_clip(raster_tiles, xmin, ymin, xmax, ymax, output_path):
	from pyproj import Proj
	import rasterio
	import subprocess

	print 'Mosaic and clip to bounding box extents'
	output_vrt = os.path.splitext(output_path)[0] + '.vrt'
	print subprocess.check_output(['gdalbuildvrt', '-overwrite', output_vrt] + raster_tiles)
	# check crs
	with rasterio.drivers():
		with rasterio.open(output_vrt) as src:
			p = Proj(src.crs)

	if not p.is_latlong():
		[xmax, xmin],[ymax, ymin] = p([xmax, xmin],[ymax,ymin])

	print subprocess.check_output(['gdalwarp', '-overwrite', '-te', repr(xmin), repr(ymin), repr(xmax), repr(ymax), output_vrt, output_path])
	print 'Output raster saved at %s', output_path


def download_tiles(path, tile_urls, tile_fmt, check_modified=False):
	raster_tiles = []

	if isinstance(tile_urls, basestring):
		tile_urls = [tile_urls]

	for i, url in enumerate(tile_urls):
		filename = os.path.split(url)[-1]
		print '... downloading tile %s of %s from %s' % (i+1, len(tile_urls), url)
		tile_path = os.path.join(path, filename)
		if tile_fmt=='':
			download_if_new(url, tile_path, check_modified=check_modified)
		else:
			zip_path = os.path.join(path, 'zip', filename)
			download_if_new(url, zip_path, check_modified=check_modified)
			print '... ... zipfile saved at %s' % zip_path
			tile_path = extract_from_zip(zip_path, tile_path, tile_fmt)

		raster_tiles.append(tile_path)
	return raster_tiles


def extract_from_zip(zip_path, tile_path, tile_fmt):
    tile_path = os.path.splitext(tile_path)[0] + tile_fmt
    with zipfile.ZipFile(zip_path) as z:
        fname = [x for x in z.namelist() if tile_fmt in x[-4:]][0]
        with open(tile_path, 'w') as f:
            f.write(z.read(fname))
            print '... ... %s format raster saved at %s' % (tile_fmt, tile_path)

    return tile_path


def generate_raster_uid(layer, xmin, ymin, xmax, ymax):
	return hashlib.md5(','.join([layer, repr(xmin), repr(ymin), repr(xmax), repr(ymax)])).hexdigest()
@@ -149,16 +149,39 @@
 d_if_new
+, mkdir_if_doesnt_exist
 %0Aimport 
@@ -272,17 +272,20 @@
 _path):%0A
-%09
+    
 from pyp
@@ -300,17 +300,20 @@
 rt Proj%0A
-%09
+    
 import r
@@ -320,17 +320,20 @@
 asterio%0A
-%09
+    
 import s
@@ -343,17 +343,20 @@
 rocess%0A%0A
-%09
+    
 print 'M
@@ -395,17 +395,20 @@
 xtents'%0A
-%09
+    
 output_v
@@ -454,17 +454,20 @@
  '.vrt'%0A
-%09
+    
 print su
@@ -547,17 +547,20 @@
 _tiles)%0A
-%09
+    
 # check 
@@ -563,17 +563,20 @@
 eck crs%0A
-%09
+    
 with ras
@@ -592,18 +592,24 @@
 vers():%0A
-%09%09
+        
 with ras
@@ -639,19 +639,28 @@
 as src:%0A
-%09%09%09
+            
 p = Proj
@@ -670,17 +670,20 @@
 c.crs)%0A%0A
-%09
+    
 if not p
@@ -697,18 +697,24 @@
 long():%0A
-%09%09
+        
 %5Bxmax, x
@@ -762,17 +762,20 @@
 ymin%5D)%0A%0A
-%09
+    
 print su
@@ -904,17 +904,20 @@
 _path%5D)%0A
-%09
+    
 print 'O
@@ -1026,17 +1026,20 @@
 False):%0A
-%09
+    
 raster_t
@@ -1049,17 +1049,20 @@
 s = %5B%5D%0A%0A
-%09
+    
 if isins
@@ -1091,18 +1091,24 @@
 tring):%0A
-%09%09
+        
 tile_url
@@ -1124,17 +1124,20 @@
 _urls%5D%0A%0A
-%09
+    
 for i, u
@@ -1164,18 +1164,24 @@
 _urls):%0A
-%09%09
+        
 filename
@@ -1206,18 +1206,24 @@
 rl)%5B-1%5D%0A
-%09%09
+        
 print '.
@@ -1289,18 +1289,116 @@
 ), url)%0A
-%09%09
+        mkdir_if_doesnt_exist(path)%0A        mkdir_if_doesnt_exist(os.path.join(path,'zip'))%0A        
 tile_pat
@@ -1430,18 +1430,24 @@
 lename)%0A
-%09%09
+        
 if tile_
@@ -1455,19 +1455,28 @@
 mt=='':%0A
-%09%09%09
+            
 download
@@ -1534,19 +1534,34 @@
 ed)%0A
-%09%09else:%0A%09%09%09
+        else:%0A            
 zip_
@@ -1603,19 +1603,28 @@
 lename)%0A
-%09%09%09
+            
 download
@@ -1677,19 +1677,28 @@
 dified)%0A
-%09%09%09
+            
 print '.
@@ -1740,11 +1740,20 @@
 ath%0A
-%09%09%09
+            
 tile
@@ -1813,10 +1813,16 @@
 t)%0A%0A
-%09%09
+        
 rast
@@ -1848,17 +1848,20 @@
 e_path)%0A
-%09
+    
 return r
@@ -2333,9 +2333,12 @@
 x):%0A
-%09
+    
 retu

fix bug when dir doesn't exist