; NAME:
;       MARS_Batch
; DATE of WORKING VERSION: 4 May 2006
;PD Dr. Philip Tregenna-Piggott,
;Laboratory for Neutron Scattering,
;ETHZ and Paul-Scherrer Institute,
;CH-5232 Villigen PSI,
;Switzerland.
;
;Tel. :+41 56 310 54 05
;Fax. :+41 56 310 29 39
;Email:philip.tregenna@psi.ch
;
;
; CATEGORY:
;
;       MARS Tools
;
; CALLING SEQUENCE:
;
;      MARS_Batch
;
;
; 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 MB_cleanup,tlb
widget_control,tlb,get_uvalue = pState_MB
if (*pstate_mb).demo_mb eq 0 then begin
sicsclose,(*pstate_mb).UnitUser
sicsclose,(*pstate_mb).UnitexeUser
sicsclose,(*pstate_mb).UnitSpy
sicsclose,(*pstate_mb).UnitManager
endif
heap_free,pState_MB
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MB_exit,event
widget_control,event.top,/destroy
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Help,event
widget_control,event.top,get_uvalue = pState_MB
delim=(*pState_MB).delim
;pdf_file = !DAVE_AUXILIARY_DIR+'PSI\MARS\MARS_Batch_Help.pdf'
pdf_file = !DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MARS_Batch_Help.pdf'
print,file_test(pdf_file)
print,pdf_file
void = launch_help(pdf_file,tlb = event.top)
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Batch_Read,event
widget_control,event.top,get_uvalue = pState_MB
workDir=(*pState_MB).workDir
Command_Table=(*pState_MB).command_table
listarr=*(*pState_MB).listarr
;
;
    filename=dialog_pickfile(path=workDir,$
      file='MarsBatchfile.bch',/read,filter="*.bch",/fix_filter)
if n_elements(filename) eq 0 then return
if filename eq '' then return
;clear the current table
;
Table_Contents=strarr(2,200)
ForegroundColors=intarr(3,400)
(*pState_MB).Table_Contents=Table_Contents
widget_control, Command_Table,set_value=Table_Contents
(*pState_MB).ForegroundColors=ForegroundColors
widget_control, Command_Table,set_table_select=[0,0,0,0]

command=strarr(200)
line=''
n=0
openr,lun,filename,/get_lun
while eof(lun) eq 0 do begin
readf,lun,line
command[n]=line
n+=1
endwhile
;number of lines = n
free_lun,lun,/force
color=intarr(3,1)
for i=0,n-1 do begin
temp=strsplit(command[i],/extract)
temp[0]=strtrim(temp[0],2)
temp[1]=strtrim(temp[1],2)
temp[0]=strlowcase(temp[0]) ; case errors
if listarr[0] ne 'No List' then begin ;object filter
;print,'listarr = ',listarr
void=where(listarr eq temp[0],count)
    if count eq 0 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'The command '''+temp[0]+''' is not valid')
return
    endif
endif

Table_Contents[0,i]=temp[0]
Table_Contents[1,i]=temp[1]
elements = n_elements(Temp)
if elements ge 3 then begin
for j = 2, elements-1 do begin
Table_Contents[1,i]+=' '+temp[j]
endfor
endif


;if temp[0] ne 'sample' then begin
;Table_Contents[0,i]=temp[0]
;Table_Contents[1,i]=temp[1]
;endif else begin
;Table_Contents[0,i]=temp[0]
;elements=n_elements(Temp)
;Table_Contents[1,i]=temp[1]
;    IF elements ge 3 then begin
;for j = 2, elements-1 do begin
;Table_Contents[1,i]+=' '+temp[j]
;endfor
;    ENDIF
;endelse

Usual_fields=['sample','temperature','count','wait','instrument_file','field']
if temp[0] eq Usual_fields[0] then color=[0,0,255]
if temp[0] eq Usual_fields[1] then color=[255,0,0]
if temp[0] eq Usual_fields[2] then color=[0,255,0]
if temp[0] eq Usual_fields[3] then color=[255,171,127]
if temp[0] eq Usual_fields[4] then color=[255,0,255]
if temp[0] eq Usual_fields[5] then color=[120,150,70]
present=where(temp[0] eq Usual_fields)
if present eq -1 then color=[0,0,0]
ForegroundColors[*,i*2]=color
ForegroundColors[*,i*2+1]=color
endfor
(*pState_MB).Table_Contents=Table_Contents
(*pState_MB).ForegroundColors=ForegroundColors
widget_control, Command_Table,set_value=Table_Contents
widget_control, Command_Table,set_table_select=[0,n,0,n], $
foreground_color=ForegroundColors
widget_control, Command_Table,set_table_view=[0,n-14]
;
;'sample' [0,0,255]
;'temperature' [255,0,0]
;'count' [0,255,0]
;'wait' [255,171,127]
; 'instrument_file' [255,0,255]
; 'field'[120,150,70]
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Batch_Save,event
widget_control,event.top,get_uvalue = pState_MB
Table_Contents=(*pState_MB).Table_Contents
workDir=(*pState_MB).workDir
    filename=dialog_pickfile(path=workDir,$
      file='MarsBatchfile.bch',/write,filter="*.bch",/fix_filter)
;
if n_elements(filename) eq 0 then return
if filename eq '' then return

if strpos(filename,'.bch') eq -1 then filename+='.bch'
;print,filename
;
workdir_length=strlen(workdir)
OutputFile=strmid(filename,workdir_length)
OutputFile=strtrim(OutputFile,2)
OutputFile_length=strlen(OutputFile)
wherepoint=strpos(OutputFile,'.')
if wherepoint ne -1 then begin
;we don't want the last 4 characters
OutputFile=strmid(OutputFile,0,OutputFile_length-4)+'.out'
endif else begin
OutputFile+='.out'
endelse
;print,'OutputFile = ',OutputFile
(*pState_MB).OutputFile=OutputFile
;
total_cells=max(where(Table_Contents ne '',count))
total_rows=(total_cells+1)/2
;rows=count/2
openw,lun,filename,/get_lun
for i=0,total_rows-1 do begin
if Table_Contents[0,i] ne '' then printf,lun, Table_Contents[0,i]+'     '+Table_Contents[1,i]
endfor
free_lun,lun,/force
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Save_Progress_Table,event
widget_control,event.top,get_uvalue = pState_MB
PB_Table_Contents=(*pState_MB).PB_Table_Contents
OutputFile=(*pState_MB).OutputFile
;
total_rows=1+max(where(PB_Table_Contents[0,*] ne '',count))
if count eq 0 then return
print,'total_rows = ',total_rows

if OutputFile ne '' then begin
file=OutputFile
endif else begin
file='MarsBatchfile.out'
endelse

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

wherenull=where(PB_Table_Contents[*,0:total_rows-1] eq '',count)
if count ne 0 then begin
PB_Table_Contents[wherenull]='-'
endif
thisformat='(A-35,1x,A-30,2x,A-15)'
openw,lun,filename,/get_lun
printf,lun, 'Command','Time Executed','File Number',Format=thisformat
printf,lun, ''
for i=0,total_rows-1 do begin
printf,lun, PB_Table_Contents[0,i],PB_Table_Contents[1,i],PB_Table_Contents[2,i],Format=thisformat
endfor
free_lun,lun,/force
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro mb_password_widget_event,event
widget_control,event.top,get_uvalue = pState_MB1
uname=widget_info(event.id,/uname)
case uname of
'pass':    $
begin
        case event.type of
            0: begin            ; Insert Single Character
                (*pState_MB1).password += string(event.ch)
            end
            1: begin            ; Insert Multiple Characters
                (*pState_MB1).password += event.str
            end
            2: begin            ; Delete Text
                (*pState_MB1).password = strmid((*pState_MB1).password,0,event.offset)
            end
            3:                  ; Text Selection
        endcase
        len = strlen((*pState_MB1).password)
        if ((len gt 0) && (event.type ne 3)) then $
          widget_control, event.id, set_value=strjoin(replicate('*',len)), set_text_select=[len,0]
    end
'ok':    $
begin
if (*pState_MB1).password eq 'MARSLNS' then begin
widget_control,event.top,/destroy
endif else begin
widget_control, (*pState_MB1).password_field,set_value=''
(*pState_MB1).password=''
endelse
return
end
'cancel':    $
begin
(*pState_MB1).password=''
widget_control,event.top,/destroy
return
end
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function mb_password_widget,group_leader = group_leader
if n_elements(group_leader) eq 0 then begin
  tlb = widget_base(/col,title = 'Password Protected',/tlb_frame_attr)
endif else begin
    tlb = widget_base(group_leader = group_leader, /col,/modal, $
        title = 'Password Protected',/tlb_frame_attr)
endelse
base = widget_base(tlb,/col,XSIZE=170)
password=''
;password_field= cw_field(base,/row,value = password,title = 'Enter Password',/all_events,uname='pass')
password_field = widget_text(base,uname='pass',value='',/editable,/all_events)

CancelButton = widget_button(base,value = 'Cancel',uname='cancel')
OKButton = widget_button(base,value = 'OK',uname='ok')
centertlb,tlb
widget_control,tlb,/realize

state1 = {CancelButton:CancelButton, $
       password_field:password_field, $
       password:password }
pState_MB1 = ptr_new(state1,/no_copy)
widget_control,tlb,set_uvalue = pState_MB1
xmanager,'mb_password_widget',tlb,event_handler = 'mb_password_widget_event'
password=(*pState_MB1).password
ptr_free,pState_MB1
return,password
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Set_Device,event,DeviceName,limit_array_sics,maxwait,settle,tolerance

   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
    void=dialog_message(dialog_parent=event.top,/error, $
    'Unable to Acquire Information from SICS.  Message: '+!ERROR_STATE.MSG)
return
endif



widget_control,event.top,get_uvalue = pState_MB2
main_event=(*pState_MB2).main_event
widget_control,main_event.top,get_uvalue = pState_MB
if (*pstate_mb).demo_mb ne 0 then begin
void = dialog_message(dialog_parent = event.top,/information, $
'Connect to instrument First')
return
endif
UnitUser=(*pstate_mb).UnitUser
UnitSpy=(*pstate_mb).UnitSpy
tunit=(*pstate_mb).tunit

;temp=strsplit(DeviceName,/extract)
;DeviceName=strtrim(temp[0],2)
;print,DeviceName

temp=strsplit(DeviceName,' ',/extract)
DeviceName=strtrim(temp[0],2)
print,DeviceName
command='samenv '+DeviceName
response=sicsexecute(main_event,UnitUser,command)
print,'response = ',response
print,''

T_lower=sicscommand(main_event,tunit,'temperature lowerlimit',datatype='long')
T_upper=sicscommand(main_event,tunit,'temperature upperlimit',datatype='long')
mf_lower=sicscommand(main_event,tunit,'mf lowerlimit',datatype='long',/no_message)
if mf_lower eq -1 then mf_lower = 0
mf_upper=sicscommand(main_event,tunit,'mf upperlimit',datatype='long',/no_message)
if mf_upper eq -1 then mf_upper = 0
;
limit_array_sics[0,0]=T_lower
limit_array_sics[1,0]=T_upper
limit_array_sics[0,1]=mf_lower
limit_array_sics[1,1]=mf_upper


;
;command='temperature tolerance '+strtrim(string(tolerance),2)
;response=sicsexecute(main_event,UnitUser,command)
;print,'response = ',response
;print,''
;command='temperature maxwait '+strtrim(string(maxwait),2)
;response=sicsexecute(main_event,UnitUser,command)
;print,'response = ',response
;print,''
;command='temperature settle '+strtrim(string(settle),2)
;response=sicsexecute(main_event,UnitUser,command)
;print,'response = ',response
;print,''
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Get_Current_Device,event,DeviceName,limit_array_sics;,maxwait,settle,tolerance

   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
    void=dialog_message(dialog_parent=event.top,/error, $
    'Unable to Get Current Device.  Message: '+!ERROR_STATE.MSG)
return
endif

widget_control,event.top,get_uvalue = pState_MB2
main_event=(*pState_MB2).main_event
widget_control,main_event.top,get_uvalue = pState_MB
if (*pstate_mb).demo_mb ne 0 then begin
void = dialog_message(dialog_parent = event.top,/information, $
'Connect to instrument First')
return
end
UnitUser=(*pstate_mb).UnitUser
UnitSpy=(*pstate_mb).UnitSpy
tunit=(*pstate_mb).tunit




command='samenv -q'
response=sicscommand(main_event,tunit,command,datatype='string')
print,'response = ',response
print,''
DeviceName=(strsplit(response,/extract))[0]
print,'DeviceName = ',DeviceName
print,''




T_lower=sicscommand(main_event,tunit,'temperature lowerlimit',datatype='long')
T_upper=sicscommand(main_event,tunit,'temperature upperlimit',datatype='long')
mf_lower=sicscommand(main_event,tunit,'mf lowerlimit',datatype='long',/no_message)
if mf_lower eq -1 then mf_lower = 0
mf_upper=sicscommand(main_event,tunit,'mf upperlimit',datatype='long',/no_message)
if mf_upper eq -1 then mf_upper = 0
;
limit_array_sics[0,0]=T_lower
limit_array_sics[1,0]=T_upper
limit_array_sics[0,1]=mf_lower
limit_array_sics[1,1]=mf_upper

;
;maxwait=sicscommand(main_event,UnitSpy,'temperature maxwait',datatype='long')
;settle=sicscommand(main_event,UnitSpy,'temperature settle',datatype='long')
;tolerance=sicscommand(main_event,UnitSpy,'temperature tolerance',datatype='long')



end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro limit_table_event,event
uname=widget_info(event.id,/uname)
widget_control,event.top,get_uvalue = pState_MB2
main_event=(*pState_MB2).main_event
widget_control,main_event.top,get_uvalue = pState_MB
delim=(*pState_MB).delim
;widget_control, (*pState_MB2).maxwait_field,get_value=maxwait
;maxwait=long(maxwait[0])
;widget_control, (*pState_MB2).settle_field,get_value=settle
;settle=long(settle[0])
;widget_control, (*pState_MB2).tolerance_field,get_value=tolerance
;tolerance=long(tolerance[0])
main_event=(*pState_MB2).main_event
widget_control,main_event.top,get_uvalue = pState_MB
limit_structure=(*pState_MB).limit_structure
widget_control,(*pState_MB2).Table_Limit_sics,get_value=limit_array_sics
widget_control,(*pState_MB2).Table_Limit_user,get_value=limit_array_user
index=widget_info((*pState_MB2).Device_Names_Droplist,/droplist_select)
Device_Names_str=(*pState_MB2).Device_Names_str
Device_Names_str_short=(*pState_MB2).Device_Names_str_short
DeviceName=Device_Names_str[index]


case uname of
'Get_Current_Device':    $
begin
Get_Current_Device,event,DeviceName,limit_array_sics;,maxwait,settle,tolerance
DeviceName=strtrim(DeviceName,2)
wheredevice=where(Device_Names_str_short eq DeviceName,count)
wheredevice=wheredevice[0]
;wheredevice=where(strpos(Device_Names_str,DeviceName) ne -1,count)
;print,'Device_Names_str[14] = ',Device_Names_str[14]
;print,'DeviceName = ',DeviceName
;print,'wheredevice = ',wheredevice
;print,'strpos(Device_Names_str,DeviceName) = ',strpos(Device_Names_str,DeviceName)
if count eq 0 then wheredevice = 0
widget_control,(*pState_MB2).Device_Names_Droplist,set_droplist_select=wheredevice
widget_control,(*pState_MB2).Table_Limit_sics,set_value=limit_array_sics
;widget_control, (*pState_MB2).maxwait_field,set_value=maxwait
;widget_control, (*pState_MB2).settle_field,set_value=settle
;widget_control, (*pState_MB2).tolerance_field,set_value=tolerance
if (limit_array_sics[0,1]) eq 0.0 AND (limit_array_sics[1,1]) eq 0.0 then begin
widget_control,(*pState_MB).Magnet_field,sensitive=0
widget_control,(*pState_MB).MagnetButton,ToolTip='The sample environment selected does not afford a magnetic field'
endif else begin
widget_control,(*pState_MB).Magnet_field,sensitive=1
widget_control,(*pState_MB).MagnetButton,ToolTip=''
endelse
return
end
'Set_Device':    $
begin
Set_Device,event,DeviceName,limit_array_sics;,maxwait,settle,tolerance
; code needs to be written here to change device name if neccessary
;help,Device_Names_str

if (limit_array_sics[0,1]) eq 0.0 AND (limit_array_sics[1,1]) eq 0.0 then begin
widget_control,(*pState_MB).Magnet_field,sensitive=0
widget_control,(*pState_MB).MagnetButton,ToolTip='The sample environment selected does not afford a magnetic field'
endif else begin
widget_control,(*pState_MB).Magnet_field,sensitive=1
widget_control,(*pState_MB).MagnetButton,ToolTip=''
endelse

return
end
'Cancel':    $
begin
widget_control,event.top,/destroy
end
'Accept':    $
begin

;populate structure
limit_structure.DeviceName=DeviceName
limit_structure.temp_low=limit_array_sics[0,0]
limit_structure.temp_high=limit_array_sics[1,0]
limit_structure.field_low=limit_array_sics[0,1]
limit_structure.field_high=limit_array_sics[1,1]
limit_structure.count_low=limit_array_user[0,0]
limit_structure.count_high=limit_array_user[1,0]
limit_structure.wait_low=limit_array_user[0,1]
limit_structure.wait_high=limit_array_user[1,1]
;limit_structure.maxwait=maxwait
;limit_structure.settle=settle
;limit_structure.tolerance=tolerance
;save,filename=workDir+'parameters.lim',limit_structure
;save,filename=!DAVE_AUXILIARY_DIR+'PSI\MARS\MB_Parameters.lim',limit_structure
;save,filename=!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MB_Parameters.lim',limit_structure
(*pState_MB).limit_structure=limit_structure
widget_control,event.top,/destroy
end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro limit_table,event
widget_control,event.top,get_uvalue = pState_MB
limit_structure=(*pState_MB).limit_structure
main_event=event
delim=(*pState_MB).delim



UnitSpy=(*pstate_mb).UnitSpy
Device_Names_str=sicscommand(main_event,UnitSpy,'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='Arbitrary'
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
m=n_elements(Device_Names_str)
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=['Arbitrary',Device_Names_str]
;
ENDELSE


    DeviceName=strtrim(string(limit_structure.DeviceName),2)

;temp=strsplit(DeviceName,/extract)
;DeviceName=strtrim(temp[0],2)
;print,DeviceName

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)
wheredevice=wheredevice[0]
;print,'wheredevice: ',wheredevice
if wheredevice eq -1 then wheredevice = 0



    tlb = widget_base(group_leader = event.top, /col,/modal,/align_center, $
        title = 'Parameter Limits',/tlb_frame_attr)

;limit_structure= {DeviceName:DeviceName, $
;             temp_low:temp_low, $
;          temp_high:temp_high, $
;          field_low:field_low, $
;          field_high:field_high, $
;          count_low:count_low, $
;          count_high:count_high, $
;          wait_low:wait_low, $
;          wait_high:wait_high}



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


;Device_field=cw_field(base1,xsize=12,/col,title='Device Name',value=DeviceName)


Device_Names_Droplist=widget_Droplist(base1,value=Device_Names_str,/dynamic_resize)

widget_control,Device_Names_Droplist,set_droplist_select=wheredevice

base2=widget_base(tlb,/col,/align_center)

limit_array_sics=strarr(2,2)

limit_array_sics[0,0]=string(limit_structure.temp_low)
limit_array_sics[1,0]=string(limit_structure.temp_high)
limit_array_sics[0,1]=string(limit_structure.field_low)
limit_array_sics[1,1]=string(limit_structure.field_high)

column_labels_sics=['Lower Limit','Upper Limit']
row_labels_sics=['temperature','Magnet']

void=widget_label(base2,value='Non-Editable Information Acquired From SICS')


Table_Limit_sics=widget_table(base2,column_labels=column_labels_sics, $
       row_labels=row_labels_sics,xsize=2,ysize=2,value=limit_array_sics,column_widths=90)

;void=widget_label(base2,value='Editable Information Acquired From SICS')
;
;base3=widget_base(base2,/row)

;maxwait=strtrim(string(limit_structure.maxwait),2)
;settle=strtrim(string(limit_structure.settle),2)
;tolerance=strtrim(string(limit_structure.tolerance),2)

;maxwait_field=cw_field(base3,xsize=12,/col,title='Max. wait Time',value=maxwait)
;settle_field=cw_field(base3,xsize=12,/col,title='Max. Settle Time',value=settle)
;tolerance_field=cw_field(base3,xsize=12,/col,title='Tolerance',value=tolerance)


void = widget_button(base2,value = 'Set Device',uname='Set_Device')
void = widget_button(base2,value = 'Get Current Device',uname='Get_Current_Device')


void=widget_label(base2,value='Information set by the instrument Responsible')


limit_array_user=strarr(2,2)

limit_array_user[0,0]=string(limit_structure.count_low)
limit_array_user[1,0]=string(limit_structure.count_high)
limit_array_user[0,1]=string(limit_structure.wait_low)
limit_array_user[1,1]=string(limit_structure.wait_high)

column_labels_user=['Lower Limit','Upper Limit']
row_labels_user=['count','wait']



Table_Limit_user=widget_table(base2,column_labels=column_labels_user, $
       row_labels=row_labels_user,xsize=2,ysize=2,value=limit_array_user,column_widths=90,/editable)



void = widget_button(tlb,value = 'Cancel',uname='Cancel')
void = widget_button(tlb,value = 'Accept',uname='Accept')
centertlb,tlb
widget_control,tlb,/realize
state2 = {Table_Limit_sics:Table_Limit_sics, $
       Table_Limit_user:Table_Limit_user, $
;       maxwait_field:maxwait_field, $
;       settle_field:settle_field, $
;       tolerance_field:tolerance_field, $
       Device_Names_Droplist:Device_Names_Droplist, $
       Device_Names_str:Device_Names_str, $
       Device_Names_str_short:Device_Names_str_short, $
       main_event:main_event}


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

xmanager,'limit_table',tlb,event_handler = 'limit_table_event'

ptr_free,pState_MB2
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Limits,event
widget_control,event.top,get_uvalue = pState_MB
password=mb_password_widget(group_leader = event.top)
if password eq '' then return
;print,'password = ',password
limit_table, event
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro helpfile,event
widget_control,event.top,get_uvalue = pState_MB
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Connect_Batch,event
widget_control,event.top,get_uvalue = pstate_mb
;
    if (*pState_MB).demo_mb eq 0 then begin
    void = dialog_message(dialog_parent = event.top,/information, $
    'Already Connected')
    return
    endif
;
widget_control,(*pstate_mb).connect_button,sensitive = 0
;
delim=(*pState_MB).delim

get_lun,UnitUser
(*pstate_mb).UnitUser=UnitUser
get_lun,UnitexeUser
(*pstate_mb).UnitexeUser=UnitexeUser
get_lun,UnitSpy
(*pstate_mb).UnitSpy=UnitSpy
get_lun,UnitManager
(*pstate_mb).UnitManager=UnitManager
get_lun,tunit
(*pState_mb).tunit=tunit


;filename='C:\Documents and Settings\tregenna\My Documents\NIST\DAVE\cvs_nist\dave\programs\auxiliary\MarsSICSInfo.txt'
;filename=!DAVE_AUXILIARY_DIR+'\PSI\MARS\MarsSICSInfo_User.txt'
filename=!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MarsSICSInfo_User.txt'
hoststring=''
portstring=''
userstring=''
passwordstring=''
openr,lun,filename,/get_lun
readf,lun,hoststring
readf,lun,portstring
readf,lun,userstring
readf,lun,passwordstring
free_lun,lun,/force
;
equalsign=strpos(hoststring,'=')
host=strmid(hoststring,equalsign+1)
equalsign=strpos(portstring,'=')
port=strmid(portstring,equalsign+1)
port=long(port)
equalsign=strpos(userstring,'=')
user=strmid(userstring,equalsign+1)
equalsign=strpos(passwordstring,'=')
password=strmid(passwordstring,equalsign+1)
;
;
response=sicsconnect(UnitUser,host,port,error=error)
;print,'response = ',response
;print,'error = ',error
;help,response
    IF response eq 0 then begin
; the program is not running in demonstration mode
print,'Connection Successful'
(*pstate_mb).demo_mb=0
logon=sicslogon(UnitUser,user,password)
;print,'woofb'
;print,logon
if logon eq 0 then begin
void = dialog_message(dialog_parent = event.top,/error, $
'SICS User login is incorrect. Please inspect and edit the file ' +  $
'in the Dave auxillary directory.')
(*pstate_mb).demo_mb=1
widget_control,(*pstate_mb).connect_button,sensitive = 1
return
endif

    ENDIF ELSE BEGIN
    void = dialog_message(dialog_parent = event.top, $
    'Connection to MARS not found.')
(*pstate_mb).demo_mb=1
widget_control,(*pstate_mb).connect_button,sensitive = 1
return
    ENDELSE
;
;
;now for the executable connection.
; note that because histogram memory commands requires manager privilge,
; the UnitexeUser connection is no longer used to run the executable batch file
response=sicsconnect(UnitexeUser,host,port,error=error)
;print,'response = ',response
;print,'error = ',error
;help,response
    IF response eq 0 then begin
; the program is not running in demonstration mode
print,'Connection Successful'
(*pstate_mb).demo_mb=0
logon=sicslogon(UnitexeUser,user,password)
;print,'woofb'
;print,logon
if logon eq 0 then begin
void = dialog_message(dialog_parent = event.top,/error, $
'SICS User login is incorrect. Please inspect and edit the file ' +  $
'in the Dave auxillary directory.')
(*pstate_mb).demo_mb=1
widget_control,(*pstate_mb).connect_button,sensitive = 1
return
endif
    ENDIF ELSE BEGIN
    void = dialog_message(dialog_parent = event.top, $
    'Connection to MARS not found.')
(*pstate_mb).demo_mb=1
    ENDELSE


; spy connection
;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
;
equalsign=strpos(hoststring,'=')
host=strmid(hoststring,equalsign+1)
equalsign=strpos(portstring,'=')
port=strmid(portstring,equalsign+1)
port=long(port)
equalsign=strpos(userstring,'=')
user=strmid(userstring,equalsign+1)
equalsign=strpos(passwordstring,'=')
password=strmid(passwordstring,equalsign+1)
;
;
response=sicsconnect(UnitSpy,host,port,error=error)
;print,'response = ',response
;print,'error = ',error
;help,response
    IF response eq 0 then begin
; the program is not running in demonstration mode
print,'Connection Successful'
(*pstate_mb).demo_mb=0
logon=sicslogon(UnitSpy,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.')
(*pstate_mb).demo_mb=1
widget_control,(*pstate_mb).connect_button,sensitive = 1
return
endif
 command='list'
response=sicsexecute(event,UnitSpy,command)
listarr=strsplit(response,',',/extract,count=count)
for i=0,count-1 do begin
listarr[i]=strtrim(listarr[i],2)
endfor
; replace 'ENDLIST' with instrument_file command that will then be translated into valid SICS commands
listarr[count-1] ='instrument_file'
;must add field to the list as this later translated into 'run mf'or 'drive mf'
listarr=[listarr,'field']
*(*pstate_mb).listarr=listarr
    ENDIF ELSE BEGIN
    void = dialog_message(dialog_parent = event.top, $
    'Connection to MARS not found.')
(*pstate_mb).demo_mb=1
    ENDELSE



; Manager connection
;filename=!DAVE_AUXILIARY_DIR+'\PSI\MARS\MarsSICSInfo_Manager.txt'
filename=!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MarsSICSInfo_Manager.txt'
hoststring=''
portstring=''
userstring=''
passwordstring=''
openr,lun,filename,/get_lun
readf,lun,hoststring
readf,lun,portstring
readf,lun,userstring
readf,lun,passwordstring
free_lun,lun,/force
;
equalsign=strpos(hoststring,'=')
host=strmid(hoststring,equalsign+1)
equalsign=strpos(portstring,'=')
port=strmid(portstring,equalsign+1)
port=long(port)
equalsign=strpos(userstring,'=')
user=strmid(userstring,equalsign+1)
equalsign=strpos(passwordstring,'=')
password=strmid(passwordstring,equalsign+1)
;
;
response=sicsconnect(UnitManager,host,port,error=error)
;print,'response = ',response
;print,'error = ',error
;help,response
    IF response eq 0 then begin
; the program is not running in demonstration mode
print,'Connection Successful'
(*pstate_mb).demo_mb=0
logon=sicslogon(UnitManager,user,password)
;print,'woofb'
;print,logon
if logon eq 0 then begin
void = dialog_message(dialog_parent = event.top,/error, $
'SICS User login is incorrect. Please inspect and edit the file ' +  $
'in the Dave auxillary directory.')
(*pstate_mb).demo_mb=1
widget_control,(*pstate_mb).connect_button,sensitive = 1
return
endif
    ENDIF ELSE BEGIN
    void = dialog_message(dialog_parent = event.top, $
    'Connection to MARS not found.')
(*pstate_mb).demo_mb=1
    ENDELSE



IF (*pstate_mb).demo_mb EQ 0 THEN BEGIN
;temperature connection
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(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)

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

command='samenv -q'
response=sicscommand(event,tunit,command,datatype='string')
print,'response = ',response
print,''
DeviceName=(strsplit(response,/extract))[0]
DeviceName=strtrim(DeviceName,2)
print,'DeviceName = ',DeviceName
print,''
T_lower=sicscommand(event,tunit,'temperature lowerlimit',datatype='long')
T_upper=sicscommand(event,tunit,'temperature upperlimit',datatype='long')
mf_lower=sicscommand(event,tunit,'mf lowerlimit',datatype='long',/no_message)
if mf_lower eq -1 then mf_lower = 0
mf_upper=sicscommand(event,tunit,'mf upperlimit',datatype='long',/no_message)
if mf_upper eq -1 then mf_upper = 0
;
;limit_structure= {DeviceName:DeviceName, $
;             temp_low:temp_low, $
;          temp_high:temp_high, $
;          field_low:field_low, $
;          field_high:field_high, $
;          count_low:count_low, $
;          count_high:count_high, $
;          wait_low:wait_low, $
;          wait_high:wait_high}


(*pState_mb).limit_structure.DeviceName=DeviceName
(*pState_mb).limit_structure.temp_low=T_lower
(*pState_mb).limit_structure.temp_high=T_upper
(*pState_mb).limit_structure.field_low=mf_lower
(*pState_mb).limit_structure.field_high=mf_upper
if mf_lower eq 0.0 AND mf_upper eq 0.0 then begin
widget_control,(*pState_mb).Magnet_field,sensitive=0
widget_control,(*pState_mb).MagnetButton,ToolTip='The sample environment selected does not afford a magnetic field'
endif else begin
widget_control,(*pState_mb).Magnet_field,sensitive=1
widget_control,(*pState_mb).MagnetButton,ToolTip=''
endelse

ENDIF


widget_control,(*pstate_mb).connect_button,sensitive = 1

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Interrupt_Batch,event
widget_control,event.top,get_uvalue = pState_MB
widget_control,(*pState_MB).Interrupt_Button,sensitive = 0
UnitUser=(*pState_MB).UnitUser

EndRunCommand='INT1712 3'
tstart=systime(/seconds)
response=sicsinterrupt(event,UnitUser,EndRunCommand)
telapsed=systime(/seconds)-tstart
print,'Time to terminate run = ',telapsed
print,'response = ',response
print,''
WIDGET_CONTROL, event.TOP, TIMER=1 ; 1 second later, the program should react

widget_control,(*pState_MB).Interrupt_Button,sensitive = 1

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MB_ViewfileClose,event
widget_control,event.top,/destroy
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Viewfile,event,tlb
widget_control,event.top,get_uvalue = pState_MB
BatchCommands=*(*pState_MB).BatchCommands
nlines=n_elements(BatchCommands)
if nlines le 1 then return

;
; Centre it.
geom = widget_info(event.top, /geometry)
xpos = geom.xoffset + geom.xsize/2 - 100
ypos = geom.yoffset + geom.ysize/2 - 50
courier_largefont = get_font_name(/large, /courier)
courier_hugefont = get_font_name(/huge, /courier)

tlb = widget_base(title='Preview of file to be Sent to SICS',/col,group_leader=event.top,xoffset=xpos,yoffset=ypos, $
      tlb_frame_attr = 3,/modal)

void = widget_button(tlb,value = 'Close',font=courier_hugefont,event_pro ='MB_ViewfileClose')
Base1=widget_base(tlb,/col)
void = widget_text(Base1,value = BatchCommands,xsize = 50,ysize=50,font=courier_largefont,/scroll)

widget_control,tlb,/realize


xmanager, 'Viewfile',tlb ;register with the xmanager


end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro ReOrderBatchfile,event,err
;the code for this procedure is a disaster, written under duress.
;Rather than debugging it, re-write it.
err=0
widget_control,event.top,get_uvalue = pState_MB
   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
    void=dialog_message(dialog_parent=event.top,/error, $
    'Programming Error.  Message: '+!ERROR_STATE.MSG+' Do not use the smart-batch-processing option')
err=1
return
endif

BatchCommands=*(*pState_MB).BatchCommands
if n_elements(BatchCommands) le 1 then begin
    void=dialog_message(dialog_parent=event.top, $
    'Batch file is Empty!')
err=1
return
endif
BatchCommands=BatchCommands[1:*]
;print,'BatchCommands = ',BatchCommands
str='count monitor'
countcommands=where(strpos(BatchCommands,str) eq 0,count)
;print,'countcommands = ',countcommands
skip = 0
;print,'count: ',count
if count eq 0 then begin
    void=dialog_message(dialog_parent=event.top, $
    'No ''count monitor'' commands found.  Please use the standard processing mode')
err=1
return
endif
BatchCommandsNew='Re-ordered Batch file'
for i=0,count-1 do begin
countpos=countcommands[i]
    if i eq 0 then begin
       if countpos eq -1 then skip=1
       if countpos eq 0 then begin
        BatchCommandsNew=[BatchCommandsNew,BatchCommands[0]]
        skip=1
        endif else begin
        prestr=BatchCommands[0:countpos-1]
       endelse
    endif else begin
    ;do the count commands follow on from each other?
        if countcommands[i] eq (countcommands[i-1]+1) then begin
        BatchCommandsNew=[BatchCommandsNew,BatchCommands[countcommands[i]]]
    skip=1
        endif else begin
    prestr=BatchCommands[countcommands[i-1]+1:countpos-1]
    skip=0
       endelse
    endelse

;inspect skip
IF skip eq 0 then begin
n=n_elements(prestr)
;print,'n = ',n
contains_colldr=where(strpos(prestr,'colldr') eq 0,count1)
    if count1 ne 0  then begin
    ;print,'colldr'
       if count1 ne 1 then begin
    ; I don't want to handle more than one colldr command
    void=dialog_message(dialog_parent=event.top, $
    'It is not sensible to change the instrument settings more than once between runs')
    err=1
    return
       endif
    ;
    BatchCommandsNew=[BatchCommandsNew,prestr[contains_colldr:contains_colldr+9]]

    IF n GT 10 then begin
    prestr_remains=strarr(n-10)
    k=0
        for j = 0,n-1 do begin
         if j lt contains_colldr then begin
         prestr_remains[k]=prestr[j]
         k+=1
         endif
         ;
         if j gt (contains_colldr+9) then begin
         prestr_remains[k]=prestr[j]
         k+=1
         endif
       endfor
       ;

        whererun=where(strpos(prestr_remains,'run') eq 0,count2)
        if count2 ne 0 then begin
            BatchCommandsNew=[BatchCommandsNew,prestr_remains[whererun]]
         BatchCommandsNew=[BatchCommandsNew,'success']
            if count2 lt (n-10) then begin;there are lines remaining; leave only one wait, the longest
        wherenerun=where(strpos(prestr_remains,'run') ne 0,count2)
       commands_remaining=prestr_remains[wherenerun]
        wherewait=where(strpos(commands_remaining,'wait') eq 0,count4)
            case count4 of
            0: $
            begin
            BatchCommandsNew=[BatchCommandsNew,commands_remaining]
            ;print,'reached here'
            end
            1: $
            begin
            BatchCommandsNew=[BatchCommandsNew,commands_remaining[wherewait]]
            wherenewait=where(strpos(commands_remaining,'wait') ne 0,count5)
            if count5 ne 0 then begin
            BatchCommandsNew=[BatchCommandsNew,commands_remaining[wherenewait]]
            endif
            end
         else: $; two or more
         begin
       waitcommands=strarr(count4)
       waittime=intarr(count4)
       ;help,waittime
       ;help,commands_remaining
       ;print,commands_remaining[wherewait]
       ;print,(strsplit(commands_remaining[wherewait[0]],' ',/extract))[1]
       ;return
       for p = 0,count4-1 do begin
       waitcommands[p]=strtrim((strsplit(commands_remaining[wherewait[p]],' ',/extract))[1],2)
       endfor
;       print,'waitcommands = ',waitcommands
       waittime=long(waitcommands)
;       print,'waittime = ',waittime
       wheremaxtime=where(waittime eq max(waittime))
       maxwaittimecommand=commands_remaining[wherewait[wheremaxtime[0]]]
;       print,'maxwaittimecommand = ',maxwaittimecommand
       BatchCommandsNew=[BatchCommandsNew,maxwaittimecommand]
            wherenewait=where(strpos(commands_remaining,'wait') ne 0,count5)
            if count5 ne 0 then begin
            BatchCommandsNew=[BatchCommandsNew,commands_remaining[wherenewait]]
            endif
          end
            endcase
;       print,' BatchCommandsNew = ', BatchCommandsNew

            endif
        endif else begin
         BatchCommandsNew=[BatchCommandsNew,'success']
        ;commands remaining leave only 1 wait
        wherenerun=where(strpos(prestr_remains,'run') ne 0,count2)
       commands_remaining=prestr_remains[wherenerun]
        wherewait=where(strpos(commands_remaining,'wait') eq 0,count4)
            case count4 of
            0: $
            begin
            BatchCommandsNew=[BatchCommandsNew,commands_remaining]
            end
            1: $
            begin
            BatchCommandsNew=[BatchCommandsNew,commands_remaining[wherewait]]
            wherenewait=where(strpos(commands_remaining,'wait') ne 0,count5)
            if count5 ne 0 then begin
            BatchCommandsNew=[BatchCommandsNew,commands_remaining[wherenewait]]
            endif
            end
         else: $; two or more
         begin
       waitcommands=strarr(count4)
       waittime=intarr(count4)
       for p = 0,count4-1 do begin
       waitcommands[p]=strtrim((strsplit(commands_remaining[wherewait[p]],' ',/extract))[1],2)
       endfor
       waittime=long(waitcommands)
       wheremaxtime=where(waittime eq max(waittime))
       maxwaittimecommand=commands_remaining[wherewait[wheremaxtime[0]]]
       BatchCommandsNew=[BatchCommandsNew,maxwaittimecommand]
            wherenewait=where(strpos(commands_remaining,'wait') ne 0,count5)
            if count5 ne 0 then begin
            BatchCommandsNew=[BatchCommandsNew,commands_remaining[wherenewait]]
            endif
          end
            endcase
         endelse
    ENDIF ELSE BEGIN
         BatchCommandsNew=[BatchCommandsNew,'success']
        ENDELSE
    endif else begin ; what a mess! there is no colldr command
        whererun=where(strpos(prestr,'run') eq 0,count3) ; are there run commands
        if count3 ne 0 then begin
            BatchCommandsNew=[BatchCommandsNew,prestr[whererun]]
         BatchCommandsNew=[BatchCommandsNew,'success']
            if count3 lt n then begin;there are lines remaining, leave only 1 wait
;         print,'count3 = ',count3
;         print,'n = ',n
        wherenerun=where(strpos(prestr,'run') ne 0,count3)
       commands_remaining=prestr[wherenerun]
        wherewait=where(strpos(commands_remaining,'wait') eq 0,count4)
            case count4 of
            0: $
            begin
            BatchCommandsNew=[BatchCommandsNew,commands_remaining]
         ;print,'BatchCommandsNew1 = ',BatchCommandsNew

            end
            1: $
            begin
            BatchCommandsNew=[BatchCommandsNew,commands_remaining[wherewait]]
            wherenewait=where(strpos(commands_remaining,'wait') ne 0,count5)
            if count5 ne 0 then begin
            BatchCommandsNew=[BatchCommandsNew,commands_remaining[wherenewait]]
            endif
            end
         else: $; two or more
         begin
       waitcommands=strarr(count4)
       waittime=intarr(count4)
       for p = 0,count4-1 do begin
       waitcommands[p]=strtrim((strsplit(commands_remaining[wherewait[p]],' ',/extract))[1],2)
       endfor
       waittime=long(waitcommands)
       wheremaxtime=where(waittime eq max(waittime))
       maxwaittimecommand=commands_remaining[wherewait[wheremaxtime[0]]]
       BatchCommandsNew=[BatchCommandsNew,maxwaittimecommand]
            wherenewait=where(strpos(commands_remaining,'wait') ne 0,count5)
            if count5 ne 0 then begin
            BatchCommandsNew=[BatchCommandsNew,commands_remaining[wherenewait]]
            endif
          end
            endcase
            endif
       endif else begin; there are no run commands, purge the waits,
               wherewait=where(strpos(prestr,'wait') eq 0,count6)
            case count6 of
            0: $
            begin
            BatchCommandsNew=[BatchCommandsNew,prestr]
            end
            1: $
            begin
            BatchCommandsNew=[BatchCommandsNew,prestr[wherewait]]
            wherenewait=where(strpos(prestr,'wait') ne 0,count7)
            if count7 ne 0 then begin
            BatchCommandsNew=[BatchCommandsNew,prestr[wherenewait]]
            endif
            end
         else: $; two or more
         begin
       waitcommands=strarr(count6)
       waittime=intarr(count6)
;         print,'waintcommands = ',waitcommands
;         print,'wainttime = ',waittime
;         print,'count6 = ',count6
       for p = 0,count6-1 do begin
       waitcommands[p]=strtrim((strsplit(prestr[wherewait[p]],' ',/extract))[1],2)
       endfor
       waittime=long(waitcommands)
       wheremaxtime=where(waittime eq max(waittime))
       maxwaittimecommand=prestr[wherewait[wheremaxtime[0]]]
       BatchCommandsNew=[BatchCommandsNew,maxwaittimecommand]
            wherenewait=where(strpos(prestr,'wait') ne 0,count7)
            if count7 ne 0 then begin
            BatchCommandsNew=[BatchCommandsNew,prestr[wherenewait]]
            endif
          end
            endcase
 ;        print,'BatchCommandsNew2 = ',BatchCommandsNew
         endelse
    endelse
         BatchCommandsNew=[BatchCommandsNew,BatchCommands[countpos]]
         ;print,'BatchCommandsNew3 = ',BatchCommandsNew
ENDIF
endfor
if (countcommands[count-1]+1) lt n_elements(BatchCommands) then begin
endstr=BatchCommands[countcommands[count-1]+1:*]
;we must append success command
contains_colldr=where(strpos(endstr,'colldr') eq 0,count1)
    if count1 ne 0  then begin
;    print,'colldr'
       if count1 ne 1 then begin
    ; I don't want to handle more than one colldr command
    void=dialog_message(dialog_parent=event.top, $
    'It is not sensible to change the instrument settings more than once between runs')
    err=1
    return
       endif
    ;
    BatchCommandsNew=[BatchCommandsNew,endstr[contains_colldr:contains_colldr+6]]

remaining = endstr[contains_colldr+10:*] ;always something remaining
whererun=where(strpos(remaining,'run') eq 0,count) ; are there run commands
if count ne 0 then begin
BatchCommandsNew=[BatchCommandsNew,remaining[whererun]]
         BatchCommandsNew=[BatchCommandsNew,'success']
wherenerun=where(strpos(remaining,'run') ne 0,count) ; are there commands remaining
    if count ne 0 then begin
    BatchCommandsNew=[BatchCommandsNew,remaining[wherenerun]]
    endif
endif else begin
         BatchCommandsNew=[BatchCommandsNew,'success']
BatchCommandsNew=[BatchCommandsNew,remaining]
endelse
endif else begin
whererun=where(strpos(endstr,'run') eq 0,count) ; are there run commands
if count ne 0 then begin
BatchCommandsNew=[BatchCommandsNew,endstr[whererun]]
         BatchCommandsNew=[BatchCommandsNew,'success']
wherenerun=where(strpos(endstr,'run') ne 0,count) ; are there commands remaining
    if count ne 0 then begin
    BatchCommandsNew=[BatchCommandsNew,endstr[wherenerun]]
    endif
endif else begin
BatchCommandsNew=[BatchCommandsNew,endstr]
endelse
endelse

endif

;help,BatchCommandsNew
;m=n_elements(BatchCommandsNew)
;openw,lun,filename,/get_lun
;for i = 0, m-1 do begin
;printf,lun,BatchCommandsNew[i]
;endfor
;free_lun,lun,/force
*(*pState_MB).BatchCommands=BatchCommandsNew

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MB_Initialise_timer,event
widget_control,event.top,get_uvalue = pState_MB
   CATCH, Error_status
if Error_status ne 0 then begin
time=10
widget_control,(*pState_MB).MB_Update,set_value = string(time)
help,time
WIDGET_CONTROL, event.TOP, TIMER=time
catch, /cancel
return
endif
widget_control,(*pState_MB).MB_Update,get_value = time
time=long(time[0])
if time lt 10 then begin
time=10
widget_control,(*pState_MB).MB_Update,set_value = string(time)
endif
if time gt 120 then begin
time=120
widget_control,(*pState_MB).MB_Update,set_value = string(time)
endif
;
WIDGET_CONTROL, event.TOP, TIMER=time
;help,time
;help,Error_status
;print,Error_status
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Processing_Destroy,tlb
widget_control,tlb,get_uvalue = pState1_MB
wdelete,(*pState1_MB).winpix_koennecke
ptr_free,pState1_MB
widget_control,tlb,/destroy
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Processing_Create,event,tlb
widget_control,event.top,get_uvalue = pState_MB
image=(*pState_MB).koennecke_pic
;
msg=strarr(3)
msg[0]='Processing batch file.'
msg[1]='Please be patient.'
msg[2]='This message should soon disappear.'
; 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='Information',/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)
    device,decomposed = 1
    dispimage = image

void = widget_text(Base1,value = msg,xsize = 32,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]

state1={winpix_koennecke:winpix_koennecke}

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

xmanager, 'Processing_Create',tlb ;register with the xmanager
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MarsBatchTableEvents,event



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


widget_control,event.top,get_uvalue = pState_MB
delim=(*pState_MB).delim
Command_Table=(*pState_MB).command_table
Table_Contents=(*pState_MB).Table_Contents
ForegroundColors=(*pState_MB).ForegroundColors
workDir=(*pState_MB).workDir
limit_structure=(*pState_MB).limit_structure
UnitUser=(*pState_MB).UnitUser
UnitexeUser=(*pState_MB).UnitexeUser
UnitSpy=(*pState_MB).UnitSpy
UnitManager=(*pState_MB).UnitManager
;limit_structure= {DeviceName:DeviceName, $
;             temp_low:temp_low, $
;          temp_high:temp_high, $
;          field_low:field_low, $
;          field_high:field_high, $
;          count_low:count_low, $
;          count_high:count_high, $
;          wait_low:wait_low, $
;          wait_high:wait_high, $
;          maxwait:maxwait, $
;          settle:settle, $
;          tolerance:tolerance}

temp_low=float(limit_structure.temp_low)
temp_high=float(limit_structure.temp_high)
field_low=float(limit_structure.field_low)
field_high=float(limit_structure.field_high)
count_low=long64(limit_structure.count_low)
count_high=long64(limit_structure.count_high)
wait_low=long(limit_structure.wait_low)
wait_high=long(limit_structure.wait_high)
uname=widget_info(event.id,/uname)
case uname of
'sample':    $
begin
widget_control, (*pState_MB).sample_field,get_value=sample_field
sample_field=string(sample_field[0])
if sample_field eq '' then begin
void=dialog_message(dialog_parent=event.top,'sample field Missing',/error)
return
endif
cells= widget_info(Command_Table,/table_select)
Table_Contents[0,cells[1]]='sample'
Table_Contents[1,cells[1]]=sample_field
ForegroundColors[*,cells[1]*2]=[0,0,255]
ForegroundColors[*,cells[1]*2+1]=[0,0,255]
widget_control, Command_Table,set_value=Table_Contents
widget_control, Command_Table,set_table_select=[0,cells[1]+1,0,cells[1]+1], $
foreground_color=ForegroundColors
widget_control, Command_Table,set_table_view=[0,cells[1]-13]
(*pState_MB).Table_Contents=Table_Contents
(*pState_MB).ForegroundColors=ForegroundColors
end
;
'temperature':    $
begin
widget_control, (*pState_MB).temperature_field,get_value=temperature_field
temperature_field=string(temperature_field[0])
;
if temperature_field eq '' then begin
void=dialog_message(dialog_parent=event.top,'temperature field Missing',/error)
return
endif
;

if float(temperature_field[0]) lt temp_low or float(temperature_field[0]) gt temp_high then begin
void=dialog_message(dialog_parent=event.top, $
'Set temperature Must Be Between '+strtrim(string(temp_low),2)+ $
' and '+strtrim(string(temp_high),2)+' K',/error)
return
endif
;
cells= widget_info(Command_Table,/table_select)
Table_Contents[0,cells[1]]='temperature'
Table_Contents[1,cells[1]]=temperature_field
ForegroundColors[*,cells[1]*2]=[255,0,0]
ForegroundColors[*,cells[1]*2+1]=[255,0,0]
widget_control, Command_Table,set_value=Table_Contents
widget_control, Command_Table,set_table_select=[0,cells[1]+1,0,cells[1]+1], $
foreground_color=ForegroundColors
widget_control, Command_Table,set_table_view=[0,cells[1]-13]
(*pState_MB).Table_Contents=Table_Contents
(*pState_MB).ForegroundColors=ForegroundColors
end
;
'Magnet':    $
begin
widget_control, (*pState_MB).Magnet_field,get_value=Magnet_field
Magnet_field=string(Magnet_field[0])
;
if Magnet_field eq '' then begin
void=dialog_message(dialog_parent=event.top,'field Missing',/error)
return
endif
;

if float(Magnet_field[0]) lt field_low or float(Magnet_field[0]) gt field_high then begin
void=dialog_message(dialog_parent=event.top,$
'Set Magnetic field Must Be Between '+strtrim(string(field_low),2)+ $
' and '+strtrim(string(field_high),2)+' Tesla',/error)
return
endif
;
cells= widget_info(Command_Table,/table_select)
Table_Contents[0,cells[1]]='field'
Table_Contents[1,cells[1]]=Magnet_field
ForegroundColors[*,cells[1]*2]=[120,150,70]
ForegroundColors[*,cells[1]*2+1]=[120,150,70]
widget_control, Command_Table,set_value=Table_Contents
widget_control, Command_Table,set_table_select=[0,cells[1]+1,0,cells[1]+1], $
foreground_color=ForegroundColors
widget_control, Command_Table,set_table_view=[0,cells[1]-13]
(*pState_MB).Table_Contents=Table_Contents
(*pState_MB).ForegroundColors=ForegroundColors
end
;
'count':    $
begin
widget_control, (*pState_MB).count_field,get_value=count_field
count_field=string(count_field[0])
;
if count_field eq '' then begin
void=dialog_message(dialog_parent=event.top,'count field Missing',/error)
return
endif
;

if long64(count_field[0]) lt count_low or long64(count_field[0]) gt count_high then begin
void=dialog_message(dialog_parent=event.top, $
'Set count Must Be Between '+strtrim(string(count_low),2)+ $
' and '+strtrim(string(count_high),2)+' Monitor counts',/error)
return
endif
;
cells= widget_info(Command_Table,/table_select)
Table_Contents[0,cells[1]]='count'
Table_Contents[1,cells[1]]=count_field
ForegroundColors[*,cells[1]*2]=[0,255,0]
ForegroundColors[*,cells[1]*2+1]=[0,255,0]
widget_control, Command_Table,set_value=Table_Contents
widget_control, Command_Table,set_table_select=[0,cells[1]+1,0,cells[1]+1], $
foreground_color=ForegroundColors
widget_control, Command_Table,set_table_view=[0,cells[1]-13]
(*pState_MB).Table_Contents=Table_Contents
(*pState_MB).ForegroundColors=ForegroundColors
end
;
'wait':    $
begin
widget_control, (*pState_MB).wait_field,get_value=wait_field
wait_field=string(wait_field[0])
;
if wait_field eq '' then begin
void=dialog_message(dialog_parent=event.top,'wait field Missing',/error)
return
endif
;

if long(wait_field[0]) lt wait_low or float(wait_field[0]) gt wait_high then begin
void=dialog_message(dialog_parent=event.top, $
'Set wait Must Be Between '+strtrim(string(wait_low),2)+ $
' and '+strtrim(string(wait_high),2)+' Seconds',/error)
return
endif
;
cells= widget_info(Command_Table,/table_select)
Table_Contents[0,cells[1]]='wait'
Table_Contents[1,cells[1]]=wait_field
ForegroundColors[*,cells[1]*2]=[255,171,127]
ForegroundColors[*,cells[1]*2+1]=[255,171,127]
widget_control, Command_Table,set_value=Table_Contents
widget_control, Command_Table,set_table_select=[0,cells[1]+1,0,cells[1]+1], $
foreground_color=ForegroundColors
widget_control, Command_Table,set_table_view=[0,cells[1]-13]
(*pState_MB).Table_Contents=Table_Contents
(*pState_MB).ForegroundColors=ForegroundColors
end
;
'instrumentfile':    $
begin
widget_control, (*pState_MB).instrumentfile_field,get_value=instrumentfile_field
instrumentfile_field=string(instrumentfile_field[0])
;
if instrumentfile_field eq '' or file_test(workDir+instrumentfile_field) ne 1 then begin
instrumentfile = dialog_pickfile(dialog_parent = event.top,/fix_filter,/read, $
                               filter = ['*.pln'],$
                               title = 'Select instrument_file',$
                               path = workDir)

pos=strlen(workDir)
instrumentfile_field=strmid(instrumentfile,pos)
if instrumentfile_field eq '' then return
widget_control, (*pState_MB).instrumentfile_field,set_value=instrumentfile_field
endif
cells= widget_info(Command_Table,/table_select)
Table_Contents[0,cells[1]]='instrument_file'
Table_Contents[1,cells[1]]=instrumentfile_field
ForegroundColors[*,cells[1]*2]=[255,0,255]
ForegroundColors[*,cells[1]*2+1]=[255,0,255]
widget_control, Command_Table,set_value=Table_Contents
widget_control, Command_Table,set_table_select=[0,cells[1]+1,0,cells[1]+1], $
foreground_color=ForegroundColors
widget_control, Command_Table,set_table_view=[0,cells[1]-13]
(*pState_MB).Table_Contents=Table_Contents
(*pState_MB).ForegroundColors=ForegroundColors
end
;
'Clear':    $
begin
Table_Contents=strarr(2,200)
ForegroundColors=intarr(3,400)
(*pState_MB).Table_Contents=Table_Contents
widget_control, Command_Table,set_value=Table_Contents
(*pState_MB).ForegroundColors=ForegroundColors
widget_control, Command_Table,set_table_select=[0,0,0,0]
end
;
'Run':    $
begin
widget_control,(*pState_MB).run_button,sensitive=0
BatchCommands='Sics Batch Commands'
;
total_cells=max(where(Table_Contents ne '',count))
total_rows=(total_cells+1)/2
;process the data by two different ways
widget_control, (*pState_MB).processing_button,get_value=processing_button

IF processing_button eq 0 THEN BEGIN ; smart processing
;
for i=0,total_rows-1 do begin
entry=Table_Contents[0,i]
entry=strtrim(string(entry[0]),2)

case entry of
'sample':    $
begin
command='sample '+strtrim(Table_Contents[1,i],2)
BatchCommands=[BatchCommands,command]
end
;
'instrument_file':    $
begin
restore,filename=workDir+strtrim(string(Table_Contents[1,i]),2)
chopper_table=SaveParametersArray.output
theta=SaveParametersArray.theta
command='colldr th '+theta
BatchCommands=[BatchCommands,command]
command='run snailphase '+strtrim(string(Chopper_Table[0,0]),2)
BatchCommands=[BatchCommands,command]
command='run masterphase '+strtrim(string(Chopper_Table[0,1]),2)
BatchCommands=[BatchCommands,command]
command='run rabbitphase '+strtrim(string(Chopper_Table[0,2]),2)
BatchCommands=[BatchCommands,command]
command='run fourphase '+strtrim(string(Chopper_Table[0,3]),2)
BatchCommands=[BatchCommands,command]
command='run fivephase '+strtrim(string(Chopper_Table[0,4]),2)
BatchCommands=[BatchCommands,command]
;command='run snailspeed '+strtrim(string(Chopper_Table[1,0]),2)
;BatchCommands=[BatchCommands,command]
command='run masterspeed '+strtrim(string(Chopper_Table[1,1]),2)
BatchCommands=[BatchCommands,command]
;command='run rabbitspeed '+strtrim(string(Chopper_Table[1,2]),2)
;BatchCommands=[BatchCommands,command]
;command='run fourspeed '+strtrim(string(Chopper_Table[1,3]),2)
;BatchCommands=[BatchCommands,command]
;command='run fivespeed '+strtrim(string(Chopper_Table[1,4]),2)
;BatchCommands=[BatchCommands,command]
;histogram memory
mica=SaveParametersArray.mica
if mica eq 0 then Target_Reflection='002'
if mica eq 1 then Target_Reflection='004'
if mica eq 2 then Target_Reflection='006'
if mica eq 3 then Target_Reflection='008'
command='TargetReflection '+Target_Reflection
BatchCommands=[BatchCommands,command]
;
TOF_start=long(SaveParametersArray.Time_Bin_Start*10.0)
TOF_step=fix(SaveParametersArray.Time_Bin_Step*10.0)
notimebin=SaveParametersArray.Total_Time_Bin_Number
TimeBinIndices=SaveParametersArray.TimeBinIndices
TOF_start=strtrim(string(TOF_start),2)
TOF_step=strtrim(string(TOF_step),2)
notimebin=strtrim(string(notimebin),2)
str=strtrim(string(TimeBinIndices[0]),2)+','
for l = 1,12 do begin
str+=strtrim(string(TimeBinIndices[l]),2)+','
endfor
str+=strtrim(string(TimeBinIndices[13]),2)
TimeBinIndices=str
command='hm genbin '+TOF_start+' '+TOF_step+' '+notimebin
BatchCommands=[BatchCommands,command]
command='hm init'
BatchCommands=[BatchCommands,command]
command='TimeBinIndices '+TimeBinIndices
BatchCommands=[BatchCommands,command]
;
Emid=strtrim(string(SaveParametersArray.Em),2)
Emax=strtrim(string(SaveParametersArray.E_upper),2)
Emin=strtrim(string(SaveParametersArray.E_lower),2)
command='Emid '+Emid
BatchCommands=[BatchCommands,command]
command='Emax '+Emax
BatchCommands=[BatchCommands,command]
command='Emin '+Emin
BatchCommands=[BatchCommands,command]
;
end
'temperature':    $
begin
command='run temperature '
argument=strtrim(Table_Contents[1,i],2)
parameters=['tolerance','settle','maxwait']
for k = 0,2 do begin
if strpos(argument,parameters[k]) ne -1 then command = 'temperature '
endfor
command+=argument
;print,'command  = ',command
BatchCommands=[BatchCommands,command]
end
'field':    $
begin
command='run mf '+strtrim(Table_Contents[1,i],2)
BatchCommands=[BatchCommands,command]
end
'count':    $
begin
command='count monitor '+strtrim(Table_Contents[1,i],2)
BatchCommands=[BatchCommands,command]
end
'wait':    $
begin
command='wait '+strtrim(Table_Contents[1,i],2)
BatchCommands=[BatchCommands,command]
end
;
'drive':    $
begin
command='drive '+strtrim(Table_Contents[1,i],2)
BatchCommands=[BatchCommands,command]
end

ELSE:   $
begin
command=entry+' '+strtrim(Table_Contents[1,i],2)
BatchCommands=[BatchCommands,command]
end
endcase
endfor
;n=n_elements(BatchCommands)
;openw,lun,filename,/get_lun
;for i = 0, n-1 do begin
;printf,lun,BatchCommands[i]
;endfor
;free_lun,lun,/force
*(*pState_MB).BatchCommands=BatchCommands
ReOrderBatchfile,event,err
if err eq 1 then return
ENDIF ELSE BEGIN ;standard processing
for i=0,total_rows-1 do begin
entry=Table_Contents[0,i]
entry=strtrim(string(entry[0]),2)

case entry of
'sample':    $
begin
command='sample '+strtrim(Table_Contents[1,i],2)
BatchCommands=[BatchCommands,command]
end
;
'instrument_file':    $
begin
restore,filename=workDir+strtrim(string(Table_Contents[1,i]),2)
chopper_table=SaveParametersArray.output
theta=SaveParametersArray.theta
command='colldr th '+theta
BatchCommands=[BatchCommands,command]
command='run snailphase '+strtrim(string(Chopper_Table[0,0]),2)
BatchCommands=[BatchCommands,command]
command='run masterphase '+strtrim(string(Chopper_Table[0,1]),2)
BatchCommands=[BatchCommands,command]
command='run rabbitphase '+strtrim(string(Chopper_Table[0,2]),2)
BatchCommands=[BatchCommands,command]
command='run fourphase '+strtrim(string(Chopper_Table[0,3]),2)
BatchCommands=[BatchCommands,command]
command='run fivephase '+strtrim(string(Chopper_Table[0,4]),2)
BatchCommands=[BatchCommands,command]
;command='run snailspeed '+strtrim(string(Chopper_Table[1,0]),2)
;BatchCommands=[BatchCommands,command]
command='run masterspeed '+strtrim(string(Chopper_Table[1,1]),2)
BatchCommands=[BatchCommands,command]
;command='run rabbitspeed '+strtrim(string(Chopper_Table[1,2]),2)
;BatchCommands=[BatchCommands,command]
;command='run fourspeed '+strtrim(string(Chopper_Table[1,3]),2)
;BatchCommands=[BatchCommands,command]
;command='run fivespeed '+strtrim(string(Chopper_Table[1,4]),2)
;BatchCommands=[BatchCommands,command]
command='success'
BatchCommands=[BatchCommands,command]
;histogram memory
mica=SaveParametersArray.mica
if mica eq 0 then Target_Reflection='002'
if mica eq 1 then Target_Reflection='004'
if mica eq 2 then Target_Reflection='006'
if mica eq 3 then Target_Reflection='008'
command='TargetReflection '+Target_Reflection
BatchCommands=[BatchCommands,command]
;
TOF_start=long(SaveParametersArray.Time_Bin_Start*10.0)
TOF_step=fix(SaveParametersArray.Time_Bin_Step*10.0)
notimebin=SaveParametersArray.Total_Time_Bin_Number
TimeBinIndices=SaveParametersArray.TimeBinIndices
TOF_start=strtrim(string(TOF_start),2)
TOF_step=strtrim(string(TOF_step),2)
notimebin=strtrim(string(notimebin),2)
str=strtrim(string(TimeBinIndices[0]),2)+','
for l = 1,12 do begin
str+=strtrim(string(TimeBinIndices[l]),2)+','
endfor
str+=strtrim(string(TimeBinIndices[13]),2)
TimeBinIndices=str
command='hm genbin '+TOF_start+' '+TOF_step+' '+notimebin
BatchCommands=[BatchCommands,command]
command='hm init'
BatchCommands=[BatchCommands,command]
command='TimeBinIndices '+TimeBinIndices
BatchCommands=[BatchCommands,command]
;
;
Emid=strtrim(string(SaveParametersArray.Em),2)
Emax=strtrim(string(SaveParametersArray.E_upper),2)
Emin=strtrim(string(SaveParametersArray.E_lower),2)
command='Emid '+Emid
BatchCommands=[BatchCommands,command]
command='Emax '+Emax
BatchCommands=[BatchCommands,command]
command='Emin '+Emin
BatchCommands=[BatchCommands,command]
;
;
end
'temperature':    $
begin
command='drive temperature '
argument=strtrim(Table_Contents[1,i],2)
parameters=['tolerance','settle','maxwait']
for k = 0,2 do begin
if strpos(argument,parameters[k]) ne -1 then command = 'temperature '
endfor
command+=argument
;print,'command  = ',command
BatchCommands=[BatchCommands,command]
end
'field':    $
begin
command='drive mf '+strtrim(Table_Contents[1,i],2)
BatchCommands=[BatchCommands,command]
end
'count':    $
begin
command='count monitor '+strtrim(Table_Contents[1,i],2)
BatchCommands=[BatchCommands,command]
end
'wait':    $
begin
command='wait '+strtrim(Table_Contents[1,i],2)
BatchCommands=[BatchCommands,command]
end
;
'drive':    $
begin
command='drive '+strtrim(Table_Contents[1,i],2)
BatchCommands=[BatchCommands,command]
end
ELSE:   $
begin
command=entry+' '+strtrim(Table_Contents[1,i],2)
BatchCommands=[BatchCommands,command]
end
;
endcase
endfor
*(*pState_MB).BatchCommands=BatchCommands
ENDELSE
BatchCommands=*(*pState_MB).BatchCommands

;p=n_elements(BatchCommands)
;for k=0,p-1 do begin
;print,BatchCommands[k]
;endfor

;now to execute the batch.
;
;if not connected to the instrument, we must exit at this point
if (*pstate_mb).demo_mb ne 0 then begin
void = dialog_message(dialog_parent = event.top,/information, $
'Connect to the instrument first')
widget_control,(*pState_MB).run_button,sensitive=1
return
endif
;
batchdir=''
;set the directory to write and search for the file
;if file_test(!DAVE_AUXILIARY_DIR+'PSI\MARS\MarsBatchDir.txt') eq 1 then begin
;openr,lun,!DAVE_AUXILIARY_DIR+'PSI\MARS\MarsBatchDir.txt',/get_lun
if file_test(!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MarsBatchDir.txt') eq 1 then begin
openr,lun,!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MarsBatchDir.txt',/get_lun
while eof(lun) eq 0 do begin
readf,lun,batchdir
batchdir=strtrim(batchdir,2)
endwhile
free_lun,lun,/force
endif else begin
batchdir='/home/mars/batch/'
endelse
;
print,'batchdir = ',batchdir
;first we must save the file
filename=batchdir+'MarsBatchfile.run'
;
Processing_Create,event,widget_id
      daveDeSensitizeButtons,event


;print,'UnitUser = ',UnitUser
;print,'UnitexeUser = ',UnitexeUser
;prepare the batch manager for uploading a buffer to sics

command='exe clearupload'
response=sicsexecute(event,UnitexeUser,command)
print,'Clearupload Upload = ',response
print,''
if strtrim(response,2) ne 'OK' then begin
Processing_Destroy,widget_id
      daveSensitizeButtons,event
widget_control,(*pState_MB).run_button,sensitive=1 ;shouldn't seem necessary
void = dialog_message(dialog_parent = event.top,/error, $
'Error: '+response)
return
endif


command='exe upload'
response=sicsexecute(event,UnitexeUser,command)
print,'Prepare Upload = ',response
print,''
if strtrim(response,2) ne 'OK' then begin
Processing_Destroy,widget_id
      daveSensitizeButtons,event
widget_control,(*pState_MB).run_button,sensitive=1 ;shouldn't seem necessary
void = dialog_message(dialog_parent = event.top,/error, $
'Error: '+response)
return
endif
;
n=n_elements(BatchCommands)
;write to the batch buffer
for i = 1, n-1 do begin ; note that the index starts from as we omit the field 'Sics Batch Commands'.
print,BatchCommands[i]
command='exe append '+BatchCommands[i]
response=sicsexecute(event,UnitexeUser,command)
if strtrim(response,2) ne 'OK' then begin
Processing_Destroy,widget_id
      daveSensitizeButtons,event
widget_control,(*pState_MB).run_button,sensitive=1 ;shouldn't seem necessary
void = dialog_message(dialog_parent = event.top,/error, $
'Error: '+response)
return
endif
print,'Append line = ',response
endfor
;
;save the file
command='exe forcesave '+filename
response=sicsexecute(event,UnitexeUser,command)
if strtrim(response,2) ne 'OK' then begin
Processing_Destroy,widget_id
      daveSensitizeButtons,event
widget_control,(*pState_MB).run_button,sensitive=1 ;shouldn't seem necessary
void = dialog_message(dialog_parent = event.top,/error, $
'Error: '+response)
return
endif
print,'Save File = ',response
print,''
;
;set search directory
;
command='exe batchpath '+batchdir
response=sicsexecute(event,UnitexeUser,command)
if strtrim(response,2) ne 'OK' then begin
Processing_Destroy,widget_id
      daveSensitizeButtons,event
widget_control,(*pState_MB).run_button,sensitive=1 ;shouldn't seem necessary
void = dialog_message(dialog_parent = event.top,/error, $
'Error: '+response)
return
endif
print,'Set search directory = ',response
print,''
;query search directories
command='exe batchpath '
response=sicsexecute(event,UnitexeUser,command)
print,'search paths = ',response
print,''
;execute the file
command='exe '+filename
print,'exe command = ',command
response=sicsexecute(event,UnitManager,command,/nowait)
print,'exe response = ',response
(*pState_MB).BatchActive=1 ; let the program know that the buffer should be read out at the end
;
(*pState_MB).PB_Table_Contents[*,*]=''
command='exe print MarsBatchfile.run'
response=sicscommand(event,UnitSpy,command,datatype='strarr')
;response=strtrim(response,2)
help,response
n=n_elements(response)
print,'buffer = '
for i = 0,n-1 do begin
print,response[i]
(*pState_MB).PB_Table_Contents[0,i]=response[i]
endfor
print,''
widget_control, (*pState_MB).PB_Command_Table,set_value=(*pState_MB).PB_Table_Contents
;
;
;initialise timer
MB_Initialise_timer,event
;
Processing_Destroy,widget_id
      daveSensitizeButtons,event
widget_control,(*pState_MB).run_button,sensitive=1
return
end
;
'Preview':    $
begin
BatchCommands='Sics Batch Commands'
;
total_cells=max(where(Table_Contents ne '',count))
total_rows=(total_cells+1)/2
;rows=count/2
;process the data by two different ways
widget_control, (*pState_MB).processing_button,get_value=processing_button
;print,'processing_button = ',processing_button
IF processing_button eq 0 THEN BEGIN ; smart processing
;print,'woof process '
;
for i=0,total_rows-1 do begin
entry=Table_Contents[0,i]
entry=strtrim(string(entry[0]),2)

case entry of
'sample':    $
begin
command='sample '+strtrim(Table_Contents[1,i],2)
BatchCommands=[BatchCommands,command]
end
;
'instrument_file':    $
begin
restore,filename=workDir+strtrim(string(Table_Contents[1,i]),2)
chopper_table=SaveParametersArray.output
theta=SaveParametersArray.theta
command='colldr th '+theta
BatchCommands=[BatchCommands,command]
command='run snailphase '+strtrim(string(Chopper_Table[0,0]),2)
BatchCommands=[BatchCommands,command]
command='run masterphase '+strtrim(string(Chopper_Table[0,1]),2)
BatchCommands=[BatchCommands,command]
command='run rabbitphase '+strtrim(string(Chopper_Table[0,2]),2)
BatchCommands=[BatchCommands,command]
command='run fourphase '+strtrim(string(Chopper_Table[0,3]),2)
BatchCommands=[BatchCommands,command]
command='run fivephase '+strtrim(string(Chopper_Table[0,4]),2)
BatchCommands=[BatchCommands,command]
;command='run snailspeed '+strtrim(string(Chopper_Table[1,0]),2)
;BatchCommands=[BatchCommands,command]
command='run masterspeed '+strtrim(string(Chopper_Table[1,1]),2)
BatchCommands=[BatchCommands,command]
;command='run rabbitspeed '+strtrim(string(Chopper_Table[1,2]),2)
;BatchCommands=[BatchCommands,command]
;command='run fourspeed '+strtrim(string(Chopper_Table[1,3]),2)
;BatchCommands=[BatchCommands,command]
;command='run fivespeed '+strtrim(string(Chopper_Table[1,4]),2)
;BatchCommands=[BatchCommands,command]
;histogram memory
mica=SaveParametersArray.mica
if mica eq 0 then Target_Reflection='002'
if mica eq 1 then Target_Reflection='004'
if mica eq 2 then Target_Reflection='006'
if mica eq 3 then Target_Reflection='008'
command='TargetReflection '+Target_Reflection
BatchCommands=[BatchCommands,command]
;
TOF_start=long(SaveParametersArray.Time_Bin_Start*10.0)
TOF_step=fix(SaveParametersArray.Time_Bin_Step*10.0)
notimebin=SaveParametersArray.Total_Time_Bin_Number
TimeBinIndices=SaveParametersArray.TimeBinIndices
TOF_start=strtrim(string(TOF_start),2)
TOF_step=strtrim(string(TOF_step),2)
notimebin=strtrim(string(notimebin),2)
str=strtrim(string(TimeBinIndices[0]),2)+','
for l = 1,12 do begin
str+=strtrim(string(TimeBinIndices[l]),2)+','
endfor
str+=strtrim(string(TimeBinIndices[13]),2)
TimeBinIndices=str
command='hm genbin '+TOF_start+' '+TOF_step+' '+notimebin
BatchCommands=[BatchCommands,command]
command='hm init'
BatchCommands=[BatchCommands,command]
command='TimeBinIndices '+TimeBinIndices
BatchCommands=[BatchCommands,command]
;
Emid=strtrim(string(SaveParametersArray.Em),2)
Emax=strtrim(string(SaveParametersArray.E_upper),2)
Emin=strtrim(string(SaveParametersArray.E_lower),2)
command='Emid '+Emid
BatchCommands=[BatchCommands,command]
command='Emax '+Emax
BatchCommands=[BatchCommands,command]
command='Emin '+Emin
BatchCommands=[BatchCommands,command]
;
;
end
'temperature':    $
begin
command='run temperature '
argument=strtrim(Table_Contents[1,i],2)
parameters=['tolerance','settle','maxwait']
for k = 0,2 do begin
if strpos(argument,parameters[k]) ne -1 then command = 'temperature '
endfor
command+=argument
;print,'command  = ',command
BatchCommands=[BatchCommands,command]
end
'field':    $
begin
command='run mf '+strtrim(Table_Contents[1,i],2)
BatchCommands=[BatchCommands,command]
end
'count':    $
begin
command='count monitor '+strtrim(Table_Contents[1,i],2)
BatchCommands=[BatchCommands,command]
end
'wait':    $
begin
command='wait '+strtrim(Table_Contents[1,i],2)
BatchCommands=[BatchCommands,command]
end
;
'drive':    $
begin
command='drive '+strtrim(Table_Contents[1,i],2)
BatchCommands=[BatchCommands,command]
end
ELSE:   $
begin
command=entry+' '+strtrim(Table_Contents[1,i],2)
BatchCommands=[BatchCommands,command]
end
;
endcase
endfor
*(*pState_MB).BatchCommands=BatchCommands
ReOrderBatchfile,event,err
if err eq 1 then return
ENDIF ELSE BEGIN ;standard processing
for i=0,total_rows-1 do begin
entry=Table_Contents[0,i]
entry=strtrim(string(entry[0]),2)

case entry of
'sample':    $
begin
command='sample '+strtrim(Table_Contents[1,i],2)
BatchCommands=[BatchCommands,command]
end
;
'instrument_file':    $
begin
restore,filename=workDir+strtrim(string(Table_Contents[1,i]),2)
chopper_table=SaveParametersArray.output
theta=SaveParametersArray.theta
command='colldr th '+theta
BatchCommands=[BatchCommands,command]
command='run snailphase '+strtrim(string(Chopper_Table[0,0]),2)
BatchCommands=[BatchCommands,command]
command='run masterphase '+strtrim(string(Chopper_Table[0,1]),2)
BatchCommands=[BatchCommands,command]
command='run rabbitphase '+strtrim(string(Chopper_Table[0,2]),2)
BatchCommands=[BatchCommands,command]
command='run fourphase '+strtrim(string(Chopper_Table[0,3]),2)
BatchCommands=[BatchCommands,command]
command='run fivephase '+strtrim(string(Chopper_Table[0,4]),2)
BatchCommands=[BatchCommands,command]
;command='run snailspeed '+strtrim(string(Chopper_Table[1,0]),2)
;BatchCommands=[BatchCommands,command]
command='run masterspeed '+strtrim(string(Chopper_Table[1,1]),2)
BatchCommands=[BatchCommands,command]
;command='run rabbitspeed '+strtrim(string(Chopper_Table[1,2]),2)
;BatchCommands=[BatchCommands,command]
;command='run fourspeed '+strtrim(string(Chopper_Table[1,3]),2)
;BatchCommands=[BatchCommands,command]
;command='run fivespeed '+strtrim(string(Chopper_Table[1,4]),2)
;BatchCommands=[BatchCommands,command]
command='success'
BatchCommands=[BatchCommands,command]
;histogram memory
mica=SaveParametersArray.mica
if mica eq 0 then Target_Reflection='002'
if mica eq 1 then Target_Reflection='004'
if mica eq 2 then Target_Reflection='006'
if mica eq 3 then Target_Reflection='008'
command='TargetReflection '+Target_Reflection
BatchCommands=[BatchCommands,command]
;
TOF_start=long(SaveParametersArray.Time_Bin_Start*10.0)
TOF_step=fix(SaveParametersArray.Time_Bin_Step*10.0)
notimebin=SaveParametersArray.Total_Time_Bin_Number
TimeBinIndices=SaveParametersArray.TimeBinIndices
TOF_start=strtrim(string(TOF_start),2)
TOF_step=strtrim(string(TOF_step),2)
notimebin=strtrim(string(notimebin),2)
str=strtrim(string(TimeBinIndices[0]),2)+','
for l = 1,12 do begin
str+=strtrim(string(TimeBinIndices[l]),2)+','
endfor
str+=strtrim(string(TimeBinIndices[13]),2)
TimeBinIndices=str
command='hm genbin '+TOF_start+' '+TOF_step+' '+notimebin
BatchCommands=[BatchCommands,command]
command='hm init'
BatchCommands=[BatchCommands,command]
command='TimeBinIndices '+TimeBinIndices
BatchCommands=[BatchCommands,command]
;
Emid=strtrim(string(SaveParametersArray.Em),2)
Emax=strtrim(string(SaveParametersArray.E_upper),2)
Emin=strtrim(string(SaveParametersArray.E_lower),2)
command='Emid '+Emid
BatchCommands=[BatchCommands,command]
command='Emax '+Emax
BatchCommands=[BatchCommands,command]
command='Emin '+Emin
BatchCommands=[BatchCommands,command]
;
;
;print,'H BatchCommands: ',BatchCommands
end
'temperature':    $
begin
command='drive temperature '
argument=strtrim(Table_Contents[1,i],2)
parameters=['tolerance','settle','maxwait']
for k = 0,2 do begin
if strpos(argument,parameters[k]) ne -1 then command = 'temperature '
endfor
command+=argument
;print,'command  = ',command
BatchCommands=[BatchCommands,command]
;print,'T BatchCommands: ',BatchCommands
end
'field':    $
begin
command='drive mf '+strtrim(Table_Contents[1,i],2)
BatchCommands=[BatchCommands,command]
end
'count':    $
begin
command='count monitor '+strtrim(Table_Contents[1,i],2)
BatchCommands=[BatchCommands,command]
end
'wait':    $
begin
command='wait '+strtrim(Table_Contents[1,i],2)
BatchCommands=[BatchCommands,command]
end
;
'drive':    $
begin
command='drive '+strtrim(Table_Contents[1,i],2)
BatchCommands=[BatchCommands,command]
end
ELSE:   $
begin
command=entry+' '+strtrim(Table_Contents[1,i],2)
BatchCommands=[BatchCommands,command]
end
;
endcase
endfor
*(*pState_MB).BatchCommands=BatchCommands
ENDELSE

viewfile,event
return
end
'Delete':    $
begin
;find selected area
selected_cells = WIDGET_INFO(Command_Table, /TABLE_SELECT)
;print,'selected_cells = ',selected_cells
StartRow=selected_cells[1]
EndRow=selected_cells[3]
Table_Contents_New=strarr(2,200)

rowindex=where(Table_Contents ne '',count)
rows=1+rowindex[count-1]/2
;rows=count/2
;print,'rows: ',rows
if StartRow ge rows then return
if EndRow ge rows then EndRow=rows-1
;
; print,'Endrow: ',Endrow
;print,'rows: ',rows

    if Endrow eq rows-1 then begin
;print,'StartRow1: ',StartRow
;print,'Endrow1: ',Endrow

       if StartRow ne 0 then Table_Contents_New[*,0:StartRow-1]=Table_Contents[*,0:StartRow-1]


    endif else begin
       if StartRow ne 0 then Table_Contents_New[*,0:StartRow-1]=Table_Contents[*,0:StartRow-1]

;
;print,'StartRow2: ',StartRow
;print,'Endrow2: ',Endrow

    Table_Contents_New[*,StartRow:(StartRow+rows-2-Endrow)]=Table_Contents[*,EndRow+1:rows-1]

    endelse

Table_Contents=Table_Contents_New
rowindex=where(Table_Contents ne '',count)

if count eq 0 then begin
Table_Contents=strarr(2,200)
ForegroundColors=intarr(3,400)
(*pState_MB).Table_Contents=Table_Contents
widget_control, Command_Table,set_value=Table_Contents
(*pState_MB).ForegroundColors=ForegroundColors
widget_control, Command_Table,set_table_select=[0,0,0,0]
return
endif

rows=1+rowindex[count-1]/2
;rows=count/2
ForegroundColors=intarr(3,400)
color=[0,0,255]
for i=0,rows-1 do begin
if Table_Contents[0,i] eq 'sample' then color=[0,0,255]
if Table_Contents[0,i] eq 'temperature' then color=[255,0,0]
if Table_Contents[0,i] eq 'count' then color=[0,255,0]
if Table_Contents[0,i] eq 'wait' then color=[255,171,127]
if Table_Contents[0,i] eq 'instrument_file' then color=[255,0,255]
if Table_Contents[0,i] eq 'field' then color=[120,150,70]
ForegroundColors[*,i*2]=color
ForegroundColors[*,i*2+1]=color
endfor
widget_control, Command_Table,set_value=Table_Contents
widget_control, Command_Table,foreground_color=ForegroundColors
(*pState_MB).Table_Contents=Table_Contents
(*pState_MB).ForegroundColors=ForegroundColors
end
;
'Insert':    $
begin
;find selected area
selected_cells = WIDGET_INFO(Command_Table, /TABLE_SELECT)
;print,'selected_cells = ',selected_cells
StartRow=selected_cells[1]
EndRow=selected_cells[3]
Table_Contents_New=strarr(2,200)
;help,
rowindex=where(Table_Contents ne '',count)
rows=1+rowindex[count-1]/2
if StartRow ge rows then return
if StartRow ne 0 then Table_Contents_New[*,0:StartRow-1]=Table_Contents[*,0:StartRow-1]
Table_Contents_New[*,StartRow:EndRow]=''
;print,'StartRow: ',StartRow
;print,'EndRow: ',EndRow
Table_Contents_New[*,EndRow+1:*]=Table_Contents[*,StartRow:199-(EndRow-StartRow+1)]
Table_Contents=Table_Contents_New
rowindex=where(Table_Contents ne '',count)
rows=1+rowindex[count-1]/2
ForegroundColors=intarr(3,400)
color=[0,0,255]
for i=0,rows-1 do begin
if Table_Contents[0,i] eq 'sample' then color=[0,0,255]
if Table_Contents[0,i] eq 'temperature' then color=[255,0,0]
if Table_Contents[0,i] eq 'count' then color=[0,255,0]
if Table_Contents[0,i] eq 'wait' then color=[255,171,127]
if Table_Contents[0,i] eq 'instrument_file' then color=[255,0,255]
if Table_Contents[0,i] eq 'field' then color=[120,150,70]
ForegroundColors[*,i*2]=color
ForegroundColors[*,i*2+1]=color
endfor
widget_control, Command_Table,set_value=Table_Contents
widget_control, Command_Table,foreground_color=ForegroundColors
(*pState_MB).Table_Contents=Table_Contents
(*pState_MB).ForegroundColors=ForegroundColors
end
'Copy_Rows':    $
begin
;find selected area
selected_cells = WIDGET_INFO(Command_Table, /TABLE_SELECT)
;print,'selected_cells = ',selected_cells
StartRow=selected_cells[1]
EndRow=selected_cells[3]
Table_Contents_Copy=(*pState_MB).Table_Contents_Copy
 ;
 for i = StartRow, EndRow do begin
 Table_Contents_copy[0,i-StartRow]=Table_Contents[0,i]
 Table_Contents_copy[1,i-StartRow]=Table_Contents[1,i]
 endfor
(*pState_MB).Table_Contents_Copy=Table_Contents_copy
end
'Paste_Rows':    $
begin
Table_Contents_copy=(*pState_MB).Table_Contents_Copy
void=where(Table_Contents_copy ne '',count)
if count eq 0 then return
rows=count/2
selected_cells = WIDGET_INFO(Command_Table, /TABLE_SELECT)
;print,'selected_cells = ',selected_cells
StartRow=selected_cells[1]
ForegroundColors=intarr(3,400)
for i=0,rows-1 do begin
Table_Contents[0,StartRow+i]=Table_Contents_copy[0,i]
Table_Contents[1,StartRow+i]=Table_Contents_copy[1,i]
endfor
total_cells=max(where(Table_Contents ne '',count))
total_rows=(total_cells+1)/2
color=[0,0,255]
for i = 0, total_rows-1 do begin
if Table_Contents[0,i] eq 'sample' then color=[0,0,255]
if Table_Contents[0,i] eq 'temperature' then color=[255,0,0]
if Table_Contents[0,i] eq 'count' then color=[0,255,0]
if Table_Contents[0,i] eq 'wait' then color=[255,171,127]
if Table_Contents[0,i] eq 'instrument_file' then color=[255,0,255]
if Table_Contents[0,i] eq 'field' then color=[120,150,70]
ForegroundColors[*,i*2]=color
ForegroundColors[*,i*2+1]=color
endfor
widget_control, Command_Table,set_value=Table_Contents
widget_control, Command_Table,foreground_color=ForegroundColors
(*pState_MB).Table_Contents=Table_Contents
(*pState_MB).ForegroundColors=ForegroundColors
end
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro BatchWrite,event,BatchCommands


   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
    void=dialog_message(dialog_parent=event.top,/error, $
    'The code compiled but the batch file could not be generated')
return
endif

widget_control,event.top,get_uvalue = pState_MB3
main_event=(*pState_MB3).main_event
widget_control,main_event.top,get_uvalue = pState_MB
workDir=(*pState_MB).workDir
Command_Table=(*pState_MB).command_table
listarr=*(*pState_MB).listarr
limit_structure=(*pState_MB).limit_structure
;limit_structure= {DeviceName:DeviceName, $
;             temp_low:temp_low, $
;          temp_high:temp_high, $
;          field_low:field_low, $
;          field_high:field_high, $
;          count_low:count_low, $
;          count_high:count_high, $
;          wait_low:wait_low, $
;          wait_high:wait_high, $
;          maxwait:maxwait, $
;          settle:settle, $
;          tolerance:tolerance}

temp_low=float(limit_structure.temp_low)
temp_high=float(limit_structure.temp_high)
field_low=float(limit_structure.field_low)
field_high=float(limit_structure.field_high)
count_low=long64(limit_structure.count_low)
count_high=long64(limit_structure.count_high)
wait_low=long(limit_structure.wait_low)
wait_high=long(limit_structure.wait_high)


;
;clear the current table
;
Table_Contents=strarr(2,200)
ForegroundColors=intarr(3,400)
(*pState_MB).Table_Contents=Table_Contents
widget_control, Command_Table,set_value=Table_Contents
(*pState_MB).ForegroundColors=ForegroundColors
widget_control, Command_Table,set_table_select=[0,0,0,0]

command=strarr(200)
n=0
for i = 0,199 do begin
if BatchCommands[i] ne '' then begin
command[n]=BatchCommands[i]
n+=1
endif
endfor
n-=1
;print,'number of lines = ', n

color=intarr(3,1)
for i=0,n-1 do begin
temp=strsplit(command[i],/extract) ;note! space or tab
if n_elements(temp) eq 1 then temp=[strtrim(temp,2),'']
temp[0]=strtrim(temp[0],2)
temp[1]=strtrim(temp[1],2)
temp[0] = strlowcase(temp[0]); case errors
if temp[0] eq 'instrumentfile' then temp[0]  = 'instrument_file' ; common mistake
;
if listarr[0] ne 'No List' then begin ;object filter + look out for 'instrument_file'
void=where(listarr eq temp[0],count)
    if count eq 0 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'The command '''+temp[0]+''' is not valid')
return
    endif
endif

Table_Contents[0,i]=temp[0]
Table_Contents[1,i]=temp[1]
elements = n_elements(Temp)
if elements ge 3 then begin
for j = 2, elements-1 do begin
Table_Contents[1,i]+=' '+temp[j]
endfor
endif

; at this point we have to check whether all the parameters are within the specfied limits
Usual_fields=['sample','temperature','count','wait','instrument_file','field']

;TEMPERATURE
IF temp[0] EQ Usual_fields[1] THEN BEGIN
    if temp[1] eq '' then begin
    void=dialog_message(dialog_parent=event.top,'temperature field missing',/error)
    return
    endif
    ;convert to float if elements=2
    IF elements eq 2 then begin
    temp[1]=float(temp[1])
    ;
    if (temp[1] lt temp_low) or (temp[1] gt temp_high) then begin
    void=dialog_message(dialog_parent=event.top, $
    'Set temperature Must Be Between '+strtrim(string(temp_low),2)+ $
    ' and '+strtrim(string(temp_high),2)+' K',/error)
    return
    endif
    ENDIF
ENDIF
;COUNT
IF temp[0] EQ Usual_fields[2] THEN BEGIN
    if temp[1] eq '' then begin
    void=dialog_message(dialog_parent=event.top,'count field missing',/error)
    return
    endif
    ;
    ;convert to long64
    temp[1]=long64(temp[1])
    if (temp[1] lt count_low) or (temp[1] gt count_high) then begin
    void=dialog_message(dialog_parent=event.top, $
    'Set count Must Be Between '+strtrim(string(count_low),2)+ $
    ' and '+strtrim(string(count_high),2)+' Monitor counts',/error)
    return
    endif
ENDIF
;WAIT
IF temp[0] EQ Usual_fields[3] THEN BEGIN
    if temp[1] eq '' then begin
    void=dialog_message(dialog_parent=event.top,'wait field missing',/error)
    return
    endif
    ;
    ;convert to long
    temp[1]=long(temp[1])
    if (temp[1] lt wait_low) or (temp[1] gt wait_high) then begin
    void=dialog_message(dialog_parent=event.top, $
    'Set wait Must Be Between '+strtrim(string(wait_low),2)+ $
    ' and '+strtrim(string(wait_high),2)+' Seconds',/error)
    return
    endif
ENDIF
;instrument_file
IF temp[0] EQ Usual_fields[4] THEN BEGIN
    if temp[1] eq '' or file_test(workDir+temp[1]) ne 1 then begin
    void=dialog_message(dialog_parent=event.top,'instrument file not found',/error)
    return
    endif
ENDIF
;FIELD
IF temp[0] EQ Usual_fields[5] THEN BEGIN
    if (field_low eq 0.0) and (field_high eq 0.0)  then begin
    void=dialog_message(dialog_parent=event.top,'The selected device is unable to generate a magnetic field',/error)
    return
    endif
;
    if temp[1] eq '' then begin
    void=dialog_message(dialog_parent=event.top,'Magnetic field value is missing',/error)
    return
    endif
    ;
    IF elements eq 2 then begin
    ;convert to float
    temp[1]=float(temp[1])
    if (temp[1] lt field_low) or (temp[1] gt field_high) then begin
    void=dialog_message(dialog_parent=event.top,$
    'Set Magnetic field Must Be Between '+strtrim(string(field_low),2)+ $
    ' and '+strtrim(string(field_high),2)+' Tesla',/error)
    return
    endif
    ENDIF
ENDIF
;
if temp[0] eq Usual_fields[0] then color=[0,0,255]
if temp[0] eq Usual_fields[1] then color=[255,0,0]
if temp[0] eq Usual_fields[2] then color=[0,255,0]
if temp[0] eq Usual_fields[3] then color=[255,171,127]
if temp[0] eq Usual_fields[4] then color=[255,0,255]
if temp[0] eq Usual_fields[5] then color=[120,150,70]
present=where(temp[0] eq Usual_fields)
if present eq -1 then color=[0,0,0]

ForegroundColors[*,i*2]=color
ForegroundColors[*,i*2+1]=color
endfor
(*pState_MB).Table_Contents=Table_Contents
(*pState_MB).ForegroundColors=ForegroundColors
widget_control, Command_Table,set_value=Table_Contents
widget_control, Command_Table,set_table_select=[0,n,0,n], $
foreground_color=ForegroundColors
widget_control, Command_Table,set_table_view=[0,n-14]
    void=dialog_message(dialog_parent=event.top,/information, $
    'Custom Batch file Generation Has Been Successful')
;
;'sample' [0,0,255]
;'temperature' [255,0,0]
;'count' [0,255,0]
;'wait' [255,171,127]
; 'instrument_file' [255,0,255]
; 'field'[120,150,70]
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MB_Custom_Destroy,event
widget_control,event.top,get_uvalue = pState_MB3
main_event=(*pState_MB3).main_event
daveSensitizeButtons,main_event
ptr_free,pstate_MB3
widget_control,event.top,/destroy
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MB_Generate,event
widget_control,event.top,get_uvalue = pState_MB3
widget_control,(*pState_MB3).code,get_value=CodeCommands

   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
    void=dialog_message(dialog_parent=event.top,/error, $
    'Could not execute code.  Message: '+!ERROR_STATE.MSG)
return
endif
Batchcommands=strarr(200)
m=n_elements(codecommands)
;help,codecommands
executecommand=''
for i = 0, m-1 do begin
temp=CodeCommands[i]
if temp ne '' then begin
temp=strtrim(temp,2)
    if strpos(temp,';') ne 0 then executecommand+=CodeCommands[i]+'&'
endif
endfor
;get rid of last '&'  ; not necessary, still works
length=strlen(executecommand)
executecommand=strmid(executecommand,0,length-1)
if executecommand eq '' then begin
    void=dialog_message(dialog_parent=event.top, $
    'No code to execute')
return
endif

;print,executecommand

r=execute(executecommand)

;print,'r = ',r

if r eq 0 then begin
    void=dialog_message(dialog_parent=event.top,/error, $
    'Could not execute code.  Message: '+!ERROR_STATE.MSG)
return
endif else begin
;    for i = 0,199 do begin
;    if BatchCommands[i] ne '' then print, BatchCommands[i]
;    print, BatchCommands[i]
;    endfor
BatchWrite,event,BatchCommands
endelse
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Custom_Batch_Save,event
widget_control,event.top,get_uvalue = pState_MB3
widget_control,(*pState_MB3).code,get_value=CodeCommands
workDir=(*pState_MB3).workDir
    filename=dialog_pickfile(path=workDir,$
      file='MarsCustomBatchfile.cus',/write,filter="*.cus",/fix_filter)
;
if n_elements(filename) eq 0 then return
if filename eq '' then return
;
total_rows=n_elements(CodeCommands)
openw,lun,filename,/get_lun
for i=0,total_rows-1 do begin
if CodeCommands[i] ne '' then printf,lun, CodeCommands[i]
endfor
free_lun,lun,/force
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Custom_Batch_Read,event
widget_control,event.top,get_uvalue = pState_MB3
workDir=(*pState_MB3).workDir
    filename=dialog_pickfile(path=workDir,$
      file='MarsCustomBatchfile.cus',/read,filter="*.cus",/fix_filter)
;
if n_elements(filename) eq 0 then return
if filename eq '' then return
;
;total_rows=n_elements(BatchCommands)


codecommands=strarr(500)
line=''
n=0
openr,lun,filename,/get_lun
while eof(lun) eq 0 do begin
readf,lun,line
codecommands[n]=line
n+=1
endwhile
;number of lines = n
free_lun,lun,/force

widget_control,(*pState_MB3).code,set_value=CodeCommands
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MB_Custom_Event,event
uname=widget_info(event.id,/uname)
case uname of
;
'MB_Custom_Destroy':   $
begin
MB_Custom_Destroy,event
end
'Custom_Batch_Generate':   $
begin
MB_Generate,event
end
'Custom_Batch_Save':   $
begin
Custom_Batch_Save,event
end
'Custom_Batch_Read':   $
begin
Custom_Batch_Read,event
end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MB_Custom_Create,event
widget_control,event.top,get_uvalue = pState_MB
workDir=(*pState_MB).workDir
delim=(*pState_MB).delim
main_event=event
;device,get_fontnames = fnames,set_font = '*'
;font = fnames[0]+'*24'

;times_font = get_font_name(/large, /times)
courier_font = get_font_name(/large, /courier)


CodeCommands=strarr(500)
CodeCommands[*]=''


;if file_test(!DAVE_AUXILIARY_DIR+'PSI\MARS\MB_Custom_Info.txt') eq 1 then begin
if file_test(!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MB_Custom_Info.txt') eq 1 then begin
n=0
line=''
;openr,lun,!DAVE_AUXILIARY_DIR+'PSI\MARS\MB_Custom_Info.txt',/get_lun
openr,lun,!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MB_Custom_Info.txt',/get_lun
while eof(lun) eq 0 do begin
readf,lun,line
CodeCommands[n]=line
n+=1
endwhile
;number of lines = n-1
free_lun,lun,/force
endif

; 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='Create a Custom Batch file in the IDL Language',/col, $
         group_leader=event.top,xoffset=xpos,yoffset=ypos, $
          tlb_frame_attr = 3,mbar=bar)


       filebuttons=widget_button(bar,value='File',/menu)
          openplan=widget_button(filebuttons,$
              value='Open Custom Batch file',uname='Custom_Batch_Read')
          savpb=widget_button(filebuttons,$
              value='Save Custom Batch file',uname='Custom_Batch_Save')
          doneb=widget_button(filebuttons,$
              value='Close',uname='MB_Custom_Destroy')

       actionbuttons=widget_button(bar,value='Execute',/menu)
          Generate=widget_button(actionbuttons,$
              value='Generate Batch file',uname='Custom_Batch_Generate')


;Base1=widget_base(tlb,/row)

;void = widget_button(Base1,value = 'Close',uname ='MB_Custom_Destroy')
;void = widget_button(Base1,value = 'Generate Batch file',uname ='MB_Generate')


Base2=widget_base(tlb,/row)

code = widget_text(Base2,value = CodeCommands,xsize = 110,ysize=50,/editable, font = courier_font,/scroll)

widget_control,tlb,/realize

state3 = {main_event:main_event ,$
         code:code, $
         workdir:workdir}


pState_MB3 = ptr_new(state3,/no_copy)
widget_control,tlb,set_uvalue = pState_MB3

xmanager,'MB_Custom_Create',tlb,event_handler = 'MB_Custom_Event'


end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro BatchStatus,event
   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
MB_Initialise_timer,event
return
endif

widget_control,event.top,get_uvalue = pState_MB
UnitexeUser=(*pState_MB).UnitexeUser
UnitManager=(*pState_MB).UnitManager
UnitSpy=(*pState_MB).UnitSpy
PB_Table_Contents=(*pState_MB).PB_Table_Contents
;
command='exe info'
response=sicsexecute(event,UnitSpy,command)
response=strtrim(response,2)
print,'status = ',response
print,''
;
case response of
'Idle': $ ; batch run has finished
begin
if (*pState_MB).BatchActive eq 1 then begin
    response=sicstranscomplete(event,UnitManager); complete the transact command
    print,'response = ',response
    if strpos(strlowcase(response),'error') eq -1 then begin
    void = dialog_message(dialog_parent = event.top,/information, $
    'Batch run accomplished without errors')
    endif else begin
    void = dialog_message(dialog_parent = event.top,/information, $
    'Batch run accomplished with errors: '+response)
    endelse
(*pState_MB).BatchActive=0
endif
end
'Executing MarsBatchfile.run':    $  ;still running
begin
;
;update table
;
command='exe info range'
response=sicsexecute(event,UnitSpy,command)
;response=strtrim(response,2)
split=strsplit(response,'=',/extract)
line_number=strtrim(split[3],2)
;print,'split[3] = ',line_number

;equal_sign=strpos(response,'= ',/reverse_offset)
;print,'equal_sign = ',equal_sign'
;print,'max(equal_sign) = ',max(equal_sign)
;line_number=strmid(response,0,1,/reverse_offset)
;print,'response = ',response
print,'line number = ',line_number
print,''
old_line_number=(*pState_MB).line_number
if old_line_number ne line_number then begin
(*pState_MB).PB_Table_Contents[1,line_number-1]=systime()
widget_control, (*pState_MB).PB_Command_Table,set_value=(*pState_MB).PB_Table_Contents
(*pState_MB).line_number=line_number
endif
;
if strpos((*pState_MB).PB_Table_Contents[0,line_number-1], 'count') eq 0 then begin
    if (*pState_MB).PB_Table_Contents[2,line_number-1] eq '' then begin
    command='sicsdatanumber'
    response=sicscommand(event,UnitSpy,command,datatype='string',/no_message)
    print,'data number = ',response
    (*pState_MB).PB_Table_Contents[2,line_number-1]=response
    widget_control, (*pState_MB).PB_Command_Table,set_value=(*pState_MB).PB_Table_Contents
    endif
endif
;
MB_Initialise_timer,event
end
else:   $ ; should be '-1'.  there are errors. Cannot retrieve the information this time around.  Better luck next time
begin
(*pState_MB).connectionfail+=1
    if (*pState_MB).connectionfail ne 3 then begin
    MB_Initialise_timer,event
    endif else begin
    void = dialog_message(dialog_parent = event.top,/error, $
    'Connection to SICS Has Been Lost')
    (*pstate_mb).demo_mb=1
;   Connect_Batch,event
    endelse
end
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MarsBatchEvents,event


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


widget_control,event.top,get_uvalue = pState_MB
uname=widget_info(event.id,/uname)
IF (TAG_NAMES(event, /STRUCTURE_NAME) EQ 'WIDGET_TIMER') THEN BEGIN
BatchStatus,event
return
ENDIF

case uname of
;
'Connect_MB':   $
begin
Connect_Batch,event
end
'Interrupt_MB':    $
begin
Interrupt_Batch,event
end
'MB_Custom':    $
begin
daveDeSensitizeButtons,event
MB_Custom_Create,event
end
'Save_Progress_Table':    $
begin
Save_Progress_Table,event
end
'ForceUpdate_Progress_Table':    $
begin
BatchStatus,event
end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro MARS_Batch, group_leader = group_leader,notify_ids = notify_ids,  $
        register_name = register_name,workDir = workDir

;print,'Register Name =',register_name
;;;;;;;added following 4 lines for non-modal widget action
if n_elements(group_leader) eq 0 then group_leader = 0L
if n_elements(notify_ids) eq 0 then notify_ids = [0L,0L]
if n_elements(register_name) eq 0 then register_name = 'MARS_Batch'
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
;print,'woof'
; First get the colors upon entering this program
tvlct,rorig,gorig,borig,/get
delim=path_sep()
;if file_test(!DAVE_AUXILIARY_DIR+'PSI\MARS\MB_Parameters.lim') ne 1 then begin
if file_test(!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MB_Parameters.lim') ne 1 then begin
DeviceName='Arbitrary'
temp_low=0.01
temp_high=999.0
field_low=0.0
field_high=15.0
count_low=long64(1)
count_high=long64(1000000000)
wait_low=1
wait_high=100000
;maxwait=60
;settle=60
;tolerance=10

limit_structure= {DeviceName:DeviceName, $
             temp_low:temp_low, $
          temp_high:temp_high, $
          field_low:field_low, $
          field_high:field_high, $
          count_low:count_low, $
          count_high:count_high, $
          wait_low:wait_low, $
          wait_high:wait_high};, $
;          maxwait:maxwait, $
;          settle:settle, $
;          tolerance:tolerance}


;save,filename=!DAVE_AUXILIARY_DIR+'PSI\MARS\MB_Parameters.lim',limit_structure
;save,filename=!DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MB_Parameters.lim',limit_structure
endif else begin
;restore, !DAVE_AUXILIARY_DIR+'PSI\MARS\MB_Parameters.lim'
restore, !DAVE_AUXILIARY_DIR+'PSI'+delim+'MARS'+delim+'MB_Parameters.lim'
endelse

;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(/row,group_leader = group_leader,title = 'MARS Batch Files',mbar=bar)

opt_tab=widget_tab(tlb)
CreateRun_base=widget_base(opt_tab,title='Create and Run',/row)
Progress_base=widget_base(opt_tab,title='View Progress of Batch file',/col,/base_align_center)

       filebuttons=widget_button(bar,value='File',/menu)
          openplan=widget_button(filebuttons,$
              value='Open Batch file',event_pro='Batch_Read')
          savpb=widget_button(filebuttons,$
              value='Save Batch file',event_pro='Batch_Save')
          doneb=widget_button(filebuttons,$
              value='EXIT',event_pro='MB_exit')
                           parameterlimits=widget_button(bar,value='Sample Environment',/menu)
          DefineLimits=widget_button(parameterlimits,$
              value='Define Parameter Limits',event_pro='Limits')
       helpbutton=widget_button(bar,value='Help',/menu)
          helpfile=widget_button(helpbutton,$
              value='Open Help file',event_pro='Help')

;
;
;
base_left = widget_base(CreateRun_base,/col)

void=widget_label(base_left,value='Construct Batch file')

basel1 = widget_base(base_left,/row,/align_right)
void = widget_button(basel1,value = 'sample', uname='sample',event_pro='MarsBatchTableEvents')
sample_field=cw_field(basel1,title='')


basel2 = widget_base(base_left,/row,/align_right)
void = widget_button(basel2,value = 'instrument_file', uname='instrumentfile',event_pro='MarsBatchTableEvents')
instrumentfile_field=cw_field(basel2,title='')

basel3 = widget_base(base_left,/row,/align_right)
void = widget_button(basel3,value = 'temperature / K', uname='temperature',event_pro='MarsBatchTableEvents')
temperature_field=cw_field(basel3,title='')

basel7 = widget_base(base_left,/row,/align_right)
MagnetButton = widget_button(basel7,value = 'field / T', uname='Magnet',event_pro='MarsBatchTableEvents')
Magnet_field=cw_field(basel7,title='')

if (limit_structure.field_high) eq 0.0 AND (limit_structure.field_low) eq 0.0 then begin
widget_control,Magnet_field,sensitive=0
widget_control,MagnetButton,ToolTip='The sample environment, currently selected, does not afford a magnetic field'
endif

basel4 = widget_base(base_left,/row,/align_right)
void = widget_button(basel4,value = 'count / Mon. cnts.', uname='count',event_pro='MarsBatchTableEvents')
count_field=cw_field(basel4,title='')

basel5 = widget_base(base_left,/row,/align_right)
void = widget_button(basel5,value = 'wait / sec.', uname='wait',event_pro='MarsBatchTableEvents')
wait_field=cw_field(basel5,title='')

basel6 = widget_base(base_left,/row,/align_center)


void = widget_button(basel6,value = 'Clear Table', uname='Clear',event_pro='MarsBatchTableEvents')

void = widget_button(basel6,value = 'Delete Rows', uname='Delete',event_pro='MarsBatchTableEvents')

void = widget_button(basel6,value = 'Insert Rows', uname='Insert',event_pro='MarsBatchTableEvents')

basel8 = widget_base(base_left,/row,/align_center)

void = widget_button(basel8,value = 'Copy Rows', uname='Copy_Rows',event_pro='MarsBatchTableEvents')

void = widget_button(basel8,value = 'Paste Rows', uname='Paste_Rows',event_pro='MarsBatchTableEvents')

connect_Button = widget_button(base_left,value = 'Connect to Instrument', uname='Connect_MB')


run_button = widget_button(base_left,value = 'Run Batch File', uname='Run',event_pro='MarsBatchTableEvents')


Interrupt_Button = widget_button(base_left,value = 'Interrupt Batch Run', uname='Interrupt_MB')


base_right = widget_base(CreateRun_base,/col)
base_rightu = widget_base(base_right,/col)
base_rightl = widget_base(base_right,/row,/align_center)
;base_rightl_left = widget_base(base_rightl,/row)
;base_rightl_right = widget_base(base_rightl,/row)


column_labels=['Command','Argument']
row_labels=strtrim(string(indgen(200)+1),2)

Command_Table=widget_table(base_rightu,column_widths=150,$
       column_labels=column_labels,row_labels=row_labels,xsize=2,ysize=200, $
       alignment=0,scr_ysize=305)

Table_Contents=strarr(2,200)
Table_Contents_Copy=strarr(2,200)
ForegroundColors=intarr(3,400)

processing_options=['Smart','Standard']


processing_button=cw_bgroup(base_rightl,processing_options,/exclusive,label_top='Batch Processing Options', $
           set_value = 1,/return_index,/no_release,/frame,/row,uname='BatchProcessing')


CustomCode_Button = widget_button(base_rightl,value = 'Custom Code', $
         uname='MB_Custom',ToolTip='Generate Command file In the IDL Language')

Preview_Button = widget_button(base_rightl,value = 'Preview Run file',$
        uname='Preview',ToolTip='Preview file to be Sent to SICS',event_pro='MarsBatchTableEvents')


PB_U= widget_base(Progress_base,/base_align_center,/row)
PB_L= widget_base(Progress_base,/row)



PB_column_labels=['Command','Time of Execution','File Number']
PB_row_labels=strtrim(string(indgen(1000)+1),2)

PB_Table_Contents=strarr(3,1000)
PB_Table_Contents[*,*]=''
PB_Command_Table=widget_table(PB_U,column_widths=[300,150,100],value=PB_Table_Contents, $
       column_labels=PB_column_labels,row_labels=PB_row_labels,xsize=3,ysize=1000, $
       alignment=0,scr_ysize=305)

MB_Update=cw_field(PB_L,title='Update Time / sec.',/row,value='10',xsize=10)
void = widget_button(PB_L,value = 'Force Update',$
        uname='ForceUpdate_Progress_Table')
void = widget_button(PB_L,value = 'Save Table',$
        uname='Save_Progress_Table')



centertlb,tlb
widget_control,tlb,/realize


state = { Command_Table:Command_Table, $
         Table_Contents:Table_Contents, $
         Table_Contents_Copy:Table_Contents_Copy, $
         sample_field:sample_field, $
         temperature_field:temperature_field, $
         Magnet_field:Magnet_field, $
         count_field:count_field, $
         ForegroundColors:ForegroundColors, $
         wait_field:wait_field, $
         instrumentfile_field:instrumentfile_field, $
         limit_structure:limit_structure, $
         Interrupt_Button:Interrupt_Button, $
         connect_Button:connect_Button, $
         UnitUser:0, $
         UnitexeUser:0, $
         UnitSpy:0, $
         UnitManager:0, $
         tunit:0, $
         demo_mb:1, $
         BatchCommands:ptr_new(/allocate_heap), $
         processing_button:processing_button, $
         MagnetButton:MagnetButton, $
         run_button:run_button, $
         PB_Command_Table:PB_Command_Table, $
         MB_Update:MB_Update, $
         line_number:0, $
         PB_Table_Contents:PB_Table_Contents, $
         listarr:ptr_new(/allocate_heap), $
         koennecke_pic:koennecke_pic, $
         OutputFile:'', $
         BatchActive:0, $
         connectionfail:0, $
         delim:delim, $
         workDir:workDir}




pState_MB = ptr_new(state,/no_copy)
*(*pstate_mb).listarr=['No List']
widget_control,tlb,set_uvalue = pState_MB

xmanager,register_name,tlb,event_handler = 'MarsBatchEvents',cleanup= 'MB_cleanup'

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