;
; NAME:
; MarsStatus
; DATE of WORKING VERSION: 25 April 2006
; MarsStatus
;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 Utilities
;
; CALLING SEQUENCE:
;
;      MarsStatus
;
;
; 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 MS_exit,event
widget_control,event.top,get_uvalue = pState
if (*pState).SICSTempERROR eq 1 then begin
widget_id=(*pState).TemperatureReadError_widget_id
TemperatureReadError_Destroy,widget_id
(*pState).SICSTempERROR=0
endif
wdelete,(*pState).winPix_p
wdelete,(*pState).winPix_tof
wdelete,(*pState).winPix_posttof
wdelete,(*pState).winPix_diff
wdelete,(*pState).winPix_mica
wdelete,(*pState).winPix_temp
device, decomposed = (*pState).old_dc
if (*pState).demo_ms eq 0 then begin
sicsclose,(*pState).unit
sicsclose,(*pState).tunit
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 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 MSEnvironmentdraw,event
widget_control,event.top,get_uvalue = pState

if (*pState).pix ne 4 then begin
        MStemp_Plot,event
(*pState).pix = 4
endif
;
;
case event.type of
0:  begin       ; button press
      (*pState).mouse = event.press
      if (*pState).mouse eq 4 then begin
        (*pState).autoscale_temp = 1
        MStemp_Plot,event
      endif
      if (*pState).mouse eq 1 then begin
        (*pState).xbox_temp[0] = event.x
        (*pState).ybox_temp[0] = event.y
        wset,(*pState).winVis_temp
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winPix_temp]
        empty
        (*pState).autoscale_temp = 0
        widget_control,(*pState).win_temp,/draw_motion_events
      endif
    end
1:  begin    ; button release
     if (*pState).mouse eq 1 then begin
      xll = (*pState).xbox_temp[0] < (*pState).xbox_temp[1]
      yll = (*pState).ybox_temp[0] < (*pState).ybox_temp[1]
      w = abs((*pState).xbox_temp[1] - (*pState).xbox_temp[0])
      h = abs((*pState).ybox_temp[1] - (*pState).ybox_temp[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_temp = [ll[0],ur[0]]
      (*pState).yrange_temp = [ll[1],ur[1]]
        MStemp_Plot,event
      (*pState).mouse = 0B
      widget_control,(*pState).win_temp,draw_motion_events = 0
     endif
     if (*pState).mouse eq 4 then begin
        MStemp_Plot,event
      (*pState).mouse = 0B
      widget_control,(*pState).win_temp,draw_motion_events = 0
     endif
    end
2:  begin    ; mouse motion
      if (*pState).mouse eq 1 then begin
       (*pState).xbox_temp[1] = event.x
       (*pState).ybox_temp[1] = event.y
       xc = [(*pState).xbox_temp[0],event.x,event.x,$
             (*pState).xbox_temp[0],$
             (*pState).xbox_temp[0]]
       yc = [(*pState).ybox_temp[0],(*pState).ybox_temp[0],$
             event.y,event.y,$
             (*pState).ybox_temp[0]]
       wset,(*pState).winVis_temp
       device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winPix_temp]
       plots,xc,yc,/device
       empty
      endif
    end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MSTOFdraw,event
widget_control,event.top,get_uvalue = pState

if (*pState).pix ne 0 then begin
        MSTOF_Plot,event
(*pState).pix = 0
endif


case event.type of
0:  begin       ; button press
      (*pState).mouse = event.press
      if (*pState).mouse eq 4 then begin
        (*pState).autoscale_tof = 1
        MSTOF_Plot,event
      endif
      if (*pState).mouse eq 1 then begin
        (*pState).xbox_tof[0] = event.x
        (*pState).ybox_tof[0] = event.y
        wset,(*pState).winVis_tof
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winPix_tof]
        empty
        (*pState).autoscale_tof = 0
        widget_control,(*pState).win_tof,/draw_motion_events
      endif
    end
1:  begin    ; button release
     if (*pState).mouse eq 1 then begin
      xll = (*pState).xbox_tof[0] < (*pState).xbox_tof[1]
      yll = (*pState).ybox_tof[0] < (*pState).ybox_tof[1]
      w = abs((*pState).xbox_tof[1] - (*pState).xbox_tof[0])
      h = abs((*pState).ybox_tof[1] - (*pState).ybox_tof[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_tof = [ll[0],ur[0]]
      (*pState).yrange_tof = [ll[1],ur[1]]
        MSTOF_Plot,event
      (*pState).mouse = 0B
      widget_control,(*pState).win_tof,draw_motion_events = 0
     endif
     if (*pState).mouse eq 4 then begin
        MSTOF_Plot,event
      (*pState).mouse = 0B
      widget_control,(*pState).win_tof,draw_motion_events = 0
     endif
    end
2:  begin    ; mouse motion
      if (*pState).mouse eq 1 then begin
       (*pState).xbox_tof[1] = event.x
       (*pState).ybox_tof[1] = event.y
       xc = [(*pState).xbox_tof[0],event.x,event.x,$
             (*pState).xbox_tof[0],$
             (*pState).xbox_tof[0]]
       yc = [(*pState).ybox_tof[0],(*pState).ybox_tof[0],$
             event.y,event.y,$
             (*pState).ybox_tof[0]]
       wset,(*pState).winVis_tof
       device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winPix_tof]
       plots,xc,yc,/device
       empty
      endif
    end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro PostMSTOFdraw,event
widget_control,event.top,get_uvalue = pState

if (*pState).pix ne 1 then begin
        PostMSTOF_Plot,event
(*pState).pix = 1
endif


case event.type of
0:  begin       ; button press
      (*pState).mouse = event.press
      if (*pState).mouse eq 4 then begin
        (*pState).autoscale_posttof = 1
        PostMSTOF_Plot,event
      endif
      if (*pState).mouse eq 1 then begin
        (*pState).xbox_posttof[0] = event.x
        (*pState).ybox_posttof[0] = event.y
        wset,(*pState).winVis_posttof
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winPix_posttof]
        empty
        (*pState).autoscale_posttof = 0
        widget_control,(*pState).win_posttof,/draw_motion_events
      endif
    end
1:  begin    ; button release
     if (*pState).mouse eq 1 then begin
      xll = (*pState).xbox_posttof[0] < (*pState).xbox_posttof[1]
      yll = (*pState).ybox_posttof[0] < (*pState).ybox_posttof[1]
      w = abs((*pState).xbox_posttof[1] - (*pState).xbox_posttof[0])
      h = abs((*pState).ybox_posttof[1] - (*pState).ybox_posttof[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_posttof = [ll[0],ur[0]]
      (*pState).yrange_posttof = [ll[1],ur[1]]
        PostMSTOF_Plot,event
      (*pState).mouse = 0B
      widget_control,(*pState).win_posttof,draw_motion_events = 0
     endif
     if (*pState).mouse eq 4 then begin
        PostMSTOF_Plot,event
      (*pState).mouse = 0B
      widget_control,(*pState).win_posttof,draw_motion_events = 0
     endif
    end
2:  begin    ; mouse motion
      if (*pState).mouse eq 1 then begin
       (*pState).xbox_posttof[1] = event.x
       (*pState).ybox_posttof[1] = event.y
       xc = [(*pState).xbox_posttof[0],event.x,event.x,$
             (*pState).xbox_posttof[0],$
             (*pState).xbox_posttof[0]]
       yc = [(*pState).ybox_posttof[0],(*pState).ybox_posttof[0],$
             event.y,event.y,$
             (*pState).ybox_posttof[0]]
       wset,(*pState).winVis_posttof
       device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winPix_posttof]
       plots,xc,yc,/device
       empty
      endif
    end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MSDiffdraw,event
widget_control,event.top,get_uvalue = pState

if (*pState).pix ne 2 then begin
        DiffDisplay,event
(*pState).pix = 2
endif


case event.type of
0:  begin       ; button press
      (*pState).mouse = event.press
      if (*pState).mouse eq 4 then begin
        (*pState).autoscale_diff = 1
        DiffDisplay,event
      endif
      if (*pState).mouse eq 1 then begin
        (*pState).xbox_diff[0] = event.x
        (*pState).ybox_diff[0] = event.y
        wset,(*pState).winVis_diff
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winPix_diff]
        empty
        (*pState).autoscale_diff = 0
        widget_control,(*pState).win_diff,/draw_motion_events
      endif
    end
1:  begin    ; button release
     if (*pState).mouse eq 1 then begin
      xll = (*pState).xbox_diff[0] < (*pState).xbox_diff[1]
      yll = (*pState).ybox_diff[0] < (*pState).ybox_diff[1]
      w = abs((*pState).xbox_diff[1] - (*pState).xbox_diff[0])
      h = abs((*pState).ybox_diff[1] - (*pState).ybox_diff[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_diff = [ll[0],ur[0]]
      (*pState).yrange_diff = [ll[1],ur[1]]
        DiffDisplay,event
      (*pState).mouse = 0B
      widget_control,(*pState).win_diff,draw_motion_events = 0
     endif
     if (*pState).mouse eq 4 then begin
        DiffDisplay,event
      (*pState).mouse = 0B
      widget_control,(*pState).win_diff,draw_motion_events = 0
     endif
    end
2:  begin    ; mouse motion
      if (*pState).mouse eq 1 then begin
       (*pState).xbox_diff[1] = event.x
       (*pState).ybox_diff[1] = event.y
       xc = [(*pState).xbox_diff[0],event.x,event.x,$
             (*pState).xbox_diff[0],$
             (*pState).xbox_diff[0]]
       yc = [(*pState).ybox_diff[0],(*pState).ybox_diff[0],$
             event.y,event.y,$
             (*pState).ybox_diff[0]]
       wset,(*pState).winVis_diff
       device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winPix_diff]
       plots,xc,yc,/device
       empty
      endif
    end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MSMicadraw,event
widget_control,event.top,get_uvalue = pState

if (*pState).pix ne 3 then begin
        MSMICA_Plot,event
(*pState).pix = 3
endif


case event.type of
0:  begin       ; button press
      (*pState).mouse = event.press
      if (*pState).mouse eq 4 then begin
        (*pState).autoscale_mica = 1
        MSMICA_Plot,event
      endif
      if (*pState).mouse eq 1 then begin
        (*pState).xbox_mica[0] = event.x
        (*pState).ybox_mica[0] = event.y
        wset,(*pState).winVis_mica
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winPix_mica]
        empty
        (*pState).autoscale_mica = 0
        widget_control,(*pState).win_mica,/draw_motion_events
      endif
    end
1:  begin    ; button release
     if (*pState).mouse eq 1 then begin
      xll = (*pState).xbox_mica[0] < (*pState).xbox_mica[1]
      yll = (*pState).ybox_mica[0] < (*pState).ybox_mica[1]
      w = abs((*pState).xbox_mica[1] - (*pState).xbox_mica[0])
      h = abs((*pState).ybox_mica[1] - (*pState).ybox_mica[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_mica = [ll[0],ur[0]]
      (*pState).yrange_mica = [ll[1],ur[1]]
        MSMICA_Plot,event
      (*pState).mouse = 0B
      widget_control,(*pState).win_mica,draw_motion_events = 0
     endif
     if (*pState).mouse eq 4 then begin
        MSMICA_Plot,event
      (*pState).mouse = 0B
      widget_control,(*pState).win_mica,draw_motion_events = 0
     endif
    end
2:  begin    ; mouse motion
      if (*pState).mouse eq 1 then begin
       (*pState).xbox_mica[1] = event.x
       (*pState).ybox_mica[1] = event.y
       xc = [(*pState).xbox_mica[0],event.x,event.x,$
             (*pState).xbox_mica[0],$
             (*pState).xbox_mica[0]]
       yc = [(*pState).ybox_mica[0],(*pState).ybox_mica[0],$
             event.y,event.y,$
             (*pState).ybox_mica[0]]
       wset,(*pState).winVis_mica
       device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winPix_mica]
       plots,xc,yc,/device
       empty
      endif
    end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MS_dspacing,event
widget_control,event.top,get_uvalue = pState
DiffArray_t=*(*pState).DiffArray_x
DiffArray_t_y=*(*pState).DiffArray_y
constants=(*pState).constants
h=constants.h
mn=constants.mn
lDiff=constants.lDiff
DiffractionAngles=constants.DiffractionAngles
DiffractionAngles/=2.0
v=lDiff/(DiffArray_t/1.0e6)
DiffArray_l=(h*1e10)/(mn*v)
;print,'min(DiffArray_l) = ',min(DiffArray_l)
;
;
   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
widget_control,(*pState).Diffraction_Normalisation,set_value = 1
time=systime()
msg=strarr(3)
msg[0]='Error at '+string(time)+' Unable to Normalise the Diffraction Data to the Incident Monitor;'
msg[1]='Check that the Time Bin Indices are Correct.'
msg[2]='error message: '+!ERROR_STATE.MSG+'.'
SICSErrorLog=*(*pState).SICSErrorLog
SICSErrorLog=[SICSErrorLog,msg]
*(*pState).SICSErrorLog=SICSErrorLog
MS_UpdateErrorLog,event
endif
;
;print,'max(DiffArray_l) = ',max(DiffArray_l)
;normalise to monitor?
widget_control,(*pState).Diffraction_Normalisation,get_value = norm
norm=long(norm[0])
IF norm eq 0 THEN BEGIN
lTOFMon=constants.lTOFMon
TOFMonitorArray_t=*(*pState).TOFMonitorArray_xCal
v=lTOFMon/(TOFMonitorArray_t/1.0e6)
TOFMonitorArray_l=(h*1e10)/(mn*v)
;help,TOFMonitorArray_l
;first extract dimension of time channels
channels_mon=(size(TOFMonitorArray_l))[1]
channels_diff=(size(DiffArray_l))[2]
;print,channels_mon
;print,channels_diff
;index mapping
index_map=intarr(2,channels_diff)
index_map[0,*]=indgen(channels_diff)
udiff=1+bytarr(channels_diff)
umon=1+bytarr(channels_mon)
;reform(DiffArray_l[0,*])#umon creates channels_mon rows of DiffArray_l[0,*]
;udiff#TOFMonitorArray_l creates channels_diff columns of TOFMonitorArray_l
diff=abs(reform(DiffArray_l[0,*])#umon-udiff#TOFMonitorArray_l)
;print,'min(abs(diff[1200,*])) = ',min(abs(diff[1200,*]))
for i=0,channels_diff-1 do begin
void=min(diff[i,*],ind)
index_map[1,i]=ind
endfor
;
TOFMonitorArray_l_y=*(*pState).TOFMonitorArray_yCal
;TOFMonitorArray_l=*(*pState).TOFMonitorArray_l
ub=(*pState).ub
Mon_Efficiency=1-exp(-ub*TOFMonitorArray_l)
TOFMonitorArray_l_y/=Mon_Efficiency

;print,'min(TOFMonitorArray_l): ',min(TOFMonitorArray_l)
;print,'max(TOFMonitorArray_l): ',max(TOFMonitorArray_l)
;print,'min(DiffArray_l): ',min(DiffArray_l)
;print,'max(DiffArray_l): ',max(DiffArray_l)
;
;now we are ready to perform the normalisation
;if the mapping occurs at the edges of the TOF monitor
;then these data points are rejected, i.e. the MicaArray_e and MicaArray_e_y
;arrays are condensed.
for i=0,channels_diff-1 do begin
;    if i lt 10 then help,i
if TOFMonitorArray_l_y[index_map[1,i]] gt 100 then begin
DiffArray_t_y[*,i]/=TOFMonitorArray_l_y[index_map[1,i]]
endif else begin
DiffArray_t_y[*,i] = 0.0
endelse
if (index_map[1,i] eq 0) or (index_map[1,i] eq (n_elements(TOFMonitorArray_l_y)-1)) then begin
    if n_elements(reject) eq 0 then begin
    reject=i
    endif else begin
    reject=[reject,i]
    endelse
endif
endfor
if n_elements(reject) ne 0 then begin
;help,reject
;print,reject
DiffArray_t_new=fltarr(12,channels_diff-n_elements(reject))
DiffArray_t_y_new=fltarr(12,channels_diff-n_elements(reject))
    j=0
    k=0
    for i=0,channels_diff-1 do begin
    whereiconrej=where(i eq reject,count)
    if count ne 0 then begin
    k+=1
    endif else begin
    DiffArray_t_new[*,j]=DiffArray_t[*,k]
    DiffArray_t_y_new[*,j]=DiffArray_t_y[*,k]
    j+=1
    k+=1
    endelse
    endfor
nelements=n_elements(DiffArray_t_new[0,*])
;
;
DiffArray_t=DiffArray_t_new
DiffArray_t_y=DiffArray_t_y_new
endif
ENDIF
*(*pState).DiffArray_t_y=DiffArray_t_y
DiffArray_d=DiffArray_t
DiffArray_d[*,*]=0.0
;
;convert to dspacing
;print,'h :',h
;print,'mn :',mn
;print,'lDiff :',lDiff
;print,'DiffractionAngles :',DiffractionAngles
for i=0,11 do begin
DiffArray_d[i,*]=DiffArray_t[i,*]*(h*1e4)/(2.0*mn*lDiff*sin(DiffractionAngles[i]*!DTOR))
endfor
*(*pState).DiffArray_d=DiffArray_d

nelements=n_elements(DiffArray_d[0,*])

;print,'DiffArray_t_y: ',DiffArray_t_y
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro EstimateEndTime,Start_time,CounterPreset,TOFMonitorArray_yTotal,event
;
   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
time=systime()
msg=strarr(2)
msg[0]='''EstimateEndTime'' Procedure has Failed'
msg[1]='error message: '+!ERROR_STATE.MSG+'.'
SICSErrorLog=*(*pState).SICSErrorLog
SICSErrorLog=[SICSErrorLog,msg]
*(*pState).SICSErrorLog=SICSErrorLog
MS_UpdateErrorLog,event
return
endif
;

widget_control,event.top,get_uvalue = pState
MonitorPreset=float(CounterPreset)
Monitor=float(TOFMonitorArray_yTotal)
proceed=Monitor/MonitorPreset
if proceed ge 1.0 then begin
widget_control,(*pState).SampleEnd_p,set_value = 'Run Completed'
return
endif
if proceed lt 0.01 then begin ; less than half a percent
widget_control,(*pState).SampleEnd_p,set_value = 'Insufficent Data'
return
endif
current_time=systime(/seconds)
TimeElapsed=current_time-Start_time
Fraction_Remaining=1-proceed
TimeRemaining=(Fraction_Remaining/proceed)*TimeElapsed
EstimatedEnd=current_time+TimeRemaining
EstimatedEndStr=systime(0,EstimatedEnd)
widget_control,(*pState).SampleEnd_p,set_value = EstimatedEndStr
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MSTemp_Plot,event
widget_control,event.top,get_uvalue = pState
   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
time=systime()
msg=strarr(2)
msg[0]='Error at '+string(time)+' Error Acquiring Temperature Data;'
msg[1]='Error message: '+!ERROR_STATE.MSG+'.'
SICSErrorLog=*(*pState).SICSErrorLog
SICSErrorLog=[SICSErrorLog,msg]
*(*pState).SICSErrorLog=SICSErrorLog
MS_UpdateErrorLog,event
return
endif


TempSample=*(*pState).TempSample
TempHeatEX=*(*pState).TempHeatEX
TempSet=*(*pState).TempSet
TempSample_time=*(*pState).TempSample_time
TempHeatEX_time=*(*pState).TempHeatEX_time
TempSet_time=*(*pState).TempSet_time


widget_control,(*pState).Environment_Result,get_value = ER
ER=long(ER[0])
;
n_TempSample=n_elements(TempSample)
n_TempHeatEX=n_elements(TempHeatEX)
n_TempSet=n_elements(TempSet)

if (n_TempSample eq 0) and (n_TempHeatEX eq 0) then return
;print,'n_elements(TempSet) = ',n_elements(TempSet)
;
IF (*pState).autoscale_temp eq 1 then begin
tempy=[TempSample,TempHeatEX,TempSet]
tempx=[TempSample_time,TempHeatEX_time,TempSet_time]
;print,tempx
where_ne_m1=where(tempy ne -1,count)
if count ne 0 then begin
    if count eq n_elements(tempy) then begin
    miny=min(tempy)-1.0
    maxy=max(tempy)+1.0
;    minx=min(tempx)
;    maxx=max(tempx)
;    print,minx
;    print,maxx
    endif else begin
    miny=min(tempy[where_ne_m1])-1.0
    maxy=max(tempy[where_ne_m1])+1.0
 ;   minx=min(tempx[where_ne_m1])
 ;   maxx=max(tempx[where_ne_m1])
 ;   print,minx
 ;   print,maxx
      endelse
endif else begin
return
endelse
maxx=0.0
if ER eq 0 then minx = -300 ;5 mins
if ER eq 1 then minx = -1800 ;30 mins
if ER eq 2 then minx = -3600 ;1 hour
if ER eq 3 then minx = -21600 ;6 hours
if ER eq 4 then minx = -43200 ;12 hours
if ER eq 5 then minx = -86400 ;1 day
if ER eq 6 then minx = -259200 ;3 days
if ER eq 7 then minx = -604800 ;7 days
;
  (*pState).xrange_temp = [minx,maxx]
  (*pState).yrange_temp = [miny,maxy]
(*pState).time_units=0
ENDIF
;
xrv=(*pState).xrange_temp[1]-(*pState).xrange_temp[0]
;print,'xrv = ',xrv
; this bit converts to seconds
if (*pState).time_units eq 1 then begin
xrv*=60
(*pState).xrange_temp*=60
endif
if (*pState).time_units eq 2 then begin
xrv*=3600
(*pState).xrange_temp*=3600
endif
if (*pState).time_units eq 3 then begin
xrv*=86400
(*pState).xrange_temp*=86400
endif
;print,'xrv = ',xrv

if xrv le 60 then begin
xtitle='Time / sec.'
(*pState).time_units=0
endif
if xrv gt 60 and xrv le 3600 then begin
TempSample_time/=60
TempHeatEX_time/=60
TempSet_time/=60
(*pState).xrange_temp/=60
xtitle='Time / mins.'
(*pState).time_units=1
endif
if xrv gt 3600 and xrv le 86400 then begin
TempSample_time/=3600
TempHeatEX_time/=3600
TempSet_time/=3600
(*pState).xrange_temp/=3600
xtitle='Time / hours'
(*pState).time_units=2
endif
if xrv gt 86400 then begin
TempSample_time/=86400
TempHeatEX_time/=86400
TempSet_time/=86400
(*pState).xrange_temp/=86400
xtitle='Time / days'
(*pState).time_units=3
endif
;
;
;
wset,(*pState).winPix_temp
;
if n_TempSample ne 0 then begin
;
plot,TempSample_time,TempSample,xrange = (*pState).xrange_temp,yrange = (*pState).yrange_temp, $
     xstyle = 1,ystyle = 1,xtitle = xtitle, min_value=0.0, $
     ytitle = 'Temperature / K', title = 'Temperature vs. Time',linestyle = 0, $
     thick = 3.0, psym=-4, symsize=0.5,color=(*pState).colors.red
;
    if n_TempHeatEX ne 0 then begin
    oplot,TempHeatEX_time,TempHeatEX,linestyle = 0, thick = 3.0, psym=-5, $
    symsize=0.5, min_value=0.0,color=(*pState).colors.sky
    endif
endif  else begin

plot,TempHeatEX_time,TempHeatEX,xrange = (*pState).xrange_temp,yrange = (*pState).yrange_temp, $
     xstyle = 1,ystyle = 1,xtitle = xtitle, min_value=0.0, $
     ytitle = 'Temperature / K', title = 'Temperature vs. Time',linestyle = 0, $
     thick = 3.0, psym=-5, symsize=0.5,color=(*pState).colors.sky
endelse

if n_TempSet ne 0 then begin
    oplot,TempSet_time,TempSet,linestyle = 0, thick = 4.0, psym=-6, $
    symsize=0.5, min_value=0.0,color=(*pState).colors.green
endif

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


xlims=!x.crange
ylims=!y.crange
;print,'xlims = ',xlims
;print,'ylims = ',ylims
xpos=xlims[0]+(xlims[1]-xlims[0])*0.1
yr=ylims[1]-ylims[0]

xyouts,xpos,(0.95*yr+ylims[0]),"Sample Temperature " ,color=(*pState).colors.red
xyouts,xpos,(0.9*yr+ylims[0]),"Heat Exchanger Temperature ",color=(*pState).colors.sky
xyouts,xpos,(0.85*yr+ylims[0]),"Set Temperature ",color=(*pState).colors.green
;xyouts,"Sample Temperature " ,color=(*pState).colors.red
;xyouts,"Heat Exchanger Temperature ",color=(*pState).colors.sky
;xyouts,"Set Temperature ",color=(*pState).colors.green
        (*pState).pix = 4

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MSTOF_Plot,event
;
   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
time=systime()
msg=strarr(2)
msg[0]='The Data for the Upstream TOF Monitor could not be Displayed'
msg[1]='error message: '+!ERROR_STATE.MSG+'.'
SICSErrorLog=*(*pState).SICSErrorLog
SICSErrorLog=[SICSErrorLog,msg]
*(*pState).SICSErrorLog=SICSErrorLog
MS_UpdateErrorLog,event
return
endif
;
;
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).TOFDisplay,get_value = TOFDisplay
;TOFDisplay=2
if TOFDisplay eq 0 then begin; energy
x = *(*pState).TOFMonitorArray_e
y = *(*pState).TOFMonitorArray_e_y

xtitle='Energy / meV'
endif
;
if TOFDisplay eq 1 then begin; wavelength
x = *(*pState).TOFMonitorArray_l
y = *(*pState).TOFMonitorArray_l_y
xtitle='Wavelength / A'
endif
;
if TOFDisplay eq 2 then begin; time
x = *(*pState).TOFMonitorArray_t
y = *(*pState).TOFMonitorArray_t_y
xtitle='Time / us'
endif
;
if (*pState).autoscale_tof eq 1 then begin
  xlo_tof = min(x) & xhi_tof = max(x)
  ylo_tof = min(y) & yhi_tof = max(y)
  (*pState).xrange_tof = [xlo_tof,xhi_tof]
  (*pState).yrange_tof = [ylo_tof,yhi_tof]
endif
;
wset,(*pState).winPix_tof
plot,x,y,xrange = (*pState).xrange_tof,yrange = (*pState).yrange_tof, $
     xstyle = 1,ystyle = 1,xtitle = xtitle, $
     ytitle = 'Intensity', title = 'Spectrum Recorded by the Pre-Sample TOF Monitor',linestyle = 0, $
     thick = 1.0, psym=0, symsize=1.0

oplot,x,y,linestyle = 0, thick = 3.0, psym=0, symsize=1.0,color=(*pState).colors.red


        wset,(*pState).winVis_tof
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winPix_tof]
        (*pState).pix = 0

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro PostMSTOF_Plot,event
;
   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
time=systime()
msg=strarr(2)
msg[0]='The Data for the Downstream TOF Monitor could not be Displayed'
msg[1]='error message: '+!ERROR_STATE.MSG+'.'
SICSErrorLog=*(*pState).SICSErrorLog
SICSErrorLog=[SICSErrorLog,msg]
*(*pState).SICSErrorLog=SICSErrorLog
MS_UpdateErrorLog,event
return
endif
;
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).PostTOFDisplay,get_value = PostTOFDisplay
;TOFDisplay=2
if PostTOFDisplay eq 0 then begin; energy
x = *(*pState).PostTOFMonitorArray_e
y = *(*pState).PostTOFMonitorArray_e_y

xtitle='Energy / meV'
endif
;
if PostTOFDisplay eq 1 then begin; wavelength
x = *(*pState).PostTOFMonitorArray_l
y = *(*pState).PostTOFMonitorArray_l_y
xtitle='Wavelength / A'
endif
;
if PostTOFDisplay eq 2 then begin; time
x = *(*pState).PostTOFMonitorArray_t
y = *(*pState).PostTOFMonitorArray_t_y
xtitle='Time / us'
endif
;
if (*pState).autoscale_posttof eq 1 then begin
  xlo_posttof = min(x) & xhi_posttof = max(x)
  ylo_posttof = min(y) & yhi_posttof = max(y)
  (*pState).xrange_posttof = [xlo_posttof,xhi_posttof]
  (*pState).yrange_posttof = [ylo_posttof,yhi_posttof]
endif
;
wset,(*pState).winPix_posttof
plot,x,y,xrange = (*pState).xrange_posttof,yrange = (*pState).yrange_posttof, $
     xstyle = 1,ystyle = 1,xtitle = xtitle, $
     ytitle = 'Intensity', title = 'Spectrum Recorded by the Post-Sample TOF Monitor',linestyle = 0, $
     thick = 1.0, psym=0, symsize=1.0

oplot,x,y,linestyle = 0, thick = 3.0, psym=0, symsize=1.0,color=(*pState).colors.red


        wset,(*pState).winVis_posttof
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winPix_posttof]
        (*pState).pix = 1

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MSMICA_Plot,event
;
   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
time=systime()
msg=strarr(3)
msg[0]='Error at '+string(time)+' in Procedure MSMICA_Plot'
msg[1]='Unable to Plot Inelastic Data'
msg[2]='error message: '+!ERROR_STATE.MSG+'.'
SICSErrorLog=*(*pState).SICSErrorLog
SICSErrorLog=[SICSErrorLog,msg]
*(*pState).SICSErrorLog=SICSErrorLog
MS_UpdateErrorLog,event
return
endif
;
;
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).AnalyserDisplay,get_value = AnalyserDisplay
widget_control,(*pState).Analyser_Result,get_value = AR
str=strarr(5)
AR=long(AR[0])
if AnalyserDisplay eq 0 then begin; energy
xa = *(*pState).MicaArray_e
ya = *(*pState).MicaArray_e_y
xtitle='Energy Transfer / meV'
str[0]='The displayed intensity'
str[1]='has been normalilsed to'
str[2]='the incident neutron flux.'
endif
;
if AnalyserDisplay eq 1 then begin; wavelength
xa = *(*pState).MicaArray_l
ya = *(*pState).MicaArray_l_y
xtitle='Incident Wavelength / A'
str[0]='The raw spectrum is'
str[1]='displayed in units of'
str[2]='Angstrom.  The intensity '
str[3]='has not been normalised '
str[4]='to the TOF Monitor.'
endif
;
if AnalyserDisplay eq 2 then begin; time
xa = *(*pState).MicaArray_x
ya = *(*pState).MicaArray_y
xtitle='Total TOF / us'
str[0]='The raw time-of-flight'
str[1]='data is displayed.  The'
str[2]='intensity has not been'
str[3]='normalised to the TOF'
str[4]='Monitor.'
endif
widget_control,(*pState).win_mica_text,set_value = str
;
if AR eq 0 then begin
x=xa[0,*]
y=total(ya,1)

if (*pState).autoscale_mica eq 1 then begin
 xlo_mica = min(xa) & xhi_mica = max(xa)
  ylo_mica = min(y) & yhi_mica = max(y)
  (*pState).xrange_mica = [xlo_mica,xhi_mica]
  (*pState).yrange_mica = [ylo_mica,yhi_mica]
endif
x=xa[0,*]
y=total(ya,1)

wset,(*pState).winPix_mica
plot,x,y,xrange = (*pState).xrange_mica,yrange = (*pState).yrange_mica, $
     xstyle = 1,ystyle = 1,xtitle = xtitle, $
     ytitle = 'Intensity', title = 'Inelastic Neutron Scattering Spectrum',linestyle = 0, $
     thick = 1.0, psym=0, symsize=1.0
oplot,x,y,linestyle = 0, thick = 3.0, psym=0, symsize=1.0,color=(*pState).colors.red
endif else begin
x=xa[AR-1,*]
y=reform(ya[AR-1,*])
if (*pState).autoscale_mica eq 1 then begin
  xlo_mica = min(x) & xhi_mica = max(x)
  ylo_mica = min(y) & yhi_mica = max(y)
  (*pState).xrange_mica = [xlo_mica,xhi_mica]
  (*pState).yrange_mica = [ylo_mica,yhi_mica]
endif
wset,(*pState).winPix_mica
plot,x,y,xrange = (*pState).xrange_mica,yrange = (*pState).yrange_mica, $
     xstyle = 1,ystyle = 1,xtitle = xtitle, $
     ytitle = 'Intensity', title = 'Inelastic Neutron Scattering Spectrum',linestyle = 0, $
     thick = 1.0, psym=0, symsize=1.0
oplot,x,y,linestyle = 0, thick = 3.0, psym=0, symsize=1.0,color=(*pState).colors.red

if total(y) eq 0.0 then begin
xlims=!x.crange
ylims=!y.crange
xpos=xlims[0]+(xlims[1]-xlims[0])*0.4
xyouts,xpos,0.9*ylims[1],'The total counts over all time channels is zero'
xyouts,xpos,0.85*ylims[1],'If the Triffid angle deviates significantly from '
xyouts,xpos,0.80*ylims[1],'the mean, the counts are automatically set to zero.'
;
;
endif

endelse
wset,(*pState).winVis_mica
device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winPix_mica]
        (*pState).pix = 3

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro timebincull,event,slider,startbin,endbin,xdata,ydata,MultiArray=MultiArray
;return
print,' '
;print,'startbin: ',startbin
;print,'endbin: ',endbin
widget_control,event.top,get_uvalue = pState
   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
xdata=oxdata
ydata=oydata
time=systime()
msg=strarr(2)
msg[0]='Error at '+string(time)+' Dimensions of data array are incompatible with the time bin indices;'
msg[1]='error message: '+!ERROR_STATE.MSG+'.'
SICSErrorLog=*(*pState).SICSErrorLog
SICSErrorLog=[SICSErrorLog,msg]
*(*pState).SICSErrorLog=SICSErrorLog
MS_UpdateErrorLog,event
if ptr_valid(pxdat) eq 1 then ptr_free,pxdat
if ptr_valid(pydat) eq 1 then ptr_free,pydat
return
endif
oxdata=xdata
oydata=ydata
HP=(*pState).constants.Histogram_Period
dimensions=size(xdata)
if dimensions[0] eq 1 then begin
channels=dimensions[1]
endif else begin
channels=dimensions[2]
endelse
;print,'channels: ',channels
;slider=100
HP_CORMINUSFIRST=0.0
HP_CORMINUSSECOND=0.0
HP_CORADDFIRST=0.0
HP_CORADDSECOND=0.0
if startbin lt 0 then begin
startbin+=channels
endbin+=channels
HP_CORMINUSFIRST=HP
HP_CORMINUSSECOND=HP
endif
;
;
IF endbin GT startbin THEN BEGIN
width=endbin-startbin+1
newwidth=fix(width*(slider/100.0))
WidthAdjustment=fix((newwidth-width)/2) ;just in case
newwidth=width+2*WidthAdjustment
newstart=startbin-WidthAdjustment
newend=endbin+WidthAdjustment
if newstart lt 0 then begin
newstart+=channels
HP_CORMINUSFIRST=HP
endif
if newend gt (channels-1) then begin
newend-=channels
HP_CORADDSECOND=HP
endif
ENDIF ELSE BEGIN
HP_CORMINUSFIRST=HP
width=channels-startbin+endbin+1
newwidth=fix(width*(slider/100.0))
WidthAdjustment=fix((newwidth-width)/2) ;just in case
newwidth=width+2*WidthAdjustment
newstart=startbin-WidthAdjustment
newend=endbin+WidthAdjustment
if newstart gt (channels-1) then begin
newstart-=channels
HP_CORADDFIRST=HP
endif
if newend lt 0 then begin
newend+=channels
HP_CORMINUSSECOND=HP
endif
ENDELSE
;print,'newwidth: ' ,newwidth
;print,'newstart: ' ,newstart
;print,'newend: ' ,newend
;print,'HP_CORMINUSFIRST: ',HP_CORMINUSFIRST
;print,'HP_CORMINUSSECOND: ',HP_CORMINUSSECOND
;print,'HP_CORADDFIRST: ',HP_CORADDFIRST
;print,'HP_CORADDSECOND: ',HP_CORADDSECOND

IF newend GT newstart THEN BEGIN
if n_elements(MultiArray) eq 0 then begin
xdata=xdata[newstart:newend]-HP_CORMINUSFIRST+HP_CORADDFIRST
ydata=ydata[newstart:newend]
endif else begin
xdata=xdata[*,newstart:newend]-HP_CORMINUSFIRST+HP_CORADDFIRST
ydata=ydata[*,newstart:newend]
endelse
ENDIF ELSE BEGIN
firstbit=channels-newstart
secondbit=newend+1
if dimensions[0] eq 1 then begin
pxdat=ptr_new(fltarr(newwidth))
pydat=ptr_new(fltarr(newwidth))
;print,'newstart: ' ,newstart
;print,'newend: ' ,newend
;print,'WidthAdjustment: ' ,WidthAdjustment
;print,'newwidth: ' ,newwidth
;print,'firstbit: ' ,firstbit
;print,'secondbit: ' ,secondbit
(*pxdat)[0:firstbit-1]=xdata[newstart:channels-1]-HP_CORMINUSFIRST+HP_CORADDFIRST
(*pydat)[0:firstbit-1]=ydata[newstart:channels-1]
(*pxdat)[firstbit:firstbit+secondbit-1]=xdata[0:newend]-HP_CORMINUSSECOND+HP_CORADDSECOND
(*pydat)[firstbit:firstbit+secondbit-1]=ydata[0:newend]
endif else begin
pxdat=ptr_new(fltarr(dimensions[1],newwidth))
pydat=ptr_new(fltarr(dimensions[1],newwidth))
(*pxdat)[*,0:firstbit-1]=xdata[*,newstart:channels-1]-HP_CORMINUSFIRST+HP_CORADDFIRST
(*pydat)[*,0:firstbit-1]=ydata[*,newstart:channels-1]
(*pxdat)[*,firstbit:firstbit+secondbit-1]=xdata[*,0:newend]-HP_CORMINUSSECOND+HP_CORADDSECOND
(*pydat)[*,firstbit:firstbit+secondbit-1]=ydata[*,0:newend]
endelse
xdata=*pxdat
ydata=*pydat
ptr_free,pxdat,pydat
ENDELSE
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MSTempupdate,event
widget_control,event.top,get_uvalue = pState
demo_ms=(*pState).demo_ms
tunit=(*pState).tunit
unit=(*pState).unit
;
IF demo_ms eq 0 then begin
widget_control,(*pState).Environment_Result,get_value = ER
ER=long(ER[0])

if ER eq 0 then tempcommand = 'graph -300 0 none -1 np 1000 tt.ts tt.tm tt.tr' ;5 mins
if ER eq 1 then tempcommand = 'graph -1800 0 none -1 np 1000 tt.ts tt.tm tt.tr' ;30 mins
if ER eq 2 then tempcommand = 'graph -3600 0 none -1 np 1000 tt.ts tt.tm tt.tr' ;1 hour
if ER eq 3 then tempcommand = 'graph -21600 0 none -1 np 1000 tt.ts tt.tm tt.tr' ;6 hours
if ER eq 4 then tempcommand = 'graph -43200 0 none -1 np 1000 tt.ts tt.tm tt.tr' ;12 hours
if ER eq 5 then tempcommand = 'graph -86400 0 none -1 np 1000 tt.ts tt.tm tt.tr' ;1 day
if ER eq 6 then tempcommand = 'graph -259200 0 none -1 np 1000 tt.ts tt.tm tt.tr' ;3 days
if ER eq 7 then tempcommand = 'graph -604800 0 none -1 np 1000 tt.ts tt.tm tt.tr' ;7 days

temperature_fields=sicstempcommand(event,tunit,tempcommand)
;
woof=strpos(tag_names(temperature_fields),'ERROR')
wherezero=where(woof eq 0,count)
IF count eq 1 then begin ;there is an error
    IF STRMATCH(temperature_fields.error,'error1') eq 1 then begin
(*pState).SICSERROR=1
print,'Connection Lost'
SICSErrorLog=*(*pState).SICSErrorLog
msg=temperature_fields.msg
SICSErrorLog=[SICSErrorLog,msg]
*(*pState).SICSErrorLog=SICSErrorLog
MS_UpdateErrorLog,event
close,/all
return    ; return to event handler
    ENDIF ELSE BEGIN ;error2
    error='error2'
    SICSErrorLog=*(*pState).SICSErrorLog
    msg=temperature_fields.msg
    SICSErrorLog=[SICSErrorLog,msg]
    *(*pState).SICSErrorLog=SICSErrorLog
    MS_UpdateErrorLog,event
    (*pState).SICSTempERROR=1
        if xregistered('TemperatureReadError') eq 0 then begin
        TemperatureReadError_Create,event,widget_id
        (*pState).TemperatureReadError_widget_id=widget_id
        endif
    return
    ENDELSE
ENDIF

if (*pState).SICSTempERROR eq 1 then begin
widget_id=(*pState).TemperatureReadError_widget_id
TemperatureReadError_Destroy,widget_id
(*pState).SICSTempERROR=0
SICSErrorLog=*(*pState).SICSErrorLog
msg='Sample environment parameters can now be read'
SICSErrorLog=[SICSErrorLog,msg]
*(*pState).SICSErrorLog=SICSErrorLog
MS_UpdateErrorLog,event
endif


;help,temperature_fields,output=type
;wherestring=where(STRPOS(type,'STRING') ne -1,count)
;IF count ne 0 then begin
;print,temperature_fields
;    IF STRMATCH(temperature_fields,'SICSConnectionLost') eq 1 then begin
;(*pState).SICSERROR=1
;print,'Connection Lost'
;close,/all
;return    ; return to event handler
;    ENDIF
;ENDIF

;
woof=strpos(tag_names(temperature_fields),'TS_TIME')
wherezero=where(woof eq 0,count)
if count eq 1 then begin
TempSample_time=temperature_fields.(wherezero)
endif else begin
TempSample_time=make_array(1,value=-1.0)
endelse
;
woof=strpos(tag_names(temperature_fields),'TS_VARIABLE')
wherezero=where(woof eq 0,count)
if count eq 1 then begin
TempSample=temperature_fields.(wherezero)
endif else begin
TempSample=make_array(1,value=-1.0)
endelse
;
woof=strpos(tag_names(temperature_fields),'TM_TIME')
wherezero=where(woof eq 0,count)
if count eq 1 then begin
TempHeatEX_time=temperature_fields.(wherezero)
endif else begin
TempHeatEX_time=make_array(1,value=-1.0)
endelse
;
woof=strpos(tag_names(temperature_fields),'TM_VARIABLE')
wherezero=where(woof eq 0,count)
if count eq 1 then begin
TempHeatEX=temperature_fields.(wherezero)
endif else begin
TempHeatEX=make_array(1,value=-1.0)
endelse
;
woof=strpos(tag_names(temperature_fields),'TR_TIME')
wherezero=where(woof eq 0,count)
if count eq 1 then begin
TempSet_time=temperature_fields.(wherezero)
endif else begin
TempSet_time=make_array(1,value=-1.0)
endelse
;
woof=strpos(tag_names(temperature_fields),'TR_VARIABLE')
wherezero=where(woof eq 0,count)
if count eq 1 then begin
TempSet=temperature_fields.(wherezero)
endif else begin
TempSet=make_array(1,value=-1.0)
endelse

command='samenv -q'
response=sicscommand(event,tunit,command,datatype='string',/no_message)
DeviceName=(strsplit(response,/extract))[0]
DeviceName=strtrim(DeviceName,2)
;
Device_Names_str=*(*pState).Device_Names_str
;wheredevice=where(strpos(Device_Names_str,DeviceName) ne -1,count)
m=n_elements(Device_Names_str)
Device_Names_str_short=strarr(m)
for i = 0,m-1 do begin
Device_Names_str_short[i]=(strsplit(Device_Names_str[i],/extract))[0]
endfor
;wheredevice=where(strpos(Device_Names_str,DeviceName) ne -1)
wheredevice=where(Device_Names_str_short eq DeviceName,count)
wheredevice=wheredevice[0]
if count eq 0 then wheredevice = 0
widget_control,(*pState).Cryogenic_Device,set_value=Device_Names_str[wheredevice]


ENDIF ELSE BEGIN

widget_control,(*pState).Environment_Result,get_value = ER
ER=long(ER[0])
if ER eq 0 then time = 300 ;5 mins
if ER eq 1 then time = 1800 ;30 mins
if ER eq 2 then time = 3600 ;1 hour
if ER eq 3 then time = 21600 ;6 hours
if ER eq 4 then time = 43200 ;12 hours
if ER eq 5 then time = 86400 ;1 day
if ER eq 6 then time = 259200 ;3 days
if ER eq 7 then time = 604800 ;7 days
dt=time/999.0
;
TempSample=fltarr(1000)+50.0
TempHeatEX=fltarr(1000)+47.0
TempSet=fltarr(1000)+44.0
TempSample_time=-findgen(1000)*dt
TempHeatEX_time=-findgen(1000)*dt
TempSet_time=-findgen(1000)*dt


ENDELSE
*(*pState).TempSample=TempSample
*(*pState).TempHeatEX=TempHeatEX
*(*pState).TempSet=TempSet
*(*pState).TempSample_time=TempSample_time
*(*pState).TempHeatEX_time=TempHeatEX_time
*(*pState).TempSet_time=TempSet_time

;
n_temp=n_elements(TempSample)
if n_temp ne 0 then begin
current_temperature=string(TempSample[n_temp-1])
widget_control,(*pState).current_temperature,set_value = current_temperature
endif
;

MSTemp_Plot,event


end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MS_Give_up,event
widget_control,event.top,get_uvalue = pState1
main_program_event=(*pState1).main_program_event
widget_control,event.top,/destroy
wdelete,(*pState1).winpix_koennecke
ptr_free,pState1
widget_control,main_program_event.top,get_uvalue = pState
(*pState).demo_ms=1 ; we have to do this as there are no files for sics to close in the MS_exit routine
MS_exit,main_program_event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro FatalError,event,msg
widget_control,event.top,get_uvalue = pState
image=(*pState).koennecke_pic
;
; Centre it.
geom = widget_info(event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50

tlb = widget_base(title='Fatal Error',/col,group_leader=event.top,xoffset=xpos,yoffset=ypos, $
      tlb_frame_attr = 3,/modal)
Base1=widget_base(tlb,/row)

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

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

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

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

void = widget_text(Base1,value = msg,xsize = 80,ysize=3)
void = widget_button(tlb,value = 'Give up and exit nicely',event_pro ='MS_Give_up')

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]

main_program_event=event
state1={main_program_event:main_program_event, $
    winpix_koennecke:winpix_koennecke}

pState1 = ptr_new(state1,/no_copy)
widget_control,tlb,set_uvalue = pState1
xmanager, 'FatalError',tlb ,event_handler = 'MS_Give_up';register with the xmanager
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro TemperatureReadError_Create,event,tlb
widget_control,event.top,get_uvalue = pState
image=(*pState).koennecke_pic
;
; Centre it.
geom = widget_info(event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50

time=systime()

msg=strarr(3)
msg[0]='An error was encountered whilst trying to access the temperature fields at '+string(time)+'.'
msg[1]='The error message is displayed in the SICS error log'
msg[2]='This message will disappear when the information has been successfull acquired.'

tlb = widget_base(title='Sample Environment Read Error',/col,group_leader=event.top,xoffset=xpos,yoffset=ypos, $
      tlb_frame_attr = 3)
Base1=widget_base(tlb,/row)

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

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

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

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



void = widget_text(Base1,value = msg,xsize = 80,ysize=3)

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]


state2={winpix_koennecke:winpix_koennecke}

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

xmanager, 'TemperatureReadError',tlb ;register with the xmanager
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro ReconnectStatus_Create,event,tlb
widget_control,event.top,get_uvalue = pState
image=(*pState).koennecke_pic
;
; Centre it.
geom = widget_info(event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50

time=systime()

msg=strarr(3)
msg[0]='The connection to SICS was lost on '+string(time)+'.'
msg[1]='An attempt to re-connect is being made every 10 seconds.'
msg[2]='This message will disappear once the connection has been re-established.'

tlb = widget_base(title='Network Connection Lost',/col,group_leader=event.top,xoffset=xpos,yoffset=ypos, $
      tlb_frame_attr = 3)
Base1=widget_base(tlb,/row)

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

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

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

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

void = widget_text(Base1,value = msg,xsize = 58,ysize=3)
void = widget_button(tlb,value = 'Give up and exit nicely',event_pro ='MS_Give_up')

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]

main_program_event=event
state1={main_program_event:main_program_event, $
    winpix_koennecke:winpix_koennecke}

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

xmanager, 'Reconnect_Status',tlb ;register with the xmanager
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro TryAgainStatus_create,event,tlb
widget_control,event.top,get_uvalue = pState
image=(*pState).koennecke_pic
;
; Centre it.
geom = widget_info(event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50

time=systime()

msg=strarr(3)
msg[0]='A non-fatal error occured at '+string(time)+'.  Reading of Histogram Data was not accomplished'
msg[1]='An attempt to obtain something sensible from SICS is being made every 10 seconds.'
msg[2]='This message will disappear when the data has once again be successfully acquired.'

tlb = widget_base(title='Error issued by SICS',/col,group_leader=event.top,xoffset=xpos,yoffset=ypos, $
      tlb_frame_attr = 3)
Base1=widget_base(tlb,/row)

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

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

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

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

void = widget_text(Base1,value = msg,xsize = 85,ysize=3)
void = widget_button(tlb,value = 'Give up and exit nicely',event_pro ='MS_Give_up')

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]

main_program_event=event
state1={main_program_event:main_program_event, $
    winpix_koennecke:winpix_koennecke}

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

xmanager, 'TryAgainStatus',tlb ;register with the xmanager
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro TemperatureReadError_Destroy,tlb
widget_control,tlb,get_uvalue = pState2
wdelete,(*pState2).winpix_koennecke
ptr_free,pState2
widget_control,tlb,/destroy
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro ReconnectStatus_Destroy,tlb
widget_control,tlb,get_uvalue = pState1
wdelete,(*pState1).winpix_koennecke
ptr_free,pState1
widget_control,tlb,/destroy
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro TryAgainStatus_Destroy,tlb
widget_control,tlb,get_uvalue = pState1
wdelete,(*pState1).winpix_koennecke
ptr_free,pState1
widget_control,tlb,/destroy
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function ReestablishSICSConnection,event
widget_control,event.top,get_uvalue = pState
;the connection details worked before so must still be valid
;
;
PasswordFields=*(*pState).PasswordFields
;
host=PasswordFields.host
port=PasswordFields.port
user=PasswordFields.user
password=PasswordFields.password
;
thost=PasswordFields.thost
tport=PasswordFields.tport
tuser=PasswordFields.tuser
tpassword=PasswordFields.tpassword
;
;
unit=(*pState).unit
tunit=(*pState).tunit
;
SICSERROR=1

if xregistered('Reconnect_Status') eq 0 then begin
      daveDeSensitizeButtons,event
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 6
ReconnectStatus_Create,event,widget_id
(*pState).reconnect_widget_id=widget_id
endif
;
;
error=sicsconnect(unit,host,port,error=error)
;print,!ERROR_STATE.MSG
IF error eq '' then begin
;print,'first step'
logon=sicslogon(unit,user,password)
    IF logon eq 1 then begin
;print,'second step'
    error=sicsconnect(tunit,thost,tport)
       IF error eq '' then begin
;print,'third step'
       logon=sicslogon(tunit,tuser,tpassword)
         IF logon eq 1 then begin
         SICSERROR=0
            if (*pState).reconnect_widget_id ne -1 then ReconnectStatus_Destroy,(*pState).reconnect_widget_id
          daveSensitizeButtons,event
          msg='Connection re-established on '+systime()+'.'
          SICSErrorLog=*(*pState).SICSErrorLog
          SICSErrorLog=[SICSErrorLog,msg]
          *(*pState).SICSErrorLog=SICSErrorLog
         MS_UpdateErrorLog,event
         ENDIF
       ENDIF
    ENDIF
ENDIF

return,SICSERROR
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function TryOnceAgain,event
widget_control,event.top,get_uvalue = pState
timebin=*(*pState).timebin
notimebin=n_elements(timebin)
unit=(*pState).unit
nodata=24*notimebin ;number of detectors (monitors included) * number of timebins

SICSErrorLog=*(*pState).SICSErrorLog

(*pState).SICSERROR=0
    if xregistered('TryAgainStatus') eq 0 then begin
      daveDeSensitizeButtons,event
      widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 6
    TryAgainStatus_create,event,widget_id
    (*pState).reconnect_widget_id=widget_id
    endif
MarsUpdate_structure=SicsMarsUpdate(event,unit,'marsupdateinfo',SICSErrorLog)
IF n_tags(MarsUpdate_structure) eq 2 then begin ;error
    IF STRMATCH(MarsUpdate_structure.error,'error1') eq 1 then begin
(*pState).SICSERROR=1
print,'Connection Lost'
*(*pState).SICSErrorLog=MarsUpdate_structure.SICSErrorLog
MS_UpdateErrorLog,event
close,/all
    ENDIF
    IF STRMATCH(MarsUpdate_structure.error,'error2') eq 1 then begin
(*pState).SICSERROR=2
print,'Non-fatal error.  The SICS command SicsMarsUpdate has failed'
*(*pState).SICSErrorLog=MarsUpdate_structure.SICSErrorLog
MS_UpdateErrorLog,event
    ENDIF
    IF STRMATCH(MarsUpdate_structure.error,'error3') eq 1 then begin
(*pState).SICSERROR=3
print,'The information acquired from sics upon issuing the command is not what was hoped for'
*(*pState).SICSErrorLog=MarsUpdate_structure.SICSErrorLog
MS_UpdateErrorLog,event
    ENDIF
ENDIF


;help,MarsUpdate_structure,output=type
;wherestring=where(STRPOS(type,'STRING') ne -1,count)
;IF count ne 0 then begin
;    IF STRMATCH(MarsUpdate_structure,'error1') eq 1 then begin
;(*pState).SICSERROR=1
;print,'Connection Lost'
;close,/all
;    ENDIF
;    IF STRMATCH(MarsUpdate_structure,'error2') eq 1 then begin
;(*pState).SICSERROR=2
;print,'Non-fatal error.  The SICS command SicsMarsUpdate has failed'
;    ENDIF
;    IF STRMATCH(MarsUpdate_structure,'error3') eq 1 then begin
;(*pState).SICSERROR=3
;print,'The information acquired from sics upon issuing the command is not what was hoped for'
;    ENDIF
;ENDIF
;help,MarsUpdate_structure,/struc

IF (*pState).SICSERROR eq 0 THEN BEGIN
notimebin=MarsUpdate_structure.notimebin
timebin=MarsUpdate_structure.timebin
timebin/=10.0
data=MarsUpdate_structure.data
monitor1=MarsUpdate_structure.monitor1
Angles_info=MarsUpdate_structure.Angles_info
Choppers_Info=MarsUpdate_structure.Choppers_Info
target_reflection=MarsUpdate_structure.target_reflection
Sample_Name=MarsUpdate_structure.Sample_Name
Start_time=MarsUpdate_structure.Start_time
TimeBinIndices=MarsUpdate_structure.TimeBinIndices
CounterPreset=MarsUpdate_structure.CounterPreset
Status=MarsUpdate_structure.Status
Datanumber=MarsUpdate_structure.Datanumber
SICSErrorLog=MarsUpdate_structure.SICSErrorLog
ErrorGen=MarsUpdate_structure.ErrorGen
;help,ErrorGen
if strlowcase(Status) eq 'counting' then begin
    command='sicsdatanumber'
    response=sicscommand(event,unit,command,datatype='string')
Status=Status+' Datanumber '+response
endif
widget_control,(*pState).Status_Field,set_value = Status

if ErrorGen eq 1 then begin
*(*pState).SICSErrorLog=SICSErrorLog
MS_UpdateErrorLog,event
endif
for i = 0,4 do Choppers_Info[1,i]/=60.0 ; convert to Hz

timeoffsets=(*pState).timeoffsets
offset=0.0
masterfundamental=fix(round(Choppers_Info[1,1]/50.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
timebin+=offset



;convert TimeBinIndices to an integer array
TimeBinIndices=strsplit(TimeBinIndices,',',/extract)
TimeBinIndices=fix(TimeBinIndices)
;the following is necessary for experiments with very slow neutrons
if (TimeBinIndices[0] ge TimeBinIndices[6]) and (TimeBinIndices[1] ge TimeBinIndices[7]) then begin
TimeBinIndices[0]-=notimebin
TimeBinIndices[1]-=notimebin
endif
if (TimeBinIndices[2] ge TimeBinIndices[6]) and (TimeBinIndices[3] ge TimeBinIndices[7]) then begin
TimeBinIndices[2]-=notimebin
TimeBinIndices[3]-=notimebin
endif
;
(*pState).TimeBinIndices=TimeBinIndices


if target_reflection eq '002' or $
target_reflection eq '004' or $
target_reflection eq '006' or $
target_reflection eq '008' then begin
;print,'Target Reflection = ',target_reflection
(*pState).target_reflection=target_reflection
endif else begin
void = dialog_message(dialog_parent = event.top, $
'No valid entry for target reflection field.  Reflection 002 assumed')
target_reflection = '002 Assumed'
(*pState).target_reflection = target_reflection
endelse


DiffArray_x=fltarr(12,notimebin)
DiffArray_y=fltarr(12,notimebin)
dp=0 ;data_pointer
for i=0,11 do begin
DiffArray_x[i,*]=timebin
DiffArray_y[i,*]=data[dp:dp+notimebin-1]
dp+=notimebin
endfor
;
MicaArray_x=fltarr(10,notimebin)
MicaArray_y=fltarr(10,notimebin)
;
for i=0,9 do begin
MicaArray_x[i,*]=timebin
MicaArray_y[i,*]=data[dp:dp+notimebin-1]
dp+=notimebin
endfor
;
TOFMonitorArray_x=fltarr(notimebin)
TOFMonitorArray_y=fltarr(notimebin)


PostTOFMonitorArray_x=fltarr(notimebin)
PostTOFMonitorArray_y=fltarr(notimebin)
;
TOFMonitorArray_x=timebin
PostTOFMonitorArray_x=timebin
TOFMonitorArray_y=data[dp:dp+notimebin-1]
dp+=notimebin
PostTOFMonitorArray_y=data[dp:dp+notimebin-1]

TOFMonitorArray_yTotal=long64(total(TOFMonitorArray_y))
EstimateEndTime,Start_time,CounterPreset,TOFMonitorArray_yTotal,event

Monitors_Info=[monitor1,TOFMonitorArray_yTotal,long64(total(PostTOFMonitorArray_y))]



;
(*pState).Monitors_Info=Monitors_Info
(*pState).Choppers_Info=Choppers_Info
(*pState).Angles_Info=Angles_Info
;tof data
*(*pState).TOFMonitorArray_xFULL=TOFMonitorArray_x
*(*pState).TOFMonitorArray_yFULL=TOFMonitorArray_y
*(*pState).PostTOFMonitorArray_xFULL=PostTOFMonitorArray_x
*(*pState).PostTOFMonitorArray_yFULL=PostTOFMonitorArray_y
*(*pState).DiffArray_xFULL=DiffArray_x
*(*pState).DiffArray_yFULL=DiffArray_y
*(*pState).MicaArray_xFULL=MicaArray_x
*(*pState).MicaArray_yFULL=MicaArray_y
;
;Apply time bin cull
;TOF Monitor
widget_control,(*pState).WindowDefine_slider_TOFMon,get_value = slider
slider=long(slider[0])
startbin=TimeBinIndices[0]
endbin=TimeBinIndices[1]
timebincull,event,slider,startbin,endbin,TOFMonitorArray_x,TOFMonitorArray_y
*(*pState).TOFMonitorArray_x=TOFMonitorArray_x
*(*pState).TOFMonitorArray_y=TOFMonitorArray_y
;define another array for calibration purposes.
slider=95
startbin=TimeBinIndices[0]
endbin=TimeBinIndices[1]
;print,'tofmonstartbin: ',startbin
;print,'tofmonendbin: ',endbin
TOFMonitorArray_xCal=*(*pState).TOFMonitorArray_xFull
TOFMonitorArray_yCal=*(*pState).TOFMonitorArray_yFull
;
timebincull,event,slider,startbin,endbin,TOFMonitorArray_xCal,TOFMonitorArray_yCal
*(*pState).TOFMonitorArray_xCal=TOFMonitorArray_xCal
*(*pState).TOFMonitorArray_yCal=TOFMonitorArray_yCal
;
;Post TOF Monitor
widget_control,(*pState).WindowDefine_slider_PostTOFMon,get_value = slider
slider=long(slider[0])
startbin=TimeBinIndices[2]
endbin=TimeBinIndices[3]
timebincull,event,slider,startbin,endbin,PostTOFMonitorArray_x,PostTOFMonitorArray_y
*(*pState).PostTOFMonitorArray_x=PostTOFMonitorArray_x
*(*pState).PostTOFMonitorArray_y=PostTOFMonitorArray_y
;
;Diffraction Detectors
widget_control,(*pState).WindowDefine_slider_diffraction,get_value = slider
slider=long(slider[0])
startbin=TimeBinIndices[4]
endbin=TimeBinIndices[5]
timebincull,event,slider,startbin,endbin,DiffArray_x,DiffArray_y,/MultiArray
*(*pState).DiffArray_x=DiffArray_x
*(*pState).DiffArray_y=DiffArray_y
;
;Inelastic Detectors
widget_control,(*pState).WindowDefine_slider_inelastic,get_value = slider
slider=long(slider[0])
case target_reflection of
'002':  $
begin
startbin=TimeBinIndices[6]
endbin=TimeBinIndices[7]
end
'002 Assumed':  $
begin
startbin=TimeBinIndices[6]
endbin=TimeBinIndices[7]
end
'004':  $
begin
startbin=TimeBinIndices[8]
endbin=TimeBinIndices[9]
end
'006':  $
begin
startbin=TimeBinIndices[10]
endbin=TimeBinIndices[11]
end
'008':  $
begin
startbin=TimeBinIndices[12]
endbin=TimeBinIndices[13]
end
endcase
timebincull,event,slider,startbin,endbin,MicaArray_x,MicaArray_y,/MultiArray
*(*pState).MicaArray_x=MicaArray_x
*(*pState).MicaArray_y=MicaArray_y;
;
;update fields
TOFMonitorUnits,event
TOFMonitorIntCor,event
MSTOF_Plot,event

PostTOFMonitorUnits,event
PostTOFMonitorIntCor,event
PostMSTOF_Plot,event

MS_dspacing,event
DiffDisplay,event
MicaUnits,event
MicaIntCor,event
MSMICA_Plot,event
;
FluxCalculator,event
;
;populate fields
;monitors
widget_control,(*pState).monitor_fields.monitor1,set_value = Monitors_Info[0]
widget_control,(*pState).monitor_fields.monitor2,set_value = Monitors_Info[1]
widget_control,(*pState).monitor_fields.monitor3,set_value = Monitors_Info[2]
;choppers
Chopper_Display,event
;widget_control,(*pState).chopper_fields.chopper1,set_value = Choppers_Info[0,0]
;widget_control,(*pState).chopper_fields.chopper2,set_value = Choppers_Info[0,1]
;widget_control,(*pState).chopper_fields.chopper3,set_value = Choppers_Info[0,2]
;widget_control,(*pState).chopper_fields.chopper4,set_value = Choppers_Info[0,3]
;widget_control,(*pState).chopper_fields.chopper5,set_value = Choppers_Info[0,4]
;diffraction detectors
widget_control,(*pState).diffraction_fields.diff1,set_value = long(total(DiffArray_y[0,*]))
widget_control,(*pState).diffraction_fields.diff2,set_value = long(total(DiffArray_y[1,*]))
widget_control,(*pState).diffraction_fields.diff3,set_value = long(total(DiffArray_y[2,*]))
widget_control,(*pState).diffraction_fields.diff4,set_value = long(total(DiffArray_y[3,*]))
widget_control,(*pState).diffraction_fields.diff5,set_value = long(total(DiffArray_y[4,*]))
widget_control,(*pState).diffraction_fields.diff6,set_value = long(total(DiffArray_y[5,*]))
widget_control,(*pState).diffraction_fields.diff7,set_value = long(total(DiffArray_y[6,*]))
widget_control,(*pState).diffraction_fields.diff8,set_value = long(total(DiffArray_y[7,*]))
widget_control,(*pState).diffraction_fields.diff9,set_value = long(total(DiffArray_y[8,*]))
widget_control,(*pState).diffraction_fields.diff10,set_value = long(total(DiffArray_y[9,*]))
widget_control,(*pState).diffraction_fields.diff11,set_value = long(total(DiffArray_y[10,*]))
widget_control,(*pState).diffraction_fields.diff12,set_value = long(total(DiffArray_y[11,*]))
;Analyser detectors
Mica_Display,event
;Sample Fields
widget_control,(*pState).SampleName,set_value = Sample_Name
;Target Reflection
widget_control,(*pState).target_reflection_field,set_value = (*pState).target_reflection
;

StartTimeStr=systime(0,Start_time)

widget_control,(*pState).SampleStart_p,set_value = StartTimeStr

ENDIF


if (*pState).SICSERROR ne 2 then begin
TryAgainStatus_Destroy,(*pState).reconnect_widget_id
daveSensitizeButtons,event
endif

return,(*pState).SICSERROR
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MS_UpdateErrorLog,event
widget_control,event.top,get_uvalue = pState
SICSErrorLog=*(*pState).SICSErrorLog
n=n_elements(SICSErrorLog)
;maxlines=50
maxlines=10000
if n gt maxlines then begin
temp=strarr(maxlines)
temp[0]=SICSErrorLog[0]
temp[1:maxlines-1]=SICSErrorLog[n+1-maxlines:*]
SICSErrorLog=temp
*(*pState).SICSErrorLog=SICSErrorLog
endif
widget_control,(*pState).win_sics_text,set_value = SICSErrorLog
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MS_Update,event
widget_control,event.top,get_uvalue = pState
demo_ms=(*pState).demo_ms
;

if demo_ms eq 0 then begin

unit=(*pState).unit
tunit=(*pState).tunit
;
SICSErrorLog=*(*pState).SICSErrorLog
;tstart=systime(/seconds)
;help,sicserrorlog
;
;temp=sicsexecute(event,unit,'hm genbin 200 1 4000')
;temp=sicsexecute(event,unit,'targetreflection 002')
;print, temp
;wait,10

error=sicserrorcheck(event,unit)
if error ne 'none' then begin
print,error
SICSErrorLog=[SICSErrorLog,error]
*(*pState).SICSErrorLog=SICSErrorLog
MS_UpdateErrorLog,event
endif
;
;
MarsUpdate_structure=SicsMarsUpdate(event,unit,'marsupdateinfo',SICSErrorLog)
IF n_tags(MarsUpdate_structure) eq 2 then begin ;error
    IF STRMATCH(MarsUpdate_structure.error,'error1') eq 1 then begin
(*pState).SICSERROR=1
print,'Connection Lost'
*(*pState).SICSErrorLog=MarsUpdate_structure.SICSErrorLog
MS_UpdateErrorLog,event
close,/all
return    ; return to event handler
    ENDIF
    IF STRMATCH(MarsUpdate_structure.error,'error2') eq 1 then begin
(*pState).SICSERROR=2
print,'Non-fatal error.  The SICS command SicsMarsUpdate has failed'
*(*pState).SICSErrorLog=MarsUpdate_structure.SICSErrorLog
MS_UpdateErrorLog,event
return    ; return to event handler
    ENDIF
    IF STRMATCH(MarsUpdate_structure.error,'error3') eq 1 then begin
(*pState).SICSERROR=3
print,'The information acquired from sics upon issuing the command is not what was hoped for'
*(*pState).SICSErrorLog=MarsUpdate_structure.SICSErrorLog
MS_UpdateErrorLog,event
return    ; return to event handler
    ENDIF
ENDIF



;help,MarsUpdate_structure,/struc

notimebin=MarsUpdate_structure.notimebin
timebin=MarsUpdate_structure.timebin
timebin/=10.0
data=MarsUpdate_structure.data
monitor1=MarsUpdate_structure.monitor1
Angles_info=MarsUpdate_structure.Angles_info
Choppers_Info=MarsUpdate_structure.Choppers_Info
target_reflection=MarsUpdate_structure.target_reflection
Sample_Name=MarsUpdate_structure.Sample_Name
Start_time=MarsUpdate_structure.Start_time
TimeBinIndices=MarsUpdate_structure.TimeBinIndices
CounterPreset=MarsUpdate_structure.CounterPreset
Status=MarsUpdate_structure.Status
Datanumber=MarsUpdate_structure.Datanumber
SICSErrorLog=MarsUpdate_structure.SICSErrorLog
ErrorGen=MarsUpdate_structure.ErrorGen
;help,ErrorGen
if strlowcase(Status) eq 'counting' then begin
    command='sicsdatanumber'
    response=sicscommand(event,unit,command,datatype='string')
Status=Status+' Datanumber '+response
endif
widget_control,(*pState).Status_Field,set_value = Status


;help,(*pState).TimeBinIndices
;help,(*pState).CounterPreset

if ErrorGen eq 1 then begin
*(*pState).SICSErrorLog=SICSErrorLog
MS_UpdateErrorLog,event
endif

for i = 0,4 do Choppers_Info[1,i]/=60.0 ; convert to Hz


timeoffsets=(*pState).timeoffsets
offset=0.0
masterfundamental=fix(round(Choppers_Info[1,1]/50.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,'masterfundamental: ' ,masterfundamental
;print,'offset: ' ,offset
timebin+=offset



;convert TimeBinIndices to an integer array
TimeBinIndices=strsplit(TimeBinIndices,',',/extract)
TimeBinIndices=fix(TimeBinIndices)
;the following is necessary for experiments with very slow neutrons
if (TimeBinIndices[0] ge TimeBinIndices[6]) and (TimeBinIndices[1] ge TimeBinIndices[7]) then begin
TimeBinIndices[0]-=notimebin
TimeBinIndices[1]-=notimebin
endif
if (TimeBinIndices[2] ge TimeBinIndices[6]) and (TimeBinIndices[3] ge TimeBinIndices[7]) then begin
TimeBinIndices[2]-=notimebin
TimeBinIndices[3]-=notimebin
endif
;
(*pState).TimeBinIndices=TimeBinIndices



DiffArray_x=fltarr(12,notimebin)
DiffArray_y=fltarr(12,notimebin)
dp=0 ;data_pointer
for i=0,11 do begin
DiffArray_x[i,*]=timebin
DiffArray_y[i,*]=data[dp:dp+notimebin-1]
dp+=notimebin
endfor
;
MicaArray_x=fltarr(10,notimebin)
MicaArray_y=fltarr(10,notimebin)
;
for i=0,9 do begin
MicaArray_x[i,*]=timebin
MicaArray_y[i,*]=data[dp:dp+notimebin-1]
dp+=notimebin
endfor

;
TOFMonitorArray_x=fltarr(notimebin)
TOFMonitorArray_y=fltarr(notimebin)


PostTOFMonitorArray_x=fltarr(notimebin)
PostTOFMonitorArray_y=fltarr(notimebin)
;
TOFMonitorArray_x=timebin
PostTOFMonitorArray_x=timebin
TOFMonitorArray_y=data[dp:dp+notimebin-1]
dp+=notimebin
PostTOFMonitorArray_y=data[dp:dp+notimebin-1]
;
TOFMonitorArray_yTotal=long64(total(TOFMonitorArray_y))
EstimateEndTime,Start_time,CounterPreset,TOFMonitorArray_yTotal,event
Monitors_Info=[monitor1,TOFMonitorArray_yTotal,long64(total(PostTOFMonitorArray_y))]

;
if target_reflection eq '002' or $
target_reflection eq '004' or $
target_reflection eq '006' or $
target_reflection eq '008' then begin
;print,'Target Reflection = ',target_reflection
(*pState).target_reflection=target_reflection
endif else begin
void = dialog_message(dialog_parent = event.top, $
'No valid entry for target reflection field.  Reflection 002 assumed')
target_reflection = '002 Assumed'
(*pState).target_reflection = target_reflection
endelse


*(*pState).timebin=timebin
(*pState).Monitors_Info=Monitors_Info
(*pState).Choppers_Info=Choppers_Info
(*pState).Angles_Info=Angles_Info
;tof data
*(*pState).TOFMonitorArray_xFULL=TOFMonitorArray_x
*(*pState).TOFMonitorArray_yFULL=TOFMonitorArray_y
*(*pState).PostTOFMonitorArray_xFULL=PostTOFMonitorArray_x
*(*pState).PostTOFMonitorArray_yFULL=PostTOFMonitorArray_y
*(*pState).DiffArray_xFULL=DiffArray_x
*(*pState).DiffArray_yFULL=DiffArray_y
*(*pState).MicaArray_xFULL=MicaArray_x
*(*pState).MicaArray_yFULL=MicaArray_y
;
;Apply time bin cull
;TOF Monitor
widget_control,(*pState).WindowDefine_slider_TOFMon,get_value = slider
slider=long(slider[0])
startbin=TimeBinIndices[0]
endbin=TimeBinIndices[1]
timebincull,event,slider,startbin,endbin,TOFMonitorArray_x,TOFMonitorArray_y
*(*pState).TOFMonitorArray_x=TOFMonitorArray_x
*(*pState).TOFMonitorArray_y=TOFMonitorArray_y
;define another array for calibration purposes.
slider=95
startbin=TimeBinIndices[0]
endbin=TimeBinIndices[1]
;print,'tofmonstartbin: ',startbin
;print,'tofmonendbin: ',endbin
TOFMonitorArray_xCal=*(*pState).TOFMonitorArray_xFull
TOFMonitorArray_yCal=*(*pState).TOFMonitorArray_yFull
;
timebincull,event,slider,startbin,endbin,TOFMonitorArray_xCal,TOFMonitorArray_yCal
*(*pState).TOFMonitorArray_xCal=TOFMonitorArray_xCal
*(*pState).TOFMonitorArray_yCal=TOFMonitorArray_yCal
;
;Post TOF Monitor
widget_control,(*pState).WindowDefine_slider_PostTOFMon,get_value = slider
slider=long(slider[0])
startbin=TimeBinIndices[2]
endbin=TimeBinIndices[3]
timebincull,event,slider,startbin,endbin,PostTOFMonitorArray_x,PostTOFMonitorArray_y
*(*pState).PostTOFMonitorArray_x=PostTOFMonitorArray_x
*(*pState).PostTOFMonitorArray_y=PostTOFMonitorArray_y
;
;Diffraction Detectors
widget_control,(*pState).WindowDefine_slider_diffraction,get_value = slider
slider=long(slider[0])
startbin=TimeBinIndices[4]
endbin=TimeBinIndices[5]
timebincull,event,slider,startbin,endbin,DiffArray_x,DiffArray_y,/MultiArray
*(*pState).DiffArray_x=DiffArray_x
*(*pState).DiffArray_y=DiffArray_y
;
;Inelastic Detectors
widget_control,(*pState).WindowDefine_slider_inelastic,get_value = slider
slider=long(slider[0])
case target_reflection of
'002':  $
begin
startbin=TimeBinIndices[6]
endbin=TimeBinIndices[7]
end
'002 Assumed':  $
begin
startbin=TimeBinIndices[6]
endbin=TimeBinIndices[7]
end
'004':  $
begin
startbin=TimeBinIndices[8]
endbin=TimeBinIndices[9]
end
'006':  $
begin
startbin=TimeBinIndices[10]
endbin=TimeBinIndices[11]
end
'008':  $
begin
startbin=TimeBinIndices[12]
endbin=TimeBinIndices[13]
end
endcase
timebincull,event,slider,startbin,endbin,MicaArray_x,MicaArray_y,/MultiArray
*(*pState).MicaArray_x=MicaArray_x
*(*pState).MicaArray_y=MicaArray_y
;
;
widget_control,(*pState).Environment_Result,get_value = ER
ER=long(ER[0])

if ER eq 0 then tempcommand = 'graph -300 0 none -1 np 1000 tt.ts tt.tm tt.tr' ;5 mins
if ER eq 1 then tempcommand = 'graph -1800 0 none -1 np 1000 tt.ts tt.tm tt.tr' ;30 mins
if ER eq 2 then tempcommand = 'graph -3600 0 none -1 np 1000 tt.ts tt.tm tt.tr' ;1 hour
if ER eq 3 then tempcommand = 'graph -21600 0 none -1 np 1000 tt.ts tt.tm tt.tr' ;6 hours
if ER eq 4 then tempcommand = 'graph -43200 0 none -1 np 1000 tt.ts tt.tm tt.tr' ;12 hours
if ER eq 5 then tempcommand = 'graph -86400 0 none -1 np 1000 tt.ts tt.tm tt.tr' ;1 day
if ER eq 6 then tempcommand = 'graph -259200 0 none -1 np 1000 tt.ts tt.tm tt.tr' ;3 days
if ER eq 7 then tempcommand = 'graph -604800 0 none -1 np 1000 tt.ts tt.tm tt.tr' ;7 days

temperature_fields=sicstempcommand(event,tunit,tempcommand)
woof=strpos(tag_names(temperature_fields),'ERROR')
wherezero=where(woof eq 0,count)
IF count eq 1 then begin ;there is an error
    IF STRMATCH(temperature_fields.error,'error1') eq 1 then begin
(*pState).SICSERROR=1
print,'Connection Lost'
SICSErrorLog=*(*pState).SICSErrorLog
msg=temperature_fields.msg
SICSErrorLog=[SICSErrorLog,msg]
*(*pState).SICSErrorLog=SICSErrorLog
MS_UpdateErrorLog,event
close,/all
return    ; return to event handler
    ENDIF ELSE BEGIN ;error2
    error='error2'
    SICSErrorLog=*(*pState).SICSErrorLog
    msg=temperature_fields.msg
    SICSErrorLog=[SICSErrorLog,msg]
    *(*pState).SICSErrorLog=SICSErrorLog
    MS_UpdateErrorLog,event
    (*pState).SICSTempERROR=1
        if xregistered('TemperatureReadError') eq 0 then begin
        TemperatureReadError_Create,event,widget_id
        (*pState).TemperatureReadError_widget_id=widget_id
        endif
    return
    ENDELSE
ENDIF

if (*pState).SICSTempERROR eq 1 then begin
widget_id=(*pState).TemperatureReadError_widget_id
TemperatureReadError_Destroy,widget_id
(*pState).SICSTempERROR=0
SICSErrorLog=*(*pState).SICSErrorLog
msg='Sample environment parameters can now be read'
SICSErrorLog=[SICSErrorLog,msg]
*(*pState).SICSErrorLog=SICSErrorLog
MS_UpdateErrorLog,event
endif

;
;
;
woof=strpos(tag_names(temperature_fields),'TS_TIME')
wherezero=where(woof eq 0,count)
if count eq 1 then begin
TempSample_time=temperature_fields.(wherezero)
endif else begin
TempSample_time=-1
endelse
;
woof=strpos(tag_names(temperature_fields),'TS_VARIABLE')
wherezero=where(woof eq 0,count)
if count eq 1 then begin
TempSample=temperature_fields.(wherezero)
endif else begin
TempSample=-1
endelse
;
woof=strpos(tag_names(temperature_fields),'TM_TIME')
wherezero=where(woof eq 0,count)
if count eq 1 then begin
TempHeatEX_time=temperature_fields.(wherezero)
endif else begin
TempHeatEX_time=-1
endelse
;
woof=strpos(tag_names(temperature_fields),'TM_VARIABLE')
wherezero=where(woof eq 0,count)
if count eq 1 then begin
TempHeatEX=temperature_fields.(wherezero)
endif else begin
TempHeatEX=-1
endelse
;
woof=strpos(tag_names(temperature_fields),'TR_TIME')
wherezero=where(woof eq 0,count)
if count eq 1 then begin
TempSet_time=temperature_fields.(wherezero)
endif else begin
TempSet_time=-1
endelse
;
woof=strpos(tag_names(temperature_fields),'TR_VARIABLE')
wherezero=where(woof eq 0,count)
if count eq 1 then begin
TempSet=temperature_fields.(wherezero)
endif else begin
TempSet=-1
endelse

*(*pState).TempSample=TempSample
*(*pState).TempHeatEX=TempHeatEX
*(*pState).TempSet=TempSet
*(*pState).TempSample_time=TempSample_time
*(*pState).TempHeatEX_time=TempHeatEX_time
*(*pState).TempSet_time=TempSet_time

command='samenv -q'
response=sicscommand(event,tunit,command,datatype='string',/no_message)
DeviceName=(strsplit(response,/extract))[0]
DeviceName=strtrim(DeviceName,2)
;
Device_Names_str=*(*pState).Device_Names_str


;wheredevice=where(strpos(Device_Names_str,DeviceName) ne -1,count)
m=n_elements(Device_Names_str)
Device_Names_str_short=strarr(m)
for i = 0,m-1 do begin
Device_Names_str_short[i]=(strsplit(Device_Names_str[i],/extract))[0]
endfor
;wheredevice=where(strpos(Device_Names_str,DeviceName) ne -1)
wheredevice=where(Device_Names_str_short eq DeviceName,count)
wheredevice=wheredevice[0]
if count eq 0 then wheredevice = 0
widget_control,(*pState).Cryogenic_Device,set_value=Device_Names_str[wheredevice]


;Target Reflection
widget_control,(*pState).target_reflection_field,set_value = (*pState).target_reflection
;
StartTimeStr=systime(0,Start_time)
;print,'StartTimeStr: ',StartTimeStr
widget_control,(*pState).SampleStart_p,set_value = StartTimeStr

endif else begin

Start_time=systime()
seed=*(*pState).seed
TOFMonitorArray_y=*(*pState).TOFMonitorArray_y
PostTOFMonitorArray_y=*(*pState).PostTOFMonitorArray_y
dimtof=(size(TOFMonitorArray_y))[1]
dimposttof=(size(PostTOFMonitorArray_y))[1]
;*(*pState).TOFMonitorArray_y=(*(*pState).TOFMonitorArray_y*temp)
temp=randomu(seed,dimtof)
*(*pState).TOFMonitorArray_y*=1.1
*(*pState).TOFMonitorArray_y+=temp*10.0
temp=randomu(seed,dimposttof)
*(*pState).PostTOFMonitorArray_y*=1.1
*(*pState).PostTOFMonitorArray_y+=temp*10.0
DiffArray_y=*(*pState).DiffArray_y
dimdiff=(size(DiffArray_y))[2]
temp=fltarr(12,dimdiff)
for i=0,11 do begin
temp[i,*]=randomu(seed,dimdiff)
endfor
*(*pState).DiffArray_y+=(*(*pState).DiffArray_y+temp*5.0)
MicaArray_y=*(*pState).MicaArray_y
dimmica=(size(MicaArray_y))[2]
temp=fltarr(10,dimmica)
for i=0,9 do begin
temp[i,*]=randomu(seed,dimmica)
endfor
*(*pState).MicaArray_y+=(*(*pState).MicaArray_y+temp*5.0)
temp=long(20*randomu(seed,3))
(*pState).Monitors_Info+=temp
Monitors_Info=(*pState).Monitors_Info
*(*pState).seed=seed
Choppers_Info=[[0,50.0],[324.60,150.0],[23.45,50.0],[129.50,50.0],[222.74,50.0]]
(*pState).target_reflection='002'
Sample_Name='Name of Sample'
;
widget_control,(*pState).Environment_Result,get_value = ER
ER=long(ER[0])
if ER eq 0 then time = 300 ;5 mins
if ER eq 1 then time = 1800 ;30 mins
if ER eq 2 then time = 3600 ;1 hour
if ER eq 3 then time = 21600 ;6 hours
if ER eq 4 then time = 43200 ;12 hours
if ER eq 5 then time = 86400 ;1 day
if ER eq 6 then time = 259200 ;3 days
if ER eq 7 then time = 604800 ;7 days
dt=time/999.0
;
TempSample=fltarr(1000)+50.0
TempHeatEX=fltarr(1000)+47.0
TempSet=fltarr(1000)+44.0
TempSample_time=-findgen(1000)*dt
TempHeatEX_time=-findgen(1000)*dt
TempSet_time=-findgen(1000)*dt
;
*(*pState).TempSample=TempSample
*(*pState).TempHeatEX=TempHeatEX
*(*pState).TempSet=TempSet
*(*pState).TempSample_time=TempSample_time
*(*pState).TempHeatEX_time=TempHeatEX_time
*(*pState).TempSet_time=TempSet_time

endelse


;update fields
TOFMonitorUnits,event
TOFMonitorIntCor,event
MSTOF_Plot,event

PostTOFMonitorUnits,event
PostTOFMonitorIntCor,event
PostMSTOF_Plot,event

MS_dspacing,event
DiffDisplay,event
MicaUnits,event
MicaIntCor,event
MSMICA_Plot,event
MSTemp_Plot,event
;
FluxCalculator,event
;
;populate fields
;monitors
widget_control,(*pState).monitor_fields.monitor1,set_value = Monitors_Info[0]
widget_control,(*pState).monitor_fields.monitor2,set_value = Monitors_Info[1]
widget_control,(*pState).monitor_fields.monitor3,set_value = Monitors_Info[2]
;choppers
Chopper_Display,event
;widget_control,(*pState).chopper_fields.chopper1,set_value = Choppers_Info[0,0]
;widget_control,(*pState).chopper_fields.chopper2,set_value = Choppers_Info[0,1]
;widget_control,(*pState).chopper_fields.chopper3,set_value = Choppers_Info[0,2]
;widget_control,(*pState).chopper_fields.chopper4,set_value = Choppers_Info[0,3]
;widget_control,(*pState).chopper_fields.chopper5,set_value = Choppers_Info[0,4]
;diffraction detectors
widget_control,(*pState).diffraction_fields.diff1,set_value = long(total(DiffArray_y[0,*]))
widget_control,(*pState).diffraction_fields.diff2,set_value = long(total(DiffArray_y[1,*]))
widget_control,(*pState).diffraction_fields.diff3,set_value = long(total(DiffArray_y[2,*]))
widget_control,(*pState).diffraction_fields.diff4,set_value = long(total(DiffArray_y[3,*]))
widget_control,(*pState).diffraction_fields.diff5,set_value = long(total(DiffArray_y[4,*]))
widget_control,(*pState).diffraction_fields.diff6,set_value = long(total(DiffArray_y[5,*]))
widget_control,(*pState).diffraction_fields.diff7,set_value = long(total(DiffArray_y[6,*]))
widget_control,(*pState).diffraction_fields.diff8,set_value = long(total(DiffArray_y[7,*]))
widget_control,(*pState).diffraction_fields.diff9,set_value = long(total(DiffArray_y[8,*]))
widget_control,(*pState).diffraction_fields.diff10,set_value = long(total(DiffArray_y[9,*]))
widget_control,(*pState).diffraction_fields.diff11,set_value = long(total(DiffArray_y[10,*]))
widget_control,(*pState).diffraction_fields.diff12,set_value = long(total(DiffArray_y[11,*]))
;Analyser detectors
Mica_Display,event
;Sample Fields
widget_control,(*pState).SampleName,set_value = Sample_Name
;
n_temp=n_elements(TempSample)
if n_temp ne 0 then begin
current_temperature=string(TempSample[n_temp-1])
widget_control,(*pState).current_temperature,set_value = current_temperature
endif
;


end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro TOFMonitorUnits,event
widget_control,event.top,get_uvalue = pState
constants=(*pState).constants
lTOFMon=constants.lTOFMon
mn=constants.mn
h=constants.h
conv=constants.meVtoJoules
TOFMonitorArray_t=*(*pState).TOFMonitorArray_x
;print,'TOFMonitorArray_t[0]',TOFMonitorArray_t[0]
v=lTOFMon/(TOFMonitorArray_t/1.0e6)
;print,'min(v) = ',min(v)
E_joules=0.5*mn*v^2
TOFMonitorArray_e=E_joules/conv[0]
;help,TOFMonitorArray_e
;TOFMonitorArray_l=sqrt(81.80321/TOFMonitorArray_e)
TOFMonitorArray_l=(h*1e10)/(mn*v)
;print,'TOFMonitorArray_l: ',TOFMonitorArray_l
;print,'min(TOFMonitorArray_l): ',min(TOFMonitorArray_l)
;print,'max(TOFMonitorArray_l): ',max(TOFMonitorArray_l)
*(*pState).TOFMonitorArray_e=TOFMonitorArray_e
*(*pState).TOFMonitorArray_l=TOFMonitorArray_l
*(*pState).TOFMonitorArray_t=TOFMonitorArray_t
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro PostTOFMonitorUnits,event
widget_control,event.top,get_uvalue = pState
constants=(*pState).constants
lTOFPostMon=constants.lTOFPostMon
mn=constants.mn
h=constants.h
conv=constants.meVtoJoules
PostTOFMonitorArray_t=*(*pState).PostTOFMonitorArray_x
v=lTOFPostMon/(PostTOFMonitorArray_t/1.0e6)
;print,'min(v) = ',min(v)
E_joules=0.5*mn*v^2
PostTOFMonitorArray_e=E_joules/conv[0]
;help,TOFMonitorArray_e
;TOFMonitorArray_l=sqrt(81.80321/TOFMonitorArray_e)
PostTOFMonitorArray_l=(h*1e10)/(mn*v)
*(*pState).PostTOFMonitorArray_e=PostTOFMonitorArray_e
*(*pState).PostTOFMonitorArray_l=PostTOFMonitorArray_l
*(*pState).PostTOFMonitorArray_t=PostTOFMonitorArray_t
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function MS_Bragg,dspace,theta
return, 2.0*dspace*sin(theta*!DTOR)
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MicaUnits,event
widget_control,event.top,get_uvalue = pState
AcceptanceLevel=0.5;
   CATCH, Error_status
if Error_status ne 0 then begin
AcceptanceLevel+=0.5
    if AcceptanceLevel eq 5.0 then begin
    catch, /cancel
    time=systime()
    msg=strarr(2)
    msg[0]='An error was encountered at '+string(time)+' in the MicaUnits Procedure.'
    msg[1]='Unable to purge the Inelastic Detector Angles of Outliers'
    SICSErrorLog=*(*pState).SICSErrorLog
    SICSErrorLog=[SICSErrorLog,msg]
    *(*pState).SICSErrorLog=SICSErrorLog
    MS_UpdateErrorLog,event
;    daveDeSensitizeButtons,event
;    FatalError,event,msg
    return
    endif
endif
constants=(*pState).constants
lprim=constants.lprim
mn=constants.mn
h=constants.h
D=constants.D
conv=constants.meVtoJoules
tr=(*pState).target_reflection
dspace_002=constants.dspace_002
if tr eq '002' then dspace=dspace_002
if tr eq '002 Assumed' then dspace=dspace_002
if tr eq '004' then dspace=dspace_002/2
if tr eq '006' then dspace=dspace_002/3
if tr eq '008' then dspace=dspace_002/4
Angles_Info=(*pState).Angles_Info
;calculate mean angle excluding outliers

stats=moment(Angles_Info,MDEV=MDEV)
while MDEV gt AcceptanceLevel do begin
AbsSD=abs(stats[0]-Angles_Info)
WhereNotOutlier=where(AbsSD lt MDEV)
Angles_Info=Angles_Info[WhereNotOutlier]
;if n_elements(Angles_Info) gt 1 then begin
stats=moment(Angles_Info,MDEV=MDEV)
;endif else begin
;stats=Angles_Info[0]
;MDEV=0.0
;endelse
endwhile
theta=stats[0] ; take the average, should all be the same
Angles_Info=(*pState).Angles_Info ;reset

;purge
for i = 0,9 do begin
;print,'(*(*pState).MicaArray_y)[i,*] 1: ',total((*(*pState).MicaArray_y)[i,*])
if abs(Angles_Info[i] - theta) gt AcceptanceLevel then (*(*pState).MicaArray_y)[i,*]=0.0
;print,'(*(*pState).MicaArray_y)[i,*] 2: ',total((*(*pState).MicaArray_y)[i,*])
print,''
endfor
;

E_analyser=81.80321/(MS_Bragg(dspace,theta))^2
v_analyser=sqrt(E_analyser*conv*2.0/mn)
t_analyser=1e6*D/v_analyser

;print,'*(*pState).MicaArray_x :',reform((*(*pState).MicaArray_x)[0,*])

MicaArray_t=*(*pState).MicaArray_x-t_analyser
;print,'MicaArray_t :',reform(MicaArray_t[0,*])
v=lprim/(MicaArray_t/1.0e6)
E_joules=0.5*mn*v^2
MicaArray_e=E_joules/conv[0]
MicaArray_e-=E_analyser
MicaArray_l=(h*1e10)/(mn*v)
;print,'minMicaArray_l:',min(MicaArray_l)
*(*pState).MicaArray_e=MicaArray_e
*(*pState).MicaArray_l=MicaArray_l
*(*pState).MicaArray_t=MicaArray_t
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro TOFMonitorIntCor,event
widget_control,event.top,get_uvalue = pState
TOFMonitorArray_l_y=*(*pState).TOFMonitorArray_y
TOFMonitorArray_l=*(*pState).TOFMonitorArray_l
TOFMonitorArray_t=*(*pState).TOFMonitorArray_t
widget_control,(*pState).Monitor_Efficiency,get_value = mon
str=strarr(5)
if mon eq 0 then begin
;correct for monitor efficency
;
ub=(*pState).ub
Mon_Efficiency=1-exp(-ub*TOFMonitorArray_l)
TOFMonitorArray_l_y/=Mon_Efficiency
str[0]='The spectrum displayed'
str[1]='is that of the incoming'
str[2]='neutron flux, i.e. that'
str[3]= 'measured by a black'
str[4]= 'detector.'
endif else begin
str[0]='The raw TOF monitor'
str[1]='spectrum approximates '
str[2]='to the neutron density '
str[3]= 'in the low wavelength '
str[4]= 'limit.'
endelse
widget_control,(*pState).win_diff_text,set_value = str
TOFMonitorArray_t_y=TOFMonitorArray_l_y
*(*pState).TOFMonitorArray_l_y=TOFMonitorArray_l_y
*(*pState).TOFMonitorArray_t_y=TOFMonitorArray_t_y
TOFMonitorArray_e_y=TOFMonitorArray_t_y
norm=(total(TOFMonitorArray_t^3))/n_elements(TOFMonitorArray_t)
;print,'norm = ',norm[0]
TOFMonitorArray_e_y*=TOFMonitorArray_t^3/norm[0]
*(*pState).TOFMonitorArray_e_y=TOFMonitorArray_e_y
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro PostTOFMonitorIntCor,event
widget_control,event.top,get_uvalue = pState
PostTOFMonitorArray_l_y=*(*pState).PostTOFMonitorArray_y
PostTOFMonitorArray_l=*(*pState).PostTOFMonitorArray_l
PostTOFMonitorArray_t=*(*pState).PostTOFMonitorArray_t
widget_control,(*pState).PostMonitor_Efficiency,get_value = mon
str=strarr(5)
if mon eq 0 then begin
;correct for monitor efficency
;
db=(*pState).db
Mon_Efficiency=1-exp(-db*PostTOFMonitorArray_l)
PostTOFMonitorArray_l_y/=Mon_Efficiency
str[0]='The spectrum displayed'
str[1]='is that of the incoming'
str[2]='neutron flux, i.e. that'
str[3]= 'measured by a black'
str[4]= 'detector.'
endif else begin
str[0]='The raw TOF monitor'
str[1]='spectrum approximates '
str[2]='to the neutron density '
str[3]= 'in the low wavelength '
str[4]= 'limit.'
endelse
widget_control,(*pState).Postwin_diff_text,set_value = str
PostTOFMonitorArray_t_y=PostTOFMonitorArray_l_y
*(*pState).PostTOFMonitorArray_l_y=PostTOFMonitorArray_l_y
*(*pState).PostTOFMonitorArray_t_y=PostTOFMonitorArray_t_y
PostTOFMonitorArray_e_y=PostTOFMonitorArray_t_y
norm=(total(PostTOFMonitorArray_t^3))/n_elements(PostTOFMonitorArray_t)
;print,'norm = ',norm[0]
PostTOFMonitorArray_e_y*=PostTOFMonitorArray_t^3/norm[0]
*(*pState).PostTOFMonitorArray_e_y=PostTOFMonitorArray_e_y
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MicaIntCor,event
widget_control,event.top,get_uvalue = pState
constants=(*pState).constants
h=constants.h
mn=constants.mn
MicaArray_l_y=*(*pState).MicaArray_y
MicaArray_t_y=*(*pState).MicaArray_y
MicaArray_e_y=*(*pState).MicaArray_y
MicaArray_l=*(*pState).MicaArray_l
MicaArray_e=*(*pState).MicaArray_e
MicaArray_t=*(*pState).MicaArray_t   ; this is ti !


   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
widget_control,(*pState).AnalyserDisplay,set_value = 1
time=systime()
msg=strarr(4)
msg[0]='Error at '+string(time)+' in Procedure MicaIntCor'
msg[1]='Unable to Normalise the Inelastic Data to the Incident Monitor'
msg[2]='Check that the Time Bin Indices are Correct and that the Triffids are at the Correct Positions'
msg[3]='Error Message: '+!ERROR_STATE.MSG
SICSErrorLog=*(*pState).SICSErrorLog
SICSErrorLog=[SICSErrorLog,msg]
*(*pState).SICSErrorLog=SICSErrorLog
MS_UpdateErrorLog,event
return
endif


;normalise
;
lTOFMon=constants.lTOFMon
TOFMonitorArray_t=*(*pState).TOFMonitorArray_xCal
v=lTOFMon/(TOFMonitorArray_t/1.0e6)
TOFMonitorArray_l=(h*1e10)/(mn*v)
;first extract dimension of time channels
channels_mon=(size(TOFMonitorArray_l))[1]
channels_mica=(size(MicaArray_l))[2]
index_map=intarr(2,channels_mica)
index_map[0,*]=indgen(channels_mica)
umica=1+bytarr(channels_mica)
umon=1+bytarr(channels_mon)
diff=abs(reform(MicaArray_l[0,*])#umon-umica#TOFMonitorArray_l)
;print,'TOFMonitorArray_l: ',TOFMonitorArray_l
;print,'MicaArray_l: ',MicaArray_l
;
;help,index_map
for i=0,channels_mica-1 do begin
void=min(diff[i,*],ind)
;print,ind
;help,ind
index_map[1,i]=ind
endfor
;
TOFMonitorArray_l_y=*(*pState).TOFMonitorArray_yCal
ub=(*pState).ub
Mon_Efficiency=1-exp(-ub*TOFMonitorArray_l)
TOFMonitorArray_l_y/=Mon_Efficiency

;now we are ready to perform the normalisation
;if the mapping occurs at the edges of the TOF monitor
;then these data points are rejected, i.e. the MicaArray_e and MicaArray_e_y
;arrays are condensed.

;print,'min(TOFMonitorArray_l): ',min(TOFMonitorArray_l)
;print,'max(TOFMonitorArray_l): ',max(TOFMonitorArray_l)
;print,'min(MicaArray_l): ',min(MicaArray_l)
;print,'max(MicaArray_l): ',max(MicaArray_l)
;print,'MicaArray_l[0,*]: ',reform(MicaArray_l[0,*])


;normt=(moment(MicaArray_t))[0]
;print,normt
;
for i=0,channels_mica-1 do begin

if TOFMonitorArray_l_y[index_map[1,i]] gt 10 then begin  ; we must have reasonable statistics in the monitor
MicaArray_e_y[*,i]/=TOFMonitorArray_l_y[index_map[1,i]] ; 1st correction according to Dorner
endif else begin
MicaArray_e_y[*,i]=0.0
endelse

;MicaArray_e_y[*,i]*=normt/MicaArray_t[i]  ;second correction according to Dorner, required because we are normalising to a black detector.
MicaArray_e_y[*,i]/=MicaArray_t[i]  ;second correction according to Dorner, required because we are normalising to a black detector.

;print,'index_map[1,i] = ',index_map[1,i]
if (index_map[1,i] eq 0) or (index_map[1,i] eq (n_elements(TOFMonitorArray_l_y)-1)) then begin
    if n_elements(reject) eq 0 then begin
    reject=i
    endif else begin
    reject=[reject,i]
    endelse
endif
endfor


if n_elements(reject) ne 0 then begin
;help,reject
;print,reject
MicaArray_e_new=fltarr(10,channels_mica-n_elements(reject))
MicaArray_e_y_new=fltarr(10,channels_mica-n_elements(reject))
    j=0
    k=0
    for i=0,channels_mica-1 do begin
    whereiconrej=where(i eq reject,count)
    if count ne 0 then begin
    k+=1
    endif else begin
    MicaArray_e_new[*,j]=MicaArray_e[*,i]
    MicaArray_e_y_new[*,j]=MicaArray_e_y[*,i]
    j+=1
    k+=1
    endelse
    endfor
MicaArray_e=MicaArray_e_new
MicaArray_e_y=MicaArray_e_y_new
endif
;
*(*pState).MicaArray_l_y=MicaArray_l_y
*(*pState).MicaArray_t_y=MicaArray_t_y
*(*pState).MicaArray_e_y=MicaArray_e_y
*(*pState).MicaArray_e=MicaArray_e
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro DiffDisplay,event

   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
time=systime()
msg=strarr(2)
msg[0]='Unable to Plot Diffraction Data at time '+string(time)
msg[1]='error message: '+!ERROR_STATE.MSG+'.'
SICSErrorLog=*(*pState).SICSErrorLog
SICSErrorLog=[SICSErrorLog,msg]
*(*pState).SICSErrorLog=SICSErrorLog
MS_UpdateErrorLog,event
return
endif


widget_control,event.top,get_uvalue = pState
DiffArray_d=*(*pState).DiffArray_d
DiffArray_t_y=*(*pState).DiffArray_t_y
widget_control,(*pState).Diffraction_Result,get_value = DR
DR=long(DR[0])
if DR eq 0 then begin
if (*pState).autoscale_diff eq 1 then begin
  xlo_diff = min(DiffArray_d) & xhi_diff = max(DiffArray_d)
  ylo_diff = min(DiffArray_t_y) & yhi_diff = max(DiffArray_t_y)
  (*pState).xrange_diff = [xlo_diff,xhi_diff]
  (*pState).yrange_diff = [ylo_diff,yhi_diff]
endif
x=DiffArray_d[0,*]
y=DiffArray_t_y[0,*]
wset,(*pState).winPix_diff
plot,x,y,xrange = (*pState).xrange_diff,yrange = (*pState).yrange_diff, $
     xstyle = 1,ystyle = 1,xtitle = 'd-spacing / A', $
     ytitle = 'Intensity', title = 'Diffraction Pattern',linestyle = 0, $
     thick = 1.0, psym=0, symsize=1.0
for i=0,11 do begin
x=DiffArray_d[i,*]
y=DiffArray_t_y[i,*]
oplot,x,y,linestyle = 0, thick = 3.0, psym=0, symsize=1.0,color=(*pState).colors.red
endfor
endif else begin
x=DiffArray_d[DR-1,*]
y=DiffArray_t_y[DR-1,*]
if (*pState).autoscale_diff eq 1 then begin
    xlo_diff = min(x) & xhi_diff = max(x)
  ylo_diff = min(y) & yhi_diff = max(y)
  (*pState).xrange_diff = [xlo_diff,xhi_diff]
  (*pState).yrange_diff = [ylo_diff,yhi_diff]
endif
wset,(*pState).winPix_diff
plot,x,y,xrange = (*pState).xrange_diff,yrange = (*pState).yrange_diff, $
     xstyle = 1,ystyle = 1,xtitle = 'd-spacing / A', $
     ytitle = 'Intensity', title = 'Diffraction Pattern',linestyle = 0, $
     thick = 1.0, psym=0, symsize=1.0
oplot,x,y,linestyle = 0, thick = 3.0, psym=0, symsize=1.0,color=(*pState).colors.red
endelse
wset,(*pState).winVis_diff
device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winPix_diff]
        (*pState).pix = 2
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MS_Initialise,event
widget_control,event.top,get_uvalue = pState
   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
if ptr_valid(pState) eq 0 then return
time=systime()
msg=strarr(3)
msg[0]='An error was encountered at '+string(time)+' whilst initialising the program.'
msg[1]='Error Message: '+!ERROR_STATE.MSG
msg[2]='If the problem persists please contact support.'
daveDeSensitizeButtons,event
FatalError,event,msg
return
endif
*(*pState).SICSErrorLog=make_array(1,value='Errors From SICS')
delim=(*pState).delim
workDir=(*pState).workDir
widget_control,(*pState).UpdateTime_p,get_value = slider
slider=long(slider[0])
if slider eq 1 then time = 60
if slider eq 2 then time = 300
if slider eq 3 then time = 1200
if slider eq 4 then time = 3600
;
time=float(time)
widget_control,(*pState).ChopperDisplay,set_value = 0
widget_control,(*pState).MicaDisplay,set_value = 0
;
;filename='C:\Documents and Settings\tregenna\My Documents\NIST\DAVE\cvs_nist\dave\programs\auxiliary\MarsSICSInfo.txt'
;filename=!DAVE_AUXILIARY_DIR+'PSI\MARS\MarsSICSInfo_Spy.txt'
filename=!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MarsSICSInfo_Spy.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
;
;tfilename=!DAVE_AUXILIARY_DIR+'PSI\MARS\MarsTempSICSInfo.txt'
tfilename=!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MarsTempSICSInfo.txt'
thoststring=''
tportstring=''
tuserstring=''
tpasswordstring=''
openr,lun,tfilename,/get_lun
readf,lun,thoststring
readf,lun,tportstring
readf,lun,tuserstring
readf,lun,tpasswordstring
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)
;
equalsign=strpos(thoststring,'=')
thost=strmid(thoststring,equalsign+1)
equalsign=strpos(tportstring,'=')
tport=strmid(tportstring,equalsign+1)
tport=long(tport)
equalsign=strpos(tuserstring,'=')
tuser=strmid(tuserstring,equalsign+1)
equalsign=strpos(tpasswordstring,'=')
tpassword=strmid(tpasswordstring,equalsign+1)

PasswordFields={host:host,port:port,user:user,password:password, $
             thost:thost,tport:tport,tuser:tuser,tpassword:tpassword}
;
*(*pState).PasswordFields=PasswordFields
;
;
;filename=!DAVE_AUXILIARY_DIR+'PSI'+delim+'PSICryostats.cry'
;;
;if file_test(filename) eq 1 then begin
;line=''
;Device_Names_str='Not Found'
;openr,lun,filename,/get_lun
;while eof(lun) eq 0 do begin
;readf,lun,line
;Device_Names_str=[Device_Names_str,line]
;endwhile
;free_lun,lun,/force
;endif
;*(*pState).Device_Names_str=Device_Names_str
;
;
;
;try and connect to sics
get_lun,unit
(*pState).unit=unit
get_lun,tunit
(*pState).tunit=tunit
;
;
;woof=sicscommand(event,unit,'hm notimebin',datatype='fltarr',dimension=2)
;return
;goto, jump
response=sicsconnect(unit,host,port,error=error)
;print,'socketerror = ',error
;print, '!ERROR_STATE.MSG = ',!ERROR_STATE.MSG
    IF response eq 0 then begin
; the program is not running in demonstration mode
(*pState).demo_ms=0
logon=sicslogon(unit,user,password)
;print,'woofb'
;print,logon
if logon eq 0 then begin
void = dialog_message(dialog_parent = event.top,/error, $
'SICS Spy login is incorrect. Please inspect and edit the file ' +  $
'in the Dave auxillary directory.  The program will now exit.')
MS_exit,event
return
endif
;
;choppers
ChopperCommand_array=strarr(10)
Choppers_Info=fltarr(2,5)
;
ChopperCommand_array[0]='snailphase'
ChopperCommand_array[1]='masterphase'
ChopperCommand_array[2]='rabbitphase'
ChopperCommand_array[3]='fourphase'
ChopperCommand_array[4]='fivephase'
ChopperCommand_array[5]='snailspeed'
ChopperCommand_array[6]='masterspeed'
ChopperCommand_array[7]='rabbitspeed'
ChopperCommand_array[8]='fourspeed'
ChopperCommand_array[9]='fivespeed'
;
for i = 0,9 do begin
temp=sicscommand(event,unit,ChopperCommand_array[i],datatype='float')
;
if i le 4 then begin
Choppers_Info[0,i]=temp
endif else begin
    if temp ne -1 then begin
    Choppers_Info[1,i-5]=temp/60.0 ; convert to Hz
    endif else begin
    Choppers_Info[1,i-5]=temp ;error
    endelse
endelse
endfor
;jump:test=sicscommand(event,unit,'hm notimebin',datatype='long')
;
;get all the histogram memory of the diffraction and and triffid detectors

notimebin=sicscommand(event,unit,'hm notimebin',datatype='long')
;print,'notimebin: ',notimebin
;
;
nodata=24*notimebin ;number of detectors (monitors included) * number of timebins
;tstart=systime(/seconds)
data=sicscommand(event,unit,'hm get 0',datatype='fltarr',dimension=nodata)
;telapsed=systime(/seconds)-tstart
;print,'Time to read in data = ',telapsed
;
timebin=sicscommand(event,unit,'hm timebin',datatype='fltarr',dimension=notimebin)
;print,'timebin1 = ',timebin
timebin/=10.0
timebin_space=(timebin[1]-timebin[0])/2.0
timebin+=timebin_space
;print,'timebin2 = ',timebin

timeoffsets=(*pState).timeoffsets
offset=0.0
masterfundamental=fix(round(Choppers_Info[1,1]/50.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,'masterfundamental: ' ,masterfundamental
;print,'offset: ' ,offset
;print,'timebin: ' ,timebin

timebin+=offset

*(*pState).timebin=timebin

DiffArray_x=fltarr(12,notimebin)
DiffArray_y=fltarr(12,notimebin)
dp=0 ;data_pointer
for i=0,11 do begin
DiffArray_x[i,*]=timebin
DiffArray_y[i,*]=data[dp:dp+notimebin-1]
dp+=notimebin
endfor

;print,'DiffArray_x[0,0]: ',DiffArray_x[0,0]

MicaArray_x=fltarr(10,notimebin)
MicaArray_y=fltarr(10,notimebin)
;
for i=0,9 do begin
MicaArray_x[i,*]=timebin
MicaArray_y[i,*]=data[dp:dp+notimebin-1]
dp+=notimebin
endfor
;
;
TOFMonitorArray_x=fltarr(notimebin)
TOFMonitorArray_y=fltarr(notimebin)
PostTOFMonitorArray_x=fltarr(notimebin)
PostTOFMonitorArray_y=fltarr(notimebin)
;
TOFMonitorArray_x=timebin
PostTOFMonitorArray_x=timebin
TOFMonitorArray_y=data[dp:dp+notimebin-1]
TOFMonitorArray_yTotal=long64(total(TOFMonitorArray_y))

;print,TOFMonitorArray_y
dp+=notimebin
;print, 'dp = ',dp
;print, 'data[dp:dp+notimebin-1] = ',data[dp+notimebin-1]
PostTOFMonitorArray_y=data[dp:dp+notimebin-1]
;print,dp+notimebin-1
;help,PostTOFMonitorArray_y
;print,'PostTOFMonitorArray_y[dp+notimebin-1] = ',PostTOFMonitorArray_y[notimebin-1]
;
;
monitor1=sicscommand(event,unit,'el737 getmonitor 2',datatype='long64')
;print,total(TOFMonitorArray_y)

Monitors_Info=[monitor1,TOFMonitorArray_yTotal,long64(total(PostTOFMonitorArray_y))]
;print,Monitors_Info
;
;triffid angles
thcommand_array=strarr(10)
Angles_info=fltarr(10)

thcommand_array[0]='th01'
thcommand_array[1]='th02'
thcommand_array[2]='th03'
thcommand_array[3]='th04'
thcommand_array[4]='th05'
thcommand_array[5]='th06'
thcommand_array[6]='th07'
thcommand_array[7]='th08'
thcommand_array[8]='th09'
thcommand_array[9]='th10'
;
;
for i = 0,9 do begin
Angles_info[i]=sicscommand(event,unit,thcommand_array[i],datatype='float')
endfor
;print,Angles_info
;

;
error=sicsconnect(tunit,thost,tport)
logon=sicslogon(tunit,tuser,tpassword)


;cryostats
Device_Names_str=sicscommand(event,tunit,'samenv list',datatype='strarr')

IF Device_Names_str[0] eq 'SICSConnectionLost' THEN BEGIN
;
filename=!DAVE_AUXILIARY_DIR+'PSI'+delim+'PSICryostats.cry'
if file_test(filename) eq 1 then begin
line=''
Device_Names_str='Not Found'
openr,lun,filename,/get_lun
while eof(lun) eq 0 do begin
readf,lun,line
Device_Names_str=[Device_Names_str,line]
endwhile
free_lun,lun,/force
endif
;
ENDIF ELSE BEGIN
;filename=!DAVE_AUXILIARY_DIR+'PSI'+delim+'PSICryostats.cry'
;m=n_elements(Device_Names_str)
;print,'Number of Cryogenic Devices: ',m
;if !version.os_family ne "UNIX" then begin
;openw,lun,filename,/get_lun
;for i = 0, m-1 do begin
;printf,lun,Device_Names_str[i]
;endfor
;free_lun,lun,/force
;endif
Device_Names_str=['Not Found',Device_Names_str]
;
ENDELSE
*(*pState).Device_Names_str=Device_Names_str


command='samenv -q'
response=sicscommand(event,tunit,command,datatype='string',/no_message)
DeviceName=(strsplit(response,/extract))[0]
DeviceName=strtrim(DeviceName,2)
;



;wheredevice=where(strpos(Device_Names_str,DeviceName) ne -1,count)
m=n_elements(Device_Names_str)
Device_Names_str_short=strarr(m)
for i = 0,m-1 do begin
Device_Names_str_short[i]=(strsplit(Device_Names_str[i],/extract))[0]
endfor
;wheredevice=where(strpos(Device_Names_str,DeviceName) ne -1)
wheredevice=where(Device_Names_str_short eq DeviceName,count)
wheredevice=wheredevice[0]
if count eq 0 then wheredevice = 0
widget_control,(*pState).Cryogenic_Device,set_value=Device_Names_str[wheredevice]


temperature_fields=sicstempcommand(event,tunit,'graph -300 0 none -1 np 1000 tt.ts tt.tm tt.tr')
;
woof=strpos(tag_names(temperature_fields),'TS_TIME')
wherezero=where(woof eq 0,count)
if count eq 1 then begin
TempSample_time=temperature_fields.(wherezero)
endif else begin
TempSample_time=make_array(1,value=-1.0)
endelse
;
woof=strpos(tag_names(temperature_fields),'TS_VARIABLE')
wherezero=where(woof eq 0,count)
if count eq 1 then begin
TempSample=temperature_fields.(wherezero)
endif else begin
TempSample=make_array(1,value=-1.0)
endelse
;
woof=strpos(tag_names(temperature_fields),'TM_TIME')
wherezero=where(woof eq 0,count)
if count eq 1 then begin
TempHeatEX_time=temperature_fields.(wherezero)
endif else begin
TempHeatEX_time=make_array(1,value=-1.0)
endelse
;
woof=strpos(tag_names(temperature_fields),'TM_VARIABLE')
wherezero=where(woof eq 0,count)
if count eq 1 then begin
TempHeatEX=temperature_fields.(wherezero)
endif else begin
TempHeatEX=make_array(1,value=-1.0)
endelse
;
woof=strpos(tag_names(temperature_fields),'TR_TIME')
wherezero=where(woof eq 0,count)
if count eq 1 then begin
TempSet_time=temperature_fields.(wherezero)
endif else begin
TempSet_time=make_array(1,value=-1.0)
endelse
;
woof=strpos(tag_names(temperature_fields),'TR_VARIABLE')
wherezero=where(woof eq 0,count)
if count eq 1 then begin
TempSet=temperature_fields.(wherezero)
endif else begin
TempSet=make_array(1,value=-1.0)
endelse
;
;
target_reflection=sicscommand(event,unit,'TargetReflection',datatype='string')
;print,target_reflection
;help,target_reflection
if target_reflection eq '002' or $
target_reflection eq '004' or $
target_reflection eq '006' or $
target_reflection eq '008' then begin
;print,'Target Reflection = ',target_reflection
(*pState).target_reflection=target_reflection
endif else begin
void = dialog_message(dialog_parent = event.top, $
'No valid entry for target reflection field.  Reflection 002 assumed')
target_reflection = '002 Assumed'
(*pState).target_reflection = target_reflection
endelse
;
Sample_Name=sicscommand(event,unit,'Sample',datatype='string')
Start_time=sicscommand(event,unit,'unixstarttime',datatype='long64')
;(*pState).Start_time=Start_time
StartTimeStr=systime(0,Start_time)

CounterPreset=sicscommand(event,unit,'counter preset',datatype='long64')
;(*pState).MonitorPreset=MonitorPreset


Status=sicscommand(event,unit,'Status',datatype='string')
;
if strlowcase(Status) eq 'counting' then begin
    command='sicsdatanumber'
    response=sicscommand(event,unit,command,datatype='string')
Status=Status+' Datanumber '+response
endif
;;

TOFMonitorArray_xFULL=TOFMonitorArray_x
TOFMonitorArray_yFULL=TOFMonitorArray_y
PostTOFMonitorArray_xFULL=PostTOFMonitorArray_x
PostTOFMonitorArray_yFULL=PostTOFMonitorArray_y
DiffArray_xFULL=DiffArray_x
DiffArray_yFULL=DiffArray_y
MicaArray_xFULL=MicaArray_x
MicaArray_yFULL=MicaArray_y
;
;
;Apply time bin cull
;first get the time bin indices
TimeBinIndices=sicscommand(event,unit,'TimeBinIndices',datatype='string')
if TimeBinIndices eq '-1' then begin
void = dialog_message(dialog_parent = event.top,/error, $
'Unable to acquire the time bin indices. ' +  $
'The program will now exit.  Please try to initialise again.')
MS_exit,event
endif
TimeBinIndices=strsplit(TimeBinIndices,',',/extract)
TimeBinIndices=fix(TimeBinIndices)
;print,'TimeBinIndices :',TimeBinIndices
;the following is necessary for experiments with very slow neutrons
if (TimeBinIndices[0] ge TimeBinIndices[6]) and (TimeBinIndices[1] ge TimeBinIndices[7]) then begin
TimeBinIndices[0]-=notimebin
TimeBinIndices[1]-=notimebin
endif
if (TimeBinIndices[2] ge TimeBinIndices[6]) and (TimeBinIndices[3] ge TimeBinIndices[7]) then begin
TimeBinIndices[2]-=notimebin
TimeBinIndices[3]-=notimebin
endif
;
;
;
(*pState).TimeBinIndices=TimeBinIndices
;help,TimeBinIndices
;help,TimeBinIndices
;print,'TimeBinIndices :',TimeBinIndices
;
;TOF Monitor
widget_control,(*pState).WindowDefine_slider_TOFMon,get_value = slider
slider=long(slider[0])
startbin=TimeBinIndices[0]
endbin=TimeBinIndices[1]
;print,'tofmonstartbin: ',startbin
;print,'tofmonendbin: ',endbin
timebincull,event,slider,startbin,endbin,TOFMonitorArray_x,TOFMonitorArray_y
;


;define another array for calibration purposes.
slider=95
startbin=TimeBinIndices[0]
endbin=TimeBinIndices[1]
;print,'tofmonstartbin: ',startbin
;print,'tofmonendbin: ',endbin
TOFMonitorArray_xCal=TOFMonitorArray_xFULL
TOFMonitorArray_yCal=TOFMonitorArray_yFULL
;
timebincull,event,slider,startbin,endbin,TOFMonitorArray_xCal,TOFMonitorArray_yCal
;
;this section is for the flux calculator
;slider=100
slider=50
startbin=TimeBinIndices[0]
endbin=TimeBinIndices[1]
TOFMonitorArray_xflux=TOFMonitorArray_xFULL
TOFMonitorArray_yflux=TOFMonitorArray_yFULL
timebincull,event,slider,startbin,endbin,TOFMonitorArray_xflux,TOFMonitorArray_yflux
ele=n_elements(TOFMonitorArray_xflux)
MidpointIndex=ele/2
;UpstreamLastCount_y=TOFMonitorArray_yflux[MidpointIndex]
UpstreamLastCount_y=total(TOFMonitorArray_yflux)
UpstreamLastCount_x=TOFMonitorArray_xflux[MidpointIndex]
;
;Post TOF Monitor
widget_control,(*pState).WindowDefine_slider_PostTOFMon,get_value = slider
slider=long(slider[0])
startbin=TimeBinIndices[2]
endbin=TimeBinIndices[3]
timebincull,event,slider,startbin,endbin,PostTOFMonitorArray_x,PostTOFMonitorArray_y
;

;this section is for the flux calculator
;slider=100
slider=50
startbin=TimeBinIndices[2]
endbin=TimeBinIndices[3]
PostTOFMonitorArray_xflux=PostTOFMonitorArray_xFULL
PostTOFMonitorArray_yflux=PostTOFMonitorArray_yFULL
timebincull,event,slider,startbin,endbin,PostTOFMonitorArray_xflux,PostTOFMonitorArray_yflux
;ele=n_elements(PostTOFMonitorArray_xflux)
;MidpointIndex=ele/2
;DownstreamLastCount_y=PostTOFMonitorArray_yflux[MidpointIndex]
DownstreamLastCount_y=total(PostTOFMonitorArray_yflux)
DownstreamLastCount_x=PostTOFMonitorArray_xflux[MidpointIndex]



;
;Diffraction Detectors
widget_control,(*pState).WindowDefine_slider_diffraction,get_value = slider
slider=long(slider[0])
startbin=TimeBinIndices[4]
endbin=TimeBinIndices[5]
timebincull,event,slider,startbin,endbin,DiffArray_x,DiffArray_y,/MultiArray
;
;Inelastic Detectors
widget_control,(*pState).WindowDefine_slider_inelastic,get_value = slider
slider=long(slider[0])
case target_reflection of
'002':  $
begin
startbin=TimeBinIndices[6]
endbin=TimeBinIndices[7]
end
'002 Assumed':  $
begin
startbin=TimeBinIndices[6]
endbin=TimeBinIndices[7]
end
'004':  $
begin
startbin=TimeBinIndices[8]
endbin=TimeBinIndices[9]
end
'006':  $
begin
startbin=TimeBinIndices[10]
endbin=TimeBinIndices[11]
end
'008':  $
begin
startbin=TimeBinIndices[12]
endbin=TimeBinIndices[13]
end
endcase

timebincull,event,slider,startbin,endbin,MicaArray_x,MicaArray_y,/MultiArray

;
;
;print,'inelasticstartbin: ',startbin
;print,'inelasticendbin: ',endbin

;
    ENDIF ELSE BEGIN
Start_time=systime(/seconds)
StartTimeStr=systime(0,Start_time)
;
;
void = dialog_message(dialog_parent = event.top, $
'Connection to MARS not found.  The program shall run in demonstration mode.')
seed=100L
void=randomu(seed)
*(*pState).seed=seed
(*pState).demo_ms=1
Monitors_Info=[3000,2000,1000]
Choppers_Info=[[0,50.0],[324.60,150.0],[23.45,50.0],[129.50,50.0],[222.74,50.0]]
;Angles_info=[72.54,72.54,72.54,72.54,72.54,72.54,72.54,72.54,72.54,72.54]
Angles_info=[72.54,55.54,55.54,72.54,32.54,72.54,88.00,72.54,72.54,72.54]
TOFMonitorArray_x=(findgen(1024)*50)+40000.0
TOFMonitorArray_y=fltarr(1024)
TOFMonitorArray_y=sqrt(TOFMonitorArray_x*10)
;TOFMonitorArray_yTotal=long64(total(TOFMonitorArray_y))
TOFMonitorArray_yTotal=2000
TOFMonitorArray_xCal=TOFMonitorArray_x
TOFMonitorArray_yCal=TOFMonitorArray_y
;
PostTOFMonitorArray_x=(findgen(1024)*50)+40000.0
PostTOFMonitorArray_y=fltarr(1024)
PostTOFMonitorArray_y=sqrt(PostTOFMonitorArray_x*10)
;data=read_ascii(!DAVE_AUXILIARY_DIR+'PSI\MARS\MS_diff.txt',count=count)
data=read_ascii(!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MS_diff.txt',count=count)
field=data.field1
x=fltarr(count)
y=fltarr(count)
DiffArray_x=fltarr(12,count)
;print,'(size(DiffArray_x))[2] = ',(size(DiffArray_x))[2]
DiffArray_y=fltarr(12,count)
for i=0,count-1 do begin
x[i]=field[i*2]
y[i]=field[i*2+1]
endfor
for i = 0,11 do begin
DiffArray_x[i,0:n_elements(x)-1]=x
DiffArray_y[i,0:n_elements(y)-1]=y
endfor
;
;
;
MicaArray_x=fltarr(10,200)
for i=0,9 do begin
MicaArray_x[i,*]=(findgen(200)*50)+50000.0
endfor
MicaArray_y=fltarr(10,200)
;data=read_ascii(!DAVE_AUXILIARY_DIR+'PSI\MARS\MS_fake_data.txt',count=count)
data=read_ascii(!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MS_fake_data.txt',count=count)
MicaArray_y[0,*]=data.field1
MicaArray_y[5,*]=data.field1
MicaArray_y[1,*]=data.field1*0.9
MicaArray_y[6,*]=data.field1*0.9
MicaArray_y[2,*]=data.field1*0.8
MicaArray_y[7,*]=data.field1*0.8
MicaArray_y[3,*]=data.field1*0.7
MicaArray_y[8,*]=data.field1*0.7
MicaArray_y[4,*]=data.field1*0.6
MicaArray_y[9,*]=data.field1*0.6

;
TempSample=fltarr(1000)+50.0
TempHeatEX=fltarr(1000)+47.0
TempSet=fltarr(1000)+44.0
dt=300/999.0 ; 5 minutes
TempSample_time=-findgen(1000)*dt
TempHeatEX_time=-findgen(1000)*dt
TempSet_time=-findgen(1000)*dt

(*pState).target_reflection='002'
Sample_Name='Name of Sample'
TOFMonitorArray_xFULL=TOFMonitorArray_x
TOFMonitorArray_yFULL=TOFMonitorArray_y
PostTOFMonitorArray_xFULL=PostTOFMonitorArray_x
PostTOFMonitorArray_yFULL=PostTOFMonitorArray_y
DiffArray_xFULL=DiffArray_x
DiffArray_yFULL=DiffArray_y
MicaArray_xFULL=MicaArray_x
MicaArray_yFULL=MicaArray_y
CounterPreset=10000
UpstreamLastCount_y=0.0
UpstreamLastCount_x=0.0
DownstreamLastCount_y=0.0
DownstreamLastCount_x=0.0
        ENDELSE



;initialise pointers
(*pState).Monitors_Info=Monitors_Info
(*pState).Choppers_Info=Choppers_Info
(*pState).Angles_Info=Angles_Info
;tof data
*(*pState).TOFMonitorArray_xFULL=TOFMonitorArray_xFULL
*(*pState).TOFMonitorArray_yFULL=TOFMonitorArray_yFULL
*(*pState).TOFMonitorArray_xCal=TOFMonitorArray_xCal
*(*pState).TOFMonitorArray_yCal=TOFMonitorArray_yCal
*(*pState).PostTOFMonitorArray_xFULL=PostTOFMonitorArray_xFULL
*(*pState).PostTOFMonitorArray_yFULL=PostTOFMonitorArray_yFULL
*(*pState).DiffArray_xFULL=DiffArray_xFULL
*(*pState).DiffArray_yFULL=DiffArray_yFULL
*(*pState).MicaArray_xFULL=MicaArray_xFULL
*(*pState).MicaArray_yFULL=MicaArray_yFULL
;
*(*pState).TOFMonitorArray_x=TOFMonitorArray_x
*(*pState).TOFMonitorArray_y=TOFMonitorArray_y
*(*pState).PostTOFMonitorArray_x=PostTOFMonitorArray_x
*(*pState).PostTOFMonitorArray_y=PostTOFMonitorArray_y
*(*pState).DiffArray_x=DiffArray_x
*(*pState).DiffArray_y=DiffArray_y
*(*pState).MicaArray_x=MicaArray_x
*(*pState).MicaArray_y=MicaArray_y
;

(*pState).UpstreamLastCount_y=UpstreamLastCount_y
(*pState).UpstreamLastCount_x=UpstreamLastCount_x
(*pState).DownstreamLastCount_y=DownstreamLastCount_y
(*pState).DownstreamLastCount_x=DownstreamLastCount_x
FluxTimeRegister=systime(/seconds);
(*pState).FluxTimeRegister=FluxTimeRegister

;
;
*(*pState).TempSample=TempSample
*(*pState).TempHeatEX=TempHeatEX
*(*pState).TempSet=TempSet
*(*pState).TempSample_time=TempSample_time
*(*pState).TempHeatEX_time=TempHeatEX_time
*(*pState).TempSet_time=TempSet_time

;
TOFMonitorUnits,event
TOFMonitorIntCor,event
MSTOF_Plot,event

PostTOFMonitorUnits,event
PostTOFMonitorIntCor,event
PostMSTOF_Plot,event

MS_dspacing,event
DiffDisplay,event
;
MicaUnits,event
MicaIntCor,event
MSMICA_Plot,event
;
MSTemp_Plot,event

;populate fields
;monitors
widget_control,(*pState).monitor_fields.monitor1,set_value = Monitors_Info[0]
widget_control,(*pState).monitor_fields.monitor2,set_value = Monitors_Info[1]
widget_control,(*pState).monitor_fields.monitor3,set_value = Monitors_Info[2]
;widget_control,(*pState).monitor_fields.monitor2,set_value = long(total(TOFMonitorArray_y))
;widget_control,(*pState).monitor_fields.monitor3,set_value = long(total(PostTOFMonitorArray_y))
;choppers
widget_control,(*pState).chopper_fields.chopper1,set_value = Choppers_Info[0,0]
widget_control,(*pState).chopper_fields.chopper2,set_value = Choppers_Info[0,1]
widget_control,(*pState).chopper_fields.chopper3,set_value = Choppers_Info[0,2]
widget_control,(*pState).chopper_fields.chopper4,set_value = Choppers_Info[0,3]
widget_control,(*pState).chopper_fields.chopper5,set_value = Choppers_Info[0,4]
;diffraction detectors
widget_control,(*pState).diffraction_fields.diff1,set_value = long(total(DiffArray_y[0,*]))
widget_control,(*pState).diffraction_fields.diff2,set_value = long(total(DiffArray_y[1,*]))
widget_control,(*pState).diffraction_fields.diff3,set_value = long(total(DiffArray_y[2,*]))
widget_control,(*pState).diffraction_fields.diff4,set_value = long(total(DiffArray_y[3,*]))
widget_control,(*pState).diffraction_fields.diff5,set_value = long(total(DiffArray_y[4,*]))
widget_control,(*pState).diffraction_fields.diff6,set_value = long(total(DiffArray_y[5,*]))
widget_control,(*pState).diffraction_fields.diff7,set_value = long(total(DiffArray_y[6,*]))
widget_control,(*pState).diffraction_fields.diff8,set_value = long(total(DiffArray_y[7,*]))
widget_control,(*pState).diffraction_fields.diff9,set_value = long(total(DiffArray_y[8,*]))
widget_control,(*pState).diffraction_fields.diff10,set_value = long(total(DiffArray_y[9,*]))
widget_control,(*pState).diffraction_fields.diff11,set_value = long(total(DiffArray_y[10,*]))
widget_control,(*pState).diffraction_fields.diff12,set_value = long(total(DiffArray_y[11,*]))
;Analyser detectors
Mica_Display,event
;Sample Fields
widget_control,(*pState).SampleName,set_value = Sample_Name
;Target Reflection Field
widget_control,(*pState).target_reflection_field,set_value = (*pState).target_reflection
;
n_temp=n_elements(TempSample)
if n_temp ne 0 then begin
current_temperature=string(TempSample[n_temp-1])
widget_control,(*pState).current_temperature,set_value = current_temperature
endif
;
widget_control,(*pState).Status_Field,set_value = Status
;
;
field='1 minute'
widget_control,(*pState).UpdateTime_p_field,set_value = field
;
widget_control,(*pState).SampleStart_p,set_value = StartTimeStr
EstimateEndTime,Start_time,CounterPreset,TOFMonitorArray_yTotal,event
;
WIDGET_CONTROL, event.TOP, TIMER=time
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MonEfficiency,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).Monitor_Efficiency,get_value = mon
TOFMonitorIntCor,event
MSTOF_Plot,event
str=strarr(5)
if mon eq 0 then begin
str[0]='The spectrum displayed'
str[1]='is that of the incoming'
str[2]='neutron flux, i.e. that'
str[3]= 'measured by a black'
str[4]= 'detector.'
endif else begin
str[0]='The raw TOF monitor'
str[1]='spectrum approximates '
str[2]='to the neutron density '
str[3]= 'in the low wavelength '
str[4]= 'limit.'
endelse
widget_control,(*pState).win_diff_text,set_value = str
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro PostMonEfficiency,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).PostMonitor_Efficiency,get_value = mon
PostTOFMonitorIntCor,event
PostMSTOF_Plot,event
str=strarr(5)
if mon eq 0 then begin
str[0]='The spectrum displayed'
str[1]='is that of the incoming'
str[2]='neutron flux, i.e. that'
str[3]= 'measured by a black'
str[4]= 'detector.'
endif else begin
str[0]='The raw TOF monitor'
str[1]='spectrum approximates '
str[2]='to the neutron density '
str[3]= 'in the low wavelength '
str[4]= 'limit.'
endelse
widget_control,(*pState).Postwin_diff_text,set_value = str
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Chopper_Display,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).ChopperDisplay,get_value = chopper
Choppers_Info=(*pState).Choppers_Info
if chopper eq 0 then begin
widget_control,(*pState).chopper_fields.chopper1,set_value = Choppers_Info[0,0]
widget_control,(*pState).chopper_fields.chopper2,set_value = Choppers_Info[0,1]
widget_control,(*pState).chopper_fields.chopper3,set_value = Choppers_Info[0,2]
widget_control,(*pState).chopper_fields.chopper4,set_value = Choppers_Info[0,3]
widget_control,(*pState).chopper_fields.chopper5,set_value = Choppers_Info[0,4]
endif else begin
widget_control,(*pState).chopper_fields.chopper1,set_value = Choppers_Info[1,0]
widget_control,(*pState).chopper_fields.chopper2,set_value = Choppers_Info[1,1]
widget_control,(*pState).chopper_fields.chopper3,set_value = Choppers_Info[1,2]
widget_control,(*pState).chopper_fields.chopper4,set_value = Choppers_Info[1,3]
widget_control,(*pState).chopper_fields.chopper5,set_value = Choppers_Info[1,4]
endelse
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro DiffractionNormalisation,event
widget_control,event.top,get_uvalue = pState
MS_dspacing,event
DiffDisplay,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Mica_Display,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).MicaDisplay,get_value = mica
Angles_Info=(*pState).Angles_Info
MicaArray_y=*(*pState).MicaArray_y
if mica eq 0 then begin
widget_control,(*pState).analyser_fields.mica1,set_value = long(total(MicaArray_y[0,*]))
widget_control,(*pState).analyser_fields.mica2,set_value = long(total(MicaArray_y[1,*]))
widget_control,(*pState).analyser_fields.mica3,set_value = long(total(MicaArray_y[2,*]))
widget_control,(*pState).analyser_fields.mica4,set_value = long(total(MicaArray_y[3,*]))
widget_control,(*pState).analyser_fields.mica5,set_value = long(total(MicaArray_y[4,*]))
widget_control,(*pState).analyser_fields.mica6,set_value = long(total(MicaArray_y[5,*]))
widget_control,(*pState).analyser_fields.mica7,set_value = long(total(MicaArray_y[6,*]))
widget_control,(*pState).analyser_fields.mica8,set_value = long(total(MicaArray_y[7,*]))
widget_control,(*pState).analyser_fields.mica9,set_value = long(total(MicaArray_y[8,*]))
widget_control,(*pState).analyser_fields.mica10,set_value = long(total(MicaArray_y[9,*]))
endif else begin
widget_control,(*pState).analyser_fields.mica1,set_value = Angles_Info[0]
widget_control,(*pState).analyser_fields.mica2,set_value = Angles_Info[1]
widget_control,(*pState).analyser_fields.mica3,set_value = Angles_Info[2]
widget_control,(*pState).analyser_fields.mica4,set_value = Angles_Info[3]
widget_control,(*pState).analyser_fields.mica5,set_value = Angles_Info[4]
widget_control,(*pState).analyser_fields.mica6,set_value = Angles_Info[5]
widget_control,(*pState).analyser_fields.mica7,set_value = Angles_Info[6]
widget_control,(*pState).analyser_fields.mica8,set_value = Angles_Info[7]
widget_control,(*pState).analyser_fields.mica9,set_value = Angles_Info[8]
widget_control,(*pState).analyser_fields.mica10,set_value = Angles_Info[9]
endelse
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mica0select,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 4
widget_control,(*pState).Analyser_Result,set_value = 1
MSMICA_Plot,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mica1select,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 4
widget_control,(*pState).Analyser_Result,set_value = 2
MSMICA_Plot,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mica2select,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 4
widget_control,(*pState).Analyser_Result,set_value = 3
MSMICA_Plot,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mica3select,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 4
widget_control,(*pState).Analyser_Result,set_value = 4
MSMICA_Plot,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mica4select,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 4
widget_control,(*pState).Analyser_Result,set_value = 5
MSMICA_Plot,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mica5select,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 4
widget_control,(*pState).Analyser_Result,set_value = 6
MSMICA_Plot,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mica6select,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 4
widget_control,(*pState).Analyser_Result,set_value = 7
MSMICA_Plot,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mica7select,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 4
widget_control,(*pState).Analyser_Result,set_value = 8
MSMICA_Plot,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mica8select,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 4
widget_control,(*pState).Analyser_Result,set_value = 9
MSMICA_Plot,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mica9select,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 4
widget_control,(*pState).Analyser_Result,set_value = 10
MSMICA_Plot,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro diff11select,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 3
widget_control,(*pState).Diffraction_Result,set_value = 12
DiffDisplay,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro diff10select,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 3
widget_control,(*pState).Diffraction_Result,set_value = 11
DiffDisplay,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro diff9select,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 3
widget_control,(*pState).Diffraction_Result,set_value = 10
DiffDisplay,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro diff8select,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 3
widget_control,(*pState).Diffraction_Result,set_value = 9
DiffDisplay,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro diff7select,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 3
widget_control,(*pState).Diffraction_Result,set_value = 8
DiffDisplay,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro diff6select,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 3
widget_control,(*pState).Diffraction_Result,set_value = 7
DiffDisplay,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro diff5select,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 3
widget_control,(*pState).Diffraction_Result,set_value = 6
DiffDisplay,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro diff4select,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 3
widget_control,(*pState).Diffraction_Result,set_value = 5
DiffDisplay,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro diff3select,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 3
widget_control,(*pState).Diffraction_Result,set_value = 4
DiffDisplay,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro diff2select,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 3
widget_control,(*pState).Diffraction_Result,set_value = 3
DiffDisplay,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro diff1select,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 3
widget_control,(*pState).Diffraction_Result,set_value = 2
DiffDisplay,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro diff0select,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 3
widget_control,(*pState).Diffraction_Result,set_value = 1
DiffDisplay,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro TOFMonselect,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro PostTOFMonselect,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 2
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro EnvironmentSelect,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 5
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro update_time,event
widget_control,event.top,get_uvalue = pState
case event.id of
(*pState).UpdateTime_p: $
begin
widget_control,(*pState).UpdateTime_p,get_value = time
end
else:
endcase
time=long(time[0])
if time eq 1 then field='1 minute'
if time eq 2 then field='5 minutes'
if time eq 3 then field='20 minutes'
if time eq 4 then field='1 hour'
widget_control,(*pState).UpdateTime_p_field,set_value = field
MS_Update,event
WIDGET_CONTROL, event.TOP, TIMER=time
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro WindowSliderTOFMon,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).WindowDefine_slider_TOFMon,get_value = slider
slider=long(slider[0])
sliderstr=strtrim(string(slider),2)+' %'
widget_control,(*pState).WindowDefine_field_TOFMon,set_value = sliderstr
if (*pState).demo_ms eq 1 then return
timebinindices=(*pState).timebinindices
startbin=TimeBinIndices[0]
endbin=TimeBinIndices[1]
TOFMonitorArray_x=*(*pState).TOFMonitorArray_xFULL
TOFMonitorArray_y=*(*pState).TOFMonitorArray_yFULL
timebincull,event,slider,startbin,endbin,TOFMonitorArray_x,TOFMonitorArray_y
;print,'TOFMonitorArray_x',n_elements(TOFMonitorArray_x)
*(*pState).TOFMonitorArray_x=TOFMonitorArray_x
*(*pState).TOFMonitorArray_y=TOFMonitorArray_y
;update fields
TOFMonitorUnits,event
TOFMonitorIntCor,event
MSTOF_Plot,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro WindowSliderPostTOFMon,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).WindowDefine_slider_PostTOFMon,get_value = slider
slider=long(slider[0])
sliderstr=strtrim(string(slider),2)+' %'
widget_control,(*pState).WindowDefine_field_PostTOFMon,set_value = sliderstr
if (*pState).demo_ms eq 1 then return
timebinindices=(*pState).timebinindices
startbin=TimeBinIndices[2]
endbin=TimeBinIndices[3]
PostTOFMonitorArray_x=*(*pState).PostTOFMonitorArray_xFULL
PostTOFMonitorArray_y=*(*pState).PostTOFMonitorArray_yFULL
timebincull,event,slider,startbin,endbin,PostTOFMonitorArray_x,PostTOFMonitorArray_y
*(*pState).PostTOFMonitorArray_x=PostTOFMonitorArray_x
*(*pState).PostTOFMonitorArray_y=PostTOFMonitorArray_y
;update fields
PostTOFMonitorUnits,event
PostTOFMonitorIntCor,event
PostMSTOF_Plot,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro WindowSliderDiffraction,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).WindowDefine_slider_Diffraction,get_value = slider
slider=long(slider[0])
sliderstr=strtrim(string(slider),2)+' %'
widget_control,(*pState).WindowDefine_field_Diffraction,set_value = sliderstr
if (*pState).demo_ms eq 1 then return
timebinindices=(*pState).timebinindices
startbin=TimeBinIndices[4]
endbin=TimeBinIndices[5]
DiffArray_x=*(*pState).DiffArray_xFull
DiffArray_y=*(*pState).DiffArray_yFull
timebincull,event,slider,startbin,endbin,DiffArray_x,DiffArray_y,/MultiArray
*(*pState).DiffArray_x=DiffArray_x
*(*pState).DiffArray_y=DiffArray_y
;update fields
MS_dspacing,event
DiffDisplay,event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro WindowSliderInelastic,event
widget_control,event.top,get_uvalue = pState
widget_control,(*pState).WindowDefine_slider_Inelastic,get_value = slider
slider=long(slider[0])
sliderstr=strtrim(string(slider),2)+' %'
widget_control,(*pState).WindowDefine_field_Inelastic,set_value = sliderstr
if (*pState).demo_ms eq 1 then return
timebinindices=(*pState).timebinindices
target_reflection=(*pState).target_reflection
case target_reflection of
'002':  $
begin
startbin=TimeBinIndices[6]
endbin=TimeBinIndices[7]
end
'002 Assumed':  $
begin
startbin=TimeBinIndices[6]
endbin=TimeBinIndices[7]
end
'004':  $
begin
startbin=TimeBinIndices[8]
endbin=TimeBinIndices[9]
end
'006':  $
begin
startbin=TimeBinIndices[10]
endbin=TimeBinIndices[11]
end
'008':  $
begin
startbin=TimeBinIndices[12]
endbin=TimeBinIndices[13]
end
endcase
MicaArray_x=*(*pState).MicaArray_xFull
MicaArray_y=*(*pState).MicaArray_yFull
timebincull,event,slider,startbin,endbin,MicaArray_x,MicaArray_y,/MultiArray
*(*pState).MicaArray_x=MicaArray_x
*(*pState).MicaArray_y=MicaArray_y
MicaUnits,event
MicaIntCor,event
MSMICA_Plot,event
;
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro FluxCalculator,event
widget_control,event.top,get_uvalue = pState
if (*pState).demo_ms eq 1 then return
;
   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
time=systime()
msg=strarr(2)
msg[0]='Unable to Calculate the Flux at time '+string(time)
msg[1]='error message: '+!ERROR_STATE.MSG+'.'
SICSErrorLog=*(*pState).SICSErrorLog
SICSErrorLog=[SICSErrorLog,msg]
*(*pState).SICSErrorLog=SICSErrorLog
MS_UpdateErrorLog,event
return
endif
;
;
TimeBinIndices=(*pState).TimeBinIndices
constants=(*pState).constants
lTOFMon=constants.lTOFMon
lTOFPostMon=constants.lTOFPostMon
mn=constants.mn
h=constants.h
conv=constants.meVtoJoules
UpstreamMonitorActiveArea=(*pState).UpstreamMonitorActiveArea
DownstreamMonitorActiveArea=(*pState).DownstreamMonitorActiveArea
ub=(*pState).ub
db=(*pState).db
;
;
;widget_control,(*pState).UpdateTime_p,get_value = slider
;slider=long(slider[0])
;if slider eq 1 then time=20.0
;if slider eq 2 then time=60.0
;if slider eq 3 then time=300.0
;if slider eq 4 then time=1200.0
FluxTimeRegister=(*pState).FluxTimeRegister
CurrentTime=systime(/seconds)
time=CurrentTime-FluxTimeRegister
(*pState).FluxTimeRegister=CurrentTime
;print,'time: ',time
;
UpstreamLastCount_y=(*pState).UpstreamLastCount_y
UpstreamLastCount_x=(*pState).UpstreamLastCount_x
DownstreamLastCount_y=(*pState).DownstreamLastCount_y
DownstreamLastCount_x=(*pState).DownstreamLastCount_x
;
;slider=100
slider=50
startbin=TimeBinIndices[0]
endbin=TimeBinIndices[1]
TOFMonitorArray_x=*(*pState).TOFMonitorArray_xFULL
TOFMonitorArray_y=*(*pState).TOFMonitorArray_yFULL
timebincull,event,slider,startbin,endbin,TOFMonitorArray_x,TOFMonitorArray_y
ele=n_elements(TOFMonitorArray_x)
;print, 'TOFMonitorArray_x[0]: ',TOFMonitorArray_x[0]
;print, 'TOFMonitorArray_x[ele-1]: ',TOFMonitorArray_x[ele-1]
MidpointIndex=ele/2
;UpstreamCurrentCount_y=TOFMonitorArray_y[MidpointIndex]
UpstreamCurrentCount_y=total(TOFMonitorArray_y)
UpstreamCurrentCount_x=TOFMonitorArray_x[MidpointIndex]
;
startbin=TimeBinIndices[2]
endbin=TimeBinIndices[3]
PostTOFMonitorArray_x=*(*pState).PostTOFMonitorArray_xFULL
PostTOFMonitorArray_y=*(*pState).PostTOFMonitorArray_yFULL
timebincull,event,slider,startbin,endbin,PostTOFMonitorArray_x,PostTOFMonitorArray_y
;ele=n_elements(PostTOFMonitorArray_x)
;MidpointIndex=ele/2
DownstreamCurrentCount_y=total(PostTOFMonitorArray_y)
;DownstreamCurrentCount_y=PostTOFMonitorArray_y[MidpointIndex]
DownstreamCurrentCount_x=PostTOFMonitorArray_x[MidpointIndex]
;
if float(UpstreamLastCount_x) ne float(UpstreamCurrentCount_x) then begin
time=systime()
msg=strarr(3)
msg[0]='Unable to Calculate the Incoming Flux at Time '+string(time)
msg[1]='Midpoint of Last Time Window = '+strtrim(string(UpstreamLastCount_x),2)
msg[2]='Midpoint of Current Time Window = '+strtrim(string(UpstreamCurrentCount_x),2)
(*pState).UpstreamLastCount_y=UpstreamCurrentCount_y
(*pState).UpstreamLastCount_x=UpstreamCurrentCount_x
(*pState).DownstreamLastCount_y=DownstreamCurrentCount_y
(*pState).DownstreamLastCount_x=DownstreamCurrentCount_x
SICSErrorLog=*(*pState).SICSErrorLog
SICSErrorLog=[SICSErrorLog,msg]
*(*pState).SICSErrorLog=SICSErrorLog
MS_UpdateErrorLog,event
return
endif


LowerTime=TOFMonitorArray_x[0]
v=lTOFMon/(LowerTime/1.0e6)
E_joules=0.5*mn*v^2
E_upper=E_joules/conv
UpperTime=TOFMonitorArray_x[ele-1]
v=lTOFMon/(UpperTime/1.0e6)
E_joules=0.5*mn*v^2
E_lower=E_joules/conv
E_diff=E_upper-E_lower
;
;print,'E_lower: ',E_lower
;print,'E_upper: ',E_upper
;print,'E_diff: ',E_diff
;assume the same for the downstream monitor

UpstreamCountsPerSecond=(UpstreamCurrentCount_y-UpstreamLastCount_y)/(time*E_diff)
DownstreamCountsPerSecond=(DownstreamCurrentCount_y-DownstreamLastCount_y)/(time*E_diff)
;
;print,'UpstreamCountsPerSecond: ',UpstreamCountsPerSecond
;print,'DownstreamCountsPerSecond: ',DownstreamCountsPerSecond

if (UpstreamCountsPerSecond eq 0.0)  or (DownstreamCountsPerSecond eq 0.0) then begin
widget_control,(*pState).monitor2flux,set_value = 0
widget_control,(*pState).monitor3flux,set_value = 0
(*pState).UpstreamLastCount_y=UpstreamCurrentCount_y
(*pState).UpstreamLastCount_x=UpstreamCurrentCount_x
(*pState).DownstreamLastCount_y=DownstreamCurrentCount_y
(*pState).DownstreamLastCount_x=DownstreamCurrentCount_x
return
endif

if (UpstreamCountsPerSecond lt 0.0)  or (DownstreamCountsPerSecond lt 0.0) then begin
;print,'woof'
widget_control,(*pState).monitor2flux,set_value =  ''
widget_control,(*pState).monitor3flux,set_value =  ''
(*pState).UpstreamLastCount_y=UpstreamCurrentCount_y
(*pState).UpstreamLastCount_x=UpstreamCurrentCount_x
(*pState).DownstreamLastCount_y=DownstreamCurrentCount_y
(*pState).DownstreamLastCount_x=DownstreamCurrentCount_x
return
endif


;calculate wavelength
v=lTOFMon/(UpstreamLastCount_x/1.0e6)
Upstream_l=(h*1e10)/(mn*v)
;
;print,'Upstream_l :',Upstream_l
;
v=lTOFPostMon/(DownstreamLastCount_x/1.0e6)
Downstream_l=(h*1e10)/(mn*v)
;calculate efficiencies
;
TOFMon_Efficiency=(1-exp(-ub*Upstream_l))*UpstreamMonitorActiveArea
;print,'TOFMon_Efficiency :',TOFMon_Efficiency
PostTOFMon_Efficiency=(1-exp(-db*Downstream_l))*DownstreamMonitorActiveArea
;
monitor2flux=UpstreamCountsPerSecond/TOFMon_Efficiency
monitor3flux=DownstreamCountsPerSecond/PostTOFMon_Efficiency
;
;monitor2flux/=1e4
monitor2flux=long(monitor2flux)
;monitor2flux*=1e4
;;
;monitor3flux/=1e4
monitor3flux=long(monitor3flux)
;monitor3flux*=1e4
;
widget_control,(*pState).monitor2flux,set_value = strtrim(string(monitor2flux),2)
widget_control,(*pState).monitor3flux,set_value = strtrim(string(monitor3flux),2)
;
(*pState).UpstreamLastCount_y=UpstreamCurrentCount_y
(*pState).UpstreamLastCount_x=UpstreamCurrentCount_x
(*pState).DownstreamLastCount_y=DownstreamCurrentCount_y
(*pState).DownstreamLastCount_x=DownstreamCurrentCount_x
;
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MS_events,event
widget_control,event.top,get_uvalue = pState
uname=widget_info(event.id,/uname)
  IF (TAG_NAMES(event, /STRUCTURE_NAME) EQ 'WIDGET_TIMER') THEN BEGIN
       CASE (*pState).SICSERROR OF
       0:   $
       begin  ; no error
       widget_control,(*pState).UpdateTime_p,get_value = slider
       slider=long(slider[0])
       if slider eq 1 then time = 60
       if slider eq 2 then time = 300
       if slider eq 3 then time = 1200
       if slider eq 4 then time = 3600
;
       time=float(time[0])
       MS_Update,event
       IF (*pState).SICSERROR eq 0 then begin
       WIDGET_CONTROL, event.TOP, TIMER=time
       ENDIF ELSE BEGIN
       WIDGET_CONTROL, event.TOP, TIMER=0.1   ;let's get the error message displayed quickly
       ENDELSE
       end
       1:   $
       begin  ; connection to SICS lost
        SICSERROR=ReestablishSICSConnection(event)
       (*pState).SICSERROR=SICSERROR
       if SICSERROR eq 0 then print,'Connection Re-established'
       WIDGET_CONTROL, event.TOP, TIMER=10.0 ;try to reconnect every 10 seconds
       end
        2:   $
       begin  ; 'Non-fatal error.  The SICS command SicsMarsUpdate has failed'
        SICSERROR=TryOnceAgain(event)
       (*pState).SICSERROR=SICSERROR
       if SICSERROR eq 0 then begin
       print,'Data successfully Acquired'
       MSTempupdate,event
       endif
       WIDGET_CONTROL, event.TOP, TIMER=10.0 ;try again every 10 seconds
       end
        3:   $
       begin  ; 'The information acquired from sics upon issuing the command is not what was hoped for'
       time=systime()
       msg=strarr(3)
       msg[0]='An error was encountered at '+string(time)+' from which the program cannot recover.'
       msg[1]='The SICS command ''marsupdateinfo'' failed to provide the expected information.'
       msg[2]='Error Message: '+!ERROR_STATE.MSG
       daveDeSensitizeButtons,event
       widget_control,(*pState).opt_tab,SET_TAB_CURRENT = 6
       FatalError,event,msg
       return
       end
       else:
       ENDCASE
ENDIF
;
  case uname of
'ChopperDisplay':    $
begin
Chopper_Display,event
end
'MicaDisplay':    $
begin
Mica_Display,event
end
'TOFDisplay':    $
begin
MSTOF_plot,event
end
'PostTOFDisplay':    $
begin
PostMSTOF_plot,event
end
'MonitorEfficiency':    $
begin
MonEfficiency,event
end
'PostMonitorEfficiency':    $
begin
PostMonEfficiency,event
end
'Diffraction_Normalisation':    $
begin
DiffractionNormalisation,event
end
'DiffractionResult':    $
begin
DiffDisplay,event
end
'Analyser_Result':    $
begin
MSMICA_Plot,event
end
'AnalyserDisplay':    $
begin
MSMICA_Plot,event
end
'Environment_Result':    $
begin
MSTempupdate,event
if (*pState).SICSERROR eq 1 then begin
WIDGET_CONTROL, event.TOP, TIMER=0.1 ; hurry along the error message
endif
end
'Update_Time':    $
begin
update_time,event
end
'WindowSlider_TOFMon':    $
begin
WindowSliderTOFMon,event
end
'WindowSlider_PostTOFMon':    $
begin
WindowSliderPostTOFMon,event
end
'WindowSlider_Diffraction':    $
begin
WindowSliderDiffraction,event
end
'WindowSlider_Inelastic':    $
begin
WindowSliderInelastic,event
end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MarsStatus, group_leader = group_leader,notify_ids = notify_ids,  $
        register_name = register_name,workDir = workDir
device, get_decomposed = old_dc
    device,decomposed = 1
tvlct,rorig,gorig,borig,/get
colors = hfbs_GetColor(/Load, Start=1)

;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 = 'Mars_Status'
if xregistered(register_name) then return
if n_elements(workDir) eq 0 then begin
workDir='C:\Documents and Settings\tregenna\My Documents\temp\dave\Working Data Directory\'
endif
delim=path_Sep()
;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
UpstreamMonitorSensitivity=float(constants.UpstreamMonitorSensitivity)
MonitorPressure=(UpstreamMonitorSensitivity/1.0e-2)*0.053 ;bars
ub=MonitorPressure*0.294 ;0.294 is the c value in Haffa's formulation
;print,'ub: ',ub*1.8
;
DownstreamMonitorSensitivity=float(constants.DownstreamMonitorSensitivity)
MonitorPressure=(DownstreamMonitorSensitivity/1.0e-2)*0.053 ;bars
db=MonitorPressure*0.294 ;0.294 is the c value in Haffa's formulation
;
UpstreamMonitorActiveArea=float(constants.UpstreamMonitorActiveArea)
DownstreamMonitorActiveArea=float(constants.DownstreamMonitorActiveArea)
;
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
;print,timeoffsets
;help,timeoffsets,/struc
;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

tlb = widget_base(/col,group_leader = group_leader,title = 'MARS Status',mbar=mbar)
opt_tab=widget_tab(tlb)
overview_base=widget_base(opt_tab,title='Instrument Overview')
PreTOFMonitor_base=widget_base(opt_tab,/row,title='Pre-Sample TOF Monitor')
PostTOFMonitor_base=widget_base(opt_tab,/row,title='Post-Sample TOF Monitor')
diffraction_base=widget_base(opt_tab,/row,title='Diffraction Detectors')
inelastic_base=widget_base(opt_tab,/row,title='Inelastic Detectors')
environment_base=widget_base(opt_tab,/row,title='Sample Environment')
SicsErrorLog_base=widget_base(opt_tab,title='SICS Error Log')
;    read_jpeg,!DAVE_AUXILIARY_DIR+'PSI\MARS\MARS_Status.jpg',image
    read_jpeg,!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MARS_Status.jpg',image
;result=query_jpeg(!DAVE_AUXILIARY_DIR+'PSI\MARS\MARS_Status.jpg',info)
result=query_jpeg(!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MARS_Status.jpg',info)
;      print,'new info.channels',info.channels
;    print,'new info.dimensions',info.dimensions
;   print,'new info.has_palette',info.has_palette

aspect = 1.0*info.dimensions[1]/info.dimensions[0]   ; find the aspect ratio of the image...
    win_pxsize = 1000  &  win_pysize = fix(aspect*win_pxsize)
 ;   winxsize = sx  &  winysize = sy

ombase1 = widget_base(overview_base,xoffset=143,yoffset=315,/frame)
ombase2 = widget_base(overview_base,xoffset=460,yoffset=280,/frame,/col)
ombase3 = widget_base(overview_base,xoffset=793,yoffset=280,/frame,/col)
odbase1 = widget_base(overview_base,xoffset=335,yoffset=250,/frame)
odbase1b = widget_base(overview_base,xoffset=410,yoffset=266)
odbase2 = widget_base(overview_base,xoffset=405,yoffset=110,/frame)
odbase2b = widget_base(overview_base,xoffset=470,yoffset=157)
odbase3 = widget_base(overview_base,xoffset=540,yoffset=35,/frame)
odbase3b = widget_base(overview_base,xoffset=577,yoffset=97)
odbase4 = widget_base(overview_base,xoffset=713,yoffset=35,/frame)
odbase4b = widget_base(overview_base,xoffset=704,yoffset=96)
odbase5 = widget_base(overview_base,xoffset=860,yoffset=110,/frame)
odbase5b = widget_base(overview_base,xoffset=812,yoffset=154)
odbase6 = widget_base(overview_base,xoffset=925,yoffset=250,/frame)
odbase6b = widget_base(overview_base,xoffset=880,yoffset=266)
odbase7 = widget_base(overview_base,xoffset=925,yoffset=385,/frame)
odbase7b = widget_base(overview_base,xoffset=880,yoffset=392)
odbase8 = widget_base(overview_base,xoffset=860,yoffset=530,/frame)
odbase8b = widget_base(overview_base,xoffset=817,yoffset=500)
odbase9 = widget_base(overview_base,xoffset=713,yoffset=600,/frame)
odbase9b = widget_base(overview_base,xoffset=702,yoffset=560)
odbase10 = widget_base(overview_base,xoffset=550,yoffset=600,/frame)
odbase10b = widget_base(overview_base,xoffset=584,yoffset=560)
odbase11 = widget_base(overview_base,xoffset=405,yoffset=530,/frame)
odbase11b = widget_base(overview_base,xoffset=471,yoffset=496)
odbase12 = widget_base(overview_base,xoffset=335,yoffset=385,/frame)
odbase12b = widget_base(overview_base,xoffset=410,yoffset=388)
ocbase1 = widget_base(overview_base,xoffset=20,yoffset=315,/frame)
ocbase2 = widget_base(overview_base,xoffset=85,yoffset=315,/frame)
ocbase3 = widget_base(overview_base,xoffset=245,yoffset=315,/frame)
ocbase4 = widget_base(overview_base,xoffset=302,yoffset=315,/frame)
ocbase5 = widget_base(overview_base,xoffset=355,yoffset=315,/frame)
oabase1 = widget_base(overview_base,xoffset=335,yoffset=170,/frame)
oabase1b = widget_base(overview_base,xoffset=409,yoffset=195)
oabase2 = widget_base(overview_base,xoffset=450,yoffset=50,/frame)
oabase2b = widget_base(overview_base,xoffset=508,yoffset=98)
oabase3 = widget_base(overview_base,xoffset=625,yoffset=5,/frame)
oabase3b = widget_base(overview_base,xoffset=640,yoffset=60)
oabase4 = widget_base(overview_base,xoffset=810,yoffset=50,/frame)
oabase4b = widget_base(overview_base,xoffset=774,yoffset=98)
oabase5 = widget_base(overview_base,xoffset=920,yoffset=170,/frame)
oabase5b = widget_base(overview_base,xoffset=878,yoffset=191)
oabase6 = widget_base(overview_base,xoffset=920,yoffset=460,/frame)
oabase6b = widget_base(overview_base,xoffset=872,yoffset=458)
oabase7 = widget_base(overview_base,xoffset=810,yoffset=590,/frame)
oabase7b = widget_base(overview_base,xoffset=772,yoffset=560)
oabase8 = widget_base(overview_base,xoffset=625,yoffset=630,/frame)
oabase8b = widget_base(overview_base,xoffset=640,yoffset=597)
oabase9 = widget_base(overview_base,xoffset=450,yoffset=590,/frame)
oabase9b = widget_base(overview_base,xoffset=511,yoffset=557)
oabase10 = widget_base(overview_base,xoffset=335,yoffset=460,/frame)
oabase10b = widget_base(overview_base,xoffset=406,yoffset=458)
obbase1 = widget_base(overview_base,xoffset=15,yoffset=7,/frame,/col)
obbase2 = widget_base(overview_base,xoffset=210,yoffset=7,/frame,/col)
obbase3 = widget_base(overview_base,xoffset=15,yoffset=500,/frame,/col)
obbase4 = widget_base(overview_base,xoffset=15,yoffset=635,/frame,/col)
obbase5 = widget_base(overview_base,xoffset=585,yoffset=275,/frame,/col)
obbase6 = widget_base(overview_base,xoffset=20,yoffset=195,/frame,/col)
obbase7 = widget_base(overview_base,xoffset=15,yoffset=584,/frame,/col)





monitor1=cw_field(ombase1,xsize=8,/col,title='Monitor',/noedit)
monitor2=cw_field(ombase2,xsize=8,/col,title='TOF Monitor',/noedit)
monitor2flux=cw_field(ombase2,xsize=8,/col,title='Flux',/noedit)
void = widget_button(ombase2,value = 'TOF',event_pro ='TOFMonselect', $
       tooltip='Display TOF Spectrum')
monitor3=cw_field(ombase3,xsize=8,/col,title='TOF Monitor',/noedit)
monitor3flux=cw_field(ombase3,xsize=8,/col,title='Flux',/noedit)
void = widget_button(ombase3,value = 'TOF',event_pro ='PostTOFMonselect', $
       tooltip='Display TOF Spectrum')


diff1=cw_field(odbase1,xsize=8,/col,title='Diff. 165',/noedit)
void = widget_button(odbase1b,value = 'TOF',event_pro ='diff0select', $
       tooltip='Display TOF Spectrum')
diff2=cw_field(odbase2,xsize=8,/col,title='Diff. 135',/noedit)
void = widget_button(odbase2b,value = 'TOF',event_pro ='diff1select', $
       tooltip='Display TOF Spectrum')
diff3=cw_field(odbase3,xsize=8,/col,title='Diff. 105',/noedit)
void = widget_button(odbase3b,value = 'TOF',event_pro ='diff2select', $
       tooltip='Display TOF Spectrum')
diff4=cw_field(odbase4,xsize=8,/col,title='Diff. 75',/noedit)
void = widget_button(odbase4b,value = 'TOF',event_pro ='diff3select', $
       tooltip='Display TOF Spectrum')
diff5=cw_field(odbase5,xsize=8,/col,title='Diff. 45',/noedit)
void = widget_button(odbase5b,value = 'TOF',event_pro ='diff4select', $
       tooltip='Display TOF Spectrum')
diff6=cw_field(odbase6,xsize=8,/col,title='Diff. 15',/noedit)
void = widget_button(odbase6b,value = 'TOF',event_pro ='diff5select', $
       tooltip='Display TOF Spectrum')
diff7=cw_field(odbase7,xsize=8,/col,title='Diff. 15',/noedit)
void = widget_button(odbase7b,value = 'TOF',event_pro ='diff6select', $
       tooltip='Display TOF Spectrum')
diff8=cw_field(odbase8,xsize=8,/col,title='Diff. 45',/noedit)
void = widget_button(odbase8b,value = 'TOF',event_pro ='diff7select', $
       tooltip='Display TOF Spectrum')
diff9=cw_field(odbase9,xsize=8,/col,title='Diff. 75',/noedit)
void = widget_button(odbase9b,value = 'TOF',event_pro ='diff8select', $
       tooltip='Display TOF Spectrum')
diff10=cw_field(odbase10,xsize=8,/col,title='Diff. 105',/noedit)
void = widget_button(odbase10b,value = 'TOF',event_pro ='diff9select', $
       tooltip='Display TOF Spectrum')
diff11=cw_field(odbase11,xsize=8,/col,title='Diff. 135',/noedit)
void = widget_button(odbase11b,value = 'TOF',event_pro ='diff10select', $
       tooltip='Display TOF Spectrum')
diff12=cw_field(odbase12,xsize=8,/col,title='Diff. 165',/noedit)
void = widget_button(odbase12b,value = 'TOF',event_pro ='diff11select', $
       tooltip='Display TOF Spectrum')
chopper1=cw_field(ocbase1,xsize=5,/col,title='Snail',/noedit)
chopper2=cw_field(ocbase2,xsize=5,/col,title='Master',/noedit)
chopper3=cw_field(ocbase3,xsize=5,/col,title='Rabbit',/noedit)
chopper4=cw_field(ocbase4,xsize=5,/col,title='Chop.4',/noedit)
chopper5=cw_field(ocbase5,xsize=5,/col,title='Chop.5',/noedit)
mica1=cw_field(oabase1,xsize=8,/col,title='MICA 150',/noedit)
void = widget_button(oabase1b,value = 'TOF',event_pro ='mica0select', $
       tooltip='Display TOF Spectrum')
mica2=cw_field(oabase2,xsize=8,/col,title='MICA 120',/noedit)
void = widget_button(oabase2b,value = 'TOF',event_pro ='mica1select', $
       tooltip='Display TOF Spectrum')
mica3=cw_field(oabase3,xsize=8,/col,title='MICA 90',/noedit)
void = widget_button(oabase3b,value = 'TOF',event_pro ='mica2select', $
       tooltip='Display TOF Spectrum')
mica4=cw_field(oabase4,xsize=8,/col,title='MICA 60',/noedit)
void = widget_button(oabase4b,value = 'TOF',event_pro ='mica3select', $
       tooltip='Display TOF Spectrum')
mica5=cw_field(oabase5,xsize=8,/col,title='MICA 30',/noedit)
void = widget_button(oabase5b,value = 'TOF',event_pro ='mica4select', $
       tooltip='Display TOF Spectrum')
mica6=cw_field(oabase6,xsize=8,/col,title='MICA 30',/noedit)
void = widget_button(oabase6b,value = 'TOF',event_pro ='mica5select', $
       tooltip='Display TOF Spectrum')
mica7=cw_field(oabase7,xsize=8,/col,title='MICA 60',/noedit)
void = widget_button(oabase7b,value = 'TOF',event_pro ='mica6select', $
       tooltip='Display TOF Spectrum')
mica8=cw_field(oabase8,xsize=8,/col,title='MICA 90',/noedit)
void = widget_button(oabase8b,value = 'TOF',event_pro ='mica7select', $
       tooltip='Display TOF Spectrum')
mica9=cw_field(oabase9,xsize=8,/col,title='MICA 120',/noedit)
void = widget_button(oabase9b,value = 'TOF',event_pro ='mica8select', $
       tooltip='Display TOF Spectrum')
mica10=cw_field(oabase10,xsize=8,/col,title='MICA 150',/noedit)
void = widget_button(oabase10b,value = 'TOF',event_pro ='mica9select', $
       tooltip='Display TOF Spectrum')
monitor_fields={monitor1:monitor1,monitor2:monitor2,monitor3:monitor3}
diffraction_fields={diff1:diff1,diff2:diff2,diff3:diff3,diff4:diff4, $
              diff5:diff5,diff6:diff6,diff7:diff7,diff8:diff8, $
              diff9:diff9,diff10:diff10,diff11:diff11,diff12:diff12}
chopper_fields={chopper1:chopper1,chopper2:chopper2, $
          chopper3:chopper3,chopper4:chopper4,chopper5:chopper5}
Analyser_fields={mica1:mica1,mica2:mica2,mica3:mica3,mica4:mica4,mica5:mica5, $
          mica6:mica6,mica7:mica7,mica8:mica8,mica9:mica9,mica10:mica10}
MicaDisplay_Field=['Accumulated Counts','Scattering Angle']
MicaDisplay = cw_bgroup(obbase1,MicaDisplay_Field,/exclusive,label_top='Analyser Detector Display', $
           set_value = 0,/return_index,/no_release,/frame,uname='MicaDisplay')
ChopperDisplay_Field=['Phase / Deg.','Angular Frequeuncy / Hz']
ChopperDisplay = cw_bgroup(obbase1,ChopperDisplay_Field,/exclusive,label_top='Chopper Display', $
           set_value = 0,/return_index,/no_release,/frame,uname='ChopperDisplay')
;obbase2a = widget_base(obbase2,/row)
UpdateTime_p=widget_slider(obbase2,$
              value=1,min=1,max=4,xsize=70,uname='Update_Time',/suppress_value, $
              event_pro='MS_events')

UpdateTime_p_field=cw_field(obbase2,xsize=21,/col,title='Update Every:',value='',/noedit)

SampleStart_p=cw_field(obbase2,xsize=21,/col,title='Start Time of Run',value='',/noedit)
SampleEnd_p=cw_field(obbase2,xsize=21,/col,title='Estimated End Time',value='',/noedit)
Initialise = widget_button(obbase3,value = 'Initialise', xsize=80, $
       event_pro ='MS_Initialise',tooltip='Start the Program')
void = widget_button(obbase4,value = 'Exit', xsize=80,event_pro ='MS_exit')

;void=widget_label(obbase5,value='Sample',/align_center)
SampleName=cw_field(obbase5,xsize=20,/col,title='Sample',value='',/noedit)
Current_Temperature=cw_field(obbase5,xsize=20,/col,title='Temperature',value='',/noedit)
void = widget_button(obbase5,value = 'Environment',event_pro ='EnvironmentSelect', $
       tooltip='Display Records of the Sample Environment')

Target_Reflection_Field=cw_field(obbase6,xsize=13,/col,title='Target Reflection',value='',/noedit)


Status_Field=cw_field(obbase7,xsize=30,/row,title='',value='',/noedit)




 win_p = widget_draw(overview_base,xsize = win_pxsize,ysize = win_pysize)
;    dispimage = congrid(image,3,winxsize,winysize)
    dispimage = image
;
;PreTOFMonitor_base
;
TOFbaseL = widget_base(PreTOFMonitor_base,/col,/frame)
TOFbaseL1 = widget_base(TOFbaseL,/col)
TOFbaseL2 = widget_base(TOFbaseL,/col,/align_center)
TOFbaseL3 = widget_base(TOFbaseL,/col,/align_center,frame=2)

WindowDefine_slider_TOFMon=widget_slider(TOFbaseL1,$
              value=100,min=50,max=150,xsize=70,uname='WindowSlider_TOFMon',/suppress_value, $
              event_pro='MS_events')

WindowDefine_field_TOFMon=cw_field(TOFbaseL1,xsize=21,/col,title='Time Bin Window',value='100 %',/noedit)


TOFDisplay_Field=['Energy / meV','Wavelength / A','Time-of-Flight / us']
TOFDisplay = cw_bgroup(TOFbaseL2,TOFDisplay_Field,/exclusive,label_top='Units', $
           set_value = 0,/return_index,/no_release,/frame,uname='TOFDisplay' )

Monitor_Efficiency_Field=['On','Off']
Monitor_Efficiency = cw_bgroup(TOFbaseL2,Monitor_Efficiency_Field,/exclusive, $
         label_top='Monitor Efficiency Cor.', $
           set_value = 0,/return_index,/no_release,/frame,/row,uname='MonitorEfficiency' )

win_diff_text=widget_text(TOFbaseL3,value=strarr(5),ysize=5)


void = widget_button(TOFbaseL,value = 'Exit', xsize=80,event_pro ='MS_exit')

 win_tof = widget_draw(PreTOFMonitor_base,xsize = 845,ysize = 670,/button_events, $
      event_pro = 'MSTOFdraw')


;PostTOFMonitor_base
;
PostTOFbaseL = widget_base(PostTOFMonitor_base,/col,/frame)
PostTOFbaseL1 = widget_base(PostTOFbaseL,/col)
PostTOFbaseL2 = widget_base(PostTOFbaseL,/col,/align_center)
PostTOFbaseL3 = widget_base(PostTOFbaseL,/col,/align_center,frame=2)

WindowDefine_slider_PostTOFMon=widget_slider(PostTOFbaseL1,$
              value=100,min=50,max=150,xsize=70,uname='WindowSlider_PostTOFMon',/suppress_value, $
              event_pro='MS_events')

WindowDefine_field_PostTOFMon=cw_field(PostTOFbaseL1,xsize=21,/col,title='Time Bin Window',value='100 %',/noedit)



PostTOFDisplay_Field=['Energy / meV','Wavelength / A','Time-of-Flight / us']
PostTOFDisplay = cw_bgroup(PostTOFbaseL2,PostTOFDisplay_Field,/exclusive,label_top='Units', $
           set_value = 0,/return_index,/no_release,/frame,uname='PostTOFDisplay' )

PostMonitor_Efficiency_Field=['On','Off']
PostMonitor_Efficiency = cw_bgroup(PostTOFbaseL2,PostMonitor_Efficiency_Field,/exclusive, $
         label_top='Monitor Efficiency Cor.', $
           set_value = 0,/return_index,/no_release,/frame,/row,uname='PostMonitorEfficiency' )

Postwin_diff_text=widget_text(PostTOFbaseL3,value=strarr(5),ysize=5)


void = widget_button(PostTOFbaseL,value = 'Exit', xsize=80,event_pro ='MS_exit')

 win_posttof = widget_draw(postTOFMonitor_base,xsize = 845,ysize = 670,/button_events, $
      event_pro = 'PostMSTOFdraw')


;Diffraction_base
DiffractionbaseL = widget_base(Diffraction_base,/col,/frame)
DiffractionbaseL1 = widget_base(DiffractionbaseL,/col)
DiffractionbaseL2 = widget_base(DiffractionbaseL,/col)
DiffractionbaseL3 = widget_base(DiffractionbaseL,/col,/align_center)
DiffractionbaseL4 = widget_base(DiffractionbaseL,/col,/align_center)

WindowDefine_slider_Diffraction=widget_slider(DiffractionbaseL1,$
              value=100,min=50,max=150,xsize=70,uname='WindowSlider_Diffraction',/suppress_value, $
              event_pro='MS_events')

WindowDefine_field_Diffraction=cw_field(DiffractionbaseL1,xsize=21,/col,title='Time Bin Window',value='100 %',/noedit)


Diffraction_Result_Names = ['All','Aare 165 deg.','Aare 135 deg.','Aare 105 deg.','Aare 75 deg.','Aare 45 deg.', $
    'Aare 15 deg.','Berg 15 deg.','Berg 45 deg.','Berg 75 deg.','Berg 105 deg.','Berg 135 deg.', $
    'Berg 165 deg.']

Diffraction_Result = cw_bgroup(DiffractionbaseL3,Diffraction_Result_Names,column=1,/exclusive,label_top = $
'Display',frame = 1,set_value = 0,/no_release, uname='DiffractionResult')

Diffraction_Normalisation_Field=['Yes','No']
Diffraction_Normalisation = cw_bgroup(DiffractionbaseL4,Diffraction_Normalisation_Field,/exclusive, $
         label_top='Normalise to Incident Flux?', $
           set_value = 0,/return_index,/no_release,/frame,/row,uname='Diffraction_Normalisation' )


void = widget_button(DiffractionbaseL,value = 'Exit', xsize=80,event_pro ='MS_exit')

 win_diff = widget_draw(Diffraction_base,xsize = 845,ysize = 670,/button_events, $
      event_pro = 'MSDiffdraw')

;inelastic_base

InelasticbaseL = widget_base(Inelastic_base,/col,/frame)
InelasticbaseL1 = widget_base(InelasticbaseL,/col)
InelasticbaseL2 = widget_base(InelasticbaseL,/col)
InelasticbaseL3 = widget_base(InelasticbaseL,/col,/align_center)
InelasticbaseL4 = widget_base(InelasticbaseL,/col,/align_center,frame=2)

WindowDefine_slider_Inelastic=widget_slider(InelasticbaseL1,$
              value=100,min=50,max=150,xsize=70,uname='WindowSlider_Inelastic',/suppress_value, $
              event_pro='MS_events')

WindowDefine_field_Inelastic=cw_field(InelasticbaseL1,xsize=21,/col,title='Time Bin Window',value='100 %',/noedit)



Analyser_Result_Names = ['All','Aare 150 deg.','Aare 120 deg.','Aare 90 deg.','Aare 60 deg.','Aare 30 deg.', $
                 'Berg 30 deg.','Berg 60 deg.','Berg 90 deg.','Berg 120 deg.','Berg 150 deg.']



Analyser_Result = cw_bgroup(InelasticbaseL3,Analyser_Result_Names,column=1,/exclusive, $
         label_top = 'Display',$
            frame = 1,set_value = 0,/no_release,uname='Analyser_Result')

AnalyserDisplay_Field=['Energy / meV','Wavelength / A','Time-of-Flight / us']
AnalyserDisplay = cw_bgroup(InelasticbaseL3,AnalyserDisplay_Field,/exclusive,label_top='Units', $
           set_value = 0,/return_index,/no_release,/frame,uname='AnalyserDisplay')
;label_top='Units',
win_mica_text=widget_text(InelasticbaseL4,value=strarr(5),ysize=5)

void = widget_button(InelasticbaseL,value = 'Exit', xsize=80,event_pro ='MS_exit')

 win_mica = widget_draw(Inelastic_base,xsize = 845,ysize = 670,/button_events, $
      event_pro = 'MSMicadraw')

;environment_base

EnvironmentbaseL = widget_base(Environment_base,/col,/frame)
EnvironmentbaseL1 = widget_base(EnvironmentbaseL,/col)
EnvironmentbaseL2 = widget_base(EnvironmentbaseL,/col,/align_center)
;EnvironmentbaseL3 = widget_base(EnvironmentbaseL,/col,/align_center)


Environment_Result_Names = ['5 mins.','30 mins.','1 hour','6 hours','12 hours','1 day', $
                 '3 days','7 days']


Environment_Result = cw_bgroup(EnvironmentbaseL2,Environment_Result_Names,column=1,/exclusive, $
         label_top = 'Display Records of last:',$
            frame = 1,set_value = 0,/no_release,uname='Environment_Result')

Cryogenic_Device=cw_field(EnvironmentbaseL,xsize=21,/col,title='Cryogenic Device', $
          value='',/noedit)


void = widget_button(EnvironmentbaseL,value = 'Exit', xsize=80,event_pro ='MS_exit')



 win_temp = widget_draw(Environment_base,xsize = 845,ysize = 670,/button_events, $
      event_pro = 'MSEnvironmentdraw')

win_sics_text=widget_text(SicsErrorLog_base,value=strarr(10000),ysize=50,xsize=160,/scroll)



centertlb,tlb
widget_control,tlb,/realize
widget_control,win_p,get_value = winVis_p
window,/free,/pixmap,xsize = win_pxsize,ysize = win_pysize
winPix_p = !d.window
wset,winPix_p
tvimage,dispImage
wset,winVis_p
device,copy = [0,0,!d.x_size,!d.y_size,0,0,winPix_p]
;
widget_control,win_tof,get_value = winVis_tof
window,/free,/pixmap,xsize = 845,ysize = 670
winPix_tof = !d.window
;
widget_control,win_posttof,get_value = winVis_posttof
window,/free,/pixmap,xsize = 845,ysize = 670
winPix_posttof = !d.window
;
widget_control,win_diff,get_value = winVis_diff
window,/free,/pixmap,xsize = 845,ysize = 670
winPix_diff = !d.window
;
widget_control,win_mica,get_value = winVis_mica
window,/free,/pixmap,xsize = 845,ysize = 670
winPix_mica = !d.window
;
widget_control,win_temp,get_value = winVis_temp
window,/free,/pixmap,xsize = 845,ysize = 670
winPix_temp = !d.window
;
state = { SampleName:SampleName, $
       old_dc:old_dc, $
         autoscale_tof:1, $
         autoscale_posttof:1, $
         autoscale_diff:1, $
         autoscale_mica:1, $
         autoscale_temp:1, $
         mouse:0B, $
         winPix_p:winPix_p, $
         winVis_p:winVis_p, $
         win_p:win_p, $
         winPix_tof:winPix_tof, $
         winVis_tof:winVis_tof, $
         winPix_posttof:winPix_posttof, $
         winVis_posttof:winVis_posttof, $
         win_tof:win_tof, $
         win_posttof:win_posttof, $
         xlo_tof:0.0, $
         xhi_tof:0.0, $
         ylo_tof:0.0, $
         yhi_tof:0.0, $
         xrange_tof:[0.0,0.0], $
         yrange_tof:[0.0,0.0], $
         xbox_tof:[0.0,0.0], $
         ybox_tof:[0.0,0.0], $
         xlo_posttof:0.0, $
         xhi_posttof:0.0, $
         ylo_posttof:0.0, $
         yhi_posttof:0.0, $
         xrange_posttof:[0.0,0.0], $
         yrange_posttof:[0.0,0.0], $
         xbox_posttof:[0.0,0.0], $
         ybox_posttof:[0.0,0.0], $
         winPix_diff:winPix_diff, $
         winVis_diff:winVis_diff, $
         win_diff:win_diff, $
         xlo_diff:0.0, $
         xhi_diff:0.0, $
         ylo_diff:0.0, $
         yhi_diff:0.0, $
         xrange_diff:[0.0,0.0], $
         yrange_diff:[0.0,0.0], $
         xbox_diff:[0.0,0.0], $
         ybox_diff:[0.0,0.0], $
         winPix_mica:winPix_mica, $
         winVis_mica:winVis_mica, $
         win_mica:win_mica, $
         xlo_mica:0.0, $
         xhi_mica:0.0, $
         ylo_mica:0.0, $
         yhi_mica:0.0, $
         xrange_mica:[0.0,0.0], $
         yrange_mica:[0.0,0.0], $
         xbox_mica:[0.0,0.0], $
         ybox_mica:[0.0,0.0], $
         Monitors_Info:intarr(3), $
         Choppers_Info:fltarr(2,5), $
         TOFMonitorArray_x:ptr_new(/allocate_heap), $
         TOFMonitorArray_t:ptr_new(/allocate_heap), $
         TOFMonitorArray_e:ptr_new(/allocate_heap), $
         TOFMonitorArray_l:ptr_new(/allocate_heap), $
         TOFMonitorArray_y:ptr_new(/allocate_heap), $
         TOFMonitorArray_t_y:ptr_new(/allocate_heap), $
         TOFMonitorArray_e_y:ptr_new(/allocate_heap), $
         TOFMonitorArray_l_y:ptr_new(/allocate_heap), $
         PostTOFMonitorArray_x:ptr_new(/allocate_heap), $
         PostTOFMonitorArray_t:ptr_new(/allocate_heap), $
         PostTOFMonitorArray_e:ptr_new(/allocate_heap), $
         PostTOFMonitorArray_l:ptr_new(/allocate_heap), $
         PostTOFMonitorArray_y:ptr_new(/allocate_heap), $
         PostTOFMonitorArray_t_y:ptr_new(/allocate_heap), $
         PostTOFMonitorArray_e_y:ptr_new(/allocate_heap), $
         PostTOFMonitorArray_l_y:ptr_new(/allocate_heap), $
         DiffArray_x:ptr_new(/allocate_heap), $
         DiffArray_d:ptr_new(/allocate_heap), $
         DiffArray_y:ptr_new(/allocate_heap), $
         DiffArray_t_y:ptr_new(/allocate_heap), $
         MicaArray_x:ptr_new(/allocate_heap), $
         MicaArray_y:ptr_new(/allocate_heap), $
         MicaArray_t:ptr_new(/allocate_heap), $
         MicaArray_e:ptr_new(/allocate_heap), $
         MicaArray_l:ptr_new(/allocate_heap), $
         MicaArray_t_y:ptr_new(/allocate_heap), $
         MicaArray_e_y:ptr_new(/allocate_heap), $
         MicaArray_l_y:ptr_new(/allocate_heap), $
         winPix_temp:winPix_temp, $
         winVis_temp:winVis_temp, $
         win_temp:win_temp, $
         TempSample:ptr_new(/allocate_heap), $
         TempHeatEX:ptr_new(/allocate_heap), $
         TempSet:ptr_new(/allocate_heap), $
         TempSample_time:ptr_new(/allocate_heap), $
         TempHeatEX_time:ptr_new(/allocate_heap), $
         TempSet_time:ptr_new(/allocate_heap), $
         xlo_temp:0.0, $
         xhi_temp:0.0, $
         ylo_temp:0.0, $
         yhi_temp:0.0, $
         xrange_temp:[0.0,0.0], $
         yrange_temp:[0.0,0.0], $
         xbox_temp:[0.0,0.0], $
         ybox_temp:[0.0,0.0], $
         seed:ptr_new(/allocate_heap), $
         UpdateTime_p:UpdateTime_p, $
         UpdateTime_p_field:UpdateTime_p_field, $
         constants:constants, $
         monitor_fields:monitor_fields, $
         diffraction_fields:diffraction_fields, $
         chopper_fields:chopper_fields, $
         Analyser_fields:Analyser_fields, $
         ChopperDisplay:ChopperDisplay, $
         MicaDisplay:MicaDisplay, $
         Angles_Info:fltarr(10), $
         TOFDisplay:TOFDisplay, $
         PostTOFDisplay:PostTOFDisplay, $
         colors:colors, $
         pix:0, $
         Monitor_Efficiency:Monitor_Efficiency, $
         PostMonitor_Efficiency:PostMonitor_Efficiency, $
         win_diff_text:win_diff_text, $
         postwin_diff_text:postwin_diff_text, $
         Diffraction_Result:Diffraction_Result, $
         Diffraction_Normalisation:Diffraction_Normalisation, $
         AnalyserDisplay:AnalyserDisplay, $
         Analyser_Result:Analyser_Result, $
         win_mica_text:win_mica_text, $
         demo_ms:1, $
         time_units:0, $
         opt_tab:opt_tab, $
         Environment_Result:Environment_Result, $
         unit:0, $
         tunit:0, $
         target_reflection:' ', $
         timebin:ptr_new(/allocate_heap), $
         SampleStart_p:SampleStart_p, $
         SampleEnd_p:SampleEnd_p, $
         Target_Reflection_Field:Target_Reflection_Field, $
         reconnect_widget_id:-1, $
         TemperatureReadError_widget_id:-1, $
         SICSERROR:0, $
         SICSTempERROR:0, $
         PasswordFields:ptr_new(/allocate_heap), $
         SICSErrorLog:ptr_new(/allocate_heap), $
         Device_Names_str:ptr_new(/allocate_heap), $
         win_sics_text:win_sics_text, $
         koennecke_pic:koennecke_pic, $
         Current_Temperature:Current_Temperature, $
         Cryogenic_Device:Cryogenic_Device, $
         delim:delim, $
         WindowDefine_slider_TOFMon:WindowDefine_slider_TOFMon, $
         WindowDefine_field_TOFMon:WindowDefine_field_TOFMon, $
         WindowDefine_slider_PostTOFMon:WindowDefine_slider_PostTOFMon, $
         WindowDefine_field_PostTOFMon:WindowDefine_field_PostTOFMon, $
         WindowDefine_slider_Diffraction:WindowDefine_slider_Diffraction, $
         WindowDefine_field_Diffraction:WindowDefine_field_Diffraction, $
         WindowDefine_slider_Inelastic:WindowDefine_slider_Inelastic, $
         WindowDefine_field_Inelastic:WindowDefine_field_Inelastic, $
         TimeBinIndices:intarr(14)-1, $
         TOFMonitorArray_xFULL:ptr_new(/allocate_heap), $
         TOFMonitorArray_yFULL:ptr_new(/allocate_heap), $
         TOFMonitorArray_xCal:ptr_new(/allocate_heap), $
         TOFMonitorArray_yCal:ptr_new(/allocate_heap), $
         PostTOFMonitorArray_xFULL:ptr_new(/allocate_heap), $
         PostTOFMonitorArray_yFULL:ptr_new(/allocate_heap), $
         DiffArray_xFULL:ptr_new(/allocate_heap), $
         DiffArray_yFULL:ptr_new(/allocate_heap), $
         MicaArray_xFULL:ptr_new(/allocate_heap), $
         MicaArray_yFULL:ptr_new(/allocate_heap), $
         timeoffsets:timeoffsets, $
         Status_Field:Status_Field, $
         ub:ub, $
         db:db, $
         UpstreamMonitorActiveArea:UpstreamMonitorActiveArea, $
         DownstreamMonitorActiveArea:DownstreamMonitorActiveArea, $
         UpstreamLastCount_y:0.0, $
         UpstreamLastCount_x:0.0, $
         DownstreamLastCount_y:0.0, $
         DownstreamLastCount_x:0.0, $
         monitor2flux:monitor2flux, $
         monitor3flux:monitor3flux, $
         FluxTimeRegister:double(0.0), $
         workDir:workDir}



pState = ptr_new(state,/no_copy)
widget_control,tlb,set_uvalue = pState


xmanager,register_name,tlb,event_handler = 'MS_Events'


end