; NAME:
;       mep
; DATE of WORKING VERSION: 1 Feb 2006
;PD Dr. Philip Tregenna-Piggott,
;Laboratory for Neutron Scattering,
;ETHZ and Paul-Scherrer Institute,
;CH-5232 Villigen PSI,
;Switzerland.
;
;Tel. :+41 56 310 54 05
;Fax. :+41 56 310 29 39
;Email:philip.tregenna@psi.ch
;
;
; CATEGORY:
;
;       MARS Tools
;
; CALLING SEQUENCE:
;
;      mep
;
;
; INPUT FIELDS:
;
;
; EXAMPLES FOR POTENTIALS (must use IDL syntax as shown below):
;
;
; DISCLAIMER
;
;     This software is provided as is without any warranty whatsoever.
;     Permission to use, copy, modify, and distribute modified or
;     unmodified copies is granted, provided this disclaimer
;     is included unchanged.
;
; MODIFICATION HISTORY:
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;get sics functions and procedures
@idlsics
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MEP_exit,event
widget_control,event.top,get_uvalue = pState
wdelete,(*pState).winPix_f
wdelete,(*pState).winPix_m
device, decomposed = (*pState).old_dc
if (*pstate).connection eq 1 then begin
sicsclose,(*pstate).UnitUser
sicsclose,(*pstate).UnitManager
endif
heap_free,pState
widget_control,event.top,/destroy
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function GetMARSConstants,filename

if file_test(filename) eq 0 then begin
filefound=0
constants={filefound:filefound}
return,constants
endif else begin
filefound=1
constants={filefound:filefound}
endelse
line=''
Constants_str='Constants'
openr,lun,filename,/get_lun
while eof(lun) eq 0 do begin
readf,lun,line
Constants_str=[Constants_str,line]
endwhile
free_lun,lun,/force
Constants_str=Constants_str[1:*]
n=n_elements(Constants_str)
for i = 0,n-1 do begin
ConstantName=strtrim((strsplit(Constants_str[i],'=',/extract))[0],2)
ConstantString=strtrim((strsplit(Constants_str[i],'=',/extract))[1],2)
    if strpos(ConstantString,',') eq -1 then begin
    ConstantValue=double(ConstantString)
    endif else begin
    ConstantString=strtrim((strsplit(ConstantString,',',/extract)),2)
    ConstantValue=double(ConstantString)
    endelse
constants=create_struct(constants,ConstantName,ConstantValue)
endfor
constants=create_struct(constants,name='MARSConstants')
return,constants

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function GetMARSAcceptableTimebins,filename

if file_test(filename) eq 0 then begin
filefound=0
TimeBins={filefound:filefound}
return,TimeBins
endif else begin
filefound=1
TimeBins={filefound:filefound}
endelse

line=''
ATB_str='ATB'
openr,lun,filename,/get_lun
while eof(lun) eq 0 do begin
readf,lun,line
ATB_str=[ATB_str,line]
endwhile
free_lun,lun,/force
ATB_str=ATB_str[1:*]
n=n_elements(ATB_str)
for i = 0,n-1 do begin
TimeBinStep=long(strtrim((strsplit(ATB_str[i],/extract))[0],2))
TimeBinNumber=long(strtrim((strsplit(ATB_str[i],/extract))[1],2))
if i eq 0 then begin
TimeBinStep_arr=[TimeBinStep]
TimeBinNumber_arr=[TimeBinNumber]
endif else begin
TimeBinStep_arr=[TimeBinStep_arr,TimeBinStep]
TimeBinNumber_arr=[TimeBinNumber_arr,TimeBinNumber]
endelse
endfor
TimeBins=create_struct(TimeBins,'TimeBinStep_arr',TimeBinStep_arr,'TimeBinNumber_arr',TimeBinNumber_arr)
TimeBins=create_struct(TimeBins,name='MARSTimeBins')
return,TimeBins
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function GetMARSTimeOffsets,filename

if file_test(filename) eq 0 then begin
filefound=0
timeoffsets={filefound:filefound}
return,timeoffsets
endif else begin
filefound=1
timeoffsets={filefound:filefound}
endelse

line=''
timeoffsets_str='timeoffsets'
openr,lun,filename,/get_lun
while eof(lun) eq 0 do begin
readf,lun,line
timeoffsets_str=[timeoffsets_str,line]
endwhile
free_lun,lun,/force
timeoffsets_str=timeoffsets_str[1:*]
n=n_elements(timeoffsets_str)
if n ne 7 then begin
filefound=0
timeoffsets={filefound:filefound}
return,timeoffsets
endif
valid_names=['master1_timeoffset', $
         'master2_timeoffset', $
         'master3_timeoffset', $
         'master4_timeoffset', $
         'master5_timeoffset', $
         'master6_timeoffset', $
         'master7_timeoffset']
for i = 0,n-1 do begin
Name=strtrim((strsplit(timeoffsets_str[i],'=',/extract))[0],2)
void=where(strmatch(valid_names,name) eq 1,count)
if count eq 0 then begin
filefound=0
timeoffsets={filefound:filefound}
return,timeoffsets
endif
Value=double(strtrim((strsplit(timeoffsets_str[i],'=',/extract))[1],2))
timeoffsets=create_struct(timeoffsets,Name,Value)
endfor
timeoffsets=create_struct(timeoffsets,name='MARSTimeOffsets')

return,timeoffsets
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro ascii_save,event
widget_control,event.top,get_uvalue = pState
;parameters in field entry
workDir=(*pState).workDir

    filename=dialog_pickfile(path=workDir,$
      file='MarsPlannerFile.txt',/write,filter="*.txt",/fix_filter)
if n_elements(filename) eq 0 then return
if filename eq '' then return

;print,'filename= ',filename
;
widget_control,(*pState).Em,get_value=Em
widget_control,(*pState).Master,get_value=Master
master=fix(master[0])
widget_control,(*pState).mica,get_value =mica
mica=fix(mica[0])
if mica eq 0 then micastring='002'
if mica eq 1 then micastring='004'
if mica eq 2 then micastring='006'
if mica eq 3 then micastring='008'
widget_control,(*pState).Chopper_Table,get_value=output
widget_control,(*pState).Ewinl,get_value=E_lower
widget_control,(*pState).Ewinu,get_value=E_upper
widget_control,(*pState).Qwinl,get_value=Qmin
widget_control,(*pState).Qwinu,get_value=Qmax
widget_control,(*pState).scatt_angle,get_value=theta
widget_control,(*pState).scatt_rel_int,get_value=scattInt
widget_control,(*pState).Res,get_value=resolution
resolution=fix(resolution[0])
if resolution eq 0 then resolutionstring='Primary Instrument'
if resolution eq 1 then resolutionstring='Secondary Instrument'
widget_control,(*pState).dspacingl,get_value=dspaceMin
widget_control,(*pState).dspacingu,get_value=dspaceMax
widget_control,(*pState).Ewinl_002,get_value=Ewinl_002
widget_control,(*pState).Ewinu_002,get_value=Ewinu_002
widget_control,(*pState).Ewinl_004,get_value=Ewinl_004
widget_control,(*pState).Ewinu_004,get_value=Ewinu_004
widget_control,(*pState).Ewinl_006,get_value=Ewinl_006
widget_control,(*pState).Ewinu_006,get_value=Ewinu_006
widget_control,(*pState).Qwinl_002,get_value=Qwinl_002
widget_control,(*pState).Qwinu_002,get_value=Qwinu_002
widget_control,(*pState).Qwinl_004,get_value=Qwinl_004
widget_control,(*pState).Qwinu_004,get_value=Qwinu_004
widget_control,(*pState).Qwinl_006,get_value=Qwinl_006
widget_control,(*pState).Qwinu_006,get_value=Qwinu_006
; other parameters
El=(*pState).El
Eu=(*pState).Eu
E_analyser=(*pState).E_analyser
Esec=(*pState).Esec
First_Neutrons_Time=(*pState).First_Neutrons_Time
Last_Neutrons_Time=(*pState).Last_Neutrons_Time
Time_Difference=(*pState).Time_Difference
Time_Bin_Number=(*pState).Time_Bin_Number
Time_Bin_Start=(*pState).Time_Bin_Start
Time_Bin_Step=(*pState).Time_Bin_Step
Time_Bin_Width=(*pState).Time_Bin_Width
Total_Time_Bin_Number=(*pState).Total_Time_Bin_Number
Histogram_Option_Value=(*pState).Histogram_Option_Value
TimeBinIndices=(*pState).TimeBinIndices
str=strtrim(string(TimeBinIndices[0]),2)+','
for i = 1,12 do begin
str+=strtrim(string(TimeBinIndices[i]),2)+','
endfor
str+=strtrim(string(TimeBinIndices[13]),2)
TimeBinIndices=str

;filename='MarsPlannerFile.txt'
openw,lun,filename,/get_lun
printf,lun, 'Instrument: MARS'
printf,lun, 'Midpoint of Energy Window: '+strtrim(string(Em),2)+' meV'
printf,lun, 'Frequency of Master Chopper x 50 Hz: '+strtrim(string(Master),2)
printf,lun, 'Mica Reflection '+strtrim(string(micastring),2)
printf,lun, 'Phase of Snail Chopper: '+strtrim(string(output[0,0]),2)+' degrees'
printf,lun, 'Phase of Master Chopper: '+strtrim(string(output[0,1]),2)+' degrees'
printf,lun, 'Phase of Rabbit Chopper: '+strtrim(string(output[0,2]),2)+' degrees'
printf,lun, 'Phase of Chopper 4: '+strtrim(string(output[0,3]),2)+' degrees'
printf,lun, 'Phase of Chopper 5: '+strtrim(string(output[0,4]),2)+' degrees'
printf,lun, 'Lower Bound of Energy Window: '+strtrim(string(E_lower),2)+' meV'
printf,lun, 'Upper Bound of Energy Window: '+strtrim(string(E_upper),2)+' meV'
printf,lun, 'Lower Bound of Momentum Transfer: '+strtrim(string(Qmin),2)+' A-1'
printf,lun, 'Upper Bound of Momentum Transfer: '+strtrim(string(Qmax),2)+' A-1'
printf,lun, 'Lower Bound of d-spacing: '+strtrim(string(dspaceMin),2)+' A'
printf,lun, 'Upper Bound of d-spacing: '+strtrim(string(dspaceMax),2)+' A'
printf,lun, 'Scattering Angle of INS Detector: '+strtrim(string(theta),2)+' degrees'
printf,lun, 'Intensity Factor: '+strtrim(string(scattInt),2)
printf,lun, 'Resolution Governed by the: '+strtrim(string(resolutionstring),2)
printf,lun, 'Flux Incident Upon the Sample in the Energy Range: '+strtrim(string(El),2)+ $
       ' to '+strtrim(string(Eu),2)+' meV'
printf,lun, 'Energy of Mica Analyser: '+strtrim(string(E_analyser),2)+' meV'
printf,lun, 'Resolution in Secondary Inatrument: '+strtrim(string(Esec),2)+' meV'

if mica eq 0 then begin
printf,lun, 'No Freebies'
endif else begin
printf,lun, 'Freebies:'
    if mica eq 1 then begin
    printf,lun, 'Energy Window Correponding to 002 Reflection also Available '
    printf,lun, 'Lower Bound of Energy Window: '+strtrim(string(Ewinl_002),2)+' meV'
    printf,lun, 'Upper Bound of Energy Window: '+strtrim(string(Ewinu_002),2)+' meV'
    printf,lun, 'Lower Bound of Momentum Transfer: '+strtrim(string(Qwinl_002),2)+' A-1'
    printf,lun, 'Upper Bound of Momentum Transfer: '+strtrim(string(Qwinu_002),2)+' A-1'
    endif
    if mica eq 2 then begin
    printf,lun, 'Energy Window Correponding to 004 Reflection also Available '
    printf,lun, 'Lower Bound of Energy Window: '+strtrim(string(Ewinl_004),2)+' meV'
    printf,lun, 'Upper Bound of Energy Window: '+strtrim(string(Ewinu_004),2)+' meV'
    printf,lun, 'Lower Bound of Momentum Transfer: '+strtrim(string(Qwinl_004),2)+' A-1'
    printf,lun, 'Upper Bound of Momentum Transfer: '+strtrim(string(Qwinu_004),2)+' A-1'
    printf,lun, 'Energy Window Correponding to 002 Reflection also Available '
    printf,lun, 'Lower Bound of Energy Window: '+strtrim(string(Ewinl_002),2)+' meV'
    printf,lun, 'Upper Bound of Energy Window: '+strtrim(string(Ewinu_002),2)+' meV'
    printf,lun, 'Lower Bound of Momentum Transfer: '+strtrim(string(Qwinl_002),2)+' A-1'
    printf,lun, 'Upper Bound of Momentum Transfer: '+strtrim(string(Qwinu_002),2)+' A-1'
    endif
    if mica eq 3 then begin
    printf,lun, 'Energy Window Correponding to 006 Reflection also Available '
    printf,lun, 'Lower Bound of Energy Window: '+strtrim(string(Ewinl_006),2)+' meV'
    printf,lun, 'Upper Bound of Energy Window: '+strtrim(string(Ewinu_006),2)+' meV'
    printf,lun, 'Lower Bound of Momentum Transfer: '+strtrim(string(Qwinl_006),2)+' A-1'
    printf,lun, 'Upper Bound of Momentum Transfer: '+strtrim(string(Qwinu_006),2)+' A-1'
    printf,lun, 'Energy Window Correponding to 004 Reflection also Available '
    printf,lun, 'Lower Bound of Energy Window: '+strtrim(string(Ewinl_004),2)+' meV'
    printf,lun, 'Upper Bound of Energy Window: '+strtrim(string(Ewinu_004),2)+' meV'
    printf,lun, 'Lower Bound of Momentum Transfer: '+strtrim(string(Qwinl_004),2)+' A-1'
    printf,lun, 'Upper Bound of Momentum Transfer: '+strtrim(string(Qwinu_004),2)+' A-1'
    printf,lun, 'Energy Window Correponding to 002 Reflection also Available '
    printf,lun, 'Lower Bound of Energy Window: '+strtrim(string(Ewinl_002),2)+' meV'
    printf,lun, 'Upper Bound of Energy Window: '+strtrim(string(Ewinu_002),2)+' meV'
    printf,lun, 'Lower Bound of Momentum Transfer: '+strtrim(string(Qwinl_002),2)+' A-1'
    printf,lun, 'Upper Bound of Momentum Transfer: '+strtrim(string(Qwinu_002),2)+' A-1'
    endif
endelse
    printf,lun, 'Histogram Memory: '
    printf,lun, 'First Neutrons Reach the TOF Monitor at: '+strtrim(string(First_Neutrons_Time),2)+' uS'
    printf,lun, 'Last Neutrons Reach the Triffids at: '+strtrim(string(Last_Neutrons_Time),2)+' uS'
    printf,lun, 'The time difference is equal to: '+strtrim(string(Time_Difference),2)+' uS'
    printf,lun, 'Number of time bins in the primary INS spectrum: '+strtrim(string(Time_Bin_Number),2)
    if Histogram_Option_Value eq 0 then begin
    printf,lun, 'The value is that recommended by the program, obtained by dividing the energy'
    printf,lun, 'width of the spectrum by the best resolution, and multiplying by a factor of 15.'
    endif else begin
    printf,lun, 'The value is defined by the user'
    endelse
    printf,lun, 'Time binning starts at: '+strtrim(string(Time_Bin_Start),2)+' uS'
    printf,lun, 'Time binning step size: '+strtrim(string(Time_Bin_Step),2)+' uS'
    printf,lun, 'Time binning width: '+strtrim(string(Time_Bin_Width),2)+' uS'
    printf,lun, 'Total number of time bins: '+strtrim(string(Total_Time_Bin_Number),2)
    printf,lun, 'The time bin indices, specifying the useful range'
    printf,lun, 'for each type of TOF detetctor: '+strtrim(string(TimeBinIndices),2)
;
free_lun,lun,/force
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MEP_restore,event
widget_control,event.top,get_uvalue = pState
workDir=(*pState).workDir
    filename=dialog_pickfile(path=workDir,$
      file='MarsPlannerFile.pln',/read,filter="*.pln",/fix_filter)
if n_elements(filename) eq 0 then return
if filename eq '' then return
;file='MEP_restore'
restore,filename=filename
Em=SaveParametersArray.Em
Master=SaveParametersArray.Master
mica=SaveParametersArray.mica
output=SaveParametersArray.output
output[1,*]/=60.0;convert to hz
E_lower=SaveParametersArray.E_lower
E_upper=SaveParametersArray.E_upper
Qmin=SaveParametersArray.Qmin
Qmax=SaveParametersArray.Qmax
theta=SaveParametersArray.theta
scattInt=SaveParametersArray.scattInt
resolution=SaveParametersArray.resolution
dspaceMin=SaveParametersArray.dspaceMin
dspaceMax=SaveParametersArray.dspaceMax
Ewinl_002=SaveParametersArray.Ewinl_002
Ewinu_002=SaveParametersArray.Ewinu_002
Ewinl_004=SaveParametersArray.Ewinl_004
Ewinu_004=Ewinu_004
Ewinl_006=SaveParametersArray.Ewinl_006
Ewinu_006=SaveParametersArray.Ewinu_006
Qwinl_002=SaveParametersArray.Qwinl_002
Qwinu_002=SaveParametersArray.Qwinu_002
Qwinl_004=SaveParametersArray.Qwinl_004
Qwinu_004=SaveParametersArray.Qwinu_004
Qwinl_006=SaveParametersArray.Qwinl_006
Qwinu_006=SaveParametersArray.Qwinu_006
El=SaveParametersArray.El
Eu=SaveParametersArray.Eu
E_analyser=SaveParametersArray.E_analyser
Esec=SaveParametersArray.Esec
First_Neutrons_Time=SaveParametersArray.First_Neutrons_Time
Last_Neutrons_Time=SaveParametersArray.Last_Neutrons_Time
Time_Difference=SaveParametersArray.Time_Difference
Time_Bin_Number=SaveParametersArray.Time_Bin_Number
Time_Bin_Start=SaveParametersArray.Time_Bin_Start
Time_Bin_Step=SaveParametersArray.Time_Bin_Step
Time_Bin_Width=SaveParametersArray.Time_Bin_Width
Total_Time_Bin_Number=SaveParametersArray.Total_Time_Bin_Number
Histogram_Option_Value=SaveParametersArray.Histogram_Option_Value
TimeBinIndices=SaveParametersArray.TimeBinIndices
Triffid_Option_Value=SaveParametersArray.Triffid_Option_Value
Energy_Window_Option_Value=SaveParametersArray.Energy_Window_Option_Value
Energy_Window_Slider=SaveParametersArray.Energy_Window_Slider
angle_index=SaveParametersArray.angle_index



;
;parameters in field entry
widget_control,(*pState).Em,set_value=Em
widget_control,(*pState).Master,set_value=Master
widget_control,(*pState).mica,set_value =mica
widget_control,(*pState).Chopper_Table,set_value=output
widget_control,(*pState).Ewinl,set_value=E_lower
widget_control,(*pState).Ewinu,set_value=E_upper
widget_control,(*pState).Qwinl,set_value=Qmin
widget_control,(*pState).Qwinu,set_value=Qmax
widget_control,(*pState).scatt_angle,set_value=theta
widget_control,(*pState).scatt_rel_int,set_value=scattInt
widget_control,(*pState).Res,set_value=resolution
widget_control,(*pState).dspacingl,set_value=dspaceMin
widget_control,(*pState).dspacingu,set_value=dspaceMax
widget_control,(*pState).Ewinl_002,set_value=Ewinl_002
widget_control,(*pState).Ewinu_002,set_value=Ewinu_002
widget_control,(*pState).Ewinl_004,set_value=Ewinl_004
widget_control,(*pState).Ewinu_004,set_value=Ewinu_004
widget_control,(*pState).Ewinl_006,set_value=Ewinl_006
widget_control,(*pState).Ewinu_006,set_value=Ewinu_006
widget_control,(*pState).Qwinl_002,set_value=Qwinl_002
widget_control,(*pState).Qwinu_002,set_value=Qwinu_002
widget_control,(*pState).Qwinl_004,set_value=Qwinl_004
widget_control,(*pState).Qwinu_004,set_value=Qwinu_004
widget_control,(*pState).Qwinl_006,set_value=Qwinl_006
widget_control,(*pState).Qwinu_006,set_value=Qwinu_006
; other parameters
(*pState).El=El
(*pState).Eu=Eu
(*pState).E_analyser=E_analyser
(*pState).Esec=Esec
(*pState).First_Neutrons_Time=First_Neutrons_Time
(*pState).Last_Neutrons_Time=Last_Neutrons_Time
(*pState).Time_Difference=Time_Difference
(*pState).Time_Bin_Number=Time_Bin_Number
(*pState).Time_Bin_Start=Time_Bin_Start
(*pState).Time_Bin_Step=Time_Bin_Step
(*pState).Time_Bin_Width=Time_Bin_Width
(*pState).Total_Time_Bin_Number=Total_Time_Bin_Number
(*pState).Histogram_Option_Value=Histogram_Option_Value
(*pState).Triffid_Option_Value=Triffid_Option_Value
(*pState).Energy_Window_Option_Value=Energy_Window_Option_Value
(*pState).Energy_Window_Slider=Energy_Window_Slider
(*pState).angle_index=angle_index
(*pState).TimeBinIndices=TimeBinIndices
mepEvents,event;
end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mepPlot,event
widget_control,event.top,get_uvalue = pState
x = (*pState).x
y = (*pState).y
El = (*pState).El
Eu = (*pState).Eu
if (*pState).autoscale eq 1 then begin
  xlo = min(x) & xhi = max(x)
  ylo = min(y) & yhi = max(y)
  (*pState).xrange = [xlo,xhi]
  (*pState).yrange = [ylo,yhi]
endif

plot,x,y,xrange = (*pState).xrange,yrange = (*pState).yrange, $
     xstyle = 1,ystyle = 1,xtitle = 'Energy / meV', $
     ytitle = 'Flux', title = 'Flux at Sample',linestyle = 0, $
     thick = 1.0, psym=0, symsize=1.0

 polyfill,x,y,/data,color=(*pState).colors.red, $
        CLIP=[El,0,Eu,max(y)], noclip = 0

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function prime_res,E,Master
return, (3.8192e-3*E^1.5)/Master
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mep_WinParameters,event
widget_control,event.top,get_uvalue = pState
if (*pState).pix ne 1 then begin
;wdelete,(*pState).winPix
mepPlotQE_range,event
(*pState).pix = 1
;print,'woofy'
endif


E_analyser=(*pState).E_analyser


Esec=(*pState).Esec
widget_control,(*pState).Master,get_value=Master

widget_control,(*pState).Ewinl,get_value=E_lower
E_lower=float(E_lower[0])
widget_control,(*pState).Ewinu,get_value=E_upper
E_upper=float(E_upper[0])
Qmin=(*pState).Qmin
Qmax=(*pState).Qmax
      coords = convert_coord(event.x, event.y, /device, /to_data)
      if (coords[0] le E_upper) and (coords[0] ge E_lower) and $
         coords[1] le Qmax and coords[1] ge Qmin then begin
;print,'coords =',coords[0],coords[1]
E_pri=prime_res((coords[0]+E_analyser),Master)
total_res=sqrt(Esec^2+E_pri^2)
widget_control,(*pState).E_mouse,set_value=coords[0]
widget_control,(*pState).E_Res,set_value=total_res
widget_control,(*pState).Q_mouse,set_value=coords[1]


alpha=2.072099427
cphi=(-(coords[1])^2*alpha+(2.0*E_analyser)+coords[0])/(2*sqrt(E_analyser*(coords[0]+E_analyser)))
;print,'cphi =',cphi
;phi=acos(cphi)*180/!pi
if (abs(cphi) le 1.0) then begin
phi=acos(cphi)*180/!pi
widget_control,(*pState).phi_mouse,set_value=phi
endif else begin
msg='Not Accessible'
widget_control,(*pState).phi_mouse,set_value=msg
endelse
       endif
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function Bragg,dspacing,theta
return, 2.0*dspacing*sin(theta*!DTOR)
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function GenerateTimebinIndices,event,vl,vu,TOF_start,TOF_width,TOF_step,mica,theta
widget_control,event.top,get_uvalue = pState
constants=(*pState).constants
lTOFMon=constants.lTOFMon
lTOFPostMon=constants.lTOFPostMon
lDiff=constants.lDiff
lprim=constants.lprim
D=constants.D
mn=constants.mn
conv=constants.meVtoJoules
dspace_array=(*pState).dspace_array
HP=constants.Histogram_Period

;
;h=constants.h
;these offsets will be applied to the real data
timeoffsets=(*pState).timeoffsets
offset=0.0
widget_control,(*pState).Master,get_value =Master
masterfundamental=fix(Master[0])
if masterfundamental eq 1 then offset=timeoffsets.master1_timeoffset
if masterfundamental eq 2 then offset=timeoffsets.master2_timeoffset
if masterfundamental eq 3 then offset=timeoffsets.master3_timeoffset
if masterfundamental eq 4 then offset=timeoffsets.master4_timeoffset
if masterfundamental eq 5 then offset=timeoffsets.master5_timeoffset
if masterfundamental eq 6 then offset=timeoffsets.master6_timeoffset
if masterfundamental eq 7 then offset=timeoffsets.master7_timeoffset
;print,'offset: ' ,offset

;
;starty=systime(1,/seconds)

n_points=long((TOF_width/TOF_step))
timebin_vec=TOF_start+TOF_step*findgen(n_points)
timebin_vec+=offset


;print,' '
;print,'n_points ',n_points
;print,'TOF_width ',TOF_width
;print,'TOF_step ',TOF_step


;TOF_end=double(TOF_start+TOF_width)
;timebin_vec=double(TOF_start)
;tb=double(TOF_start)
;TOF_step=double(TOF_step)



;while tb lt TOF_end do begin
;tb+=TOF_step
;timebin_vec=[timebin_vec,tb]
;endwhile
;print,'timebin_vec: ',timebin_vec
;
;endy=systime(1,/seconds)
;duration=endy-starty
;print,'duration: ',duration


time=1e6*lTOFMon/vu
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices=index[0]
endelse
;
;
;
time=1e6*lTOFMon/vl
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices=[TimeBinIndices,index[0]]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices=[TimeBinIndices,index[0]]
endelse
;
;
;
time=1e6*lTOFPostMon/vu
;print,'1e6*lTOFPostMon/vu: ',time
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices=[TimeBinIndices,index[0]]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices=[TimeBinIndices,index[0]]
endelse
;
;
time=1e6*lTOFPostMon/vl
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices=[TimeBinIndices,index[0]]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices=[TimeBinIndices,index[0]]
endelse
;
;
time=1e6*ldiff/vu
;print,'1e6*ldiff/vu: ',time
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices=[TimeBinIndices,index[0]]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices=[TimeBinIndices,index[0]]
endelse
;
;
time=1e6*ldiff/vl
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices=[TimeBinIndices,index[0]]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices=[TimeBinIndices,index[0]]
endelse
;
;
;
tprim_lower=1e6*lprim/vu
tprim_higher=1e6*lprim/vl
TimeBinIndices=[TimeBinIndices,-1,-1,-1,-1,-1,-1,-1,-1]
;
;
case mica of
0:    $  ;002 reflection
begin
dspacing=dspace_array[mica]
E_analyser=81.80321/(Bragg(dspacing,theta))^2
v_sec=sqrt(E_analyser*conv*2.0/mn)
t_sec=1e6*D/v_sec
;
time=tprim_lower+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[6]=index[0]
;
time=tprim_higher+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[7]=index[0]
;
;print,' '
;print,'n_elements(tempdiff7) ',n_elements(tempdiff)
;print,'n_elements(time) ',n_elements(time)
;print,'n_elements(timebin_vec) ',n_elements(timebin_vec)
;print,'dspacing ',dspacing
;print,'E_analyser ',E_analyser
;print,'tprim_lower ',tprim_lower
;print,'v_sec ',v_sec
;print,'t_sec ',t_sec
;print,'time ',time
;print,'index ',index
;print,'TimeBinIndices ',TimeBinIndices


;
end
1:    $  ;004 reflection
begin
dspacing=dspace_array[mica]
E_analyser=81.80321/(Bragg(dspacing,theta))^2
v_sec=sqrt(E_analyser*conv*2.0/mn)
t_sec=1e6*D/v_sec
;
time=tprim_lower+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[8]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[8]=index[0]
endelse
;
time=tprim_higher+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[9]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[9]=index[0]
endelse
;
dspacing=dspace_array[0]    ; 002 freebie
E_analyser=81.80321/(Bragg(dspacing,theta))^2
v_sec=sqrt(E_analyser*conv*2.0/mn)
t_sec=1e6*D/v_sec
;
time=tprim_lower+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[6]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[6]=index[0]
endelse
;
time=tprim_higher+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[7]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[7]=index[0]
endelse
;
end
2:    $  ;006 reflection
begin
dspacing=dspace_array[mica]
E_analyser=81.80321/(Bragg(dspacing,theta))^2
v_sec=sqrt(E_analyser*conv*2.0/mn)
t_sec=1e6*D/v_sec
;
time=tprim_lower+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[10]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[10]=index[0]
endelse

;
time=tprim_higher+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[11]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[11]=index[0]
endelse
;
dspacing=dspace_array[1] ; 004 freebie
E_analyser=81.80321/(Bragg(dspacing,theta))^2
v_sec=sqrt(E_analyser*conv*2.0/mn)
t_sec=1e6*D/v_sec
;
time=tprim_lower+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[8]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[8]=index[0]
endelse
;
time=tprim_higher+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[9]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[9]=index[0]
endelse
;
dspacing=dspace_array[0]    ; 002 freebie
E_analyser=81.80321/(Bragg(dspacing,theta))^2
v_sec=sqrt(E_analyser*conv*2.0/mn)
t_sec=1e6*D/v_sec
;
time=tprim_lower+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[6]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[6]=index[0]
endelse
;
time=tprim_higher+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[7]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[7]=index[0]
endelse
;
end
3:    $  ;008 reflection
begin
dspacing=dspace_array[mica]
E_analyser=81.80321/(Bragg(dspacing,theta))^2
v_sec=sqrt(E_analyser*conv*2.0/mn)
t_sec=1e6*D/v_sec
;
time=tprim_lower+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[12]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[12]=index[0]
endelse
;
time=tprim_higher+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[13]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[13]=index[0]
endelse
;
dspacing=dspace_array[2]   ; 006 freebie
E_analyser=81.80321/(Bragg(dspacing,theta))^2
v_sec=sqrt(E_analyser*conv*2.0/mn)
t_sec=1e6*D/v_sec
;
time=tprim_lower+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[10]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[10]=index[0]
endelse
;
time=tprim_higher+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[11]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[11]=index[0]
endelse
;
;
dspacing=dspace_array[1] ; 004 freebie
E_analyser=81.80321/(Bragg(dspacing,theta))^2
v_sec=sqrt(E_analyser*conv*2.0/mn)
t_sec=1e6*D/v_sec
;
time=tprim_lower+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[8]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[8]=index[0]
endelse
;
time=tprim_higher+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[9]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[9]=index[0]
endelse
;
dspacing=dspace_array[0]    ; 002 freebie
E_analyser=81.80321/(Bragg(dspacing,theta))^2
v_sec=sqrt(E_analyser*conv*2.0/mn)
t_sec=1e6*D/v_sec
;
time=tprim_lower+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[6]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[6]=index[0]
endelse
;
time=tprim_higher+t_sec
tempdiff=time-timebin_vec
void=min(tempdiff,index,/absolute)
if index ne 0 then begin
TimeBinIndices[7]=index[0]
endif else begin
tempdiff=(time+HP)-timebin_vec
void=min(tempdiff,index,/absolute)
TimeBinIndices[7]=index[0]
endelse
end
endcase
;print,'TimeBinIndices: ',strtrim(string(TimeBinIndices),2)+','
;print,'n_points: ',strtrim(string(n_points),2)
return,TimeBinIndices
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function scatt_int,theta
int=43.8912620646-1.44346340914*theta+0.0175708164766*theta^2-7.59708485871e-05*theta^3
int90=0.920414
return, int/int90
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function sec_res_check,Esec,dspacing
theta=50.03
alpha=1.0*!DTOR
eta=1.0*!DTOR
deltheta=-83.6815055585+7.7481576722*theta-0.245416584669*theta^2+0.00378347849795* $
theta^3-2.91056998545e-05*theta^4+8.94561691674e-08*theta^5
deltheta*=!DTOR
low_res_sec=((81.80321/(2.0*dspacing^2))*(cos(theta*!DTOR)/sin(theta*!DTOR)^3)*sqrt(deltheta^2+alpha^2+eta^2))
cont = 0
if Esec lt low_res_sec then cont = 1
return, cont
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function secondary_resolution,theta,dspacing
alpha=1.0*!DTOR
eta=1.0*!DTOR
deltheta=-83.6815055585+7.7481576722*theta-0.245416584669*theta^2+0.00378347849795* $
theta^3-2.91056998545e-05*theta^4+8.94561691674e-08*theta^5
deltheta*=!DTOR
Esec=((81.80321/(2.0*dspacing^2))*(cos(theta*!DTOR)/sin(theta*!DTOR)^3)*sqrt(deltheta^2+alpha^2+eta^2))
;print,'Esec: ',Esec
;print,'Esec no deltheta: ',((81.80321/(2.0*dspacing^2))*(cos(theta*!DTOR)/sin(theta*!DTOR)^3)*sqrt(alpha^2+eta^2))
return, Esec
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function SelectDiscrete,theta,event
widget_control,event.top,get_uvalue = pState
Calibration_Angles_str=(*pState).Calibration_Angles_str
Calibration_Angles=Calibration_Angles_str[1,*]

thetadiff=Calibration_Angles-theta
wherepos=where(thetadiff ge 0.0)
wheremin=where(thetadiff[wherepos] eq min(thetadiff[wherepos]))
theta=(Calibration_Angles[wherepos])[wheremin]
;print,'theta: ',theta
return,float(theta[0])
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mepChopperPhases,event
widget_control,event.top,get_uvalue = pState
common vc_find_share, l14,l15,mn,delt,Em
common Esec_share, Esec,dspacing
x=(*pState).x
y=(*pState).y
; polyfill,x,y,/data,color=(*pState).colors.black, $
;        CLIP=[min(x),min(y),max(x),max(y)], noclip = 0
;get constants
TimeBins=(*pState).TimeBins
constants=(*pState).constants
l21=constants.l21
l23=constants.l23
;
l14=constants.l14
l15=constants.l15
l24=constants.l24
l25=constants.l25
; note that lDiff,lTOFMon and lprim should correspond to the lengths measured from the Master'
; chopper and not the snail chopper.  These parameters are used in the calculation of the
; time binning
lDiff=constants.lDiff
lTOFMon=constants.lTOFMon
lprim=constants.lprim
HP=constants.Histogram_Period
;
;
;
conv=constants.meVtoJoules
TimeWinRatio=double(l25/lprim)
D=constants.D
v002=constants.v002
mn=constants.mn
h=constants.h
omega=constants.omega
PulseWidth=constants.PulseWidth
dspace_array=(*pState).dspace_array
;get input parameters
widget_control,(*pState).EM,get_value = Em_set
Em_set=float(Em_set[0])
; define limits
if Em_set gt 20.0 then begin
Em_set=20.0
widget_control,(*pState).EM,set_value = Em_set
endif
widget_control,(*pState).Master,get_value =Master
Master=float(Master[0])
widget_control,(*pState).mica,get_value =mica
mica=fix(mica[0])
dspacing=dspace_array[mica]
;
if (Em_set lt -0.2) and (mica eq 0) then begin
Em_set=-0.2
widget_control,(*pState).EM,set_value = Em_set
endif
;
;calculate delt
delt=D/(2.0*v002)
;print,'delt =',delt


Energy_Window_Option_Value=(*pState).Energy_Window_Option_Value

if Energy_Window_Option_Value eq 0 then begin
    if mica eq 1 then delt/=3.0 ;004 reflection
    if mica eq 2 then delt/=6.0 ;006 reflection
    if mica eq 3 then delt/=6.0 ;008 reflection
endif
;
if Energy_Window_Option_Value eq 2 then begin
delt*=(*pState).Energy_Window_Slider*0.001
endif

;
if mica eq 0 then mica_int=(*pState).constants.mica_int_002 ;002 reflection
if mica eq 1 then mica_int=(*pState).constants.mica_int_004 ;004 reflection
if mica eq 2 then mica_int=(*pState).constants.mica_int_006 ;006 reflection
if mica eq 3 then mica_int=(*pState).constants.mica_int_008 ;008 reflection


delt*=TimeWinRatio ;convert to time window at choppers
;print,'foo =',360.0*50.0*delt
deltmax=omega/(360.0*50.0)
if delt gt deltmax then delt = deltmax


Triffid_Option_Value=(*pState).Triffid_Option_Value
IF Triffid_Option_Value EQ 0 THEN BEGIN ; RESOLUTION MATCHING


;first guess is Em+backscattering
theta=90.0
;Em=Em_set
E_analyser=81.80321/(Bragg(dspacing,theta))^2
FOR i = 0,9 do begin ;ten cycles
Em=Em_set+E_analyser
;if i eq 9 then print,'Em =',Em
;if i eq 9 then print,'E_analyser =',E_analyser
;
Em*=conv
vm=sqrt((Em*2.0)/mn)
;these expressions are not correct; they are needed just for the input to the FX_ROOT function.
; vl and and vu must encompass vc.
tm=l24/vm
tl=tm+delt
tu=tm-delt
vl=l24/tl
vu=l24/tu
;
;find vc
;first define initial guess
;guess =[lower_limit,middle, upper_limit]
;inital guess is vm
vec=[vl,vm,vu]
;print,vec
vc=FX_ROOT(vec, 'vc_find',/double)
;if i eq 9 then print,'vc =',vc
; print,'vec =',vec
;print,'vc =',vc
;
PulseWidth/=Master
;print,'delt: ',delt
;Find lower and higher energy limits
tc24=l24/vc
tc25=l25/vc
vl=l25/(tc25+(delt/2.0)+PulseWidth)
vu=l24/(tc24-(delt/2.0)-PulseWidth)
El=0.5*mn*vl^2
Eu=0.5*mn*vu^2
El/=conv ;convert to meV
Eu/=conv ;convert to meV
;print,'El =',El
;print,'Eu =',Eu
;in order to determine the energy transfer
;we need to know the energy of the analyser.  This is determined
;by the scattering angle, which itself is set to match the best
;primary resolution at El
E=El
El_res=prime_res(E,Master)
Esec=El_res
;print,'Esec = ',Esec
cont=sec_res_check(Esec,dspacing)
if cont eq 1 then begin
theta_guess=[40.0,52.0,92.0]
theta=FX_ROOT(theta_guess, 'sec_res',/double)
theta=abs(theta);just in case it is complex
    if theta gt 87.42 then theta = 87.42
endif else begin
theta = 50.06
endelse
;
;lambda of analyser found from Bragg Law
lambda=Bragg(dspacing,theta)
;
E_analyser=81.80321/lambda^2
;print,'E_analyser =',E_analyser
ENDFOR

;now run through the script once more choosing theta from the list
;of discrete values

theta=SelectDiscrete(theta,event)

;print,'theta_res = ',theta

ENDIF ELSE BEGIN ; SELECT YOUR OWN VALUE OF THETA
Calibration_Angles_str=(*pState).Calibration_Angles_str
angle_index=(*pState).angle_index
theta=Calibration_Angles_str[1,angle_index]
;print,'theta_nores = ',theta
ENDELSE


E_analyser=81.80321/(Bragg(dspacing,theta))^2
Em=Em_set+E_analyser
Em*=conv
vm=sqrt((Em*2.0)/mn)
tm=l24/vm
tl=tm+delt
tu=tm-delt
vl=l24/tl
vu=l24/tu
vec=[vl,vm,vu]
vc=FX_ROOT(vec, 'vc_find',/double)
;
;
;
master_freq=50.0*Master
Master_phase=180.0
ChopperPhasesFine=0
while ChopperPhasesFine eq 0 do begin
MasterTimeDelay=1/(50.0*4*Master)+(Master_phase/(360.0*50.0*Master))
;calculate snail phase
;
SnailTimeDelay=MasterTimeDelay+l21/vc-0.005
while SnailTimeDelay lt 0 do begin
SnailTimeDelay+=0.02
endwhile
Snail_Phase=360.0*(SnailTimeDelay/0.02)
;
RabbitTimeDelay=MasterTimeDelay+l23/vc-0.005
while RabbitTimeDelay lt 0 do begin
RabbitTimeDelay+=0.02
endwhile
while RabbitTimeDelay gt 0.02 do begin
RabbitTimeDelay-=0.02
endwhile
Rabbit_Phase=360.0*(RabbitTimeDelay/0.02)
;
Chopper4TimeDelay=MasterTimeDelay+l24/vc-0.005-((0.02/360.0)*((omega-(360.0*50.0*delt))/2.0))
while Chopper4TimeDelay lt 0 do begin
Chopper4TimeDelay+=0.02
endwhile
while Chopper4TimeDelay gt 0.02 do begin
Chopper4TimeDelay-=0.02
endwhile
chopper4_phase=360.0*(Chopper4TimeDelay/0.02)
;
Chopper5TimeDelay=MasterTimeDelay+l25/vc-0.005+((0.02/360.0)*((omega-(360.0*50.0*delt))/2.0))
while Chopper5TimeDelay lt 0 do begin
Chopper5TimeDelay+=0.02
endwhile
while Chopper5TimeDelay gt 0.02 do begin
Chopper5TimeDelay-=0.02
endwhile
chopper5_phase=360.0*(Chopper5TimeDelay/0.02)
;
if (Snail_Phase ge 5.0) and (Snail_Phase le 355.0) and $
    (Master_phase ge 5.0) and (Master_phase le 355.0) and $
    (rabbit_phase ge 5.0) and (rabbit_phase le 355.0) and $
    (chopper4_phase ge 5.0) and (chopper4_phase le 355.0) and $
    (chopper5_phase ge 5.0) and (chopper5_phase le 355.0) then begin
    ChopperPhasesFine = 1
endif else begin
Master_phase+=1.0
    if Master_phase eq 180.0 then begin
    msg=strarr(2)
    msg[0]='Unable to find acceptable phases for all five choppers.'
    msg[1]='Please vary the input parameters'
    void = dialog_message(dialog_parent = event.top,/error,msg)
    return
    endif
endelse
endwhile
;Find lower and higher energy limits
tc24=l24/vc
tc25=l25/vc
;vl=l25/(tc25+(delt/2.0)+PulseWidth)
;vu=l24/(tc24-(delt/2.0)-PulseWidth)
vl=l24/(tc24+(delt/2.0)+PulseWidth)
vu=l25/(tc25-(delt/2.0)-PulseWidth)
;vl=l24/(tc24+(delt/2.0))
;vu=l25/(tc25-(delt/2.0))
El=0.5*mn*vl^2
Eu=0.5*mn*vu^2
El/=conv ;convert to meV
Eu/=conv ;convert to meV
;print,'El =',El
;print,'Eu =',Eu
(*pState).El=El
(*pState).Eu=Eu
;in order to determine the energy transfer
;we need to know the energy of the analyser.  This is determined
;by the scattering angle, which itself is set to match the best
;primary resolution at El
E=El
El_res=prime_res(E,Master)
;Esec=El_res
;print,'Esec = ',Esec
;cont=sec_res_check(Esec,dspacing)
;if cont eq 1 then begin
;theta_guess=[40.0,52.0,92.0]
;theta=FX_ROOT(theta_guess, 'sec_res',/double)
;theta=abs(theta);just in case it is complex
;    if theta gt 87.42 then theta = 87.42
;endif else begin
;theta = 50.03
;endelse
;print,'abstheta =',abs(theta)
;
;lambda of analyser found from Bragg Law
;lambda=Bragg(dspacing,theta)
;
;E_analyser=81.80321/lambda^2
;print,'E_analyser =',E_analyser
;print,'v_analyser =',sqrt((conv*E_analyser*2.0)/mn)
;print,'t_analyser =',D*1e6/(sqrt((conv*E_analyser*2.0)/mn))

;widget_control,(*pState).E_analyser,set_value=E_analyser
;
E_lower=El-E_analyser
E_upper=Eu-E_analyser
;print,'E_lower =',E_lower
;print,'E_upper =',E_upper
;as an aside, determine theta for Eu.  If also
; in backscattering, then resolution limited by the secondary instrument

resolution = 0 ;primary
E=Eu
;print,'E = ',E
Eu_res=prime_res(E,Master)
Esec=Eu_res
theta_guess=[40.0,52.0,92.0]
thetau=FX_ROOT(theta_guess, 'sec_res',/double)
;print,'thetau: ',thetau
thetau=abs(thetau);just in case it is complex
if thetau ge theta then resolution = 1 ;secondary
Esec=secondary_resolution(theta,dspacing)
;


;resolution = 0 ;primary
;if theta eq 87.42 then begin
;E=Eu
;;print,'E = ',E
;Eu_res=prime_res(E,Master)
;Esec=Eu_res
;theta_guess=[40.0,52.0,92.0]
;thetau=FX_ROOT(theta_guess, 'sec_res',/double)
;;print,'thetau: ',thetau
;thetau=abs(thetau);just in case it is complex
;if thetau ge 87.42 then resolution = 1 ;secondary
;;it is not possible to match the secondary to the primary resolution
;;   secondary resolution is the value at 87.42 for the given d-spacing
;if mica eq 0 then Esec=0.000990355 ;002 reflection
;if mica eq 1 then Esec=0.00396142 ;004 reflection
;if mica eq 2 then Esec=0.00891320 ;006 reflection
;if mica eq 3 then Esec=0.0158457 ;008 reflection
;;
;endif

;print,'resolution =',resolution
E_centre=(E_upper+E_lower)/2.0
;print,'E_centre =',E_centre

;print,'El_res = ',El_res
;if n_elements(Eu_res) gt 0 then print,'Eu_res = ',Eu_res
;print,'Esec = ',Esec
(*pState).Esec=Esec
;print,'theta =',theta
scatt_enhancement=scatt_int(theta)
;print,'theta =',theta
;print,'scatt_enhancement =',scatt_enhancement
scattInt=scatt_enhancement*mica_int/Master
widget_control,(*pState).scatt_rel_int,set_value=scattInt
widget_control,(*pState).Ewinl,set_value=E_lower
widget_control,(*pState).Ewinu,set_value=E_upper
;write chopper phases into table
widget_control,(*pState).chopper_table,get_value =output
output[0,0]=Snail_Phase
output[0,1]=Master_phase
output[0,2]=rabbit_phase
output[0,3]=chopper4_phase
output[0,4]=chopper5_phase
output[1,1]=Master_freq

widget_control,(*pState).chopper_table,set_value=output

; calculate Q limits

phivals=[30,60,90,120,150]
Erange=[E_lower,E_upper]
ny=n_elements(phivals)
nx=n_elements(Erange)
uy = 1+bytarr(ny)
ux = 1+bytarr(nx)
phimat = ux#phivals
xmat = Erange#uy
alpha=2.072099427
qmat = sqrt((2.0*E_analyser+xmat-2.0*sqrt(E_analyser*(xmat+E_analyser))*cos(phimat*!dtor))/alpha)

Qmin=min(qmat)
Qmax=max(qmat)
(*pState).Qmin=Qmin
(*pState).Qmax=Qmax
;print, 'Qmin =',Qmin
;print, 'Qmax =',Qmax

widget_control,(*pState).Qwinl,set_value=Qmin
widget_control,(*pState).Qwinu,set_value=Qmax

widget_control,(*pState).scatt_angle,set_value=theta
widget_control,(*pState).Res,set_value=resolution
(*pState).E_analyser=E_analyser

;print,'E_analyser:',E_analyser


; time bins...
v_sec=sqrt(E_analyser*conv*2.0/mn)
t_sec=D/v_sec
tl_prim=lprim/vl
tu_prim=lprim/vu
tm_prim=lprim/vm
;
;print,'tl_prim: ',tl_prim
;print,'tu_prim: ',tu_prim
;print,'t_sec: ',t_sec
;print,'t_sec: ',1e6*t_sec

tofl=tl_prim+t_sec
tofu=tu_prim+t_sec
tofm=tm_prim+t_sec
;
tofl*=1e6
tofu*=1e6
tofm*=1e6

tu_TOFMon=1e6*lTOFMon/vu
first_neutrons=tu_TOFMon
tl_TOFMon=1e6*lTOFMon/vl

;print,'tl_TOFMon :',tl_TOFMon
;print,'tu_TOFMon :',tu_TOFMon

;
;last neutrons are from v002 reflection
;
E_002analyser=81.80321/(Bragg(dspace_array[0],theta))^2
v_002sec=sqrt(E_002analyser*conv*2.0/mn)
t_002sec=D/v_002sec

;print,'tl_prim: ',tl_prim
;print,'tu_prim: ',tu_prim
;print,'dspace_array[0]: ',dspace_array[0]
;print,'t_002sec: ',t_002sec
last_neutrons=tl_prim+t_002sec
last_neutrons*=1e6
;print,'first_neutrons',(tu_prim+t_002sec)*1e6
;print,'last_neutrons',(tl_prim+t_002sec)*1e6
;
(*pState).First_Neutrons_Time=first_neutrons
(*pState).Last_Neutrons_Time=last_neutrons
Time_Difference=last_neutrons-tu_TOFMon
(*pState).Time_Difference=Time_Difference

;print,'(*pState).First_Neutrons_Time: ',(*pState).First_Neutrons_Time
;print,'(*pState).Last_Neutrons_Time: ',(*pState).Last_Neutrons_Time
;print,'(*pState).Time_Difference: ',(*pState).Time_Difference



;print,'El_res = ',El_res
;print,'El = ',El
;print,'Eu = ',Eu

dDoD_prim=(El_res/(2.0*El))
d_theta=1/246.0
dDoD_sec=d_theta/tan(82.5*!DTOR)
;help,dDoD
;print,'dDoD: ',dDoD
dspaceMin=(h*1e10)/(2.0*mn*vu*sin(82.5*!DTOR))
;help,dspaceMin
dspaceMax=(h*1e10)/(2.0*mn*vl*sin(82.5*!DTOR))
;help,dspaceMax
dspacerange=dspaceMax-dspaceMin
;help,dspacerange
BestRes_prim=dDoD_prim*dspaceMin
BestRes_sec=dDoD_sec*dspaceMin
BestRes=sqrt(BestRes_prim^2+BestRes_sec^2)
;help,BestRes
nodiffbins=4.0*dspacerange/BestRes
;help,nodiffbins
nodiffbins=long(nodiffbins) ;turns out to be the same for all angles

;print,'nodiffbins: ',nodiffbins
;print,'dDoD_prim: ',dDoD_prim
;print,'dDoD_sec: ',dDoD_sec

; calculate the number of time bins
if (*pState).Histogram_Option_Value eq 0 then begin
E_window=E_upper-E_lower
resol=sqrt(El_res^2+Esec^2)
TimeBinNumber=long(4.0*E_window/resol)
if TimeBinNumber lt 1 then TimeBinNumber = 1
(*pState).Time_Bin_Number = TimeBinNumber
endif
if (*pState).Histogram_Option_Value eq 1 then (*pState).Time_Bin_Number = nodiffbins

;help,(*pState).Time_Bin_Number
TimeBinNumber = (*pState).Time_Bin_Number





TOF_step=(tofl-tofu)/(TimeBinNumber)

;
;The step size must be an integer in the units of 100ns.
;
TOF_step*=10
TOF_step=long(TOF_step)

if TOF_step gt 1000 then TOF_step =  1000


if TimeBins.filefound eq 1 then begin
TimeBinStep_arr=TimeBins.TimeBinStep_arr
TimeBinNumber_arr=TimeBins.TimeBinNumber_arr
TOF_step_original=TOF_step
difference=TOF_step-TimeBinStep_arr
mindiff=min(difference,minsubscript,/absolute)
TOF_step=TimeBinStep_arr[minsubscript]
TimeBinNumber_Fanni=TimeBinNumber_arr[minsubscript]
    if TOF_step_original lt TOF_step then begin
       if minsubscript gt 0 then begin
       TOF_step = TimeBinStep_arr[minsubscript-1]
       TimeBinNumber_Fanni=TimeBinNumber_arr[minsubscript-1]
       endif
    endif
endif



TOF_step=float(TOF_step/10.0)
TimeBinNumber=((tofl-tofu)/TOF_step)
(*pState).Time_Bin_Number=TimeBinNumber
;
;
;
;
;start and end the time binning with plenty of room
;
;TOF_start=first_neutrons-(1e6*(tl_prim-tu_prim))
;print,'TOF_start: ',TOF_start
;print,'first_neutrons: ',first_neutrons
TOF_end=last_neutrons+((1e6*(tl_prim-tu_prim))/2.0)
;print,'last_neutrons: ',last_neutrons
;print,'((1e6*(tl_prim-tu_prim))/2.0) :',((1e6*(tl_prim-tu_prim))/2.0)
TOF_start=TOF_end-HP
;
;anticipate the timeoffsets
timeoffsets=(*pState).timeoffsets
offset=0.0
masterfundamental=fix(Master[0])
if masterfundamental eq 1 then offset=timeoffsets.master1_timeoffset
if masterfundamental eq 2 then offset=timeoffsets.master2_timeoffset
if masterfundamental eq 3 then offset=timeoffsets.master3_timeoffset
if masterfundamental eq 4 then offset=timeoffsets.master4_timeoffset
if masterfundamental eq 5 then offset=timeoffsets.master5_timeoffset
if masterfundamental eq 6 then offset=timeoffsets.master6_timeoffset
if masterfundamental eq 7 then offset=timeoffsets.master7_timeoffset
;
TOF_start-=offset
TOF_end-=offset
;
;
;TOF_start=long(TOF_start)
tof_width=TOF_end-TOF_start
;
;print, 'vl: ',vl
;print, 'vu: ',vu
;
;
TimeBinIndices=GenerateTimebinIndices(event,vl,vu,TOF_start,TOF_width,TOF_step,mica,theta)
(*pState).TimeBinIndices=TimeBinIndices
;
;print,'TimeBinIndices: ',TimeBinIndices
(*pState).Time_Bin_Start=TOF_start
(*pState).Time_Bin_Step=TOF_step
(*pState).Total_Time_Bin_Number=long(tof_width/TOF_step)
(*pState).Time_Bin_Width=tof_width

;print,'(*pState).Time_Bin_Start: ',(*pState).Time_Bin_Start
;print,'(*pState).Time_Bin_Step: ',(*pState).Time_Bin_Step
;print,'(*pState).Total_Time_Bin_Number: ',(*pState).Total_Time_Bin_Number
;print,'(*pState).Time_Bin_Width: ',(*pState).Time_Bin_Width


;calculate minimum and maximum d-spacing
dspaceMin=(h*1e10)/(2.0*mn*vu*sin(82.5*!DTOR))
dspaceMax=(h*1e10)/(2.0*mn*vl*sin(7.5*!DTOR))
    widget_control,(*pState).dspacingl,set_value=dspaceMin
    widget_control,(*pState).dspacingu,set_value=dspaceMax
;sensitize freebie bases appropriatley
; and then write to sensitized fields
case mica of
0:  begin       ;002 reflection
    widget_control,(*pState).R002,sensitive=0
    widget_control,(*pState).Ewinl_002,set_value=''
    widget_control,(*pState).Ewinu_002,set_value=''
    widget_control,(*pState).Qwinl_002,set_value=''
    widget_control,(*pState).Qwinu_002,set_value=''
;
    widget_control,(*pState).R004,sensitive=0
    widget_control,(*pState).Ewinl_004,set_value=''
    widget_control,(*pState).Ewinu_004,set_value=''
    widget_control,(*pState).Qwinl_004,set_value=''
    widget_control,(*pState).Qwinu_004,set_value=''
;
    widget_control,(*pState).R006,sensitive=0
    widget_control,(*pState).Ewinl_006,set_value=''
    widget_control,(*pState).Ewinu_006,set_value=''
    widget_control,(*pState).Qwinl_006,set_value=''
    widget_control,(*pState).Qwinu_006,set_value=''
    end
1:  begin       ;004 reflection
    widget_control,(*pState).R002,sensitive=1
    lambda=Bragg(dspace_array[0],theta)
    E_analysert=81.80321/lambda^2
    E_lowert=El-E_analysert
    E_uppert=Eu-E_analysert
    widget_control,(*pState).Ewinl_002,set_value=E_lowert
    widget_control,(*pState).Ewinu_002,set_value=E_uppert
;
    Eranget=[E_lowert,E_uppert]
    xmatt = Eranget#uy
    qmatt = sqrt((2.0*E_analysert+xmatt-2.0*sqrt(E_analysert*(xmatt+E_analysert))*cos(phimat*!dtor))/alpha)
    Qmint=min(qmatt)
    Qmaxt=max(qmatt)
    widget_control,(*pState).Qwinl_002,set_value=Qmint
    widget_control,(*pState).Qwinu_002,set_value=Qmaxt
    widget_control,(*pState).R004,sensitive=0
    widget_control,(*pState).Ewinl_004,set_value=''
    widget_control,(*pState).Ewinu_004,set_value=''
    widget_control,(*pState).Qwinl_004,set_value=''
    widget_control,(*pState).Qwinu_004,set_value=''
    widget_control,(*pState).R006,sensitive=0
    widget_control,(*pState).Ewinl_006,set_value=''
    widget_control,(*pState).Ewinu_006,set_value=''
    widget_control,(*pState).Qwinl_006,set_value=''
    widget_control,(*pState).Qwinu_006,set_value=''
    end
2:  begin       ;006 reflection
    widget_control,(*pState).R002,sensitive=1
    lambda=Bragg(dspace_array[0],theta)
    E_analysert=81.80321/lambda^2
    E_lowert=El-E_analysert
    E_uppert=Eu-E_analysert
    widget_control,(*pState).Ewinl_002,set_value=E_lowert
    widget_control,(*pState).Ewinu_002,set_value=E_uppert
;
    Eranget=[E_lowert,E_uppert]
    xmatt = Eranget#uy
    qmatt = sqrt((2.0*E_analysert+xmatt-2.0*sqrt(E_analysert*(xmatt+E_analysert))*cos(phimat*!dtor))/alpha)
    Qmint=min(qmatt)
    Qmaxt=max(qmatt)
    widget_control,(*pState).Qwinl_002,set_value=Qmint
    widget_control,(*pState).Qwinu_002,set_value=Qmaxt
;
    widget_control,(*pState).R004,sensitive=1
    lambda=Bragg(dspace_array[1],theta)
    E_analysert=81.80321/lambda^2
    E_lowert=El-E_analysert
    E_uppert=Eu-E_analysert
    widget_control,(*pState).Ewinl_004,set_value=E_lowert
    widget_control,(*pState).Ewinu_004,set_value=E_uppert
;
    Eranget=[E_lowert,E_uppert]
    xmatt = Eranget#uy
    qmatt = sqrt((2.0*E_analysert+xmatt-2.0*sqrt(E_analysert*(xmatt+E_analysert))*cos(phimat*!dtor))/alpha)
    Qmint=min(qmatt)
    Qmaxt=max(qmatt)
    widget_control,(*pState).Qwinl_004,set_value=Qmint
    widget_control,(*pState).Qwinu_004,set_value=Qmaxt
;
    widget_control,(*pState).R006,sensitive=0
    widget_control,(*pState).Ewinl_006,set_value=''
    widget_control,(*pState).Ewinu_006,set_value=''
    widget_control,(*pState).Qwinl_006,set_value=''
    widget_control,(*pState).Qwinu_006,set_value=''
    end
3:  begin       ;008 reflection
    widget_control,(*pState).R002,sensitive=1
    lambda=Bragg(dspace_array[0],theta)
    E_analysert=81.80321/lambda^2
    E_lowert=El-E_analysert
    E_uppert=Eu-E_analysert
    widget_control,(*pState).Ewinl_002,set_value=E_lowert
    widget_control,(*pState).Ewinu_002,set_value=E_uppert
;
    Eranget=[E_lowert,E_uppert]
    xmatt = Eranget#uy
    qmatt = sqrt((2.0*E_analysert+xmatt-2.0*sqrt(E_analysert*(xmatt+E_analysert))*cos(phimat*!dtor))/alpha)
    Qmint=min(qmatt)
    Qmaxt=max(qmatt)
    widget_control,(*pState).Qwinl_002,set_value=Qmint
    widget_control,(*pState).Qwinu_002,set_value=Qmaxt
    widget_control,(*pState).R004,sensitive=1
    lambda=Bragg(dspace_array[1],theta)
    E_analysert=81.80321/lambda^2
    E_lowert=El-E_analysert
    E_uppert=Eu-E_analysert
    widget_control,(*pState).Ewinl_004,set_value=E_lowert
    widget_control,(*pState).Ewinu_004,set_value=E_uppert
;
    Eranget=[E_lowert,E_uppert]
    xmatt = Eranget#uy
    qmatt = sqrt((2.0*E_analysert+xmatt-2.0*sqrt(E_analysert*(xmatt+E_analysert))*cos(phimat*!dtor))/alpha)
    Qmint=min(qmatt)
    Qmaxt=max(qmatt)
    widget_control,(*pState).Qwinl_004,set_value=Qmint
    widget_control,(*pState).Qwinu_004,set_value=Qmaxt
;
    widget_control,(*pState).R006,sensitive=1
    lambda=Bragg(dspace_array[2],theta)
    E_analysert=81.80321/lambda^2
    E_lowert=El-E_analysert
    E_uppert=Eu-E_analysert
    widget_control,(*pState).Ewinl_006,set_value=E_lowert
    widget_control,(*pState).Ewinu_006,set_value=E_uppert
;
    Eranget=[E_lowert,E_uppert]
    xmatt = Eranget#uy
    qmatt = sqrt((2.0*E_analysert+xmatt-2.0*sqrt(E_analysert*(xmatt+E_analysert))*cos(phimat*!dtor))/alpha)
    Qmint=min(qmatt)
    Qmaxt=max(qmatt)
    widget_control,(*pState).Qwinl_006,set_value=Qmint
    widget_control,(*pState).Qwinu_006,set_value=Qmaxt
;
    end
endcase


wset,(*pState).winpix_f

 plot,x,y,xrange = [0,max(x)],yrange = [0,max(y)], $
     xstyle = 1,ystyle = 1,xtitle = 'Energy / meV', $
     ytitle = 'Flux', title = 'Flux at Sample',linestyle = 0, $
     thick = 1.0, psym=0, symsize=1.0

 polyfill,x,y,/data,color=(*pState).colors.red, $
        CLIP=[El,0,Eu,max(y)], noclip = 0

wset,(*pState).fluxwinVis
device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winPix_f]

;print,'El: ',El
;print,'Eu: ',Eu

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Allenspach_Message_destroy,event
widget_control,event.top,get_uvalue = pState4
widget_control,event.top,/destroy
wdelete,(*pState4).winpix_Allenspach
main_event=(*pState4).main_event
widget_control,main_event.top,get_uvalue = pState
mepPlotQE_range,main_event
(*pState).pix = 1
;ptr_free,pState4
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Allenspach_Message_events,event
widget_control,event.top,get_uvalue = pState4
uname=widget_info(event.id,/uname)
  case uname of
'Allenspach_Abort':    $
begin
(*pState4).abort=0
Allenspach_Message_destroy,event
end
'Allenspach_Proceed':    $
begin
(*pState4).abort=1
Allenspach_Message_destroy,event
end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function Allenspach_Message,event,MasterSet,MasterRecommend
widget_control,event.top,get_uvalue = pState
image=(*pState).Allenspach_pic
;
MasterSetFund=strtrim(string(MasterSet),2)
MasterSet=strtrim(string(MasterSet*50),2)+' Hz'
MasterRecommendSec=MasterRecommend
MasterRecommend=strtrim(string((MasterRecommend-1)*50),2)+' Hz'
MasterRecommendSec=strtrim(string(MasterRecommendSec*50),2)+' Hz'
;
main_event=event
abort = 0
; Centre it.
geom = widget_info(event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50
courier_largefont = get_font_name(/large, /courier)
courier_hugefont = get_font_name(/huge, /courier)

tlb = widget_base(title='Warning from the Big Boss',/col,group_leader=event.top,xoffset=xpos,yoffset=ypos, $
      tlb_frame_attr = 3,/modal)

Base1=widget_base(tlb,/row,/align_center)
;Base2=widget_base(Base1,/row)

    s = size(image)
    sx = s[2] & sy = s[3]
aspect = 1.0*sy/sx              ; find the aspect ratio of the image...

picxsize = 90 & picysize = fix(aspect*picxsize)

picbase = widget_base(Base1,xsize = picxsize,ysize = picysize)

picwin = widget_draw(picbase,xsize = picxsize,ysize = picysize)
    dispimage = image



Allenspach_text=strarr(6)
Allenspach_text[0]='He du blöde user, wa machsch?'
Allenspach_text[1]='Mi Instrumänt isch so planed das d''uflösig vom zwote Teil'
Allenspach_text[2]= 'mit äm erschtä Teil vom Instrumänt gmätscht wird - cool gäl !'
Allenspach_text[3]='Au wänn du jetzt die primäri uflösig no wiiter ufäschrubsch'
Allenspach_text[4]='chasch die sekundäri uflösig nümä verbesserä.'
Allenspach_text[5]='Du verlürsch nu no meh intensität...für nünt!!'

void = widget_text(base1,value = Allenspach_text,xsize = 61,ysize=6,font=courier_largefont)



Base2=widget_base(tlb,/row,/align_center)

Translation_text=strarr(16)
Translation_text[0]='                          Translation:'
Translation_text[1]='The designer of the instrument is somewhat upset with the settings with'
Translation_text[2]='which you plan to execute your experiment.  The instrument is designed
Translation_text[3]='to match the secondary to the primary resolution. However, with the'
Translation_text[4]='settings specified, the secondary resolution can be improved no'
Translation_text[5]='further. In this instance, increasing the master chopper frequency will'
Translation_text[6]='improve the resolution in the primary instrument with little effect'
Translation_text[7]='on the overall resolution.  You will simply lose intensity.  The master'
Translation_text[8]='chopper frequency is currently set to '+MasterSet+' ('+MasterSetFund+' times the fundamental'


if MasterRecommendSec ne '50 Hz' then begin
Translation_text[9]='frequency).  We would recommend reducing this down to at least '+MasterRecommendSec
Translation_text[10]='where the resolution is only just governed by the secondary instrument.'
Translation_text[11]='Reducing the master chopper frequency further to '+MasterRecommend+' is also an'
Translation_text[12]='option, as you are in the realm where resolution matching is still'
Translation_text[13]='possible, and the resolution function is optimal.  Check and see'
Translation_text[14]='whether the overall resolution would be acceptable with the master'
Translation_text[15]='chopper frequency set to '+MasterRecommend+'.'
endif else begin
Translation_text[9]='frequency).  We would recommend reducing this down to '+MasterRecommendSec
Translation_text[10]='where the resolution is only just governed by the secondary instrument.'
Translation_text[11]=''
Translation_text[12]=''
Translation_text[13]=''
Translation_text[14]=''
Translation_text[15]=''
endelse



void = widget_text(base2,value = Translation_text,xsize = 71,ysize=16,font=courier_largefont)

Base3=widget_base(tlb,/row,/align_center)

void = widget_button(Base3,value = 'Heed the Warning and Abort',font=courier_hugefont,uname = 'Allenspach_Abort')

void = widget_button(Base3,value = 'Proceed Regardless',font=courier_hugefont,uname = 'Allenspach_Proceed')

widget_control,tlb,/realize

widget_control,picwin,get_value = picVis


window,/free,/pixmap,xsize = picxsize,ysize = picysize
winpix_Allenspach = !d.window

wset,winpix_Allenspach
tvimage,dispImage
wset,picVis

device,copy = [0,0,!d.x_size,!d.y_size,0,0,winpix_Allenspach]



state4={winpix_Allenspach:winpix_Allenspach, $
    abort:abort, $
    main_event:main_event}

pState4 = ptr_new(state4,/no_copy)
widget_control,tlb,set_uvalue = pState4


xmanager, 'Allenspach_Message',tlb,event_handler='Allenspach_Message_events' ;register with the xmanager
abort=(*pState4).abort
;print,'abortw = ',abort
ptr_free,pState4
return,abort
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function SensibleSettingsCheck,master,resolution,Eu
common Esec_share
MasterSet=Master
;print,'MasterSet: ',MasterSet
;
MasterRecommend = 1
for Master = 1,7 do begin
E=Eu
Eu_res=prime_res(E,Master)
;print,'Eu_res: ',Eu_res
Esec=Eu_res
theta_guess=[40.0,52.0,92.0]
thetau=FX_ROOT(theta_guess, 'sec_res',/double)
;print,'thetau: ',thetau
thetau=abs(thetau);just in case it is complex
if thetau lt 87.42 then MasterRecommend=Master+1
endfor
if MasterRecommend eq MasterSet then begin
MasterChange=0
endif else begin
MasterChange=1
endelse
;print,'MasterChange: ',MasterChange
MasterSettingsStructure={MasterChange:MasterChange, $
                 MasterSet:MasterSet, $
                 MasterRecommend:MasterRecommend}
return,MasterSettingsStructure
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MEP_save,event
widget_control,event.top,get_uvalue = pState
;parameters in field entry
widget_control,(*pState).Em,get_value=Em
widget_control,(*pState).Master,get_value=Master
widget_control,(*pState).mica,get_value =mica
widget_control,(*pState).Chopper_Table,get_value=output
output[1,*]*=60.0;convert to rpm
;help,output
widget_control,(*pState).Ewinl,get_value=E_lower
widget_control,(*pState).Ewinu,get_value=E_upper
widget_control,(*pState).Qwinl,get_value=Qmin
widget_control,(*pState).Qwinu,get_value=Qmax
widget_control,(*pState).scatt_angle,get_value=theta
widget_control,(*pState).scatt_rel_int,get_value=scattInt
widget_control,(*pState).Res,get_value=resolution
widget_control,(*pState).dspacingl,get_value=dspaceMin
widget_control,(*pState).dspacingu,get_value=dspaceMax
widget_control,(*pState).Ewinl_002,get_value=Ewinl_002
widget_control,(*pState).Ewinu_002,get_value=Ewinu_002
widget_control,(*pState).Ewinl_004,get_value=Ewinl_004
widget_control,(*pState).Ewinu_004,get_value=Ewinu_004
widget_control,(*pState).Ewinl_006,get_value=Ewinl_006
widget_control,(*pState).Ewinu_006,get_value=Ewinu_006
widget_control,(*pState).Qwinl_002,get_value=Qwinl_002
widget_control,(*pState).Qwinu_002,get_value=Qwinu_002
widget_control,(*pState).Qwinl_004,get_value=Qwinl_004
widget_control,(*pState).Qwinu_004,get_value=Qwinu_004
widget_control,(*pState).Qwinl_006,get_value=Qwinl_006
widget_control,(*pState).Qwinu_006,get_value=Qwinu_006
; other parameters
El=(*pState).El
Eu=(*pState).Eu
E_analyser=(*pState).E_analyser
Esec=(*pState).Esec
First_Neutrons_Time=(*pState).First_Neutrons_Time
Last_Neutrons_Time=(*pState).Last_Neutrons_Time
Time_Difference=(*pState).Time_Difference
Time_Bin_Number=(*pState).Time_Bin_Number
Time_Bin_Start=(*pState).Time_Bin_Start
Time_Bin_Step=(*pState).Time_Bin_Step
Time_Bin_Width=(*pState).Time_Bin_Width
Total_Time_Bin_Number=(*pState).Total_Time_Bin_Number
Histogram_Option_Value=(*pState).Histogram_Option_Value
TimeBinIndices=(*pState).TimeBinIndices
angle_index=(*pState).angle_index

;print,'Histogram_Option_Value = ',Histogram_Option_Value
;master, resolution, Histogram_Option_Value

Triffid_Option_Value=(*pState).Triffid_Option_Value
Energy_Window_Option_Value=(*pState).Energy_Window_Option_Value
Energy_Window_Slider=(*pState).Energy_Window_Slider
if (master ne 0) and (resolution eq 1) and $
(Histogram_Option_Value ne 1) and (Triffid_Option_Value eq 0) then begin
MasterSettingsStructure=SensibleSettingsCheck(master,resolution,Eu)
MasterChange=MasterSettingsStructure.MasterChange
MasterSet=MasterSettingsStructure.MasterSet
MasterRecommend=MasterSettingsStructure.MasterRecommend
;print,MasterSettingsStructure.MasterChange
;print,MasterSettingsStructure.MasterSet
;print,MasterSettingsStructure.MasterRecommend
    if MasterChange eq 1 then begin
abort=Allenspach_Message(event,MasterSet,MasterRecommend)
if abort eq 0 then return
    endif
endif

;save parameters aray
SaveParametersArray={Em:Em, $
               Master:Master, $
               mica:mica, $
               output:output, $
               E_lower:E_lower, $
               E_upper:E_upper, $
               Qmin:Qmin, $
               Qmax:Qmax, $
               theta:theta, $
               scattInt:scattInt, $
               resolution:resolution, $
               dspaceMin:dspaceMin, $
               dspaceMax:dspaceMax, $
               Ewinl_002:Ewinl_002, $
               Ewinu_002:Ewinu_002, $
               Ewinl_004:Ewinl_004, $
               Ewinu_004:Ewinu_004, $
               Ewinl_006:Ewinl_006, $
               Ewinu_006:Ewinu_006, $
               Qwinl_002:Qwinl_002, $
               Qwinu_002:Qwinu_002, $
               Qwinl_004:Qwinl_004, $
               Qwinu_004:Qwinu_004, $
               Qwinl_006:Qwinl_006, $
               Qwinu_006:Qwinu_006, $
               El:El, $
               Eu:Eu, $
               E_analyser:E_analyser, $
               Esec:Esec, $
               First_Neutrons_Time:First_Neutrons_Time, $
               Last_Neutrons_Time:Last_Neutrons_Time, $
               Time_Difference:Time_Difference, $
               Time_Bin_Number:Time_Bin_Number, $
               Time_Bin_Start:Time_Bin_Start, $
               Time_Bin_Step:Time_Bin_Step, $
               Time_Bin_Width:Time_Bin_Width, $
               Total_Time_Bin_Number:Total_Time_Bin_Number, $
               Histogram_Option_Value:Histogram_Option_Value, $
               Triffid_Option_Value:Triffid_Option_Value, $
               Energy_Window_Option_Value:Energy_Window_Option_Value, $
               Energy_Window_Slider:Energy_Window_Slider, $
               angle_index:angle_index, $
               TimeBinIndices:TimeBinIndices $
               }



workDir=(*pState).workDir



    filename=dialog_pickfile(path=workDir,$
      file='MarsPlannerFile.pln',/write,filter="*.pln",/fix_filter)

if n_elements(filename) eq 0 then return
if filename eq '' then return

;file='MEP_restore'
;   fileOut = filepath(file,root_dir = workDir)


;arrayptr=ptr_new(SaveParametersArray)
;save, filename=fileout, arrayptr
;ptr_free, arrayptr

save, filename=filename, SaveParametersArray


end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function sec_res,theta
common Esec_share
alpha=1.0*!DTOR
eta=1.0*!DTOR
deltheta=-83.6815055585+7.7481576722*theta-0.245416584669*theta^2+0.00378347849795* $
theta^3-2.91056998545e-05*theta^4+8.94561691674e-08*theta^5
deltheta*=!DTOR
;Esec=((81.80321/(2.0*dspacing^2))*(cos(theta*!DTOR)/sin(theta*!DTOR)^3)*sqrt(deltheta^2+alpha^2+eta^2))
return, Esec-((81.80321/(2.0*dspacing^2))*(cos(theta*!DTOR)/sin(theta*!DTOR)^3)*sqrt(deltheta^2+alpha^2+eta^2))
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function vc_find,x
common vc_find_share
return, Em-0.25*mn*((l15/((l15/x)+(delt/2.0)))^2+(l14/((l14/x)-(delt/2.0)))^2)
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mepdraw,event
widget_control,event.top,get_uvalue = pState


if (*pState).pix ne 0 then begin
        wset,(*pState).winPix_f
        mepPlot,event
        wset,(*pState).fluxwinVis
       device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winPix_f]
(*pState).pix = 0
;print,'woofpix'
endif



        wset,(*pState).fluxwinVis
case event.type of
0:  begin       ; button press
            (*pState).mouse = event.press
      if (*pState).mouse eq 4 then begin
        (*pState).autoscale = 1
        wset,(*pState).winPix_f
        mepPlot,event
        wset,(*pState).fluxwinVis
       device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winPix_f]
      endif
      if (*pState).mouse eq 1 then begin
        (*pState).xbox[0] = event.x
        (*pState).ybox[0] = event.y
        wset,(*pState).fluxwinVis
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winPix_f]
      empty
        (*pState).autoscale = 0
        widget_control,(*pState).fluxwin,/draw_motion_events
;   print,'woof'
     endif
    end
1:  begin    ; button release
     if (*pState).mouse eq 1 then begin
      xll = (*pState).xbox[0] < (*pState).xbox[1]
      yll = (*pState).ybox[0] < (*pState).ybox[1]
      w = abs((*pState).xbox[1] - (*pState).xbox[0])
      h = abs((*pState).ybox[1] - (*pState).ybox[0])
      xur = xll + w
      yur = yll + h
      ll = convert_coord(xll,yll,/device,/to_data)
      ur = convert_coord(xur,yur,/device,/to_data)
      (*pState).xrange = [ll[0],ur[0]]
      (*pState).yrange = [ll[1],ur[1]]
      wset,(*pState).winPix_f
        mepPlot,event
        wset,(*pState).fluxwinVis
      device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winPix_f]
      (*pState).mouse = 0B
      widget_control,(*pState).fluxwin,draw_motion_events = 0
     endif
     if (*pState).mouse eq 4 then begin
      wset,(*pState).winPix_f
        mepPlot,event
        wset,(*pState).fluxwinVis
      device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winPix_f]
      (*pState).mouse = 0B
      widget_control,(*pState).fluxwin,draw_motion_events = 0
     endif
    end
2:  begin    ; mouse motion
      if (*pState).mouse eq 1 then begin
       (*pState).xbox[1] = event.x
       (*pState).ybox[1] = event.y
       xc = [(*pState).xbox[0],event.x,event.x,$
             (*pState).xbox[0],$
             (*pState).xbox[0]]
       yc = [(*pState).ybox[0],(*pState).ybox[0],$
             event.y,event.y,$
             (*pState).ybox[0]]
        wset,(*pState).fluxwinVis
       device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winPix_f]
       plots,xc,yc,/device
       empty
      endif
    end
else:
endcase
return
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function flux,x
;theoretical flux
;
;wheregt1=where(x gt 1.45)
;wheregt2=where(x gt 2.65)
;y=3.9514e+06*exp(-(alog(x[where(x ne 0.0)]/1.0343)/2.5194)^2)
;;y[wheregt1]=1.0534e+06+3.9499e+06*exp(-0.22534*x[wheregt1])
;y[wheregt1]= 3.975e+06+1.7173e+05*x[wheregt1]-1.652e+05*(x[wheregt1])^2
;y[wheregt2]=83100+2.6206e+06*exp(-0.24483*x[wheregt2])+ $
;3.4821e+06*exp(-0.24473*x[wheregt2])

;experimental flux
;
wheregt1=where(x gt 1.505)
wheregt2=where(x gt 2.405)
y=2.4716e+06*exp(-(alog(x[where(x ne 0.0)]/1.4482)/1.9393)^2)-29926
;y[wheregt1]=1.0534e+06+3.9499e+06*exp(-0.22534*x[wheregt1])
;y[wheregt1]= 2.4676e+06+2.8774e+05*x[wheregt1]-2.0228e+05*(x[wheregt1])^2

;y[wheregt1]= 2.2703e+06+4.865e+05*x[wheregt1]-2.5133e+05*(x[wheregt1])^2
y[wheregt1]= -4.0097e+05+4.8791e+06*x[wheregt1]-2.6151e+06*(x[wheregt1])^2+4.1629e+05*(x[wheregt1])^3


;y[wheregt2]=-1.3068e+05+5.3414e+05*exp(-0.052362*x[wheregt2])+ $
;3.9716e+06*exp(-0.36715*x[wheregt2])


y[wheregt2]=-1.3068e+05+5.3414e+05*exp(-0.052362*x[wheregt2])+ $
3.9716e+06*exp(-0.36715*x[wheregt2])



;multiply by the x axis to convert units (see Fig. 29 on Page 28 of MARS - A Concept Study)
;y*=x
return,y
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function calcTriangle,E,E_analyser,phi
alpha=2.072099427
return,sqrt((2.0*E_analyser+E-2.0*sqrt(E_analyser*(E+E_analyser))*cos(phi*!dtor))/alpha)
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mepPlotQE_range,event
;help,event
;print,'event =',event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).Ewinl,get_value=E_lower
E_lower=float(E_lower[0])
widget_control,(*pState).Ewinu,get_value=E_upper
E_upper=float(E_upper[0])
E_analyser=(*pState).E_analyser
x=(*pState).x
y=(*pState).y
El=(*pState).El
Eu=(*pState).Eu
Qmin=(*pState).Qmin
Qmax=(*pState).Qmax


npts=1000
dE=(E_upper-E_lower)/(npts-1.0)
E=E_lower+dE*findgen(npts)
phi=30.0
Q=calcTriangle(E,E_analyser,phi)



wset,(*pState).winpix_m


  plot,E,Q,ytitle = 'Q (!6!sA!r!u!9 %!6!n!E-1!N)', $
     xtitle = '!6Energy Transfer (meV)',xrange = [E_lower,E_upper],yrange = [Qmin,Qmax],$
     xstyle = 1,ystyle = 1, title = 'Accessible Energy and Momentum Transfer Range'

  oplot,E,Q,linestyle = 0, thick = 3.0, psym=0, symsize=1.0,color=(*pState).colors.blue



phi=60.0
Q=calcTriangle(E,E_analyser,phi)
  oplot,E,Q,linestyle = 0, thick = 3.0, psym=0, symsize=1.0,color=(*pState).colors.red

phi=90.0
Q=calcTriangle(E,E_analyser,phi)
  oplot,E,Q,linestyle = 0, thick = 3.0, psym=0, symsize=1.0,color=(*pState).colors.green

phi=120.0
Q=calcTriangle(E,E_analyser,phi)
  oplot,E,Q,linestyle = 0, thick = 3.0, psym=0, symsize=1.0,color=(*pState).colors.beige

phi=150.0
Q=calcTriangle(E,E_analyser,phi)
  oplot,E,Q,linestyle = 0, thick = 3.0, psym=0, symsize=1.0,color=(*pState).colors.magenta

wset,(*pState).winVis

device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winPix_m]

(*pState).pix=1

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro SICS_Dialogue_Update,event
widget_control,event.top,get_uvalue = pState
Connection_Update_tlb=(*pState).Connection_Update_tlb
widget_control,Connection_Update_tlb,get_uvalue = pState3
SICS_Dialogue=*(*pState).SICS_Dialogue
widget_control,(*pState3).win_sics_text,set_value = SICS_Dialogue
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Terminate_SICS_Commands,event
widget_control,event.top,get_uvalue = pState3
widget_control,(*pState3).terminate_button,sensitive=0
main_event=(*pState3).main_event
widget_control,main_event.top,get_uvalue = pState
(*pState).stage=0
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Connection_Update_Destroy,event
widget_control,event.top,get_uvalue = pState3
widget_control,event.top,/destroy
wdelete,(*pState3).winpix_koennecke
main_event=(*pState3).main_event
widget_control,main_event.top,get_uvalue = pState
mepPlotQE_range,main_event
(*pState).pix = 1
ptr_free,pState3
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Connection_Update,event
widget_control,event.top,get_uvalue = pState
image=(*pState).koennecke_pic
;
main_event=event
;
; Centre it.
geom = widget_info(event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50
courier_largefont = get_font_name(/large, /courier)
courier_hugefont = get_font_name(/huge, /courier)

tlb = widget_base(title='Progress of Dialogue with SICS ',/col,group_leader=event.top,xoffset=xpos,yoffset=ypos, $
      tlb_frame_attr = 3)

(*pState).Connection_Update_tlb=tlb

Base1=widget_base(tlb,/row,/align_center)
;Base2=widget_base(Base1,/row)

    s = size(image)
    sx = s[2] & sy = s[3]
aspect = 1.0*sy/sx              ; find the aspect ratio of the image...

picxsize = 50 & picysize = fix(aspect*picxsize)

picbase = widget_base(Base1,xsize = picxsize,ysize = picysize)

picwin = widget_draw(picbase,xsize = picxsize,ysize = picysize)
    dispimage = image


terminate_button = widget_button(Base1,value = 'Terminate Dialogue with SICS',font=courier_hugefont,event_pro = 'Terminate_SICS_Commands')

close_button = widget_button(Base1,value = 'Close Display',font=courier_hugefont,event_pro = 'Connection_Update_Destroy')

win_sics_text = widget_text(tlb,value = strarr(500),xsize = 60,ysize=50,font=courier_largefont,/scroll)

widget_control,tlb,/realize

widget_control,picwin,get_value = picVis


window,/free,/pixmap,xsize = picxsize,ysize = picysize
winpix_koennecke = !d.window

wset,winpix_koennecke
tvimage,dispImage
wset,picVis

device,copy = [0,0,!d.x_size,!d.y_size,0,0,winpix_koennecke]



state3={win_sics_text:win_sics_text, $
    winpix_koennecke:winpix_koennecke, $
    terminate_button:terminate_button, $
    close_button:close_button, $
    main_event:main_event}

pState3 = ptr_new(state3,/no_copy)
widget_control,tlb,set_uvalue = pState3
xmanager, 'Connection_Update',tlb ;register with the xmanager


end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Planner_Connect,event
widget_control,event.top,get_uvalue = pState
delim=(*pstate).delim
get_lun,UnitUser
(*pstate).UnitUser=UnitUser
get_lun,UnitManager
(*pstate).UnitManager=UnitManager
;filename=!DAVE_AUXILIARY_DIR+'PSI\MARS\MarsSICSInfo_User.txt'
filename=!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MarsSICSInfo_User.txt'
hoststring=''
portstring=''
userstring=''
passwordstring=''
openr,lun,filename,/get_lun
readf,lun,hoststring
readf,lun,portstring
readf,lun,userstring
readf,lun,passwordstring
free_lun,lun,/force
;
equalsign=strpos(hoststring,'=')
host=strmid(hoststring,equalsign+1)
equalsign=strpos(portstring,'=')
port=strmid(portstring,equalsign+1)
port=long(port)
equalsign=strpos(userstring,'=')
user=strmid(userstring,equalsign+1)
equalsign=strpos(passwordstring,'=')
password=strmid(passwordstring,equalsign+1)
;
;
response=sicsconnect(UnitUser,host,port,error=error)
    IF response eq 0 then begin
Dialogue='Connection to SICS with User privilege has been successful.'
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
;print,'Connection Successful'
(*pstate).connection=1
logon=sicslogon(UnitUser,user,password)
if logon eq 0 then begin
Dialogue='However, the SICS User login details are incorrect. Please inspect '
Dialogue=[Dialogue,'and edit the file in the Dave auxillary directory']
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
(*pstate).connection=0
;void = dialog_message(dialog_parent = event.top, $
;'SICS User login is incorrect. Please inspect and edit the file ' +  $
;'in the Dave auxillary directory.  The program will now exit.')
;MEP_exit,event
return
endif
    ENDIF ELSE BEGIN
Dialogue='Unable to connect to MARS'
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
;    void = dialog_message(dialog_parent = event.top, $
;    'Connection to MARS not found.')
    return
    ENDELSE

filename=!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MarsSICSInfo_Manager.txt'
hoststring=''
portstring=''
userstring=''
passwordstring=''
openr,lun,filename,/get_lun
readf,lun,hoststring
readf,lun,portstring
readf,lun,userstring
readf,lun,passwordstring
free_lun,lun,/force
;
equalsign=strpos(hoststring,'=')
host=strmid(hoststring,equalsign+1)
equalsign=strpos(portstring,'=')
port=strmid(portstring,equalsign+1)
port=long(port)
equalsign=strpos(userstring,'=')
user=strmid(userstring,equalsign+1)
equalsign=strpos(passwordstring,'=')
password=strmid(passwordstring,equalsign+1)


response=sicsconnect(UnitManager,host,port,error=error)
    IF response eq 0 then begin
Dialogue='Connection to SICS with Manager privilege has been successful.'
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
;print,'Connection Successful'
(*pstate).connection=1
logon=sicslogon(UnitManager,user,password)
if logon eq 0 then begin
Dialogue='However, the SICS Manager login detailes are incorrect. Please inspect '
Dialogue=[Dialogue,'and edit the file in the Dave auxillary directory']
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
(*pstate).connection=0
;void = dialog_message(dialog_parent = event.top, $
;'SICS User login is incorrect. Please inspect and edit the file ' +  $
;'in the Dave auxillary directory.  The program will now exit.')
;MEP_exit,event
return
endif
    ENDIF ELSE BEGIN
Dialogue='Unable to connect to MARS'
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
;    void = dialog_message(dialog_parent = event.top, $
;    'Connection to MARS not found.')
    ENDELSE


end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Send_Choppers,event
widget_control,event.top,get_uvalue = pState
if (*pState).connection eq 0 then begin
Planner_Connect,event
endif
if (*pState).connection eq 0 then return
UnitUser=(*pstate).UnitUser
;
widget_control,(*pState).Chopper_Table,get_value=Chopper_Table
chopper_info=fltarr(2,5)
reads,Chopper_Table,chopper_info
chopper_info[1,*]*=60.0 ; convert to rpm
Chopper_Table=string(chopper_info)
;choppers
ChopperCommand_array=strarr(6)
ChopperCommand_array[0]='run snailphase '
ChopperCommand_array[1]='run masterphase '
ChopperCommand_array[2]='run rabbitphase '
ChopperCommand_array[3]='run fourphase '
ChopperCommand_array[4]='run fivephase '
ChopperCommand_array[5]='run masterspeed '
;
for i = 0,5 do begin
if i le 4 then begin
ChopperCommand_array[i]+=strtrim(Chopper_Table[0,i],2)
endif else begin
ChopperCommand_array[i]+=strtrim((Chopper_Table[1,1]),2)
endelse
;print,ChopperCommand_array[i]
endfor
for i = 0,5 do begin
Dialogue='Issuing command: '+ChopperCommand_array[i]
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
response=sicsexecute(event,UnitUser,ChopperCommand_array[i])
Dialogue='Response from SICS: '+response
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
;print,'response = ',i,response
;print,''
endfor
command='success'
Dialogue='Issuing command: '+command
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
response=sicsexecute(event,UnitUser,command)
Dialogue='Response from SICS: '+response
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
;print,'response = ',response
;print,''

widget_control,(*pState).mica,get_value =mica
mica=fix(mica[0])

if mica eq 0 then Target_Reflection='002'
if mica eq 1 then Target_Reflection='004'
if mica eq 2 then Target_Reflection='006'
if mica eq 3 then Target_Reflection='008'
command='TargetReflection '+Target_Reflection
Dialogue='Issuing command: '+command
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
response=sicsexecute(event,UnitUser,command)
Dialogue='Response from SICS: '+response
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
;print,'response = ',response



widget_control,(*pState).Em,get_value=Em
widget_control,(*pState).Ewinu,get_value=E_upper
widget_control,(*pState).Ewinl,get_value=E_lower


command='Emid '+strtrim(string(Em),2)
Dialogue='Issuing command: '+command
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
response=sicsexecute(event,UnitUser,command)
Dialogue='Response from SICS: '+response
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
;print,'response = ',response
command='Emax '+strtrim(string(E_upper),2)
Dialogue='Issuing command: '+command
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
response=sicsexecute(event,UnitUser,command)
Dialogue='Response from SICS: '+response
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
;print,'response = ',response
command='Emin '+strtrim(string(E_lower),2)
Dialogue='Issuing command: '+command
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
response=sicsexecute(event,UnitUser,command)
Dialogue='Response from SICS: '+response
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
;print,'response = ',response



Dialogue='No more chopper commands to execute'
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event





end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Send_Triffid,event
widget_control,event.top,get_uvalue = pState
if (*pState).connection eq 0 then begin
Planner_Connect,event
endif
if (*pState).connection eq 0 then return

UnitUser=(*pstate).UnitUser
widget_control,(*pState).scatt_angle,get_value=theta
theta=strtrim(string(theta),2)
command='colldr th '+theta

Dialogue='Issuing command: '+Command
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
response=sicsexecute(event,UnitUser,command)
;print,'response = ',response
Dialogue='Response from SICS: '+response
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
Dialogue='No more triffid commands to execute'
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Send_Histogram,event
widget_control,event.top,get_uvalue = pState
if (*pState).connection eq 0 then begin
Planner_Connect,event
endif
if (*pState).connection eq 0 then return
UnitUser=(*pstate).UnitUser
UnitManager=(*pstate).UnitManager
;
TOF_start=long((*pState).Time_Bin_Start*10.0)
TOF_step=fix((*pState).Time_Bin_Step*10.0)
notimebin=(*pState).Total_Time_Bin_Number
TOF_start=strtrim(string(TOF_start[0]),2)
notimebin=strtrim(string(notimebin[0]),2)
TOF_step=strtrim(string(TOF_step[0]),2)


;HM genbin start step n
;Generates a new equally spaced time binning array.
;Number n time bins will be generated starting from start with a stepwidth of step (example: HM genbin 10 1 5).


command='hm genbin '+TOF_start+' '+TOF_step+' '+notimebin
Dialogue='Issuing command: '+Command
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event

;print,'hm command = ',command

response=sicsexecute(event,UnitManager,command)
Dialogue='Response from SICS: '+response
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event

;print,'response = ',response
command='hm init'
Dialogue='Issuing command: '+Command
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event

response=sicsexecute(event,UnitManager,command)
;print,'response = ',response
Dialogue='Response from SICS: '+response
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event

TimeBinIndices=(*pState).TimeBinIndices
str=strtrim(string(TimeBinIndices[0]),2)+','
for i = 1,12 do begin
str+=strtrim(string(TimeBinIndices[i]),2)+','
endfor
str+=strtrim(string(TimeBinIndices[13]),2)
command='TimeBinIndices '+str
Dialogue='Issuing command: '+Command
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
response=sicsexecute(event,UnitUser,command)
Dialogue='Response from SICS: '+response
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
;print,'response = ',response
;
Dialogue='No more histogram commands to execute'
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Triffid_Set_Events,event
widget_control,event.top,get_uvalue = pState1
main_event=(*pState1).main_event
widget_control,main_event.top,get_uvalue = pState
uname=widget_info(event.id,/uname)
case uname of
'TriffidExit':    $
begin
ptr_free,pState1
widget_control,event.top,/destroy
end
'TriffidOption':    $
begin
widget_control,(*pState1).Triffid_Option,get_value=Triffid_Option_Value
(*pState).Triffid_Option_Value=Triffid_Option_Value
if Triffid_Option_Value eq 0 then begin
widget_control,(*pState1).analyser_angle_droplist,sensitive=0
endif else begin
(*pState).angle_index=widget_info((*pState1).analyser_angle_droplist,/droplist_select)
widget_control,(*pState1).analyser_angle_droplist,sensitive=1
endelse
mepEvents,main_event
end
'analyser_angle':    $
begin
(*pState).angle_index=widget_info((*pState1).analyser_angle_droplist,/droplist_select)
mepEvents,main_event
end
else:
endcase
end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Triffid_Set,event
widget_control,event.top,get_uvalue = pState
Calibration_Angles_str=(*pState).Calibration_Angles_str
Triffid_Option_Value=(*pState).Triffid_Option_Value
angle_index=(*pState).angle_index

geom = widget_info(event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50

tlb = widget_base(title='Select Triffid Angles',/row,group_leader=event.top,xoffset=xpos,yoffset=ypos, $
      tlb_frame_attr = 3,/modal)

base1=widget_base(tlb,/row)


Triffid_Option_Types = ['Resolution Matching',$
              'Manual Select']

Triffid_Option = cw_bgroup(base1,Triffid_Option_Types,/row,/exclusive, $
           set_value = Triffid_Option_Value,/return_index,/no_release,uname='TriffidOption', /frame)


analyser_angle_droplist=widget_Droplist(base1,value=reform(Calibration_Angles_str[1,*]), $
              /dynamic_resize,uname='analyser_angle' )

widget_control,analyser_angle_droplist,set_droplist_select=angle_index
widget_control,analyser_angle_droplist,sensitive=Triffid_Option_Value

void = widget_button(base1,value = 'Exit', uname='TriffidExit')

widget_control,tlb,/realize

main_event=event
state1={main_event:main_event, $
    analyser_angle_droplist:analyser_angle_droplist, $
    Triffid_Option:Triffid_Option $
    }

pState1 = ptr_new(state1,/no_copy)
widget_control,tlb,set_uvalue = pState1

xmanager, 'Triffid_Set',tlb,event_handler = 'Triffid_Set_Events' ;register with the xmanager


end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Energy_Window_Set_Events,event
widget_control,event.top,get_uvalue = pState1
main_event=(*pState1).main_event
widget_control,main_event.top,get_uvalue = pState
uname=widget_info(event.id,/uname)
case uname of
'EWExit':    $
begin
ptr_free,pState1
widget_control,event.top,/destroy
end
'EWOption':    $
begin
widget_control,(*pState1).EW_Option,get_value=EW_Option
(*pState).Energy_Window_Option_Value=EW_Option
if EW_Option ne 2 then begin
widget_control,(*pState1).Energy_Window_Slider,sensitive=0
endif else begin
widget_control,(*pState1).Energy_Window_Slider,sensitive=1
endelse
mepEvents,main_event
end
'EWS':    $
begin
widget_control,(*pState1).Energy_Window_Slider,get_value=Energy_Window_Slider
(*pState).Energy_Window_Slider=Energy_Window_Slider
mepEvents,main_event
end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Energy_Window_Set,event
widget_control,event.top,get_uvalue = pState

geom = widget_info(event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50

tlb = widget_base(title='Energy Window Option',/col,group_leader=event.top,xoffset=xpos,yoffset=ypos, $
      tlb_frame_attr = 3,/modal)

base1=widget_base(tlb,/row)


EW_Option_Types = ['Avoid Inelastic Overlap',$
              'Maximise Energy Window',$
              'Manual Adjust']

EW_Option = cw_bgroup(base1,EW_Option_Types,/row,/exclusive, $
           set_value = (*pState).Energy_Window_Option_Value,/return_index,$
           /no_release,uname='EWOption', /frame)

base2=widget_base(tlb,/row)

Energy_Window_Slider=widget_slider(base2,$
              value=(*pState).Energy_Window_Slider,min=1,max=1000,xsize=410, $
              uname='EWS',/suppress_value, $
              title='                                                Width of Energy Window')

if (*pState).Energy_Window_Option_Value ne 2 then widget_control,Energy_Window_Slider,sensitive=0

void = widget_button(tlb,value = 'Exit', uname='EWExit')

widget_control,tlb,/realize

main_event=event
state1={main_event:main_event, $
    EW_Option:EW_Option, $
        Energy_Window_Slider:Energy_Window_Slider}

pState1 = ptr_new(state1,/no_copy)
widget_control,tlb,set_uvalue = pState1

xmanager, 'Energy_Window_Set',tlb,event_handler = 'Energy_Window_Set_Events' ;register with the xmanager
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Histogram_Set_Events,event
widget_control,event.top,get_uvalue = pState2
main_event=(*pState2).main_event
widget_control,main_event.top,get_uvalue = pState
uname=widget_info(event.id,/uname)
case uname of
'HistogramExit':    $
begin
ptr_free,pState2
widget_control,event.top,/destroy
;daveSensitizeButtons,main_event
end
'HistogramOption':    $
begin
widget_control,(*pState2).Histogram_Option,get_value=Histogram_Option_Value
(*pState).Histogram_Option_Value=Histogram_Option_Value
if (Histogram_Option_Value eq 0) OR (Histogram_Option_Value eq 1) then begin
widget_control,(*pState2).TimeBinNumber,sensitive=0
mepChopperPhases,main_event
Time_Bin_Number=(*pState).Time_Bin_Number
First_Neutrons_Time=(*pState).First_Neutrons_Time
Last_Neutrons_Time=(*pState).Last_Neutrons_Time
Time_Difference=(*pState).Time_Difference
Time_Bin_Start=(*pState).Time_Bin_Start
Time_Bin_Step=(*pState).Time_Bin_Step
Time_Bin_Width=(*pState).Time_Bin_Width
Total_Time_Bin_Number=(*pState).Total_Time_Bin_Number
widget_control,(*pState2).FirstNeutronsTime,set_value=First_Neutrons_Time
widget_control,(*pState2).LastNeutronsTime,set_value=Last_Neutrons_Time
widget_control,(*pState2).TimeDifference,set_value=Time_Difference
widget_control,(*pState2).TimeBinStart,set_value=Time_Bin_Start
widget_control,(*pState2).TimeBinStep,set_value=Time_Bin_Step
widget_control,(*pState2).TimeBinWidth,set_value=Time_Bin_Width
widget_control,(*pState2).TotalTimeBinNumber,set_value=Total_Time_Bin_Number
widget_control,(*pState2).TimeBinNumber,set_value=Time_Bin_Number
endif else begin
widget_control,(*pState2).TimeBinNumber,sensitive=1
endelse
end
'TimeBinUpdate':    $
begin
widget_control,(*pState2).TimeBinNumber,get_value=Time_Bin_Number
(*pState).Time_Bin_Number=Time_Bin_Number
mepChopperPhases,main_event
First_Neutrons_Time=(*pState).First_Neutrons_Time
Last_Neutrons_Time=(*pState).Last_Neutrons_Time
Time_Difference=(*pState).Time_Difference
Time_Bin_Start=(*pState).Time_Bin_Start
Time_Bin_Step=(*pState).Time_Bin_Step
Time_Bin_Width=(*pState).Time_Bin_Width
Total_Time_Bin_Number=(*pState).Total_Time_Bin_Number
widget_control,(*pState2).FirstNeutronsTime,set_value=First_Neutrons_Time
widget_control,(*pState2).LastNeutronsTime,set_value=Last_Neutrons_Time
widget_control,(*pState2).TimeDifference,set_value=Time_Difference
widget_control,(*pState2).TimeBinStart,set_value=Time_Bin_Start
widget_control,(*pState2).TimeBinStep,set_value=Time_Bin_Step
widget_control,(*pState2).TimeBinWidth,set_value=Time_Bin_Width
widget_control,(*pState2).TotalTimeBinNumber,set_value=Total_Time_Bin_Number
end
else:
endcase
end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Histogram_Set,event
widget_control,event.top,get_uvalue = pState
;      daveDeSensitizeButtons,event

First_Neutrons_Time=(*pState).First_Neutrons_Time
Last_Neutrons_Time=(*pState).Last_Neutrons_Time
Time_Difference=(*pState).Time_Difference
Time_Bin_Number=(*pState).Time_Bin_Number
Time_Bin_Start=(*pState).Time_Bin_Start
Time_Bin_Step=(*pState).Time_Bin_Step
Time_Bin_Width=(*pState).Time_Bin_Width
Total_Time_Bin_Number=(*pState).Total_Time_Bin_Number
Histogram_Option_Value=(*pState).Histogram_Option_Value


geom = widget_info(event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50

tlb = widget_base(title='Histogram Memory',/row,group_leader=event.top,xoffset=xpos,yoffset=ypos, $
      tlb_frame_attr = 3,/modal)

base1=widget_base(tlb,/row)


base1c=widget_base(base1,/col,/align_center)


Histogram_Option_Types = ['Optimised for INS',$
              'Optimised for Diffraction', $
              'Specify the Number of Time Bins']

Histogram_Option = cw_bgroup(base1c,Histogram_Option_Types,/col,/exclusive, $
           set_value = Histogram_Option_Value,/return_index,/no_release,uname='HistogramOption', /frame)


basela=widget_base(base1c,/col,/frame,/align_center)

FirstNeutronsTime=cw_field(basela,/col,title='First Neutrons to Reach TOF Monitor', $
          value=First_Neutrons_Time,xsize=15,/noedit)
LastNeutronsTime=cw_field(basela,/col,title='Last 002 Neutrons to Reach Triffids',value=Last_Neutrons_Time,xsize=15,/noedit)
TimeDifference=cw_field(basela,/col,title='Time Difference / us',value=Time_Difference,xsize=15,/noedit)

void = widget_button(base1c,value = 'Exit', uname='HistogramExit')


baselb=widget_base(base1,/col,/frame,/align_center)

;void=widget_label(baselb,value='Histogram Memory')
TimeBinNumber=cw_field(baselb,/col,title='Number of INS Time Bins ', $
              value=Time_Bin_Number,xsize=20,/return_events,uname='TimeBinUpdate')
TimeBinStart=cw_field(baselb,/col,title='Start of Time Bin',value=Time_Bin_Start,xsize=20,/noedit)
TimeBinStep=cw_field(baselb,/col,title='Time Bin Step',value=Time_Bin_Step,xsize=20,/noedit)
TimeBinWidth=cw_field(baselb,/col,title='TOF Window',value=Time_Bin_Width,xsize=20,/noedit)
TotalTimeBinNumber=cw_field(baselb,/col,title='Total Number of Time Bins',value=Total_Time_Bin_Number,xsize=20,/noedit)
if (Histogram_Option_Value eq 0) OR (Histogram_Option_Value eq 1) then begin
widget_control,TimeBinNumber,sensitive=0
endif else begin
widget_control,TimeBinNumber,sensitive=1
endelse



widget_control,tlb,/realize

main_event=event
state2={main_event:main_event, $
    TimeBinNumber:TimeBinNumber, $
    FirstNeutronsTime:FirstNeutronsTime, $
    LastNeutronsTime:LastNeutronsTime, $
    TimeDifference:TimeDifference, $
    TimeBinStart:TimeBinStart, $
    TimeBinStep:TimeBinStep, $
    TimeBinWidth:TimeBinWidth, $
    TotalTimeBinNumber:TotalTimeBinNumber, $
    Histogram_Option:Histogram_Option $
    }

pState2 = ptr_new(state2,/no_copy)
widget_control,tlb,set_uvalue = pState2

xmanager, 'Histogram_Set',tlb,event_handler = 'Histogram_Set_Events' ;register with the xmanager


end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mepEvents,event
widget_control,event.top,get_uvalue = pState

;
   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
    void=dialog_message(dialog_parent=event.top,/error, $
    !ERROR_STATE.MSG)
return
endif
;


IF (TAG_NAMES(event, /STRUCTURE_NAME) EQ 'WIDGET_TIMER') THEN BEGIN
Connection_Update_tlb=(*pState).Connection_Update_tlb
widget_control,Connection_Update_tlb,get_uvalue = pState3
case (*pState).stage of
0:  $
begin
widget_control,(*pState3).close_button,sensitive=1
widget_control,(*pState3).terminate_button,sensitive=1
Dialogue=['Script terminated prematurely.']
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
return
end
1:  $
begin
widget_control,(*pState3).terminate_button,sensitive=0
send_Triffid,event
widget_control,(*pState3).terminate_button,sensitive=1
(*pState).stage=2
Dialogue='The parameters specifying the histogram memory
Dialogue=[Dialogue,'will be sent to the instrument in 10 seconds.']
Dialogue=[Dialogue,'You may terminate the script during this time.']
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
WIDGET_CONTROL, event.TOP, TIMER=10
return
end
2:  $
begin
widget_control,(*pState3).terminate_button,sensitive=0
send_Histogram,event
widget_control,(*pState3).terminate_button,sensitive=1
widget_control,(*pState3).close_button,sensitive=1
return
end
else:
endcase
ENDIF
uname=widget_info(event.id,/uname)
case uname of
;
'Send_All':   $
begin
;check and see whether settings are sensible
widget_control,(*pState).Master,get_value=Master
widget_control,(*pState).Res,get_value=resolution
Histogram_Option_Value=(*pState).Histogram_Option_Value
Eu=(*pState).Eu
Triffid_Option_Value=(*pState).Triffid_Option_Value
if (master ne 0) and (resolution eq 1) and $
(Histogram_Option_Value ne 1) and (Triffid_Option_Value eq 0) then begin
MasterSettingsStructure=SensibleSettingsCheck(master,resolution,Eu)
MasterChange=MasterSettingsStructure.MasterChange
MasterSet=MasterSettingsStructure.MasterSet
MasterRecommend=MasterSettingsStructure.MasterRecommend
;print,MasterSettingsStructure.MasterChange
;print,MasterSettingsStructure.MasterSet
;print,MasterSettingsStructure.MasterRecommend
    if MasterChange eq 1 then begin
abort=Allenspach_Message(event,MasterSet,MasterRecommend)
if abort eq 0 then return
    endif
endif
Connection_Update,event
Connection_Update_tlb=(*pState).Connection_Update_tlb
widget_control,Connection_Update_tlb,get_uvalue = pState3
widget_control,(*pState3).close_button,sensitive=0
widget_control,(*pState3).terminate_button,sensitive=0
SICS_Dialogue='SICS Dialogue'
*(*pState).SICS_Dialogue=SICS_Dialogue
SICS_Dialogue_Update,event
Send_Choppers,event
widget_control,(*pState3).terminate_button,sensitive=1
(*pState).stage=1
if (*pState).connection eq 0 then begin
widget_control,(*pState3).close_button,sensitive=1
return
endif
Dialogue='The triffid motors will be driven to their'
Dialogue=[Dialogue,'new positions in 10 seconds.']
Dialogue=[Dialogue,'You may terminate the script during this time.']
*(*pState).SICS_Dialogue=[*(*pState).SICS_Dialogue,Dialogue]
SICS_Dialogue_Update,event
WIDGET_CONTROL, event.TOP, TIMER=10
end
'Send_Choppers':   $
begin
;check and see whether settings are sensible
widget_control,(*pState).Master,get_value=Master
widget_control,(*pState).Res,get_value=resolution
Histogram_Option_Value=(*pState).Histogram_Option_Value
Eu=(*pState).Eu
Triffid_Option_Value=(*pState).Triffid_Option_Value
if (master ne 0) and (resolution eq 1) and $
(Histogram_Option_Value ne 1) and (Triffid_Option_Value eq 0) then begin
MasterSettingsStructure=SensibleSettingsCheck(master,resolution,Eu)
MasterChange=MasterSettingsStructure.MasterChange
MasterSet=MasterSettingsStructure.MasterSet
MasterRecommend=MasterSettingsStructure.MasterRecommend
;print,MasterSettingsStructure.MasterChange
;print,MasterSettingsStructure.MasterSet
;print,MasterSettingsStructure.MasterRecommend
    if MasterChange eq 1 then begin
abort=Allenspach_Message(event,MasterSet,MasterRecommend)
if abort eq 0 then return
    endif
endif
Connection_Update,event
Connection_Update_tlb=(*pState).Connection_Update_tlb
widget_control,Connection_Update_tlb,get_uvalue = pState3
widget_control,(*pState3).terminate_button,sensitive=0
widget_control,(*pState3).close_button,sensitive=0
SICS_Dialogue='SICS Dialogue'
*(*pState).SICS_Dialogue=SICS_Dialogue
SICS_Dialogue_Update,event
Send_Choppers,event
widget_control,(*pState3).close_button,sensitive=1
end
'Send_Triffid':   $
begin
Connection_Update,event
Connection_Update_tlb=(*pState).Connection_Update_tlb
widget_control,Connection_Update_tlb,get_uvalue = pState3
widget_control,(*pState3).terminate_button,sensitive=0
widget_control,(*pState3).close_button,sensitive=0
SICS_Dialogue='SICS Dialogue'
*(*pState).SICS_Dialogue=SICS_Dialogue
SICS_Dialogue_Update,event
Send_Triffid,event
widget_control,(*pState3).close_button,sensitive=1
end
'Send_Histogram':   $
begin
Connection_Update,event
Connection_Update_tlb=(*pState).Connection_Update_tlb
widget_control,Connection_Update_tlb,get_uvalue = pState3
widget_control,(*pState3).terminate_button,sensitive=0
widget_control,(*pState3).close_button,sensitive=0
SICS_Dialogue='SICS Dialogue'
*(*pState).SICS_Dialogue=SICS_Dialogue
SICS_Dialogue_Update,event
Send_Histogram,event
widget_control,(*pState3).close_button,sensitive=1
end
else:
endcase
mepChopperPhases,event
mepPlotQE_range,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mep, group_leader = group_leader,notify_ids = notify_ids,  $
        register_name = register_name,workDir = workDir

;print,'Register Name =',register_name
;;;;;;;added following 4 lines for non-modal widget action
if n_elements(group_leader) eq 0 then group_leader = 0L
if n_elements(notify_ids) eq 0 then notify_ids = [0L,0L]
if n_elements(register_name) eq 0 then register_name = 'MARSPlanner'
if xregistered(register_name) then return

if n_elements(workDir) eq 0 then begin
workDir='C:\'
endif

; First get the colors upon entering this program
tvlct,rorig,gorig,borig,/get
device, get_decomposed = old_dc
device,decomposed = 1
colors = hfbs_GetColor(/Load, Start=1)
;       COLOR: A string with the "name" of the color. Valid names are:
;           black
;           magenta
;           cyan
;           yellow
;           green
;           red
;           blue
;           navy
;           pink
;           aqua
;           orchid
;           sky
;           beige
;           charcoal
;           gray
;           white

delim=path_sep()


;
filename=!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MARS_TimeOffsets.txt'
timeoffsets=GetMARSTimeOffsets(filename)
;help,timeoffsets,/struc
if timeoffsets.filefound eq 0 then begin
msg=strarr(2)
msg[0]='The file '+filename
msg[1]='has not been found or the information in the file is invalid.  All time offsets will be set to zero.'
        void=dialog_message(dialog_parent=group_leader,/error,msg)
master1_timeoffset=0.0
master2_timeoffset=0.0
master3_timeoffset=0.0
master4_timeoffset=0.0
master5_timeoffset=0.0
master6_timeoffset=0.0
master7_timeoffset=0.0
timeoffsets={MARSTimeOffsets, $
              filefound:0, $
              master1_timeoffset:master1_timeoffset, $
              master2_timeoffset:master2_timeoffset, $
              master3_timeoffset:master3_timeoffset, $
              master4_timeoffset:master4_timeoffset, $
              master5_timeoffset:master5_timeoffset, $
              master6_timeoffset:master6_timeoffset, $
              master7_timeoffset:master7_timeoffset}
endif



;read_jpeg,!DAVE_AUXILIARY_DIR+'PSI\MARS\koennecke_pic.jpg',koennecke_pic
read_jpeg,!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'koennecke_pic.jpg',koennecke_pic
read_jpeg,!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'Allenspach_pic.jpg',Allenspach_pic

;filename=!DAVE_AUXILIARY_DIR+'PSI\MARS\Calibrated_Analyser_Angles.txt'
filename=!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'Calibrated_Analyser_Angles.txt'
;
line=''
Calibration_Angles_str=strarr(2,32)
openr,lun,filename,/get_lun
for i=0,31 do begin
readf,lun,line
temp=strsplit(line,/extract)
Calibration_Angles_str[0,i]=strtrim(temp[0],2)
Calibration_Angles_str[1,i]=strtrim(temp[1],2)
endfor
free_lun,lun,/force

  tlb = widget_base(/col,group_leader = group_leader,title = 'MARS Experiment Planner',mbar=bar)


;if n_elements(group_leader) eq 0 then begin
;  tlb = widget_base(/col,title = 'MARS Experiment Planner',mbar=bar)
;endif else begin
;  tlb = widget_base(group_leader = group_leader, /col,/modal, $
;        title = 'MARS Experiment Planner',mbar=bar)
;endelse

;tlb=widget_base(title="Kinematically Allowed Region",$
;   /column,xoffset=screensize[0]*0.05,$
;   group_leader=group_leader,ysize=ysk,mbar=bar)


;filename=!DAVE_AUXILIARY_DIR+'PSI\MARS\MARSConstants.txt'
filename=!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MARSConstants.txt'
constants=GetMARSConstants(filename)
if constants.filefound eq 0 then begin
        void=dialog_message(dialog_parent=group_leader,/error, $
    'The file '+filename+' has not been found.  The program must exit.')
return
endif
;
filename=!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'AcceptableTimebins.txt'
TimeBins=GetMARSAcceptableTimebins(filename)
;help,TimeBins
;print,'TimeBins.filefound: ',TimeBins.filefound
;help,timebins,/struc


;
dspace_002=constants.dspace_002
dspace_array=[dspace_002,dspace_002/2,dspace_002/3,dspace_002/4]


El = 2.7259462
Eu = 3.7512623
;
       filebuttons=widget_button(bar,value='File',/menu)
          savpb=widget_button(filebuttons,$
              value='Save parameters',event_pro='MEP_save')
          respb=widget_button(filebuttons,$
              value='Restore parameters',event_pro='MEP_restore')
          savascii=widget_button(filebuttons,$
              value='Save ascii',event_pro='ascii_save')
          doneb=widget_button(filebuttons,$
              value='EXIT',event_pro='MEP_exit')
       PreferencesButtons=widget_button(bar,value='Preferences',/menu)
          Triffidb=widget_button(PreferencesButtons,$
              value='Set Triffid Angles',event_pro='Triffid_Set')
          Histogramb=widget_button(PreferencesButtons,$
              value='Set Histogram Parameters',event_pro='Histogram_Set')
          Histogramb=widget_button(PreferencesButtons,$
              value='Set Energy Window',event_pro='Energy_Window_Set')
       InstrumentButtons=widget_button(bar,value='Instrument Control',/menu)
          SendAllb=widget_button(InstrumentButtons,$
              value='Send All Parameters to Instrument',uname='Send_All')
       IndividualInstrumentButtons=widget_button(InstrumentButtons,value='Send Parameters Individually',/menu)
                    SendChoppersb=widget_button(IndividualInstrumentButtons,$
              value='Send Chopper Settings to Instrument',uname='Send_Choppers')
          SendTriffidb=widget_button(IndividualInstrumentButtons,$
              value='Send Triffid Angles to Instrument',uname='Send_Triffid')
          SendHistogramb=widget_button(IndividualInstrumentButtons,$
              value='Send Histogram Settings to Instrument',uname='Send_Histogram')

;
;
;
base_upper = widget_base(tlb,/row)
base_lower = widget_base(tlb,/row)
baseu1=widget_base(base_upper,/frame,/col,/align_center)
baseu1A=widget_base(baseu1,/row,/align_center)
Em = cw_field(baseu1A,/col,title = 'Midpoint of Energy Window',value=3.0,/return_events)
Master=widget_slider(baseu1A,$
              value=1,min=1,max=7,title='Master * 50Hz',xsize=70, $
              event_pro='mepevents')
Mica_Reflection = ['002',$
              '004', $
              '006', $
              '008']
Mica = cw_bgroup(baseu1,Mica_Reflection,/row,/exclusive,label_top='Mica Reflection', $
           set_value = 0,/return_index,/no_release, /frame)
;column_labels=['Phase','Distances','Frequencies']
column_labels=['Phase','Frequencies']
chopper_names=['Snail','Master','Rabbit','Chopper 4','Chopper 5']
output=strarr(2,5)
output[0,0]=172.88980
output[0,1]=180.0000
output[0,2]=180.15087
output[0,3]=255.02558
output[0,4]=256.29526
;
;
output[1,0]=50.0
output[1,1]=50.0
output[1,2]=50.0
output[1,3]=50.0
output[1,4]=50.0

Chopper_Table=widget_table(base_upper,column_widths=70,$
       column_labels=column_labels,row_labels=chopper_names,xsize=2,ysize=5,$
       value=output,alignment=2,scr_xsize=160)
baseu2=widget_base(base_upper,/frame,/col,/align_center)
void=widget_label(baseu2,value='Energy Window Limits',/align_center)
baseu2a=widget_base(baseu2,/row,/align_center)

Ewinl = cw_field(baseu2a,xsize=5,title = 'Lower',value=2.4929828,/noedit)
Ewinu = cw_field(baseu2a,xsize=5,title = 'Upper',value=3.5182989,/noedit)
void=widget_label(baseu2,value='Q Window Limits',/align_center)
baseu2b=widget_base(baseu2,/row,/align_center)
Qwinl = cw_field(baseu2b,/row,xsize=5,title = 'Lower',value=0.87284395,/noedit)
Qwinu = cw_field(baseu2b,/row,xsize=5,title = 'Higher',value=1.6444492,/noedit)
Qmin=0.87082116
Qmax=1.6480104


baseu3=widget_base(base_upper,/frame,/col,/align_center)
;void=widget_label(baseu3,value='Scattering Angle and Intensity Enhancement ',/align_center)
baseu3a=widget_base(baseu3,/row,/align_center)
scatt_angle = cw_field(baseu3a,/col,xsize=5,title = 'Theta',value='69.810',/noedit)
scatt_rel_int = cw_field(baseu3a,/col,xsize=10,title = 'Intensity Factor',value='3.1582925',/noedit)
Res_field = ['Primary',$
              'Secondary']
Res = cw_bgroup(baseu3,Res_field,/row,/exclusive,label_top='Resolution Limited By', $
           set_value = 0,/return_index,/no_release, /frame)

baseu4=widget_base(base_upper,/frame,/col,/align_center)
void=widget_label(baseu4,value='d-spacing Range and Inelastic Freebies',/align_center)
freebies=widget_Tab(baseu4)
dspace = widget_base(freebies,/col,title='d-spacing')
dspace_child=widget_base(dspace,/row,/align_center)
dspacingl = cw_field(dspace_child,/row,xsize=5,title = 'Lower',value='2.3550516',/noedit)
dspacingu = cw_field(dspace_child,/row,xsize=5,title = 'Higher',value='20.984632',/noedit)
R002 = widget_base(freebies,/col,title='002',sensitive=0)
baseR002a=widget_base(R002,/row,/align_center)
Ewinl_002 = cw_field(baseR002a,xsize=5,title = 'E Lower',value='',/noedit)
Ewinu_002 = cw_field(baseR002a,xsize=5,title = 'E Upper',value='',/noedit)
baseR002b=widget_base(R002,/row,/align_center)
Qwinl_002 = cw_field(baseR002b,/row,xsize=5,title = 'Q Lower',value='',/noedit)
Qwinu_002 = cw_field(baseR002b,/row,xsize=5,title = 'Q Higher',value='',/noedit)
;
R004 = widget_base(freebies,/col,title='004',sensitive=0)
baseR004a=widget_base(R004,/row,/align_center)
Ewinl_004 = cw_field(baseR004a,xsize=5,title = 'E Lower',value='',/noedit)
Ewinu_004 = cw_field(baseR004a,xsize=5,title = 'E Upper',value='',/noedit)
baseR004b=widget_base(R004,/row,/align_center)
Qwinl_004 = cw_field(baseR004b,/row,xsize=5,title = 'Q Lower',value='',/noedit)
Qwinu_004 = cw_field(baseR004b,/row,xsize=5,title = 'Q Higher',value='',/noedit)
;
R006 = widget_base(freebies,/col,title='006',sensitive=0)
baseR006a=widget_base(R006,/row,/align_center)
Ewinl_006 = cw_field(baseR006a,xsize=5,title = 'E Lower',value='',/noedit)
Ewinu_006 = cw_field(baseR006a,xsize=5,title = 'E Upper',value='',/noedit)
baseR006b=widget_base(R006,/row,/align_center)
Qwinl_006 = cw_field(baseR006b,/row,xsize=5,title = 'Q Lower',value='',/noedit)
Qwinu_006 = cw_field(baseR006b,/row,xsize=5,title = 'Q Higher',value='',/noedit)


baseu5=widget_base(base_upper,/frame,/col,/align_center)
void=widget_label(baseu5,value='Parameters at Mouse Position',/align_center)

baseu5a=widget_base(baseu5,/row,/align_center)

E_mouse = cw_field(baseu5a,/col,xsize=15,title = 'Energy Transfer',value='',/noedit)
E_Res = cw_field(baseu5a,/col,xsize=15,title = 'Energy Resolution',value='',/noedit)

baseu5b=widget_base(baseu5,/row,/align_center)

Q_mouse = cw_field(baseu5b,/col,xsize=15,title = 'Momentum Transfer',value='',/noedit)
Phi_mouse = cw_field(baseu5b,/col,xsize=15,title = 'Phi',value='',/noedit)


E_analyser=0.23296342
xysize=get_screen_size()
    winxsize = xysize[0]*0.6
    winysize = xysize[1]*0.6
win = widget_draw(base_lower,xsize = winxsize,ysize = winysize,/motion_events, $
      event_pro = 'mep_WinParameters')
    ;read_jpeg,!DAVE_AUXILIARY_DIR+'PSI\MARS\MEP_Schematic.jpg',image
    read_jpeg,!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MEP_Schematic.jpg',image
    s = size(image)
    sx = s[2] & sy = s[3]
aspect = 1.0*sx/sy              ; find the aspect ratio of the image...

picysize = winysize*0.5 & picxsize = fix(aspect*picysize)

fluxxsize=picxsize
fluxysize=picysize

base_lowerA = widget_base(base_lower,/col)
flux_win_base=widget_base(base_lowerA)
fluxwin = widget_draw(flux_win_base,xsize = fluxxsize,ysize = fluxysize, $
       /button_events,event_pro = 'mepdraw')

picbase = widget_base(base_lowerA,xsize = picxsize,ysize = picysize)
picwin = widget_draw(picbase,xsize = picxsize,ysize = picysize)
    device,decomposed = 1
    dispimage = image
centertlb,tlb
widget_control,tlb,/realize
!p.charsize = 1.0
widget_control,picwin,get_value = picVis
widget_control,win,get_value = winVis
widget_control,fluxwin,get_value = fluxwinVis

window,/free,/pixmap,xsize = picxsize,ysize = picysize
winPix_p = !d.window

wset,winPix_p
tvimage,dispImage
wset,picVis


device,copy = [0,0,!d.x_size,!d.y_size,0,0,winPix_p]
wdelete,winPix_p

window,/free,/pixmap,xsize = fluxxsize,ysize = fluxysize
winPix_f = !d.window
window,/free,/pixmap,xsize = winxsize,ysize = winysize
winPix_m = !d.window
;
x=0.005+0.01*findgen(2001)
y=flux(x)
;
;filename=workdir+'theoreticalflux.out'
;openw,lun,filename,/get_lun
;for i = 0, 2000 do begin
;printf,lun,x[i],y[i]
;endfor
;free_lun,lun,/force

;
  xlo = min(x) & xhi = max(x)
  ylo = min(y) & yhi = max(y)
;
;
Esec=0.016802927
pix=0
;

state = { winVis:winVis, $
       fluxwinVis:fluxwinVis, $
        picVis:picVis, $
        winPix_f:winPix_f, $
        winPix_m:winPix_m, $
         autoscale:1, $
         xrange:[xlo,xhi], $
         yrange:[ylo,yhi], $
         xrangedel:[0.0,1.0], $
         yrangedel:[0.0,1.0], $
         xbox:[xlo,xhi], $
         ybox:[ylo,yhi], $
         xlo:xlo, $
         xhi:xhi, $
         ylo:ylo, $
         yhi:yhi, $
         mouse:0B, $
         workDir:workDir, $
         fluxwin:fluxwin, $
         win:win, $
         Em:Em, $
         El:El, $
         Eu:Eu, $
         E_analyser:E_analyser, $
         Master:Master, $
         mica:mica, $
         Chopper_Table:Chopper_Table, $
         Ewinl:Ewinl, $
         Ewinu:Ewinu, $
         Qwinl:Qwinl, $
         Qwinu:Qwinu, $
         Qmin:Qmin, $
         Qmax:Qmax, $
         dspacingl:dspacingl, $
         dspacingu:dspacingu, $
         Ewinl_002:Ewinl_002, $
         Ewinu_002:Ewinu_002, $
         Ewinl_004:Ewinl_004, $
         Ewinu_004:Ewinu_004, $
         Ewinl_006:Ewinl_006, $
         Ewinu_006:Ewinu_006, $
         Qwinl_002:Qwinl_002, $
         Qwinu_002:Qwinu_002, $
         Qwinl_004:Qwinl_004, $
         Qwinu_004:Qwinu_004, $
         Qwinl_006:Qwinl_006, $
         Qwinu_006:Qwinu_006, $
         scatt_angle:scatt_angle, $
         scatt_rel_int:scatt_rel_int, $
         Res:Res, $
         R002:R002, $
         R004:R004, $
         R006:R006, $
         Esec:Esec, $
         dspace_array:dspace_array, $
         x:x, $
         y:y, $
         E_Res:E_Res, $
         E_mouse:E_mouse, $
         Q_mouse:Q_mouse, $
         Phi_mouse:Phi_mouse, $
         pix:pix, $
         fluxxsize:fluxxsize, $
         fluxysize:fluxysize, $
         winxsize:winxsize, $
         winysize:winysize, $
         colors:colors, $
         constants:constants, $
         TimeBins:TimeBins, $
         koennecke_pic:koennecke_pic, $
         Allenspach_pic:Allenspach_pic, $
         Calibration_Angles_str:Calibration_Angles_str, $
         angle_index:0, $
         Triffid_Option_Value:0, $
         Histogram_Option_Value:0, $
         Energy_Window_Option_Value:0, $
         First_Neutrons_Time:45142.5, $
         Last_Neutrons_Time:67605.0, $
         Time_Difference:22462.5, $
         Time_Bin_Number:196, $
         Time_Bin_Start:56535.1, $
         Time_Bin_Step:40.0, $
         Time_Bin_Width:20000.0, $
         Total_Time_Bin_Number:long(500), $
         TimeBinIndices:[340,36,369,69,417,126,205,402,-1,-1,-1,-1,-1,-1], $
         UnitUser:0, $
         UnitManager:0, $
         Connection:0, $
         delim:delim, $
         stage:0, $
         Connection_Update_tlb:1, $
         SICS_Dialogue:ptr_new(/allocate_heap), $
         timeoffsets:timeoffsets, $
         Energy_Window_Slider:1000, $
         old_dc:old_dc $
         }


pState = ptr_new(state,/no_copy)
widget_control,tlb,set_uvalue = pState
wset,(*pState).winPix_f

plot,x,y,xrange = [0,max(x)],yrange = [0,max(y)], $
     xstyle = 1,ystyle = 1,xtitle = 'Energy / meV', $
     ytitle = 'Flux', title = 'Flux at Sample',linestyle = 0, $
     thick = 1.0, psym=0, symsize=1.0

  polyfill,x,y,/data,color=(*pState).colors.red, $
        CLIP=[2.7232741,0,3.7612419,max(y)], noclip = 0

wset,(*pState).fluxwinVis

device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winPix_f]

  polyfill,x,y,/data,color=(*pState).colors.red, $
        CLIP=[2.7232741,0,3.7612419,max(y)], noclip = 0

;widget_control,tlb,get_uvalue=pState

pseudoEvent = {event,id:void,top:tlb,handler:0l}
mepPlotQE_range,pseudoEvent

xmanager,register_name,tlb,event_handler = 'mepEvents'

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;