import sys
import VisaDriver
import time
import string
import os
import matplotlib.pyplot as plt
import RedLine as rl


def getSerial():
	serial_entry = '0'
	if len(sys.argv) > 1:
		serial_entry = sys.argv[1]
	return serial_entry

def getTraceName():
	serial_entry = '000000000'
	if len(sys.argv) > 1:
		serial_entry = string.zfill(sys.argv[1], 9)
	label = time.strftime("%Y%m%d%H%M%S__" + serial_entry)
	if len(sys.argv) > 2:
		for arg_value in sys.argv[2:]:
			label = label + "_" + arg_value
			
	return label

def createDirectory(trace_sn):
	my_path = "I:\\common\\tests\\isfetCT\\" + trace_sn
	if not os.path.exists(my_path):
		os.makedirs(my_path)

def dataToFile(tracer_data, trace_name, trace_sn, channel):
	dataFile = open("I:\\common\\tests\\isfetCT\\" + trace_sn + "\\" + trace_name + "_" + channel + ".txt", 'w+')
	for dataPoint in tracer_data:
		print>>dataFile, dataPoint
	dataFile.close()
	
def dataFromFile(trace_name, trace_sn, channel):
	dataFile = open("I:\\common\\tests\\isfetCT\\" + trace_sn + "\\" + trace_name + "_" + channel + ".txt", 'r')
	my_data = []
	for dataPoint in dataFile:
		my_data.append(dataPoint.strip())
	dataFile.close()
	return my_data
	
def dataAppendCsv(tracer_data_A, tracer_data_B, trace_name, trace_sn):
	i_data_a = []
	i_data_b = []
	
	for ia in tracer_data_A:
		i_data_a.append(-1.0 * float(ia))
		
	for ib in tracer_data_B:
		i_data_b.append(-1.0 * float(ib))
		
	leakage_A = abs(min(i_data_a))
	leakage_B = abs(min(i_data_b))
	
	try:
		csvFile = open("I:\\common\\tests\\isfetCT\\historic_isfet_data.csv", 'a+')
		csvFile.write(time.strftime("%m/%d/%Y,"))
		csvFile.write("%s,"%trace_sn)
		csvFile.write("%e,"%leakage_A)
		csvFile.write("%e,"%leakage_B)
		csvFile.write("%s\n"%trace_name)
		csvFile.close()
	except:
		print('csv is open my dudes')
	
	
	

def dataToPlot(tracer_data_A, tracer_data_B, trace_name, trace_sn):
	v_data = []
	i_data_a = []
	i_data_b = []
	for v in range(-25, 26, 1):
		v_data.append(float(v)/5.0)
		
	for ia in tracer_data_A:
		i_data_a.append(-1.0 * float(ia))
		
	for ib in tracer_data_B:
		i_data_b.append(-1.0 * float(ib))
		
	my_title = trace_name
	fail = 0
	if min(i_data_a) < rl.getLeakageSpec():
		my_title = my_title + "\nA channel exceeds leakage spec"
		fail += 1
	if min(i_data_b) < rl.getLeakageSpec():
		my_title = my_title + "\nB channel exceeds leakage spec"
		fail += 1
	if fail == 0:
		my_title += "\n\nPASS"
	
	plt.figure(figsize = [9.6, 9.6])
	plt.suptitle(my_title)
	
	plt.subplot(221)
	plt.title("A: %eA" %abs(min(i_data_a)))
	plt.plot(v_data, i_data_a)
	plt.xlabel("v (V)")
	plt.ylabel("i (A)")
	plt.xlim(-5, 5)
	plt.grid(True)

	plt.subplot(223)
	plt.plot(v_data, i_data_a)
	plt.xlabel("v (V)")
	plt.ylabel("i (A)")
	plt.xlim(-5, 0)
	plt.ylim(-1.0 * abs(min(i_data_a)), 0)
	print rl.getLeakageSpec()
	plt.axhline(rl.getLeakageSpec(), linewidth=4, color='r')
	plt.grid(True)
	
	plt.subplot(222)
	plt.title("B: %eA" %abs(min(i_data_b)))
	plt.plot(v_data, i_data_b)
	plt.xlabel("v (V)")
	plt.ylabel("i (A)")
	plt.xlim(-5, 5)
	plt.grid(True)

	plt.subplot(224)
	plt.plot(v_data, i_data_b)
	plt.xlabel("v (V)")
	plt.ylabel("i (A)")
	plt.xlim(-5, 0)
	plt.ylim(-1.0 * abs(min(i_data_b)), 0)
	plt.axhline(rl.getLeakageSpec(), linewidth=4, color='r')
	plt.grid(True)
	
	plt.draw()
	
	plt.savefig("I:\\common\\tests\\isfetCT\\" + trace_sn + "\\" + trace_name + "_curves.png")
	plt.show()

	

def tracerConnect():
	hp = VisaDriver.GetInstrument("HP4145B", "*IDN?")
	hp_inst = VisaDriver.OpenInstrument(hp)
	return hp_inst
	
def tracerDisconnect(tracer):
	VisaDriver.CloseInstrument(tracer)

def tracerRunAndWait(tracer, channel):
	if channel == 'A' or channel == 'B': 

		VisaDriver.WriteData(tracer, "GT\'P TRACE" + channel + "\'")
		VisaDriver.WriteData(tracer, "BC")
		VisaDriver.WriteData(tracer, "MD")
		VisaDriver.WriteData(tracer, "IT3")
		VisaDriver.WriteData(tracer, "ME1")
		
		time.sleep(16)

def tracerGetData(tracer):
	ret = None
	
	while ret == None:
		VisaDriver.WriteData(tracer, "DO\'ITEST\'")
		ret = VisaDriver.ReadData(tracer)
		
	data_str = string.split(ret[0], ',')
	data_flt = []
	
	for value in data_str:
		value = value.replace('N','')
		value = value.replace('C','')
		value = value.replace('X','')
		data_flt.append(float(value))
	
	return data_flt