#-------------------------------------------------------------------------------
# Name:			Sediment Wedge Model Generator Aug 2013 Part V.py
# Purpose:
#
#
# Author:		Dr. Arghya Goswami
# Contact:		arghya.goswami@gmail.com
#
# Created:		06/08/2013
#
# Copyright:	(c) Dr. Arghya Goswami 2013
#
# Licence:		This program is free software; you can redistribute it and/or
#				modify it under the terms of the GNU General Public License,
#				version 2, as published by the Free Software Foundation.
#
#				This program is distributed in the hope that it will be useful,
#				but WITHOUT ANY WARRANTY; without even the implied warranty of
#				MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#				GNU General Public License for more details.
#
#				You should have received a copy of the GNU General Public License
#				along with this program; if not, write to:
#
#				Free Software Foundation, Inc.,
#				51 Franklin St, Fifth Floor,
#				Boston, MA, 02110-1301  USA
#-------------------------------------------------------------------------------
#!/usr/bin/env python
#
#-------------------------------------------------------------------------------
import arcpy, sets, numpy, sys, os, shutil, glob, time, fileinput, string, Tkinter, tkFileDialog
from operator import itemgetter
from Tkinter import *
from arcpy.sa import *
"""-----------------------------------------------------------------------------
# Start Time
-----------------------------------------------------------------------------"""
StartTime = time.asctime(time.localtime(time.time()))
print "Start Time: ", StartTime,"\n"
"""-----------------------------------------------------------------------------
# Check Script name
-----------------------------------------------------------------------------"""
#scriptname = os.path.basename(__file__)
#if "module" in scriptname:
#	print "Please SAVE the script with a Meaningful NAME and RE-RUN!\n"
"""-----------------------------------------------------------------------------
# Definitions used in this Script
-----------------------------------------------------------------------------"""
""" Browse a file function """
def BrowseFile(msg1,indir,ext):
	#Creating Main Window
	root = Tk()
	if ext == "csv":
		desc1 = "Comma Seperated Value Files"
		desc2 = "*." + ext
	elif ext == "txt":
		desc1 = "Text Files"
		desc2 = "*." + ext
	elif ext == "shp":
		desc1 = "Shape Files"
		desc2 = "*." + ext
    # Creating Secondary Window for File Browsing
	filename = tkFileDialog.askopenfilename(filetypes = [(desc1,desc2),('All files','*')], title = msg1, initialdir = indir)
    # Close the Main Window
	root.withdraw()
    # Return Filename
	return filename

""" Browse a directory function """
def BrowseDir(msg2,indir):
    #Creating Main Window
	root = Tk()
    # Creating Secondary Window for Folder Browsing
	dirname = tkFileDialog.askdirectory(title = msg2, initialdir=indir)
    # Close the Main Window
	root.withdraw()
    # Return Dirname
	return dirname

""" Check the existance of a directory function """
def DirCheck(filename):
	# Check if the string is a file name or directory name
	if filename[len(filename)-4] == ".":
		dname = os.path.dirname(filename)
	else:
		dname = filename
	# Check if Dir exists, else create
	if os.path.exists(dname):
	    pass
	else:
	    os.mkdir(dname)
	# Check if the path name if Dir ends with a '/' else add it
	if dname[(len(dname)-1):]=="\\" or dname[(len(dname)-1):] == "/":
		dpath = dname
	else:
		dpath = dname + "/"
	return dpath

""" Returns field names in a shapefile """
def AllFields(infile):
	FieldNnames = []
	fields = arcpy.ListFields(infile)
	FieldNnames = []
	for field in fields:
		FieldNnames.append(field.name)
	return FieldNnames

""" Create the list of files in a folder """
def getFileList(root,ext):
	# for folder path either use "Browse"/"browse" or provide the path to a folder
	# for all filetypes send extention as an empty string (""), else use like ".csv"
	filelist = []
	if root == "Browse" or root == "browse":
		root = BrowseDir("Please select the Directory", "C:/")
	# select the type of file, for instance *.jpg or all files *.*
	for folder in glob.glob(root):
		print "Files in", folder, "is being populated to a list"
	if ext == "":
		ext = "/*.*"
	else:
		ext = "/*" + ext
	for file in glob.glob(folder + ext):
	# retrieves the stats for the current file as a tuple
	# (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)
	# the tuple element mtime at index 8 is the last-modified-date
		filelist.append(file)
	return filelist
	print "\nFile List Prepared, starting to list them......\n"
"""-----------------------------------------------------------------------------
# Main Script
-----------------------------------------------------------------------------"""
inFC= BrowseFile("Select input sediment layer","C:/OES/PaleoBathymetry/Projected Shapes/Averaged Distances/","csv")

# Open and read the input sediment file
fIn = open(inFC,'r')
fInText = fIn.readlines()
fIn.close()

SedType = raw_input("Please enter \"D\" for Divins & \"M\" for Muller")
Age = "000"

# Get output file name and open for writing
outFC = DirCheck(inFC) + "MLSC_" + SedType + Age + "2.csv"
fOut = open(outFC,'w')
RhoS = [1.67,1.74,1.81,1.88,1.95,2.02,2.09,2.16,2.23,2.3,2.37,2.44,2.51,2.58,2.65,2.72]

# Process data
lno = 1
for lines in fInText:
	line = lines.replace("\n","")
	sedtk = line.split(",")
	wline = ""
	for stk in sedtk:
		if stk == "NaN":
			dz = "NaN"
		else:
			dz = 0.0
			rCounter = 0
			sedpile = float(stk)
			while sedpile > 100 and rCounter <15:
				dz = dz + (100*((3300-(RhoS[rCounter]*1000))/2300))
				sedpile = sedpile - 100
				rCounter = rCounter + 1
			dz = round((dz + ((sedpile)*((3300-(RhoS[rCounter]*1000))/2300))),2)
		if wline == "":
			wline = str(dz)
		else:
			wline = wline + "," + str(dz)
	if lno == 1801:
		pass
	else:
		wline = wline + "\n"
	fOut.write(wline)
	lno = lno + 1
fOut.close()
print "complete"

"""-----------------------------------------------------------------------------
# End Time
-----------------------------------------------------------------------------"""
EndTime = time.asctime(time.localtime(time.time()))
print "\nEnd Time: ", EndTime,"\n"