#Script imported from: MgE_plus.xml

#Parameters
"""
E1 = 710
E2 = 720
TIME = 1 #min
DELAY = 10.0 #s
MODE = 'CIRC +'
OFFSET = -9.0
FOLDER = '2015_04/20150417'
FILE = 'Fe_plus'
ALPHA=0
"""


print "\nStarting energy scan - Parameters: ",
print E1,E2,TIME,DELAY,MODE ,OFFSET ,FOLDER ,FILE ,ALPHA

start = time.localtime()

folder = os.path.expanduser("~/Data1/") + FOLDER + "/";
def getNewestFile():
    global folder
    import glob
    try:        
        return max(glob.iglob(folder+'/*.txt'), key=os.path.getctime)
    except:
        return None
newest = getNewestFile()

def wait_channel(name, value, type):
    print "Waiting " + str(name) + " = " + str(value)
    cawait(name, value, type  = type)
    print "Done"


#Pre-actions
#wait_channel('ACOAU-ACCU:OP-MODE', 'Light Available', type = 's')
caput('X07MA-ID:MODE', MODE)
time.sleep(1.0)
if MODE == 'LINEAR':
    caput('X07MA-ID:ALPHA', ALPHA)
wait_channel('X07MA-ID:DONE', 'DONE', type = 's')
caput('X07MA-ID:ENERGY-OFFS', OFFSET)
wait_channel('X07MA-ID:DONE', 'DONE', type = 's')
caput('E1', E1)
caput('E2', E2)
caput('TIME', TIME)
caput('FOLDER', FOLDER)
caputq('X07MA-PHS-E:GO.A', E1)
wait_channel('X07MA-PHS:alldone', '1', type = 's')
time.sleep(0.5)
caput('FILE', FILE)
time.sleep(0.1)
caput('X07MA-OP-VG13:WT_SET', 'Try open')
time.sleep(5.0)
caput('X07MA-OP-VG13:WT_SET', 'Try open')
time.sleep(DELAY)
caput('START', '1')

#Post-actions
wait_channel('START', 'STOP', type = 's')

time.sleep(2.0)
print "Finished Energy scan"


#File convertion
newName = folder + time.strftime("%Y%m%d_%H%M_", start) + FILE + "_0000.txt";             
#name = caget("MSG").split(' ')[0]
name = getNewestFile()

if name == newest:
    raise Exception("Data file not created")

if not os.path.isfile(name):
    raise Exception("Data file not found: " + name)

cmd = "/sls/X07MA/data/x07maop/bin/modify_otf.pl " + name + " " + newName;
print("Converting data file: " + cmd);               
import os
os.system(cmd)
print("Success")        


