#!/usr/bin/env python
'''
process_cast.py castnumber
USAGE:
c:\> python process_cast.py castlabel
Example:
c:\> python process_cast.py 001
DESCRIPTION: 
Look for the mark scan information, edit the Data Conversion Programs
and process the cast for Hydro and LADCP.
'''
# process_cast.py castnumber
# USAGE:
# c:\> python process_cast.py castlabel
# Example:
# c:\> python process_cast.py 001
# DESCRIPTION: 
# Look for the mark scan information, edit the Data Conversion Programs
# and process the cast for Hydro and LADCP.

__author__ = "Derrick Snowden <derrick.snowden@noaa.gov>"

def make_mark_scan_log(ctd_dir,mark_file_name,ctd_file_stub):
	"""Create a mark scan log from all of the *.mrk files in ctd_dir"""
	print 'In make_mark_scan_log'
	
	raw_data = os.path.join(ctd_dir,'1-BRUTOS')
	out_log = file(mark_file_name,'w')
	#for fullpath in os.listdir(os.getcwd()):
	for partialpath in os.listdir(raw_data):
		fullpath = os.path.join(raw_data,partialpath)
		path, fullname = os.path.split(fullpath)
		#print "Path: %s, Filename: %s" % (path,fullname)
		basename,ext = os.path.splitext(fullname)
		#print "Basename: %s, Extension: %s" % (basename, ext)
		ext = ext.lstrip('.').lower()
		if ext in "mrk" and ext not in "":
			#print "Mark file found: %s" % fullname
			#station = basename.lower()[-3:]
			station = basename.upper()
			station = station.replace(ctd_file_stub,'')
			if station in "2up":
				continue
			if station in "5up":
				continue
			f = file(fullpath)
			l1 = f.readline()
			tmp = f.readline()
			tmp = tmp.replace(',','').split()
			col_names = []
			for col in tmp:
				col_names.append(col.lstrip().rstrip().lower())
			l2 = f.readline()
			#if station.startswith('066'):
			#	# Skip two lines for this station with a double mark scan
			#	l2 = f.readline()
			#	l2 = f.readline()
			tmp = f.readline().split(',')
			col_values = []
			for col in tmp:
				col_values.append(col.lstrip().rstrip())
			col_names.append('station')
			col_values.append(station)
			D = dict(zip(col_names,col_values))
			#print D.keys()
			line = "%s %s %s %s %s\n" % (D['station'], D['scan'], D['depsm'], '9999', fullname)
			out_log.write(line)
			
	out_log.close()
	return D['station'], D['scan']


def determine_mark_scan(mark_file_name,this_cast_label):
	"""Grab the mark scan from the log in the mark_scan_log.txt file."""
	
	# 2. Read the mark scan log to determine how to alter the DatCnv.psa file for 
	# processing the downcast.
	print "Determining mark scan for this cast: %s" % this_cast_label
	fid = file(mark_file_name)
	#marks= fid.readlines()
	#fid.close()
	out_cast = None
	out_scan = None
	for line in fid.readlines():
		#print line.split()[0], line.split()[1]
		cast_label = line.split()[0].strip()
		scan_num = int(line.split()[1])
		if cast_label == this_cast_label:
			print cast_label, scan_num
			out_cast, out_scan = cast_label, scan_num
			break

	fid.close()
	return out_cast, out_scan
	
#######################################################################
import os, sys,time

# Cast num should be only input argument
this_cast_label = sys.argv[1].strip()

# Base directory is c:\CTDDATA\
base = os.environ['CTDPROC']
ctd_dir = os.path.join(base,'PIRA')
psa_dir = os.path.join(base,'PSA')
ctd_file_stub = 'PIRA_'  # data files are AB0804_001.dat etc.

# 1. Create the mark scan log in raw_data
mark_file_name = os.path.join(ctd_dir,'1-BRUTOS')
print mark_file_name
mark_file_name = os.path.join(mark_file_name,'mark_scan_log.txt')
print mark_file_name
cast_label, mark_scan_num = make_mark_scan_log(ctd_dir,mark_file_name,ctd_file_stub)

# 2. Determine the mark scan for the cast label input in argv
cast_label,mark_scan_num = determine_mark_scan(mark_file_name,this_cast_label)
print "exited determine_mark_scan with cast_label = %s" %cast_label
if cast_label is None:
	print "Unable to find mark scan for cast %s" % this_cast_label
	sys.exit()
	
print cast_label, mark_scan_num

print sys.argv[0], "Running station %s" % this_cast_label.strip()
print "Creating mark scan log"
#stat = os.system('python make_mark_scan_log.py ')

print "Editing DatCnv.psa for Hydro Processing"
print "Current this_cast_label is %s" % this_cast_label.strip()
print "Current cast_label is %s" % cast_label.strip()
cmd = "python edit_datcnv.py %03d" % mark_scan_num
print cmd
os.system(cmd)

#print "Editing DatCnv.psa for LADCP Processing"
#print "Current this_cast_label is %s" % this_cast_label.strip()
#print "Current cast_label is %s" % cast_label.strip()
#cmd = "python edit_datcnv_ladcp.py %03d" % mark_scan_num
#print cmd
#os.system(cmd)




# Now run the sbebatch
print "Beginning sbebatch"
print "Hydro Batch"
cmd = 'sbebatch PIRA_H39_HYDRO.txt %s' %cast_label
#cmd = 'SBEBatch D:\COMISSOES\2017\2-PIRATA_XVII\DADOS\PIRA_H39_HYDRO.txt %s' %cast_label
os.system(cmd)
#time.sleep(10)
#print "LADCP Batch"
#cmd = "sbebatch C:\DATA\AB0904\ADCP\ABACO_APR_2009_LADCP.dat %s" % #cast_label
#os.system(cmd)

