import math,sys,csv,scipy,numpy,Gnuplot,Gnuplot.funcutils, TRCurves151208#prior to 151211, used TRCurves150512
from scipy import integrate,special
from numpy import vectorize
#This script Reads RTD resistance measurements and corrects them using TRCurves151208 data to produce calibrated temperature measurements
filename=sys.argv[1]

######################################Older, Less Accurate Correction Method############################
#def Ch2Temp(R):#Returns calibrated (to Ch1 in 140904ControlTwoHeatingStepsFrom40K.txt) Ch2 temperature
#	m=2.432#K/Ohm
#	b=25.749#K
#	return m*R+b
	
#def Ch3Temp(R):#Returns calibrated (to Ch1 in 140904ControlTwoHeatingStepsFrom40K.txt) Ch3 temperature
#	m=2.510#K/Ohm
#	b=31.674#K
#	return m*R+b
#	#a=-0.00163949
#	#b=2.55149
#	#c=31.6116
#	#return a*R**2+b*R+c

#output = open(filename[:-4]+"Corrected.txt",'w')
#with open(filename,'r') as rdata:
#	reader=csv.reader(rdata,delimiter='\t')
#	for b,Ch1T,Ch2T,Ch3T,Ch4T,VoltAT,VoltBT,TimeT,x,RCh1,RCh2,RCh3,RCh4,y,y2 in reader:
#		Ch2=Ch2Temp(float(RCh2))
#		Ch3=Ch3Temp(float(RCh3))
#		output.write(str(Ch1T)+'\t'+str(Ch2)+'\t'+str(Ch3)+'\t'+str(Ch4T)+'\t'+str(VoltAT)+'\t'+str(VoltBT)+'\t'+str(TimeT)+'\n')
########################################################################################################

Ch1Final=[]
Ch2Final=[]
Ch3Final=[]
output = open(filename[:-4]+"Corrected.txt",'w')
with open(filename,'r') as rdata:
	reader=csv.reader(rdata,delimiter='\t')
	for b,Ch1T,Ch2T,Ch3T,Ch4T,WattAT,WattBT,TimeT,x,RCh1,RCh2,RCh3,RCh4,Ch1Ch2Stable,LRStateFlag in reader:
		#Ch1Ch2Stable 1 if Ch1 and Ch2 are stable by LR, 0 if not
		#LRStateFlag=0 if not LR run, 1 if initial heating step of a V0 setting, 2 meas process of V0 setting, 3 final heating step of V0 setting
		#Temperatures in K, Wattages in W, Resistances in Ohms
		Ch1=TRCurves151208.interpolate(float(RCh1),1)
		if float(Ch2T)>280:
			Ch2=TRCurves151208.interpolate(float(RCh2),1)
		else:
			Ch2=TRCurves151208.interpolate(float(RCh2),2)
		if float(Ch3T)>280:
			Ch3=TRCurves151208.interpolate(float(RCh3),1)
		else:
			Ch3=TRCurves151208.interpolate(float(RCh3),3)
		Ch1Final.append(Ch1)
		Ch2Final.append(Ch2)
		Ch3Final.append(Ch3)
		output.write(str(Ch1)+'\t'+str(Ch2)+'\t'+str(Ch3)+'\t'+str(Ch4T)+'\t'+str(WattAT)+'\t'+str(WattBT)+'\t'+str(TimeT)+'\t'+str(Ch1Ch2Stable)+'\t'+str(LRStateFlag)+'\n')
###########error propagator for use with observed TR in exp decays
#x=498#lesser B value from fit
#y=567#greater Bvalue from fit
#ex=1
#ey=1
#print 100*(ex**2/(y**2)+(ey*x)**2/(y**4))**0.5
