#!/usr/bin/python
import sys
import pexpect
import re
import time
import math
import mapscript
import os
import gdal
import urllib
import struct
from gdalconst import *

def spawn(mapset):
	grassp='su user -c "grass60 -text '+mapset+'"'
	child=pexpect.spawn(grassp)
	child.expect("Password:")
	time.sleep(0.1)
	child.sendline("xxx")
	e=child.expect(['>','allowed'])
	if e==0:
		return child
	else:
		return 0
		
def g_region(extent,child,mapset):
	if child==0:
		child=spawn(mapset)
	g_region='g.region n='+str(extent[3])+' s='+str(extent[1])+' w='+str(extent[0])+' e='+str(extent[2])
	print g_region
	child.sendline('cd ~')
	child.expect('>')
	child.sendline(g_region)
	child.expect('>')
	
def r_what(layer,east_north_list):
	coords=[] #Defining list for coords
	dataset = gdal.Open(layer, GA_ReadOnly )
	geotransform = dataset.GetGeoTransform()
	band = dataset.GetRasterBand(1)
	for u in east_north_list:
		c=u.split(',')
		pix_x=int(round(((float(c[0])-geotransform[0])/geotransform[1]),0))
		pix_y=int(round(((geotransform[3]-float(c[1]))/geotransform[1]),0))
		scanline = band.ReadRaster(pix_x,pix_y, 1, 1, 1, 1, GDT_Float32 )
		z = struct.unpack('f' * 1, scanline)
		xyz=[float(c[0]),float(c[1]),z[0]]
		coords.append(xyz)
	return coords
	
def write_tag(type,ns,tag,attr,depth,n):
	str=''
	for i in range(depth):
			str=str+' '
	if ns!='null':
		tag=ns+":"+tag;
	str=str+'<'
	if type=="close":
		str=str+'/'
	str=str+tag
	if attr!='null':
		for key, value in attr.iteritems():
			str=str+ ' '+key+'="'+value+'"'
	if type=="selfclose":
		str=str+'/'
  	str=str+'>'
	if n=='true':
		str=str+'\n'
	return str
	
print g_region([90,-90,90,90],0,"/var/grassdata/wgs84/PERMANENT")
