#Arg1=filename
#Arg2=base PV inc channel

#python UploadTempCurve.py U08910.340 SARES31-DIL-LS1:CV1


from epics import caget, caput

#Comment:	 04.03.2024, FP and CMN & 300mK calibrated Cernox, 10mK--300K
#Sensor Model:	 RX-1000-BF0.007
#Serial Number:	 U08910
#Data Format:	 4	(Log Ohms/Kelvin)
#SetPoint Limit:	 300	 (Kelvin)
#Temperature coefficient:	 1 (Negative)
#Number of Breakpoints:	 198

#No.	 Units	 Temperature (K)


#1	 3.2956295902328776	 302.29637503738195
#2	 3.296971553758573	 286.59226140605614
#3	 3.2983135172842686	 271.70396696844415
#4	 3.299655480809964	 257.58911041144177


import sys
#import re

with open(sys.argv[1], 'r') as f:                 #File of pv names to a list
    data= f.readlines()


Model="?"
SN="?"
DF="?"
DFU="?"
TC="?"
TCU="?"
BPS="?"

SPL="?"
SPLU="?"

a = [0] * 205 
b = [0] * 205 
c = [0] * 205 
lastpoint="0"

for line in data:
    #print(len(line))
    if (len(line)>10):
        sp=line.replace("\t"," ")
        sp=sp.replace("\n","")
#    sp =re.split(' |\n', sp)
        if ":" in line:
            sp=sp.split(":")
            sp0=sp[0]
            pos=sp[1].lstrip()
            #print("line:"+line)
            #print(" '"+sp0.lower()+"' ")
            #print(pos.split(" "))
            if sp0.lower()=="sensor model" :
                Model=pos.split(" ")[0]

            if sp0.lower()=="serial number" :
                SN=pos.split(" ")[0]
  
            if sp0.lower()=="data format" :
                DF=pos.split(" ")[0]
                DFU=pos.split(" ")[1]

            if sp0.lower()=="setpoint limit" :
                SPL=pos.split(" ")[0]
                SPLU=pos.split(" ")[1]

            if sp0.lower()=="temperature coefficient" :
                TC=pos.split(" ")[0]
                TCU=pos.split(" ")[1]

            if sp0.lower()=="number of breakpoints" :
                BPS=pos.split(" ")[0]


        else:
            q=sp.split()
            #print(sp)
            #print(">"+q[0]+"<")
            if (q[0].isdigit() ):
                #print(">"+q[0]+"<")
                #print(q[1])
                val=int(q[0])
                a[val-1]=val
                b[val-1]=float(q[1])
                c[val-1]=float(q[2])
                lastpoint=q[0]
                
            else:
                sp="XXXX"

     


    



pv = sys.argv[2].strip()

print ("Upload: "+Model+","+SN+","+DF+","+SPL+","+TC+","+BPS+","+str(lastpoint)+"   PV:"+pv)

#print(a)
#print(b) 
#print(c)

caput(pv+"_NAME"     ,Model.encode()) 
caput(pv+"_SN"       ,SN.encode()) 
caput(pv+"_FORMAT"   ,DF.encode())
caput(pv+"_SPLIM"    ,SPL.encode()) 
caput(pv+"_COEF"     ,TC.encode())
caput(pv+"_BPTS"     ,BPS.encode())

caput(pv+"_NO"       ,a)
caput(pv+"_UNITS"    ,b)
caput(pv+"_TEMP"     ,c)
caput(pv+"_NUM_ROWS" ,lastpoint.encode())


print ('Finished')



