import numpy as np
import csv
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import glob
import os
from matplotlib.ticker import MaxNLocator
from matplotlib import rc, rcParams
from numpy.random import uniform, seed
from matplotlib.mlab import griddata
from numpy import arange,array,ones#,random,linalg
from pylab import plot,show
import simplekml
import seawater.gibbs as gsw
from numpy import linalg as LA
import math

os.chdir('/data/orbprocess_mail/alex/data/type')
fullnames = glob.glob('Full*')
gradnames = glob.glob('Grad*')
infonames = glob.glob('Text*')
arraylen =  len(fullnames)
floatdate = np.zeros(arraylen)
lat = [None]*arraylen
lon = [None]*arraylen
day = np.zeros(arraylen)
month=[None]*arraylen
year=[None]*arraylen
daystr=[None]*arraylen

for d in range(0,int(arraylen)):
	f = open(infonames[d], 'r')
	while 1:
		line = f.readline()
		if line[:4] == "Date":
			month[d] = str(line[5:7])
			day[d] = int(line[8:10])
			daystr[d] = str(line[8:10])
			year[d] = str(line[11:15])
			break
	f = open(infonames[d], 'r')
	while 1:
		line = f.readline()
		if line[:3] == "Lat":
			lat[d] = str(line[5:12])
			break
	f = open(infonames[d], 'r')
	while 1:
		line = f.readline()
		if line[:3] == "Lon":
			lon[d] = str(line[5:12])
			break
	
	if (year[d] == '2013'):
		yr = 0
	elif (year[d] == '2014'):
		yr = 365
	elif (year[d] == '2015'):
		yr = 365*2


	if(month[d] == '01'):
		mon = 0
	elif(month[d] == '02'):
		mon = 31
	elif(month[d] == '03'):
		mon = 31 + 28
	elif(month[d] == '04'):
		mon = (31 + 28 + 31)
	elif(month[d] == '05'):
		mon = (31 + 28 + 31 + 30)
	elif(month[d] == '06'):
		mon = (31 + 28 + 31 + 30 + 31)
	elif(month[d] == '07'):
		mon = (31 + 28 + 31 + 30 + 31 + 30)
	elif(month[d] == '08'):
		mon = (31 + 28 + 31 + 30 + 31 + 30 + 31)
	elif(month[d] == '09'):
		mon = (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31)
	elif(month[d] == '10'):
		mon = (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30)
	elif(month[d] == '11'):
		mon = (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31)
	elif(month[d] == '12'):
		mon = (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30)
	else:
		print 'invalid month'

	floatdate[d] = yr + mon + day[d]


def csvread(filename):
	with open(filename, 'rb') as f:
	    reader = csv.reader(f, delimiter=',')
	    nrow = 0;
	    for row in reader:
	    	nrow = nrow +1
	    	ncol = len(row)
	array = np.zeros([ncol,nrow]) 
	with open(filename, 'rb') as f:
	    reader = csv.reader(f, delimiter=',')
	    counter = 0
	    for row in reader:
	    	for jj in range(ncol - 1):
	    		array[jj,counter] = row[jj]
	    	counter = counter + 1
	return array, nrow, ncol  


def dataread(filename, arraylength, items,xnum):
	#
	# An array with each of the row lengths from each file
	rowlengths = np.zeros(arraylength)
	#
	# Looping over all the files
	for r in range(0,int(arraylength)):
		#
		# Calls the csvread function to parse and extra the data from a csv file
		dataout, rows, cols = csvread('/data/orbprocess_mail/alex/data/type/' + filename[r])
		#
		# Tell the row lengths array how many rows this file had
		rowlengths[r] = rows
		#
		# Counter 
	 	# countp = 0
	 	#
	 	# If it is the first file, we need to do something differently, else rock and roll
	 	if r == 0:
	 		#
	 		# Initial or "old" data array.  Initialize it here with dim for first file. Updated later as we loop
	 		data0 = np.zeros((items,rows))
	 		#
	 		# Dump data to the data0 array
	 		for init in range(0,int(rows)):
	 			data0[0,init] = xnum[r] # xnum
	 			data0[1,init] = dataout[0,init] # depth
	 			data0[2,init] = dataout[1,init] # temperature
	 			data0[3,init] = dataout[2,init] # density
	 			data0[4,init] = dataout[3,init] # salinity
	 			data0[5,init] = dataout[4,init] # pressure
	 			data0[6,init] = dataout[5,init] # oxygen solubility
	 			data0[7,init] = dataout[7,init] # oxygen concentration
	 			data0[8,init] = dataout[9,init] # oxygen saturation
	 			data0[9,init] = dataout[10,init] # CO2 solubility
	 			data0[10,init] = dataout[11,init] # borophyll
	 			data0[11,init] = dataout[12,init] # backscatter
	 			data0[12,init] = dataout[13,init] # CDOM
	 	else:
	 		#
	 		# Length all subsquent files combined
	 		prevlen = len(data0[0,:])
	 		#
	 		# Length of this file plus all subsequent files combined
	 		newlen = prevlen + rows
			#
			# Initialize the data file
			data = np.zeros((items,newlen))
			#
			# Fill data file with data from subsequent files in data0.  First loop over rows
			for p in range(0, int(prevlen)):
				#
				# Loop over columns
				for dd in range(0, int(items)):
					data[dd,p] = data0[dd,p]
			#
			# Counter to figure out how many rows total were in data0; maybe not needed
			countp = prevlen
			#
			# Fill the end of the data file with the current data
			for pp in range(0, int(rows)):
				ppp = countp + pp
	 			data[0,ppp] = xnum[r] # xnum
	 			data[1,ppp] = dataout[0,pp] # depth
	 			data[2,ppp] = dataout[1,pp] # temperature
	 			data[3,ppp] = dataout[2,pp] # density
	 			data[4,ppp] = dataout[3,pp] # salinity
	 			data[5,ppp] = dataout[4,pp] # pressure
	 			data[6,ppp] = dataout[5,pp] # oxygen solubility
	 			data[7,ppp] = dataout[7,pp] # oxygen concentration
	 			data[8,ppp] = dataout[9,pp] # oxygen saturation
	 			data[9,ppp] = dataout[10,pp] # CO2 solubility
	 			data[10,ppp] = dataout[11,pp] # borophyll
	 			data[11,ppp] = dataout[12,pp] # backscatter
	 			data[12,ppp] = dataout[13,pp] # CDOM
	 		data0 = data
	return data, rowlengths

data, fullarray_rowlengths = dataread(fullnames, arraylen, 13,floatdate)


data2  = data.T
temp = data2[:,2]
salt = data2[:,4]
dep = data2[:,1]

# Figure out boudaries (mins and maxs)
smin = salt.min() - (0.01 * salt.min())
smax = salt.max() + (0.01 * salt.max())
tmin = temp.min() - (0.1 * temp.max())
tmax = temp.max() + (0.1 * temp.max())
 
print tmin 
print tmax
print smin
print smax
# Calculate how many gridcells we need in the x and y dimensions
xdim = round((smax-smin)/0.1+1,0)
ydim = math.ceil((tmax-tmin)+1)
 
# Create empty grid of zeros
dens = np.zeros((ydim,xdim))
 
# Create temp and salt vectors of appropiate dimensions
ti = np.linspace(tmin,tmax,ydim)
si = np.linspace(smin,smax,xdim)
 
# Loop to fill in grid with densities
for j in range(0,int(ydim)):
    for i in range(0, int(xdim)):
        dens[j,i]=gsw.rho(si[i],ti[j],0)
 
# Substract 1000 to convert to sigma-t
dens = dens - 1000
 
# Plot data ***********************************************
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
CS = plt.contour(si,ti,dens, linestyles='dashed', colors='k')
plt.clabel(CS, fontsize=12, inline=1, fmt='%1.1f') # Label every second level

llll = len(temp)
dotcolor = [None]*llll
for i in range(0,llll):
	if (dep[i] <= -1500.):
		dotcolor[i] = '#6633FF'
	elif ((dep[i] > -1500.0) and (dep[i] <= -1250.0)):
		dotcolor[i] = '#CC33FF'
	elif ((dep[i] > -1250.0) and (dep[i] <= -1000.0)):
		dotcolor[i] = '#FF33CC'
	elif ((dep[i] > -1000.0) and (dep[i] <= -750.0)):
		dotcolor[i] = '#003DF5'
	elif ((dep[i] > -750.0) and (dep[i] <= -500.0)):
		dotcolor[i] = '#33CCFF'
	elif ((dep[i] > -500.0) and (dep[i] <= -250.0)):
		dotcolor[i] = '#33FF66'
	elif ((dep[i] > -250.0) and (dep[i] <= -150.0)):
		dotcolor[i] = '#CCFF33'
	elif ((dep[i] > -150.0) and (dep[i] <= -125.0)):
		dotcolor[i] = '#FFCC33'
	elif ((dep[i] > -125.0) and (dep[i] <= -100.0)):
		dotcolor[i] = '#F5B800'
	elif ((dep[i] > -100.0) and (dep[i] <= -75.0)):
		dotcolor[i] = '#FF6633'
	elif ((dep[i] > -75.0) and (dep[i] <= -50.0)):
		dotcolor[i] = '#FF3366'
	elif ((dep[i] > -50.0) and (dep[i] <= -25.0)):
		dotcolor[i] = '#B88A00'
	elif ((dep[i] > -25.0) and (dep[i] <= 0.0)):
		dotcolor[i] = '#000000'

CS1 = ax1.scatter(salt,temp, c = dotcolor)
fig1.colorbar(CS1)
ax1.set_xlabel('Salinity')
ax1.set_ylabel('Temperature (C)')
fig1.suptitle('T-S Diagram')
fig1.savefig("/data/orbprocess_mail/alex/tsdiag" + ".png")