#Parameters (global variables):
#    ranges: list of RangeSelection havinf args = (step_size, step_time, iterations)
#    pass_energy
#
#    skip_iteration: if set to 1 then skips after end of current iteration

from ch.psi.pshell.data.LayoutDefault import ATTR_WRITABLE_DIMENSION as ATTR_WRITABLE_DIMENSION

cur_range = 0
cur_iteration = 0



print "back = ", str(get_exec_pars().background)

print "source = ", str(get_exec_pars().source)

print "args = ", 
print get_exec_pars().args


if scienta.acquisitionMode == scienta.AcquisitionMode.Fixed:
    scienta.acquisitionMode = scienta.AcquisitionMode.Swept
ret=[]


#Global arguments
scienta.passEnergy = pass_energy

names=[]
names.append("Spectrum")
for i in range(len(ranges)):       
    names.append(str(ranges[i]))
plots = plot(None, names)
spectrum_plot = plots[0]

def plot_cur_spectrum():
    global spectrum_plot
    count = 1
    try:
      while True:
        y = scienta.spectrum.take()
        y[10] = count 
        count = count + 1
        x = scienta.spectrumX
        spectrum_plot.getSeries(0).setData(x, y)        
        #plots[len(names)-1].update(False)
        time.sleep(0.1)
    finally:
        print "Quit"        

task = fork(plot_cur_spectrum)


try:
    for cur_range in range(len(ranges)): 
        cur_iteration = 0 
        skip_iteration = False        
        scienta.lowEnergy.write(ranges[cur_range].min)
        scienta.highEnergy.write(ranges[cur_range].max)
        scienta.update()

        vars = ranges[cur_range].vars
        scienta.stepTime.write(vars[0])
        scienta.stepSize.write(vars[1])
        scienta.setIterations(1)

        #iterations done in script
        xdata = None
        ydata = None
        for cur_iteration in range(vars[2]):   
            plots[cur_range+1].setTitle(str(ranges[cur_range]) + " - iteration " + str(cur_iteration+1))
            trig_scienta()
            spectrum_array = scienta.spectrum.read()
            if ydata is None:
                ydata = spectrum_array
            else:
                for k in range (len(spectrum_array)):
                    ydata[k] = ydata[k] + spectrum_array[k]
            if xdata is None:
                xdata = scienta.spectrumX
            plots[cur_range+1].getSeries(0).setData(xdata, ydata)
            if skip_iteration: 
                break            

        plots[cur_range+1].setTitle(str(ranges[cur_range]))
        ret.append((xdata, ydata))

        data1d = [1,2,3,4,5]
        path="scan" + str(cur_range+1) + "/"
        save_dataset(path + "spectrum", ydata)
        save_dataset(path + "channels", xdata)
        set_attribute(path + "channels", ATTR_WRITABLE_DIMENSION, 1)
        set_attribute(path, "Range Low", ranges[cur_range].min)
        set_attribute(path, "Range High", ranges[cur_range].max)
        set_attribute(path, "Step Time",vars[0])
        set_attribute(path, "Step Size",vars[1])
        set_attribute(path, "Pass Energy",pass_energy)
        set_attribute(path, "Iterations",cur_iteration+1)


finally:
    cur_range = -1
    if not scienta.isReady():
        scienta.stop()
    scienta.update()
    task[0].cancel(True)
set_return(to_array(ret,'o'))