#!/usr/bin/env python
# r.out.geotiffz
#%Module 
#%  description: Mass raster export to GTiff
#%  keywords: raster
#%End
#%Option
#%  key: pattern
#%  type: string
#%  required: no
#%  key_desc: name
#%  description: Pattern to select rasters
#%End
#%Option
#%  key: path
#%  type: string
#%  required: yes
#%  key_desc: name
#%  description: Path to export rasters
#%End


import os

try:
    import grass.script as grass
except:
    try:
        from grass.script import core as grass
    except:
        if not os.environ.has_key("GISBASE"):
            print "You must be in GRASS GIS to run this program."
            sys.exit(1)



def main():
    pattern = options['pattern']
    out_path = options['path']
    ext = '.tif'
    mapset = grass.gisenv()['MAPSET']
    
    if not os.path.exists(out_path):
        grass.fatal(_("Output path not exists!"))
    
    if not pattern:
        pattern = '*'

    for rast in grass.read_command("g.mlist", type = "rast", pattern = pattern,
                                   mapset = mapset).splitlines():
		name = rast + ext
		outf = os.path.join(out_path,name)
		
		grass.run_command("g.region", rast = rast, quiet = True)
		grass.run_command("r.out.gdal", _input = rast, _format = "GTiff",
						  output = outf, quiet = True)
		
        
        
if __name__ == "__main__":
    options, flags = grass.parser()
    main()
