; $Id: tas_scan_mapper.pro,v 1.3 2008/05/22 21:10:20 kneller Exp $

pro tas_scan_mapper_populate_scantree,pstate

    parent = widget_info((*pstate).scanTree,/parent)

    widget_control,(*pstate).scanTree,/destroy
    (*pstate).scanTree = widget_tree(parent,xsize=250,ysize=300,/context_events);,/drop_events)
    folder = widget_tree((*pstate).scanTree,value='Loaded Files',/folder,/expanded)

    nleaves = (*pstate).scanContainer->count()
    for i=0,nleaves-1 do begin

        name = ''
        ref = (*pstate).scanContainer->get(position=i)
        ref->getproperty,name=name
        leaf = widget_tree(folder,value=name)

        ;OTHER PORTIONS OF THE PROGRAM RELY ON A TREE SELECTION.
        widget_control,leaf,set_tree_select=1
    endfor;i

end;tas_scan_mapper_populate_scantree
pro tas_scan_mapper_update_scantree_selection,pstate
    parent = widget_info((*pstate).scanTree,/parent)

    widget_control,(*pstate).scanTree,/destroy
    (*pstate).scanTree = widget_tree(parent,xsize=250,ysize=300,/context_events);,/drop_events)
    folder = widget_tree((*pstate).scanTree,value='Loaded Files',/folder,/expanded)

    nleaves = (*pstate).scanContainer->count()

    for i=0,nleaves-1 do begin

        name = ''
        ref = (*pstate).scanContainer->get(position=i)
        ref->getproperty,name=name
        leaf = widget_tree(folder,value=name)

        ;OTHER PORTIONS OF THE PROGRAM RELY ON A TREE SELECTION.
        if i eq (*pstate).currentscannumber then begin
            widget_control,leaf,set_tree_select=1
        endif
    endfor;i


end;tas_scan_mapper_update_scantree_selection
pro tas_scan_mapper_createContextMenu,pstate

    (*pstate).scanTreeContextMenu = widget_base((*pstate).float_controlbase,/context_menu,$
                                                /col,uname='TAS_SCAN_MAPPER_SCANTREECONTEXTMENU',$
                                                uvalue=pstate)

    (*pstate).scanTreeContextMenu_open = widget_button((*pstate).scanTreeContextMenu, value='Load File',$
                                                        uname='TAS_SCAN_MAPPER_SCANTREECONTEXTMENU_OPEN',$
                                                        uvalue=pstate)

end;tas_scan_mapper_createContextMenu



;######################################################
function tas_scan_mapper_make_floating_controls,tlb,q

    widget_control,tlb,get_uvalue=pstate
    tlb = (*pstate).tlb
    (*pstate).float_controlbase = widget_base(xoffset = 250,yoffset=250,$
                                ;xsize = 200,ysize=200,$
;                                title='Spurion2_controls',$;tas_scan_mapper_controls',$
                                title='Scan Mapper controls',$;tas_scan_mapper_controls',$
                                floating=1,group_leader=tlb,$
                                /tlb_size_events,uvalue=pstate)
checkboxyoffset = 25

    tabs = widget_tab((*pstate).float_controlbase,xsize = 500)

    tab0 = widget_base(tabs,title='Scan List')
    (*pstate).scanListTab = tab0
    tab1 = widget_base(tabs,title='General Inputs')
    tab2 = widget_base(tabs,title='Other Inputs')
    tab3 = widget_base(tabs,title='Plot Ranges',/col)
    tab4 = widget_base(tabs,title='DisplayChoices')
    tab5 = widget_base(tabs,title='Spurion List',/col)


;print,'tas_scan_mapper_make_floating_controls set current tab to 2'
widget_control,tabs,set_tab_current=1
;SPURION TEXT OUTPUT
    ;(*pstate).spurionoutputtext = widget_text(tab5,xsize=55,ysize =35)


;ADD THE SLIDER HERE:
    tab5topbase = widget_base(tab5,/row)
    (*pstate).pointchoiceslider       = widget_slider(tab5topbase,minimum=0,maximum=1)
    (*pstate).selectallpointscheckbox = cw_bgroup(tab5topbase,'Select All Points',/nonexclusive)

    (*pstate).spurionoutputlistdraw = widget_draw(tab5,xsize=400,ysize=500)
    window,/free,/pixmap,xsize=400,ysize=500
    (*pstate).spurionoutputlistpix=!d.window
;NOTE THE REALIZATION/GET_VALUE AT END OF THIS METHOD.

    (*pstate).scanTree = widget_tree(tab0,xsize=250,ysize=300);,/drop_events)
    test1 = widget_tree((*pstate).scantree,value='Scans',folder=1,/expanded)

    tas_scan_mapper_populate_scantree,pstate
    tas_scan_mapper_createContextMenu,pstate




    featurelist = ['Q','ki','kf','xhat','yhat','lattice','harmonics','incoherent',$
                   'Instr. max','Al Spheres']

    featurecolors = [(*pstate).qcolor,(*pstate).kicolor,(*pstate).kfcolor,$
                     0L,0L,(*pstate).red,long((*pstate).blue*0.4),$
                     ((*pstate).kicolor+(*pstate).kfcolor)/2,0L,(*pstate).green]

    label = widget_label(tab4,value="Display Selections",xoffset = 25,yoffset=checkboxyoffset)
    (*pstate).qcheckbox = cwo_lk_multicheckbox(tab4,obj=qcheckboxobj,$
                                                xoffset=25,yoffset=checkboxyoffset+25,$
                                                label=featurelist,$
                                                color=featurecolors)
    (*pstate).qcheckboxobj = qcheckboxobj
    (*pstate).qcheckboxobj->setchecked,intarr(n_elements(featurelist))+1

    harmlist = ['[1,1]','[1,2]','[1,3]','[1,4]','[2,1]','[2,2]','[2,3]','[2,4]',$
                '[3,1]','[3,2]','[3,3]','[3,4]','[4,1]','[4,2]','[4,3]','[4,4]']

    red = 255L
    green = 256L*red
    blue = 256L*green
    black = 0L
    yellow = red + green
    offyellow = 200L+256L*200L
    purple = blue + green
    violet = red + blue
    yellow1 = 150L+256L*150L
    yellow2 = 90L+256L*90L

    harmcolors = [red,blue,green,black,yellow,100L,100L*256L,100L*256L*256L,100L*256L*256L,$
                  red,blue,green,purple,100L,100L*256L,100L*256L*256L]
    harmcolors = spurion2_harmonic_colors()


    label = widget_label(tab4,value="Harmonic Selection *",xoffset = 300,yoffset=checkboxyoffset)
    (*pstate).harmcheckbox = cwo_lk_multicheckbox(tab4,obj=harmcheckboxobj,$
                                                  xoffset=300,yoffset=checkboxyoffset+25,$
                                                  label=harmlist,$
                                                  color=harmcolors)

    label = widget_label(tab4,value='* Note: Press "Calculate" button to' ,$
                            xoffset = 200,yoffset=checkboxyoffset+400)
    label = widget_label(tab4,value='        update spurion listing based on ',$
                            xoffset = 200,yoffset=checkboxyoffset+425)
    label = widget_label(tab4,value='        selected harmonics.',$
                            xoffset = 200,yoffset=checkboxyoffset+450)

    (*pstate).harmcheckboxobj = harmcheckboxobj
    (*pstate).harmcheckboxobj->setchecked,intarr(n_elements(harmlist))+1

    spurionlist = ['Al Primary','Al Harmonic','Al Incoherent',$
                   'Primary Elastic','Harmonic Elastic',$
                   'RL Primary','RL Harmonic','RL Incoherent']
    ;spurioncolors = [green,violet,blue,offyellow,yellow1,red,purple,green]

    spurioncolors = spurion2_spurion_colors()


    label = widget_label(tab4,value="Feature Selection",xoffset = 150,yoffset=checkboxyoffset)
    (*pstate).spurcheckbox = cwo_lk_multicheckbox(tab4,obj=spurcheckboxobj,$
                                                xoffset=150,yoffset=checkboxyoffset+25,$
                                                label=spurionlist,$
                                                color=spurioncolors)
    (*pstate).spurcheckboxobj = spurcheckboxobj
    (*pstate).spurcheckboxobj->setchecked,intarr(n_elements(spurionlist))+1

    floatcontrolcol1 = widget_base(tab2,xoffset=0,yoffset=0);,/col)
    floatcontrolcol2 = widget_base(tab2,xoffset=230,yoffset=0,/col)
    this_yo = 29
    samplecanbase = widget_base(floatcontrolcol1,$
                                xoffset=13,$
                                yoffset=this_yo,/col)
    samplecanlabel = widget_label(samplecanbase,value='Sample Can/Holder Material ',xoffset=13,yoffset=0)
    samplecanbaserow = widget_base(samplecanbase,/row,xoffset = 0,yoffset = this_yo)
    samplecanlabel = widget_label(samplecanbaserow,value='Powder Ring',yoffset=0)
    (*pstate).samplecancombo = widget_combobox(samplecanbaserow,$
                                                xoffset=50,$
                                                yoffset=0,$
                                                value=['Al','Cu','Mo'])

    scanaxisbase = widget_base(floatcontrolcol1,$
                                xoffset=13,$
                                yoffset=29+2*this_yo,/row)
    scanaxislabel = widget_label(scanaxisbase,value='Scan Axis')
    (*pstate).scanaxiscombo = widget_combobox(scanaxisbase,$
                                                xoffset=13,$
                                                yoffset=0,$
                                                value=['PointNumber',$
                                                        'h','k','l','E'])

    (*pstate).qtolfield = better_cw_field(floatcontrolcol1,$
                            xoffset=13,yoffset=54+2*this_yo,value=0.05,title='Qtol [1/'+angstrom()+']',$
                            /return_events)
    (*pstate).Etolfield = better_cw_field(floatcontrolcol1,$
                            xoffset=13,yoffset=81+2*this_yo,value=1,title='Etol [meV]',$
                            /return_events)
    (*pstate).A4field = better_cw_field(floatcontrolcol1,$
                            xoffset=0,yoffset=106+2*this_yo,value=104.0,title='A4max [deg]',$
                            /return_events)

    b1 = widget_base(floatcontrolcol2,/row)
    b2 = widget_base(floatcontrolcol2,/row)
    b3 = widget_base(floatcontrolcol2,/row)

    label = widget_label(b1,value='Qhkl values for Z-Q Plane Calculation:')

    (*pstate).zqhfield = cw_field(b2,title='Qh',value = q[0],/integer,xsize=4)
    (*pstate).zqkfield = cw_field(b2,title='Qk',value = q[1],/integer,xsize=4)
    (*pstate).zqlfield = cw_field(b2,title='Ql',value = q[2],/integer,xsize=4)
    (*pstate).qzcalculate = widget_button(b3,value='Calculate Z-Q Plane')

    if n_elements(instrument_orient) ne 2 then orient=[1,1]
    if n_elements(qetrans) ne 5 then qetrans = [1.0,2.0,0,0,14.7]

    yoffset0range = 140
    (*pstate).eranges = cwo_plotrangeloglin(tab3,$
                                     obj=erangeobj,$
                                     /row,$
                                     ;/column,$
                                     xoffset=0,$
                                     yoffset=211+yoffset0range,$
                                     xunits='?',$
                                     yunits='meV',$
                                     xlabel='x',$
                                     ylabel='dE',$
                                     frame=1,$
                                     title='E Plot ranges',$
                                     /nolog)
    (*pstate).erangeobj = erangeobj

    (*pstate).qranges = cwo_plotrangeloglin(tab3,$
                                     obj=qrangeobj,$
                                     /row,$
                                     ;/column,$
                                     xoffset=250,$;0,$
                                     yoffset=211+yoffset0range,$;0+yoffset0range,$
                                     frame=1,$
                                     title='Scattering Plane Plot ranges (1/Ang)',$
                                     xunits='1/Ang',$
                                     yunits='1/Ang',$
                                     xlabel='Qx ',$
                                     ylabel='Qy ',$
                                     /nolog)

    (*pstate).qrangeobj = qrangeobj
    (*pstate).scanranges = cwo_plotrangeloglin(tab3,$
                                     obj=scanrangeobj,$
                                     /row,$
                                     ;/column,$
                                     xoffset=0,$
                                     yoffset=93+yoffset0range,$
                                     xunits='?',$
                                     yunits='Counts',$
                                     xlabel='x',$
                                     ylabel='I',$
                                     frame=1,$
                                     title='Scan Plot ranges')
    (*pstate).scanrangeobj = scanrangeobj

    ;tas_scan_mapper_make_basic_controls,(*pstate).tlb,tab1
    parms = Spurion2_scanparms(tab1,obj=scanparmsobj,ressensitive=0)
    (*pstate).scanparmsobj = scanparmsobj
    (*pstate).scanparms = parms




    ;tas_scan_mapper_make_res_controls,(*pstate).tlb,tab4
;    return,(*pstate).float_controlbase

    widget_control,(*pstate).float_controlbase,/realize,set_uvalue=pstate

    widget_control,(*pstate).spurionoutputlistdraw,get_value=thedrawvalue
    (*pstate).spurionoutputlistvis = thedrawvalue



    xmanager,'tas_scan_mapper',(*pstate).float_controlbase,event_handler='tas_scan_mapper_event',/no_block
    return,(*pstate).float_controlbase

end;tas_scan_mapper_make_floating_controls

pro tas_scan_mapper_select_default_axis,pstate,str

        if n_elements(str) eq 0 then begin
            axisselection = 0
        endif else begin
            ;SET DEFAULT AXIS BASED ON FILE
            if str.step[0] ne 0.0 then begin
                axisselection = 1
            endif else begin
                if str.step[1] ne 0.0 then begin
                    axisselection = 2
                endif else begin
                    if str.step[2] ne 0.0 then begin
                        axisselection = 3
                    endif else begin
                        if str.step[3] ne 0.0 then begin
                            axisselection = 4
                        endif else begin
                            ;POINT NUMBER
                            axisselection = 0
                        endelse
                    endelse
                endelse
            endelse
        endelse

        if n_elements(pstate) ne 0 then begin
            widget_control,(*pstate).scanaxiscombo,set_combobox_select=axisselection
        endif

end;tas_scan_mapper_select_default_axis



pro tas_scan_mapper_open_file,event,str,startfile=startfile
    widget_control,event.handler,get_uvalue=pstate

    if n_elements(startfile) eq 0 then startfile = ''

    fn = dialog_pickfile(path = (*pstate).workdir,filter=['*.bt7','*.bt9','*.ng5','*.buf'],file=startfile)

    if fn ne '' then begin

        if file_test(fn,/read) ne 0 then begin

                len = strlen(fn)
                ext = strmid(fn,len-4,len)
                ;print,'ext=',ext

        ;        str = {abc:dblarr(3),abg:dblarr(3),cen:dblarr(4),step:dblarr(4),eif:1,dm:3.54,da:3.54,$
        ;                   o1:intarr(3),o2:intarr(3),npts:1,efix:14.7,fn:file_basename(fn),$
        ;                   data:[0],complete:0,noscan:1}
                str = {data:[0],noscan:1,fn:fn}

                (*pstate).workdir = file_dirname(fn)
                case strlowcase(ext) of
                '.buf':begin
                    tas_scan_mapper_open_buf_file,event,fn,str
                end;.buf
                '.bt9':begin
                    tas_scan_mapper_open_bt9_file,event,fn,str
                end;.bt9
                '.ng5':begin
                    tas_scan_mapper_open_bt9_file,event,fn,str
                end;.ng5
                '.bt7':begin
                    tas_scan_mapper_open_bt7_file,event,fn,str
                end;.bt7
                else:begin
                    void = dialog_message('Unrecognized file type.');print,'tas_scan_mapper_fill_scanparms else'
                    return
                endelse
                endcase

                if str.noscan eq 0 then begin
                    tas_scan_mapper_fill_scanparms,event,str

                    (*pstate).scandrawplotobj->setproperty,title=file_basename(fn)

                endif;noscan eq 0
        endif else begin
            void = dialog_message('Invalid file selection or file does not exist.')
            ;RE-OPEN, BUT DON'T MAKE ANY CHANGES.
            ;tas_scan_mapper_open_file,event,str,startfile=fn
        endelse

    endif;fn ne ''

end;tas_scan_mapper_open_file
;######################################################
pro tas_scan_mapper_fill_scanparms,event,str
        widget_control,event.handler,get_uvalue=pstate

        ;REINSTATE THE CONTROLS IF NECESSARY
        if obj_valid((*pstate).scanparmsobj) eq 0 then begin
            Qxy = hkl_to_Qxy(str.cen[0],str.cen[1],str.cen[2],$
                             str.abc[0],str.abc[1],str.abc[2],$
                             str.abg[0],str.abg[1],str.abg[2],$
                             str.o1,str.o2,$
                             /invang,zhat_hkl=zhat_hkl)

            ;zhat_hkl = round(zhat_hkl/min(zhat_hkl[where(zhat_hkl ne 0)]))
            zhat_hkl = round(zhat_hkl/min(abs(zhat_hkl[where(zhat_hkl ne 0)])))

            fc = tas_scan_mapper_make_floating_controls((*pstate).tlb,zhat_hkl)
        endif

;print,'tas_scan_mapper_fill_scanparms,str.da=',str.da

        ;PUT VALUES INTO SCANPARMS OBJ
        (*pstate).scanparmsobj->set_values,str=str

;print,'tas_scan_mapper_fill_scanparms'
;print,tag_names(str)
        tas_scan_mapper_select_default_axis,pstate,str
;        ;SET DEFAULT AXIS BASED ON FILE
;        if str.step[0] ne 0.0 then begin
;            axisselection = 1
;        endif else begin
;            if str.step[1] ne 0.0 then begin
;                axisselection = 2
;            endif else begin
;                if str.step[2] ne 0.0 then begin
;                    axisselection = 3
;                endif else begin
;                    if str.step[3] ne 0.0 then begin
;                        axisselection = 4
;                    endif else begin
;                        ;POINT NUMBER
;                        axisselection = 0
;                    endelse
;                endelse
;            endelse
;        endelse
;        widget_control,(*pstate).scanaxiscombo,set_combobox_select=axisselection


;        ;HIT GO
;        ;CALL go PROCEDURE DIRECTLY
;        tas_scan_mapper_update_plots,event,str

end;tas_scan_mapper_fill_scanparms



;######################################################
pro tas_scan_mapper_default_str,str

        str = {abc:[3.14,3.14,3.14],abg:[90,90,90.],$
               cen:[0,0,0,0.],step:[0,0,0,0.],eif:1,dm:3.5,da:3.5,$
               o1:[1,0,0],o2:[0,1,0],npts:1,efix:14.7,fn:'NO DATA READ',$
               data:[0.0],newbt7:0,$
               initfinal:0,censtep:1,$  ;str ALWAYS DEFINES SCANS IN TERMS OF cen/step, BUT
                                        ;THESE FLAGS WILL TELL HOW THE FILE DEFINED IT ORIGINALLY
                                        ;THIS WILL BE USED LATER IN A FACILITY FOR DISPLAYING SCAN DEFS.
               initstep:0,$
               complete:1,noscan:0}
end;tas_scan_mapper_default_str,str

;######################################################
pro tas_scan_mapper_open_bt7_file,event,fn,str
;help,/traceback
    catch,es
    if es ne 0 then begin
        void = dialog_message('Problem reading file: '+file_basename(fn))
        print,es
        catch,/cancel
        tas_scan_mapper_default_str,str
        return
    endif

    o1 = [-1,-1,-1]
    o2 = [-1,-1,-1]
    newbt7 = 1
    censtep = 1
    initfinal = 0
    initstep = 0

;FIRST RUN CHECK FOR NEW-NEW BT7 FORMAT.  ORIGINAL NEW BT7 FORMAT DEFINED SCANS
;WITH CEN,STEP.
;
;NEW-NEW BT7 FORMAT DEFINES SCANS AS START,STOP.  THEREFORE THE SCAN CANNOT BE
;DEFINED UNTIL npts IS DEFINED.  NOTE: npts IS IN THE scandef LINE.
;
;CHECK FOR NEW BT7 SCANS WHERE THEY ARE DEFINED IN TERMS OF START/STOP INSTEAD OF CENTER/STEP
;
;THIS INFORMATION IS IN THE ScanDescr LINE WITH EITHER NOTHING, 'S' OR 'I' AT THE END OF THE
;RANGE ITEM.  THIS CODING DETERMINES THE TYPE OF SCAN.
;
;for icheck = 0,1 do begin
;
;    if fn ne '' then begin
;            nlines = file_lines(fn)
;            s = strarr(nlines)
;            openr,lun,fn,/get_lun
;            readf,lun,s
;            free_lun,lun
;
;            wh = where(stregex(s,'#',/fold_case,/boolean) gt 0,count)
;            ;NEW BT7 SCANS HAVE orient FIELD
;            for i=0,count-1 do begin
;                theline = s[wh[i]]
;                segs = strsplit(theline,/extract)
;                if stregex(theline,'orient',/fold_case,/boolean) gt 0 then begin
;                    newbt7 = 1
;                    censtep = 0
;                    initfinal = 1
;                    initstep = 0
;                endif
;                if stregex(theline,'npoints',/fold_case,/boolean) gt 0 then begin
;                    npoints = fix(segs[1])
;                    npts = npoints
;                endif
;            endfor;count
;
;    endif;fn
;endfor;icheck


    if fn ne '' then begin
        ;FIRST CHECK TO SEE THAT THIS IS A DATA FILE AND NOT SOME ALIGNMENT SCAN
        ;FOR .bt7 FILES THIS MUST BE CHECKED IN THE DATA FIELDS.

            nlines = file_lines(fn)
            s = strarr(nlines)
            openr,lun,fn,/get_lun
            readf,lun,s
            free_lun,lun

            wh = where(stregex(s,'#',/fold_case,/boolean) gt 0,count)
            if count ne 0 then npts_collected = nlines - n_elements(wh)

            for i=0,count-1 do begin
                theline = s[wh[i]]
                segs = strsplit(theline,/extract)
                if stregex(theline,'npoints',/fold_case,/boolean) gt 0 then begin
                    npoints = fix(segs[1])
                    npts = npoints
                endif
                if stregex(theline,'ncolumns',/fold_case,/boolean) gt 0 then begin
                    ncolumns = fix(segs[1])
                endif
                if stregex(theline,'signal',/fold_case,/boolean) gt 0 then begin
                    signalcol = fix(segs[1])
                endif
                if stregex(theline,'reference',/fold_case,/boolean) gt 0 then begin
                    refcol = fix(segs[1])
                endif
                if stregex(theline,'monospacing',/fold_case,/boolean) gt 0 then begin
                    dm = double(segs[1])
                endif
                if stregex(theline,'anaspacing',/fold_case,/boolean) gt 0 then begin
                    da = double(segs[1])
                endif
                if stregex(theline,'orient',/fold_case,/boolean) gt 0 then begin

                    o1[0] = fix(segs[1])
                    o1[1] = fix(segs[2])
                    o1[2] = fix(segs[3])

                    o2[0] = fix(segs[4])
                    o2[1] = fix(segs[5])
                    o2[2] = fix(segs[6])

                    newbt7 = 1
                endif
                if stregex(theline,'lattice',/fold_case,/boolean) gt 0 then begin
                    a = double(segs[1])
                    b = double(segs[2])
                    c = double(segs[3])
                    alpha = double(segs[4])
                    beta = double(segs[5])
                    gamma = double(segs[6])
                endif
                if stregex(theline,'ScanDescr',/fold_case,/boolean) gt 0 then begin
                    newsegs = strsplit(theline,':',/regex,/extract)
                    ;print,transpose(newsegs)
                    for j=0,n_elements(newsegs)-1 do begin
                        nl = newsegs[j]
                        ;print,'tas_scan_mapper_open_bt7_file'
                        ;print,nl
                        if stregex(nl,'npts',/fold_case,/boolean) gt 0 then begin
                            ss = strsplit(nl,'=',/regex,/extract)
                            npts = fix(ss[1])
                            ;print,'npts=',npts
                        endif

                        if stregex(nl,'fixed',/fold_case,/boolean) gt 0 then begin
                            ss = strsplit(nl,'=',/regex,/extract)
                            if stregex(nl,'fixedE',/fold_case,/boolean) gt 0 then begin
                                efix = double(ss[1])
                                ;print,'efix=',efix
                            endif else begin
                                eif = fix(ss[1])
                                ;print,'eif=',eif
                            endelse
                        endif
                        if stregex(nl,'Range=E',/fold_case,/boolean) gt 0 then begin

                            ss = strsplit(nl,'=',/regex,/extract)
                            ess = strsplit(ss[2],/extract)

                            ;print,'Range=E:'

                            case n_elements(ess) of
                            3:begin
                                if strupcase(ess[n_elements(ess)-1]) eq 'S' then begin
                                    ;print,'Init/Final'
                                    e_init = double(ess[0])
                                    e_final = double(ess[1])
                                    ecen = (e_init + e_final)/2.0

                                    if npts gt 1 then begin
                                        estep = (double(ess[1])-double(ess[0]))/double(npts-1)
                                    endif else begin
                                        estep = 0.0
                                    endelse

                                endif else begin
                                    if strupcase(ess[n_elements(ess)-1]) eq 'I' then print,'Init/Step'
                                    estep = double(ess[1])
                                    if npts gt 1 then begin
                                        e_init = double(ess[0])
                                        e_final = e_init + (npts-1)*estep
                                    endif else begin
                                        e_init = double(ess[0])
                                        e_final = e_init
                                    endelse
                                    e_init = double(ess[0])
                                    ecen = (e_final + e_init)/2.0
                                endelse
                            end;3
                            else:begin
                                ;DEFAULT IS CEN/STEP
                                ecen=double(ess[0])
                                estep=double(ess[1])
                            endelse
                            endcase
                        endif
                        if stregex(nl,'Range=Q',/fold_case,/boolean) gt 0 then begin
                            ss = strsplit(nl,'=',/regex,/extract)
                            qss = strsplit(ss[2],/extract)

;                            print,'Range=Q:'
;                            print,n_elements(qss)
;                            print,qss[n_elements(qss)-1]


                            qcss = strsplit(qss[0],'~',/regex,/extract)
                            qsss = strsplit(qss[1],'~',/regex,/extract)


                            case n_elements(qss) of
                            3:begin

                                if strupcase(qss[n_elements(qss)-1]) eq 'S' then begin
                                    ;print,'Init/Final'
                                    h_init = double(qcss[0]) & h_final = double(qsss[0])
                                    h = (h_init+h_final)/2.0
                                    k_init = double(qcss[1]) & k_final = double(qsss[1])
                                    k = (k_init+k_final)/2.0
                                    l_init = double(qcss[2]) & l_final = double(qsss[2])
                                    l = (l_init+l_final)/2.0

                                    if npts gt 1 then begin
                                        hs = (h_final-h_init)/double(npts-1)
                                        ks = (k_final-k_init)/double(npts-1)
                                        ls = (l_final-l_init)/double(npts-1)
                                    endif else begin
                                        hs = 0.0
                                        ks = 0.0
                                        ls = 0.0
                                    endelse

                                endif else begin
                                    if strupcase(qss[n_elements(qss)-1]) eq 'I' then print,'Init/Step'
                                    hs = double(qsss[0])
                                    ks = double(qsss[1])
                                    ls = double(qsss[2])

                                    ;GET INIT AND FINAL THEN SPECIFY CEN.

                                    if npts gt 1 then begin

                                        h_final = double(qcss[0]) + (npts-1)*hs
                                        h_init = double(qcss[0])
                                        h = (h_final + h_init)/2.0
                                        k_final = double(qcss[1]) + (npts-1)*ks
                                        k_init  = double(qcss[1])
                                        k = (k_final + k_init)/2.0
                                        l_final = double(qcss[2]) + (npts-1)*ls
                                        l_init  = double(qcss[2])
                                        l = (l_final + l_init)/2.0
                                    endif else begin
                                        h = double(qcss[0])
                                        k = double(qcss[1])
                                        l = double(qcss[2])
                                    endelse

                                endelse

                            end;3
                            else:begin
                                ;DEFAULT IS CEN/STEP

                                h = double(qcss[0])
                                k = double(qcss[1])
                                l = double(qcss[2])

                                hs = double(qsss[0])
                                ks = double(qsss[1])
                                ls = double(qsss[2])
                            endelse
                            endcase



;;NEW FORMAT GIVES RANGE AS START, STOP
;print,'h=',h,'hs=',hs
;print,'k=',k,'ks=',ks
;print,'l=',l,'ls=',ls
                        endif
                    endfor;j

                endif
            endfor;i


            npts = npts
            abc = [a,b,c]
            abg = [alpha,beta,gamma]

            efix = efix
            ecen = ecen
            estep = estep
            dm = dm
            da = da
            eif = eif
;print,'eif=',eif
;help,h,k,l,ecen
            cen = [h,k,l,ecen]
            step = [hs,ks,ls,estep]


            ;NOTE THIS MUST BE OUTSIDE THE for LOOP!!!
            if o1[0] eq -1 then begin
                ;ORIENTATION VECTORS NOT AVAILABLE IN THE ORGINAL NEW .bt7 FILE!!!!!
                ;IN THE LATEST VERSION THEY ARE AVAILABLE
                o1 = [1,0,0]
                o2 = [0,1,0]

            endif

            data = dblarr(npts)
            if count lt nlines then begin
                for i = count,nlines-1 do begin
                    segs = strsplit(s[i],/extract)
                    data[i-count] = double(segs[signalcol-1])
                endfor;i
            endif

            complete = (npts_collected lt npts) ? 0 : 1
            str = {abc:abc,abg:abg,cen:cen,step:step,eif:eif,dm:dm,da:da,$
                   o1:o1,o2:o2,npts:npts,efix:efix,fn:file_basename(fn),$
                   data:data,newbt7:newbt7,$
                   censtep:censtep,initfinal:initfinal,initstep:initstep,$
                   complete:complete,noscan:0}
;print,'str=',str

    endif;fn

end;tas_scan_mapper_open_bt7_file
;######################################################
pro tas_scan_mapper_open_bt9_file,event,fn,str


;    catch, e_state
;    if e_state ne 0 then begin
;        str = {data:[0],noscan:1,fn:'NO DATA READ'}
;        catch,/cancel
;    endif
    catch,es
    if es ne 0 then begin
        void = dialog_message('Problem reading file: '+file_basename(fn))
        print,es
        catch,/cancel
        tas_scan_mapper_default_str,str
;        str = {abc:[3.14,3.14,3.14],abg:[90,90,90.],$
;               cen:[0,0,0,0.],step:[0,0,0,0.],eif:1,dm:3.5,da:3.5,$
;               o1:[1,0,0],o2:[0,1,0],npts:1,efix:14.7,fn:'NO DATA READ',$
;               data:[0.0],complete:1,noscan:0}
        return
    endif
    if fn ne '' then begin
        ;FIRST CHECK TO SEE THAT THIS IS A DATA FILE AND NOT SOME ALIGNMENT SCAN
        line = ''
        openr,lun,fn,/get_lun
        readf,lun,line
        free_lun,lun
        segs = strsplit(line,"'",/regex,/extract)



        if strcmp(segs[0],file_basename(fn)) eq 0 then begin
            void = dialog_message('This is not a data scan.')
            tas_scan_mapper_default_str,str
            ;str = {data:[0],noscan:1}
        endif else begin

                line = strarr(12);''

                nlines = file_lines(fn)
                openr,lun,fn,/get_lun

                readf,lun,line

                segs = strsplit(line[0],"'",/extract,/regex)

                npts = fix(segs[7])

                    segs = strsplit(line[5],/extract)
                    abc = double([segs[0],segs[1],segs[2]])
                    abg = double([segs[3],segs[4],segs[5]])

            ;;;;;        readf,lun,line  ;READ ENERGY VALUES
                    segs = strsplit(line[7],/extract)
                    efix = double(segs[2])
                    ecen = double(segs[0])
                    estep = double(segs[1])

                    dm = double(segs[3])
                    da = double(segs[4])


        ;SELECT MONO/ANA FIXED E:
            segs = strsplit(line[8],/extract)
            if strcmp(strlowcase(segs[4]),'em') eq 1 then eif = 0 else eif = 1

            segs = strsplit(line[9],/extract)
            h = double(segs[0])
            k = double(segs[1])
            l = double(segs[2])
            hs = double(segs[3])
            ks = double(segs[4])
            ls = double(segs[5])

            cen  = [h,k,l,ecen]
            step = [hs,ks,ls,estep]

        ;o1,o2
            segs = strsplit(line[3],/extract)
            o1 = fix([segs[7],segs[8],segs[9]])
            o2 = fix([segs[11],segs[12],segs[13]])

            ;NOW GET THE DATA.
            segs = strsplit(line[11])
            segs = strsplit(line[11],/extract)
            ncols = n_elements(segs)

            data = dblarr(nlines - 12)
            line = ''
            for i=12,nlines-1 do begin
                readf,lun,line
                segs = strsplit(line,/extract)
                data[i-12] = double(segs[ncols-1])
            endfor;i
            free_lun,lun


            if n_elements(data) lt npts then complete = 0 else complete = 1
            str = {abc:abc,abg:abg,cen:cen,step:step,eif:eif,dm:dm,da:da,$
                   o1:o1,o2:o2,npts:npts,efix:efix,fn:file_basename(fn),$
                   data:data,newbt7:0,$
                   censtep:1,initfinal:0,initstep:0,$
                   complete:complete,noscan:0}

            tas_scan_mapper_fill_scanparms,event,str


        endelse;fn in first line.


    endif;fn
end;tas_scan_mapper_open_bt9_file

;######################################################
pro tas_scan_mapper_open_buf_file,event,fn,str
    widget_control,event.handler,get_uvalue=pstate

;    fn = dialog_pickfile(filter='*.buf')
;    catch, e_state
;    if e_state ne 0 then begin
;;        print, 'Error index: ', e_state
;;        print, 'Error message: ', !error_state.msg
;        str = {data:[0],noscan:1,fn:'NO DATA READ'}
;        catch,/cancel
;    endif
    catch,es
    if es ne 0 then begin
        void = dialog_message('Problem reading file: '+file_basename(fn))
        print,es
        catch,/cancel
        tas_scan_mapper_default_str,str
;        str = {abc:[3.14,3.14,3.14],abg:[90,90,90.],$
;               cen:[0,0,0,0.],step:[0,0,0,0.],eif:1,dm:3.5,da:3.5,$
;               o1:[1,0,0],o2:[0,1,0],npts:1,efix:14.7,fn:'NO DATA READ',$
;               data:[0.0],complete:1,noscan:0}
        return
    endif
    if fn ne '' then begin
        line = ''
        openr,lun,fn,/get_lun

        readf,lun,line  ;READ HEADER LINE
        readf,lun,line  ;READ abc,aa,bb,cc
        segs = strsplit(line,':',/regex,/extract)
        asegs = strsplit(segs[2],/extract)
        bsegs = strsplit(segs[3],/extract)
        csegs = strsplit(segs[4],/extract)
        alphasegs = strsplit(segs[5],/extract)
        betasegs = strsplit(segs[6],/extract)
        gammasegs = strsplit(segs[7],/extract)

        abc = double([asegs[0],bsegs[0],csegs[0]])
        abg = double([alphasegs[0],betasegs[0],gammasegs[0]])

        readf,lun,line  ;READ ENERGY VALUES

        segs = strsplit(line,':',/regex,/extract)
        ecsegs = strsplit(segs[2],/extract)
        essegs = strsplit(segs[3],/extract)
        fesegs = strsplit(segs[4],/extract)
        monsegs = strsplit(segs[4],'=',/regex,/extract)

        dm = double((strsplit(monsegs[1],/extract))[0])
        da = double((strsplit(monsegs[2],/extract))[0])

        efix = double(fesegs[0])

        if stregex(fesegs[1],'ANA',/fold_case) eq 1 then eief = 1
        if stregex(fesegs[1],'MON',/fold_case) eq 1 then eief = 0

        readf,lun,line  ;READ 'SPACE' LINE WITH Qhkl AND Qstep_hkl
        segs = strsplit(line,':',/regex,/extract)
        hsegs = strsplit(segs[2],/extract)
        ksegs = strsplit(segs[3],/extract)
        lsegs = strsplit(segs[4],/extract)

        ;STEPS FOR THE SCAN
        hssegs = strsplit(segs[5],/extract)
        kssegs = strsplit(segs[6],/extract)
        lssegs = strsplit(segs[7],/extract)

        cen  = double([hsegs[0],ksegs[0],lsegs[0],ecsegs[0]])
        step = double([hssegs[0],kssegs[0],lssegs[0],essegs[0]])
        eif = eief

        readf,lun,line  ;READ ORIENTATION LINE
        segs = strsplit(line,':',/regex,/extract)
        o1segs = strsplit(segs[2],',',/extract)

        o1vals = double([o1segs[0],o1segs[1],o1segs[2]])
        o1     = round(o1vals/min(o1vals[where(o1vals ne 0)]))

        o2segs = strsplit(segs[4],',',/extract)
        o2vals = double([o2segs[0],o2segs[1],o2segs[2]])
        o2     = round(o2vals/min(o2vals[where(o2vals ne 0)]))

        readf,lun,line  ;TEMP/H LINE
        readf,lun,line  ;TIME/MON LINE
        segs = strsplit(line,':',/regex,/extract)
        nptssegs = strsplit(segs[5],/extract)
        npts = fix(nptssegs[0])

        free_lun,lun

        data = dblarr(npts)+1
        complete = 1
;        str = {abc:abc,abg:abg,cen:cen,step:step,eif:eif,o1:o1,o2:o2,npts:npts,efix:efix,$
;               data:data,complete:complete,noscan:0}
        str = {abc:abc,abg:abg,cen:cen,step:step,eif:eif,dm:dm,da:da,$
               o1:o1,o2:o2,npts:npts,efix:efix,fn:file_basename(fn),$
               data:data,newbt7:0,$
               censtep:1,initfinal:0,initstep:0,$
               complete:complete,noscan:0}

        tas_scan_mapper_fill_scanparms,event,str
    endif;fn

end;tas_scan_mapper_open_buf_file

;######################################################
pro tas_scan_mapper_redraw,event
    widget_control,event.handler,get_uvalue=pstate

    geom = widget_info((*pstate).tlb,/geom)
    xsize = event.x;geom.xsize
    ysize = event.y;geom.ysize
    pad = 40

    offset = pad/2

    plotxsize = xsize/2 - 50
    plotysize = ysize/2 - 50

    ;widget_control,
    (*pstate).qdrawplotobj->resize,plotxsize,2*plotysize,$
                                                  xoffset=offset,yoffset=50;20;ysize/2
    ;widget_control,
    (*pstate).edrawplotobj->resize,plotxsize,plotysize,$
                                                  xoffset=xsize/2,yoffset=ysize/2
    ;widget_control,
    (*pstate).scandrawplotobj->resize,plotxsize,plotysize,$
                                                  xoffset=xsize/2,yoffset=20

    widget_control,(*pstate).statusText,xoffset=offset,yoffset=2*plotysize+60
    tas_scan_mapper_update_background,event


end;tas_scan_mapper_redraw
;######################################################
pro tas_scan_mapper_update_background,event
    widget_control,event.handler,get_uvalue=pstate

    xpad = 8
    ypad = 46

    tlb  = (*pstate).tlb
    draw = (*pstate).background
    winpix = (*pstate).backgroundpix
    winvis = (*pstate).backgroundvis
    general_update_background,(*pstate).tlb,(*pstate).background,$
                              winpix,winvis,$
                              (*pstate).soothing,xsize=event.x,ysize=event.y

    (*pstate).backgroundpix = winpix

end;tas_scan_mapper_update_background
;######################################################

pro general_update_background,tlb,draw,winpix,winvis,color,xsize=xsize,ysize=ysize

    xpad = 0;8
    ypad = 0;42

    device,get_decomposed=dc
    device,decomposed=1


    geom = widget_info(tlb,/geometry)
    if n_elements(xsize) eq 0 then xsize = geom.scr_xsize
    if n_elements(ysize) eq 0 then ysize = geom.scr_ysize

    widget_control,draw,xsize=xsize-xpad,ysize=ysize-ypad
    wdelete,winpix
    window,/free,/pixmap,xsize=xsize-xpad,ysize=ysize-ypad
    winpix = !d.window
    erase,color

    wset,winvis
    device,copy=[0,0,xsize,ysize,0,0,winpix]

    device,decomposed=dc

end;general_update_background
;######################################################


pro tas_scan_mapper_update_scanplot_axis,scanobj,energyobj,axisindex

        if n_elements(axisindex) eq 0 then axisindex = 0


        if n_elements(energyobj) gt 0 then begin
            if energyobj->count() gt 0 then begin
                eref = energyobj->get(/all)
                ;help,eref
                for i=0,n_elements(eref)-1 do begin
                    ;help,eref[i]
                    if obj_isa(eref[i],'Spurion2_data') gt 0 then begin
                        ;print,'eref'
                        eref[i]->setXAxis,axisindex
                    endif;obj_valid(eref)
                endfor;i
            endif;count
        end;ifenergyobj

        if n_elements(scanobj) gt 0 then begin
            if scanobj->count() gt 0 then begin
                sref = scanobj->get(/all)
                ;help,sref
                for i=0,n_elements(sref)-1 do begin
                    ;help,sref[i]
                    if obj_isa(sref[i],'Spurion2_data') gt 0 then begin
                        ;print,'sref'
                        sref[i]->setXAxis,axisindex
                    endif;obj_valid(sref)
                endfor;i
            endif;count
            case axisindex of
            0:xtitle = 'Point #'
            1:xtitle = 'H (rlu)'
            2:xtitle = 'K (rlu)'
            3:xtitle = 'L (rlu)'
            4:xtitle = 'E (meV)'
            else:xtitle = 'Point #'
            endcase

            energyobj->setproperty,xtitle=xtitle
            scanobj->setproperty,xtitle=xtitle

            energyobj->getdatarange,xmin=xmin,ymin=ymin,xmax=xmax,ymax=ymax
            energyobj->defaultDraw,xmin=xmin,ymin=ymin,xmax=xmax,ymax=ymax

            scanobj->getDataRange,xmin=xmin,ymin=ymin,xmax=xmax,ymax=ymax
            scanobj->defaultDraw,ymin=0.0,xmin=xmin,ymax=ymax,xmax=xmax

       endif;n_elements(scanobj)
end;tas_scan_mapper_update_scanplot_axis
function tas_scan_mapper_reduce_ovec,o
  ;LOOK FOR CASES WHERE o HAS ONLY ONE NONZERO ELEMENT.  IF SO, THEN REDUCE TO UNIT VECTOR.

  onew = o
;help,o
  if o[0] eq 0 then begin
  
    ;ONE ELEMENT NON-ZERO AND NOT 1
    if o[1] eq 0 then begin
      onew = [0,0,1]
    endif
    if o[2] eq 0 then begin
       onew = [0,1,0]
    endif

    ;TWO ELEMENTS NOT ZERO AND NOT 1, BUT EQUAL
    if o[1] eq o[2] then begin
      onew = [0,1,1]
    endif
  endif 

  if o[1] eq 0 then begin
    ;ONE ELEMENT NON-ZERO AND NOT 1
    if o[0] eq 0 then begin
      onew = [0,0,1]
    endif
    if o[2] eq 0 then begin
       onew = [1,0,0]
    endif
    ;TWO ELEMENTS NOT ZERO AND NOT 1, BUT EQUAL
    if o[0] eq o[2] then begin
      onew = [1,0,1]
    endif
  endif 

  if o[2] eq 0 then begin
    ;ONE ELEMENT NON-ZERO AND NOT 1
    if o[0] eq 0 then begin
      onew = [0,1,0]
    endif
    if o[1] eq 0 then begin
       onew = [1,0,0]
    endif
    ;TWO ELEMENTS NOT ZERO AND NOT 1, BUT EQUAL
    if o[0] eq o[1] then begin
      onew = [1,1,0]
    endif
  endif 

  ;THREE ELEMENTS ALL EQUAL
  if ((o[0] eq o[1]) and (o[1] eq o[2])) then onew = [1,1,1]


  return,onew
end;tas_scan_mapper_reduce_ovec
;##########################################################################
pro tas_scan_mapper_update_plots,event,str,noqrescale=noqrescale
t1 = systime(/seconds)
    if n_elements(noqrescale) eq 0 then noqrescale = 0
;    progbase = widget_base(xoffset=400,yoffset=400)
;    prog =  cw_progress(progbase,value=[1],title='Please Wait')
;    widget_control,progbase,/realize
    ;help,prog

    widget_control,event.handler,get_uvalue=pstate

    widget_control,(*pstate).pointchoiceslider,get_value=PointChoiceSliderValue
    ;print,'PointChoiceSliderValue=',PointChoiceSliderValue
    widget_control,(*pstate).selectAllPointsCheckbox,get_value=SelectAllPointsCheckboxValue
    ;print,'SelectAllPointsCheckboxValue=',SelectAllPointsCheckboxValue




    (*pstate).scanparmsobj->check_scattering_plane,checkScatPlane
    (*pstate).scanparmsobj->checkQClosed,checkQClosed

if checkScatPlane lt 1 or checkQClosed lt 1 then begin

    if checkScatPlane ne 1 then begin
        void = dialog_message('Unphysical Settings: Q not in scattering plane.')
        widget_control,(*pstate).statusText,set_value='Unphysical Settings: Q not in scattering plane.'
    endif

    if checkQClosed   ne 1 then begin
        void = dialog_message('Unphysical settings: Scattering Triangle does not close.')
        widget_control,(*pstate).statusText,set_value='Unphysical settings: Scattering Triangle does not close'
    endif

    if checkScatPlane ne 1 and CheckQClosed ne 1 then begin
        void = dialog_message('Unphysical settings: See status bar.')
        widget_control,(*pstate).statusText,set_value='Unphysical settings: Scattering Triangle does not close ' + $
                                                      'and Q is not in scattering plane.'
    endif

;    print,'tas_scan_mapper_update_plots: Scattering Triangle does not close.';void = dialog_message('Scattering Triangle does not close.')
;    widget_control,(*pstate).statusText,set_value='Unphysical settings: Scattering Triangle does not close'

endif else begin

    if n_elements(str) eq 0 then begin

        ;NEED TO ADD INDEX IF USER-DEFINED SCAN SO str.fn IS UNIQUE.
        nuserdefined = 0
        for i=0,(*pstate).scanContainer->count()-1 do begin
            ref = (*pstate).scanContainer->get(position=i)
            ref->getproperty,pstr=pstr
            if stregex((*pstr).fn,'USER',/fold_case,/boolean) ne 0 then nuserdefined++
        endfor;i

        vals = (*pstate).scanparmsobj->get_values(str=str)
        str.fn = str.fn+strtrim(string(nuserdefined),2)

        ;IF str IS NOT PASSED IN AS AN ARGUMENT, THEN SET THE SLIDER.
        widget_control,(*pstate).pointchoiceslider,set_value=0
        widget_control,(*pstate).pointchoiceslider,set_slider_max=str.npts-1
        widget_control,(*pstate).selectAllPointsCheckbox,set_value=1;SelectAllPointsCheckboxValue


        data = fltarr(vals.npts)+1
        fn = str.fn;'DATA'
    endif else begin
        vals = (*pstate).scanparmsobj->get_values()
        data = str.data
        fn = str.fn
    endelse

    tas_scan_mapper_select_default_axis,pstate,str

    a = vals.a
    b = vals.b
    c = vals.c
    alpha = vals.alpha
    beta = vals.beta
    gamma = vals.gamma
    h = vals.CEN[0]
    k = vals.CEN[1]
    l = vals.CEN[2]
    E = vals.CEN[3]
    npts = vals.npts

    o1h = vals.o1h
    o1k = vals.o1k
    o1l = vals.o1l
    o2h = vals.o2h
    o2k = vals.o2k
    o2l = vals.o2l
    Eifselect = vals.eif
    Efix = vals.efix

    eif = vals.eif
    Q = [h,k,l]
    ei = vals.ei
    ef = vals.ef

    o1 = [o1h,o1k,o1l]
    o2 = [o2h,o2k,o2l]

    ;042908
    ;NOW CHECK THE LEAST COMMON DENOMINATOR STATES OF o1,o2
    ;REDUCE ANY [0,0,4] TYPE o's TO [0,0,1] AT THIS STAGE.
    ;
    ;
    o1 = tas_scan_mapper_reduce_ovec(o1)
    o2 = tas_scan_mapper_reduce_ovec(o2)

;help,/heap,/brief
;print,'got some values ',systime(/seconds)-t1

    (*pstate).qdrawplotobj->setLatticeValues,abc=[a,b,c],$
                                             abg=[alpha,beta,gamma],$
                                             o1=o1,$
                                             o2=o2
;print,'set up lattice ',systime(/seconds)-t1

;help,/heap,/brief

    Qxy = hkl_to_Qxy(h,k,l,a,b,c,alpha,beta,gamma,o1,o2,$
                     invang=invang,hklunits=hklunits,zhat_hkl=zhat_hkl)


    axisindex = nse_comboindex((*pstate).scanaxiscombo)
    tas_scan_mapper_update_scanplot_axis,(*pstate).scandrawplotobj,(*pstate).edrawplotobj,axisindex


;print,'Qplot'
;help,/heap,/brief
    (*pstate).qdrawplotobj->cleardata
;print,'Eplot'
;help,/heap,/brief
    (*pstate).edrawplotobj->cleardata
;print,'scanplot'
;help,/heap,/brief
    (*pstate).scandrawplotobj->cleardata
;print,'After scanplot'
;help,/heap,/brief

;print,'cleared data ',systime(/seconds)-t1

    invang = 1
    hklunits = 0

    if widget_info((*pstate).float_controlbase,/valid_id) eq 0 then begin
        fc = tas_scan_mapper_make_floating_controls((*pstate).tlb,Q)
        ;widget_control,fc,/realize
    endif
    widget_control,(*pstate).a4field,get_value=a4

    check = closed_scat_triangle(Ei,Ef,Qxy)
;help,/heap,/brief

    if check eq 1 then begin

        lims = obj_new('spurion2_instrmax_data',ei,ef,A4,color=0L,qmax=qmax,q180max=q180max,id='SPURION2INSTRMAX')
;print,'set instr limits ',systime(/seconds)-t1



;SHOULD ALSO DO THIS FOR THE Al SPHERES.


;NEED TO GET MAXIMUM Q FOR SCAN RANGE BEFORE DEFINING 2d LATTICE.
        scanqmax = 0.0
        hvec = findgen(npts)*vals.step[0] + vals.init[0]
        kvec = findgen(npts)*vals.step[1] + vals.init[1]
        lvec = findgen(npts)*vals.step[2] + vals.init[2]
        Evec = findgen(npts)*vals.step[3] + vals.init[3]
        harmdata = obj_new('spurion2_harmonics_data',$
                                                hvec,kvec,lvec,a,b,c,$
                                                alpha,beta,gamma,o1,o2,$
                                                Evec,Efix,Eif);,$

        scanqmax = harmdata->getqxymax()
        scanqxmax = harmdata->getqxmax()
        scanqymax = harmdata->getqymax()

        obj_destroy,harmdata
        lat  = obj_new('spurion2_2dlattice_data',o1,o2,a,b,c,alpha,beta,gamma,$
                                                invang=invang,hklunits=hklunits,$
                                                scanqmax=scanqmax,$
                                                scanqxmax=scanqxmax,$
                                                scanqymax=scanqymax)
        (*pstate).qdrawplotobj->setproperty,xmaxrange=[-q180max,q180max],$
                                            ymaxrange=[-q180max,q180max],$
                                            bigtitle=fn

;print,'set 2d lattice ',systime(/seconds)-t1
        widget_control,(*pstate).qtolfield,get_value=qtol
        widget_control,(*pstate).etolfield,get_value=etol

        nharm = 4
        o1o2data = obj_new('spurion2_orientationvecs_data',a,b,c,alpha,beta,gamma,o1,o2)
;print,'set orientation vectors ',systime(/seconds)-t1



        ;DECIDE ON SAMPLE CAN MATERIAL:
        alflag = 1
        cuflag = 0
        moflag = 0

        canindex  = nse_comboindex((*pstate).samplecancombo)
        case canindex of
        0:begin
            alflag = 1
            cuflag = 0
            moflag = 0
        end;0
        1:begin
            alflag = 0
            cuflag = 1
            moflag = 0
        end;1
        2:begin
            alflag = 0
            cuflag = 0
            moflag = 1
        end;2
        else:begin
            alflag = 1
            cuflag = 0
            moflag = 0
        end;else
        endcase

        axisindex = nse_comboindex((*pstate).scanaxiscombo)
        case axisindex of
        0:begin
            usexdata = 1
            useHdata = 0
            useKdata = 0
            useLdata = 0
            useEdata = 0
        end;0
        1:begin
            usexdata = 0
            useHdata = 1
            useKdata = 0
            useLdata = 0
            useEdata = 0
        end;1
        2:begin
            usexdata = 0
            useHdata = 0
            useKdata = 1
            useLdata = 0
            useEdata = 0
        end;2
        3:begin
            usexdata = 0
            useHdata = 0
            useKdata = 0
            useLdata = 1
            useEdata = 0
        end;3
        4:begin
            usexdata = 0
            useHdata = 0
            useKdata = 0
            useLdata = 0
            useEdata = 1
        end;4
        else:begin
            usexdata = 1
            useHdata = 0
            useKdata = 0
            useLdata = 0
            useEdata = 0
        end;else
        endcase

        aldata = obj_new('spurion2_alspheres_data',color=256L*255L,cu = cuflag,mo=moflag)

;print,'set al spheres ',systime(/seconds)-t1

        ;DO FOR LOOP HERE TO MAKE ALL OF THE Q POINTS.
        ;BASICALLY SHOW 1 Q VECTOR AND ALL OF THE ELLIPSES.
        h0 = h
        k0 = k
        l0 = l
        E0 = E

        hvec = findgen(npts)*vals.step[0] + vals.init[0]
        kvec = findgen(npts)*vals.step[1] + vals.init[1]
        lvec = findgen(npts)*vals.step[2] + vals.init[2]
        Evec = findgen(npts)*vals.step[3] + vals.init[3]

;###############   BEGIN LOOP HERE    ###############;
        spurlist = ['']
        spurqs   = [0.0]
        spurlabs = ['']
        already_told_you_about_q = 0

    ;############
        for i=0,npts-1 do begin ;2 do begin;npts-1 do begin
            h = hvec[i]
            k = kvec[i]
            l = lvec[i]
            E = Evec[i]

            ;CONVERT TO Qxy
            Qxy = hkl_to_Qxy(h,k,l,a,b,c,alpha,beta,gamma,o1,o2,$
                             invang=invang,hklunits=hklunits,zhat_hkl=zhat_hkl)

    ;CHECK SCATTERING TRIANGLE AT EACH POINT
            ;E = Ei - Ef
            if eif eq 0 then begin  ;FIX INIT
                Eitemp = Efix
                Eftemp = Efix - Evec[i]
            endif else begin        ;FIX FINAL
                Eftemp = Efix
                Eitemp = Evec[i] + Efix
            endelse
            innercheck  = closed_scat_triangle(Eitemp,Eftemp,Qxy)
            if innercheck eq 1 then begin

                    ;JUST DRAW Q FOR FIRST AND LAST POINTS.
                    if (h eq vals.init[0] and $
                        k eq vals.init[1] and $
                        l eq vals.init[2] and $
                        E eq vals.init[3]) or $
                       (h eq vals.final[0] and $
                        k eq vals.final[1] and $
                        l eq vals.final[2] and $
                        E eq vals.final[3]) then begin
                            qdata = obj_new('spurion2_scanqpoint_data', h,k,l,a,b,c,alpha,beta,gamma,o1,o2,$
                                                                        E,Efix,Eif,nharm=nharm,$
                                                                        /showq,/showki,/showkf,/showsymbol,$
                                                                        already_told_you_about_q=already_told_you_about_q,$
                                                                        Qcolor  = (*pstate).Qcolor,$
                                                                        kicolor = (*pstate).kicolor,$
                                                                        kfcolor = (*pstate).kfcolor)
                    endif

;                    qincoherentdata = obj_new('spurion2_scanqpoint_incoherent_data', $
;                                                                h,k,l,a,b,c,alpha,beta,gamma,o1,o2,$
;                                                                E,Efix,Eif,nharm=4,$
;                                                                showq=0,$
;                                                                showki=0,$
;                                                                showkf=0,$
;                                                                /showsymbol,$
;                                                                /showanaincoherent,$
;                                                                /showmonoincoherent,$
;                                                                Qcolor  = (*pstate).Qcolor,$
;                                                                kicolor = (*pstate).kicolor,$
;                                                                kfcolor = (*pstate).kfcolor)
;                    (*pstate).qdrawplotobj->add,qincoherentdata,/no_draw



                    (*pstate).qdrawplotobj->add,qdata,/no_draw
                    (*pstate).qdrawplotobj->add,aldata,/no_draw

            endif;innercheck
        endfor;i
;END OF i LOOP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


        ;ALL ENERGY HARMONICS WILL BE IN A SINGLE DATA SET
        ;NOW CALCULATE ENERGY HARMONICS:
        eharmdata = obj_new('spurion2_energyharmonics_data',$
                                        hvec,kvec,lvec,a,b,c,$
                                        alpha,beta,gamma,o1,o2,$
                                        Evec,Efix,Eif,$
                                        xaxischoice=axisindex,$
                                        usexdata = usexdata,$
                                        useHdata = useHdata,$
                                        useKdata = useKdata,$
                                        useLdata = useLdata,$
                                        useEdata = useEdata);,$
                                        ;nharm=4,pointnumber=i)
;print,'set eharm data ',systime(/seconds)-t1

        (*pstate).edrawplotobj->add,eharmdata,/no_draw

        harmdata = obj_new('spurion2_harmonics_data',$
                                                hvec,kvec,lvec,a,b,c,$
                                                alpha,beta,gamma,o1,o2,$
                                                Evec,Efix,Eif);,$
                                                ;nharm=4,pointnumber=i)
        (*pstate).qdrawplotobj->add,harmdata,/no_draw

;print,'set harm data ',systime(/seconds)-t1


        qincoherentdata = obj_new('spurion2_scanqpoint_incoherent_data', $
                                                    hvec,kvec,lvec,a,b,c,$
                                                    alpha,beta,gamma,o1,o2,$
                                                    Evec,Efix,Eif,nharm=4,$
                                                    showq=0,$
                                                    showki=0,$
                                                    showkf=0,$
                                                    /showsymbol,$
                                                    /showanaincoherent,$
                                                    /showmonoincoherent,$
                                                    Qcolor  = (*pstate).Qcolor,$
                                                    kicolor = (*pstate).kicolor,$
                                                    kfcolor = (*pstate).kfcolor)
        (*pstate).qdrawplotobj->add,qincoherentdata,/no_draw


        harmcheckboxstate = (*pstate).harmcheckboxobj->getChecked()
        spurcheckboxstate = (*pstate).spurcheckboxobj->getChecked()


;print,'tas_scan_mapper_update_plots time Before Calculating Spurions ',systime(/seconds)-t1



;CHECK THE SPURION POINT SELECTION
pointchoice = -1
widget_control,(*pstate).pointchoiceslider,get_value=pointchoice
widget_control,(*pstate).selectAllPointsCheckbox,get_value=allpointschosen
if allpointschosen gt 0 then pointchoice = -1




        ;NOW LOOP OVER ALL THE Q VALUES IN THE SCAN AND CALCULATE THE SPURIONS AT
        ;EACH POINT.
        latspur = lat->getspurions(qtol,etol,hvec,kvec,lvec,a,b,c,$
                                   alpha,beta,gamma,o1,o2,evec,efix,eif,$
                                   sym=sym,$
                                   latspurQ=latspurQ,$
                                   latspursym=latspursym,$
                                   latspurincsym=latspurincsym,$
                                   latspurcap=latspurcap,pointnumber=i,$
                                   harmcheckboxstate=harmcheckboxstate,$
                                   spurcheckboxstate=spurcheckboxstate,$
                                   pointchoice=pointchoice)

;print,'tas_scan_mapper_update_plots time after Calculated Lat Spurions ',systime(/seconds)-t1

        alspur = aldata->getspurions(qtol,etol,hvec,kvec,lvec,a,b,c,$
                                   alpha,beta,gamma,o1,o2,evec,efix,eif,$
                                   harmcheckboxstate=harmcheckboxstate,$
                                   spurcheckboxstate=spurcheckboxstate,$
                                   pointchoice=pointchoice););,$
                                   ;sym=sym);,$
                                   ;latspurQ=latspurQ,$
                                   ;latspursym=latspursym,$
                                   ;latspurincsym=latspurincsym,$
                                   ;latspurcap=latspurcap,pointnumber=i);,$

spurlist = [latspur.latspurcap,alspur.alspurcap]
spurcolors = [latspur.latspurcolor,alspur.alspurcolor]

;print,'tas_scan_mapper_update_plots Calculated Al Spurions ',systime(/seconds)-t1


;print,'######################################################'
if widget_info((*pstate).spurionoutputtext,/valid_id) ne 0 or $
    widget_info((*pstate).spurionoutputlistdraw,/valid_id) ne 0 then begin
    ;print,'######################################################'
    ;print,'TEST'
    ;print,'Spurlist='
    ;print,transpose(spurlist)
;    widget_control,(*pstate).spurionoutputtext,set_value=spurlist
!p.font=1
    wset,(*pstate).spurionoutputlistpix
    plot,[0,1],[0,1],background=((2L)^24)-1,/nodata,xstyle=4,ystyle=4,position=[0,0,1,1]

    listoffset = 0.0
    xco = 0.05
    yco = 0.96
    xc = xco
    yc = yco - listoffset
    xyouts,xc-0.05,yc,'Reciprocal Lattice Spurions',color=0L,/normal
    listoffset += 0.03
    for iii=0,n_elements(latspur.latspurcap)-1 do begin;spurlist)-1 do begin
        xc = xco
        yc = yco - listoffset
        listoffset += 0.03
        ;xyouts,xc,yc,spurlist[iii],color=latspur.latspurcolor[iii];spurcolors[iii]
        xyouts,xc,yc,latspur.latspurcap[iii],color=latspur.latspurcolor[iii],/normal,charsize=1.15
    endfor;iii
    yc = yco - listoffset
    xyouts,xc-0.05,yc,'Sample Can Spurions',color=0L,/normal
    listoffset += 0.03
    for iii=0,n_elements(alspur.alspurcap)-1 do begin;spurlist)-1 do begin
        xc = xco
        yc = yco - listoffset
        listoffset += 0.03
        ;xyouts,xc,yc,spurlist[iii],color=spurcolors[iii]
        xyouts,xc,yc,alspur.alspurcap[iii],color=alspur.alspurcolor[iii],/normal,charsize=1.15
    endfor;iii

    wset,(*pstate).spurionoutputlistvis
    device,copy=[0,0,400,500,0,0,(*pstate).spurionoutputlistpix]
endif




;spurobj = obj_new('Spurion2_spurions_data',spurqs,spurlabs,color=256L*256L*255L)


latspurobj = obj_new('Spurion2_spurions_data',latspur.pointnumber,$
                                              latspur.latspurcap,$
                                              latspur.latspursym,$
                                              latspur.latspurcolor,$
                                              latspur.latspurEnergy,$
                                              latspur.latspurQ,$
                                              data,$
                                              evec=evec,hvec=hvec,$
                                              kvec=kvec,lvec=lvec,$
                                              xaxischoice=axisindex,$
                                              usexdata = usexdata,$
                                              useHdata = useHdata,$
                                              useKdata = useKdata,$
                                              useLdata = useLdata,$
                                              useEdata = useEdata,$
                                              color=255L)
;print,'made lat spurions ',systime(/seconds)-t1

alspurobj = obj_new('Spurion2_spurions_data',alspur.pointnumber,$
                                             alspur.alspurcap,$
                                             alspur.alspursym,$
                                             alspur.alspurcolor,$
                                             alspur.alspurEnergy,$
                                             alspur.alspurQ,$
                                             data,$
                                             evec=evec,hvec=hvec,$
                                             kvec=kvec,lvec=lvec,$
                                             xaxischoice=axisindex,$
                                             usexdata = usexdata,$
                                             useHdata = useHdata,$
                                             useKdata = useKdata,$
                                             useLdata = useLdata,$
                                             useEdata = useEdata,$
                                             color=255L)
;print,'made Al Spurions ',systime(/seconds)-t1

energylatspurobj = obj_new('Spurion2_spurions_data',latspur.pointnumber,$
                                                    latspur.latspurcap,$
                                                    latspur.latspursym,$
                                                    latspur.latspurcolor,$
                                                    latspur.latspurEnergy,$
                                                    latspur.latspurQ,$
                                                    /energy,$
                                                    evec=evec,hvec=hvec,$
                                                    kvec=kvec,lvec=lvec,$
                                                    xaxischoice=axisindex,$
                                                    usexdata = usexdata,$
                                                    useHdata = useHdata,$
                                                    useKdata = useKdata,$
                                                    useLdata = useLdata,$
                                                    useEdata = useEdata,$
                                                    color=255L)

energyalspurobj = obj_new('Spurion2_spurions_data',alspur.pointnumber,$
                                                   alspur.alspurcap,$
                                                   alspur.alspursym,$
                                                   alspur.alspurcolor,$
                                                   alspur.alspurEnergy,$
                                                   alspur.alspurQ,$
                                                   /energy,$
                                                   evec=evec,hvec=hvec,$
                                                   kvec=kvec,lvec=lvec,$
                                                   xaxischoice=axisindex,$
                                                   usexdata = usexdata,$
                                                   useHdata = useHdata,$
                                                   useKdata = useKdata,$
                                                   useLdata = useLdata,$
                                                   useEdata = useEdata,$
                                                   color=255L)
;print,'Two more spurions ',systime(/seconds)-t1

;alspurobj = obj_new('Spurion2_spurions_data',alspurq,alspur,color=255L*256L)

        ;RESET THE VALUES TO THE CENTERS AT THE END OF THE SCAN.
        h = h0
        k = k0
        l = l0
        E = E0

        Qxy = hkl_to_Qxy(h,k,l,a,b,c,alpha,beta,gamma,o1,o2,$
                         invang=invang,hklunits=hklunits,zhat_hkl=zhat_hkl)

    ;ADD THE NEW DATA TO THE PLOTS.
    ;NOTE: THE SPURIONS CONSTITUTE A NEW DATA SET.
        format = '(f6.2)'

        zhat_hkl = round(zhat_hkl/min(abs(zhat_hkl[where(zhat_hkl ne 0)])))

        (*pstate).qdrawplotobj->setproperty,bigtitle=fn,$;'ADD THE BIG TITLE HERE IN tas_scan_mapper_update_plots',$
                                    title='Scat plane perp to z=['+ $
                                    strtrim(string(zhat_hkl[0]/max(zhat_hkl),format=format),2)+','+ $
                                    strtrim(string(zhat_hkl[1]/max(zhat_hkl),format=format),2)+','+ $
                                    strtrim(string(zhat_hkl[2]/max(zhat_hkl),format=format),2)+']'
        (*pstate).qdrawplotobj->add,lims,/no_draw
        (*pstate).qdrawplotobj->add,lat,/no_draw
        (*pstate).qdrawplotobj->add,o1o2data,/no_draw
        if noqrescale eq 0 then $
            (*pstate).qdrawplotobj->setDataRange,xmin=-qmax,xmax=qmax,$
                                                 ymin=-qmax,ymax=qmax,$
                                                 /no_draw
        (*pstate).qdrawplotobj->draw;,a,b,c,alpha,beta,gamma,o1,o2

        (*pstate).edrawplotobj->add,energylatspurobj,/no_draw
        (*pstate).edrawplotobj->add,energyalspurobj,/no_draw

        (*pstate).edrawplotobj->getdatarange,xmin=xmin,ymin=ymin,xmax=xmax,ymax=ymax
        (*pstate).edrawplotobj->defaultDraw,xmin=xmin,ymin=ymin,xmax=xmax,ymax=ymax

;        (*pstate).edrawplotobj->defaultdraw



;HOW IS 'data' BEING CHOSEN IN THE FILE READER, SPECIFICALLY FOR .bt7 FILES??????
;
;help,/traceback
        dataobj = obj_new('Spurion2_data',findgen(n_elements(data)),data,$
                                                        evec=evec,$
                                                        hvec=hvec,$
                                                        kvec=kvec,$
                                                        lvec=lvec,$
                                                        psym=-8,color=0L,$
                                                        showlegend=1,id=fn,$
                                                        xaxischoice=axisindex,$
                                                        usexdata = usexdata,$
                                                        useHdata = useHdata,$
                                                        useKdata = useKdata,$
                                                        useLdata = useLdata,$
                                                        useEdata = useEdata,$
                                                        legend=fn)

;print,'set data ',systime(/seconds)-t1


red = 255L
green = 256L*red
blue = 256L*green
black = 0L
yellow = red + green
offyellow = 200L+256L*200L
purple = blue + green
violet = red + blue
yellow1 = 150L+256L*150L
yellow2 = 90L+256L*90L
spurioncolor = spurion2_spurion_colors()
spurionsymbol = spurion2_spurion_symbols()
spurionlabel = spurion2_spurion_labels()

        Alharm1spurlegend =  obj_new('Spurion2_data',$
                                      findgen(n_elements(data)),data,$
                                      evec=evec,$
                                      hvec=hvec,$
                                      kvec=kvec,$
                                      lvec=lvec,$
                                      xaxischoice=axisindex,$
                                      showdata=0,$
                                      psym=spurionsymbol[0],$;8,$
                                      color=spurioncolor[0],$;green,$
                                      showlegend=1,id=fn,$
                                      legend=spurionlabel[0]);'Al Primary')
        Alharm2spurlegend =  obj_new('Spurion2_data',$
                                      findgen(n_elements(data)),data,$
                                      evec=evec,$
                                      hvec=hvec,$
                                      kvec=kvec,$
                                      lvec=lvec,$
                                      xaxischoice=axisindex,$
                                      showdata=0,$
                                      psym=spurionsymbol[1],$;8,$
                                      color=spurioncolor[1],$;violet,$
                                      showlegend=1,id=fn,$
                                      legend=spurionlabel[1]);'Al Harmonic')
        Alharm3spurlegend =  obj_new('Spurion2_data',$
                                      findgen(n_elements(data)),data,$
                                      evec=evec,$
                                      hvec=hvec,$
                                      kvec=kvec,$
                                      lvec=lvec,$
                                      xaxischoice=axisindex,$
                                      showdata=0,$
                                      psym=spurionsymbol[2],$;8,$
                                      color=spurioncolor[2],$;blue,$
                                      showlegend=1,id=fn,$
                                      legend=spurionlabel[2]);'Al Incoherent')
        ElasticPrimaryspurlegend =  obj_new('Spurion2_data',$
                                      findgen(n_elements(data)),data,$
                                      evec=evec,$
                                      hvec=hvec,$
                                      kvec=kvec,$
                                      lvec=lvec,$
                                      showdata=0,$
                                      xaxischoice=axisindex,$
                                      psym=spurionsymbol[3],$;7,$
                                      color=spurioncolor[3],$;offyellow,$
                                      showlegend=1,id=fn,$
                                      legend=spurionlabel[3]);'Primary Elastic')
        ElasticHarmspurlegend =  obj_new('Spurion2_data',$
                                      findgen(n_elements(data)),data,$
                                      evec=evec,$
                                      hvec=hvec,$
                                      kvec=kvec,$
                                      lvec=lvec,$
                                      xaxischoice=axisindex,$
                                      showdata=0,$
                                      psym=spurionsymbol[4],$;7,$
                                      color=spurioncolor[4],$;yellow1,$
                                      showlegend=1,id=fn,$
                                      legend=spurionlabel[4]);'Harmonic Elastic')
        RLharm1spurlegend =  obj_new('Spurion2_data',$
                                      findgen(n_elements(data)),data,$
                                      evec=evec,$
                                      hvec=hvec,$
                                      kvec=kvec,$
                                      lvec=lvec,$
                                      xaxischoice=axisindex,$
                                      showdata=0,$
                                      psym=spurionsymbol[5],$;4,$
                                      color=spurioncolor[5],$;red,$
                                      showlegend=1,id=fn,$
                                      legend=spurionlabel[5]);'RL Primary')
        RLharm2spurlegend =  obj_new('Spurion2_data',$
                                      findgen(n_elements(data)),data,$
                                      evec=evec,$
                                      hvec=hvec,$
                                      kvec=kvec,$
                                      lvec=lvec,$
                                      xaxischoice=axisindex,$
                                      showdata=0,$
                                      psym=spurionsymbol[6],$;4,$
                                      color=spurioncolor[6],$;purple,$
                                      showlegend=1,id=fn,$
                                      legend=spurionlabel[6]);'RL Harmonic')
        RLharm3spurlegend =  obj_new('Spurion2_data',$
                                      findgen(n_elements(data)),data,$
                                      evec=evec,$
                                      hvec=hvec,$
                                      kvec=kvec,$
                                      lvec=lvec,$
                                      xaxischoice=axisindex,$
                                      showdata=0,$
                                      psym=spurionsymbol[7],$;6,$
                                      color=spurioncolor[7],$;green,$
                                      showlegend=1,id=fn,$
                                      legend=spurionlabel[7]);'RL Incoherent')


        (*pstate).scandrawplotobj->add,spurobj,/no_draw
        (*pstate).scandrawplotobj->add,latspurobj,/no_draw
        (*pstate).scandrawplotobj->add,alspurobj,/no_draw
        (*pstate).scandrawplotobj->add,dataobj,/no_draw

;ADD SPURION LEGENDS TO SCAN PLOT.
        (*pstate).scandrawplotobj->add,Alharm1spurlegend,/no_draw
        (*pstate).scandrawplotobj->add,Alharm2spurlegend,/no_draw
        (*pstate).scandrawplotobj->add,Alharm3spurlegend,/no_draw

        (*pstate).scandrawplotobj->add,ElasticPrimaryspurlegend,/no_draw
        (*pstate).scandrawplotobj->add,ElasticHarmspurlegend,/no_draw

        (*pstate).scandrawplotobj->add,RLharm1spurlegend,/no_draw
        (*pstate).scandrawplotobj->add,RLharm2spurlegend,/no_draw
        (*pstate).scandrawplotobj->add,RLharm3spurlegend,/no_draw



        (*pstate).scandrawplotobj->getDataRange,xmin=xmin,ymin=ymin,xmax=xmax,ymax=ymax

        (*pstate).scandrawplotobj->defaultDraw,ymin=0.0,xmin=xmin,ymax=ymax,xmax=xmax


        tas_scan_mapper_event,{handler:(*pstate).tlb,id:(*pstate).spurcheckbox}
        tas_scan_mapper_event,{handler:(*pstate).tlb,id:(*pstate).qcheckbox}
        tas_scan_mapper_event,{handler:(*pstate).tlb,id:(*pstate).harmcheckbox}



;        (*pstate).scandrawplotobj->defaultdraw,ymin=0.0
        ;print,(*pstate).spurbase

;        if widget_info((*pstate).spurbase,/valid_id) eq 0 then begin
;            (*pstate).spurbase = widget_base(title='Spurion list:',$
;                                             group_leader=(*pstate).tlb,$
;                                             /floating)
;            (*pstate).spurlist = widget_list((*pstate).spurbase,xsize=200,ysize=30)
;            widget_control,(*pstate).spurbase,/realize
;        endif
;        widget_control,(*pstate).spurlist,set_value=spurlist

        widget_control,(*pstate).statusText,set_value='Displaying Scan: '+str.fn
    endif else begin
        print,'tas_scan_mapper_update_plots: Scattering Triangle does not close.';void = dialog_message('Scattering Triangle does not close.')
        widget_control,(*pstate).statusText,set_value='Unphysical settings: Scattering Triangle does not close'
    endelse;scat_triangle

endelse;CHECKED BOTH SCATTERING PLANE AND Q TRIANGLE CLOSED

end;tas_scan_mapper_update_plots
;######################################################
pro tas_scan_mapper_synch_plot_to_range,plotobj,rangeobj,exact=exact

    if obj_valid(rangeobj) ne 0 then begin
        plotobj->retrieveDataRanges, xmin=xmin,xmax=xmax,$
                                     ymin=ymin,ymax=ymax,$
                                     xlog=xlog,ylog=ylog

        rangeobj->setvalues,xmin=xmin,ymin=ymin,$
                                       xmax=xmax,ymax=ymax,$
                                       xlog=xlog,ylog=ylog
    endif
end;tas_scan_mapper_synch_plot_to_range
;######################################################
pro tas_scan_mapper_synch_range_to_plot,plotobj,rangeobj,exact = exact

    if n_elements(exact) eq 0 then exact = 0

    if obj_valid(rangeobj) gt 0 then begin



        dum = rangeobj->getvalues(xmin=xmin,ymin=ymin,$
                                  xmax=xmax,ymax=ymax,$
                                  xlog=xlog,ylog=ylog)

        if exact eq 0 then begin
            plotobj->updateDataRanges, xmin=xmin,xmax=xmax,$
                                         ymin=ymin,ymax=ymax,$
                                         xlog=xlog,ylog=ylog
        endif else begin
            plotobj->updateDataRanges,xlog=xlog,ylog=ylog
            plotobj->range, xmin=xmin,xmax=xmax,$
                            ymin=ymin,ymax=ymax
            plotobj->draw
        endelse
    endif

end;tas_scan_mapper_synch_plot_to_range
;######################################################
pro tas_scan_mapper_update_qzplane,event

    widget_control,event.handler,get_uvalue=pstate

    if n_elements(noqrescale) eq 0 then noqrescale = 0
    already_told_you_about_q = 0

    vals = (*pstate).scanparmsobj->get_values()
    a = vals.a
    b = vals.b
    c = vals.c
    alpha = vals.alpha
    beta = vals.beta
    gamma = vals.gamma
    h = vals.CEN[0]
    k = vals.CEN[1]
    l = vals.CEN[2]

    E = vals.CEN[3]

    o1h = vals.o1h
    o1k = vals.o1k
    o1l = vals.o1l
    o2h = vals.o2h
    o2k = vals.o2k
    o2l = vals.o2l
    Eifselect = vals.eif
    Efix = vals.efix
    Ei = vals.Ei
    Ef = vals.Ef

    eif = vals.eif

    widget_control,(*pstate).zqhfield,get_value=qh
    widget_control,(*pstate).zqkfield,get_value=qk
    widget_control,(*pstate).zqlfield,get_value=ql

    ;MAKE Q AND REDUCE IT BY LCDs
    Q = [Qh,Qk,Ql]
    minQ = 1.0
    wh_Q = where(Q ne 0,count)
    if count ne 0 then begin
        minQ = min(abs(Q[wh_Q]))
    endif
    Q = round(Q/minQ)
    qh = q[0]
    qk = q[1]
    ql = q[2]

    o1 = [o1h,o1k,o1l]
    o2 = [o2h,o2k,o2l]


    if obj_valid((*pstate).qzdrawplotobj) ne 0 then $
        (*pstate).qzdrawplotobj->cleardata

    invang = 1
    hklunits = 0

    widget_control,(*pstate).a4field,get_value=a4

    widget_control,(*pstate).qtolfield,get_value=qtol
    widget_control,(*pstate).etolfield,get_value=etol



    Qxy = hkl_to_Qxy(qh,qk,ql,a,b,c,alpha,beta,gamma,o1,o2,$
                     invang=invang,hklunits=hklunits,zhat_hkl=zhat_hkl)
    for i=0,2 do begin
        minzhat_hkl = min(abs(zhat_hkl[where(zhat_hkl ne 0)]))
        zhat_hkl = round(zhat_hkl/minzhat_hkl)
    endfor;i
    ;print,'zhat_hkl=',zhat_hkl
;NOW THAT I HAVE zhat I CAN CALCULATE THE Z-Q PLANE
    zhat_hkl = round(zhat_hkl/min(zhat_hkl))

    Qxy = hkl_to_Qxy(qh,qk,ql,a,b,c,alpha,beta,gamma,[qh,qk,ql],zhat_hkl,$
                     /invang);=invang,hklunits=hklunits)

    if Qxy[2] ne 0 then begin
        if already_told_you_about_q eq 0 then begin
            void = dialog_message('NOTE: Q not in scattering plane!')
            already_told_you_about_q = 1
        endif
    endif;Qxy[2] ne 0

    kikf = getkikf(Ei,Ef,Qxy,closed)
    ki = kikf.ki
    kf = kikf.kf

    if closed eq 1 then begin
            lims = obj_new('spurion2_instrmax_data',ei,ef,A4,color=0L,qmax=qmax,q180max=q180max)

            lat  = obj_new('spurion2_2dlattice_data',[qh,qk,ql],zhat_hkl,a,b,c,$
                                                    alpha,beta,gamma,$
                                                    invang=invang,hklunits=hklunits)
            aldata = obj_new('spurion2_alspheres_data',color=256L*255L)


        ;    o1o2data = obj_new('spurion2_orientationvecs_data',a,b,c,alpha,beta,gamma,o1,o2)


        ;DO FOR LOOP HERE TO MAKE ALL OF THE Q POINTS.
        ;BASICALLY SHOW 1 Q VECTOR AND ALL OF THE ELLIPSES.

        ;RENORMALIZE Q HERE SO THAT IT IS DISPLAYED WITH ITS PROPER LENGTH.
        qh = qh * minq
        qk = qk * minq
        ql = ql * minq
            qdata = obj_new('spurion2_scanqpoint_data', qh,qk,ql,a,b,c,alpha,beta,gamma,$
                                                        [qh,qk,ql],zhat_hkl,$
                                                        E,Efix,Eif,nharm=5,$
                                                        /showq,showki=0,showkf=0,$
                                                        /showsymbol,color=256L*256L*255L)

            plotxsize = 300
            plotysize = 300

            ;CREATE QZPLOT OBJECT IF NECESSARY
            if obj_valid((*pstate).qzdrawplotobj) eq 0 then begin
                (*pstate).qzdrawplotbase = widget_base(xoffset=0,yoffset=0,$
                                                       group_leader=(*pstate).tlb,$
                                                       /floating,uvalue=pstate,$
                                                       title='Q-Z Plane')
                (*pstate).qzdrawplot = cwo_drawplot((*pstate).qzdrawplotbase,xsize=plotxsize,ysize=plotysize,$
                                         xtitle = 'Q ['+angstrom()+'^-1]',$
                                         ytitle = 'Z   ['+angstrom()+'^-1]',$
                                         title = 'Perp Scattering Plane',$
                                         obj=qzdrawplotobj)
                ;help,qzdrawplotobj
                (*pstate).qzdrawplotobj = qzdrawplotobj
                widget_control,(*pstate).qzdrawplotbase,/realize
                xmanager,'tas_scan_mapper',(*pstate).qzdrawplotbase,/no_block

            endif


        ;ADD THE NEW DATA TO THE PLOTS.
        ;NOTE: THE SPURIONS CONSTITUTE A NEW DATA SET.
            (*pstate).qzdrawplotobj->setproperty,title='Perp to Scat Plane containing q'
            (*pstate).qzdrawplotobj->add,lims,/no_draw
            (*pstate).qzdrawplotobj->add,lat,/no_draw
            ;(*pstate).qzdrawplotobj->add,o1o2data,/no_draw
            (*pstate).qzdrawplotobj->add,qdata,/no_draw
            (*pstate).qzdrawplotobj->add,aldata,/no_draw
            ;(*pstate).qzdrawplotobj->add,harmdata,/no_draw
            (*pstate).qzdrawplotobj->setproperty,xmaxrange=[-q180max,q180max],$
                                                 ymaxrange=[-q180max,q180max]

            if noqrescale eq 0 then $
                (*pstate).qzdrawplotobj->setDataRange,xmin=-qmax,xmax=qmax,$
                                                     ymin=-qmax,ymax=qmax,$
                                                     /no_draw
            (*pstate).qzdrawplotobj->draw;,a,b,c,alpha,beta,gamma,o1,o2
    endif else begin
        void = dialog_message('Scattering Triangle did not close.')
    endelse


end;tas_scan_mapper_create_qzplane
;######################################################
pro tas_scan_mapper_cleanup,id
    widget_control,id,get_uvalue=pstate

    wdelete,(*pstate).backgroundpix

    if obj_valid((*pstate).scanContainer) gt 0 then begin
        if (*pstate).scanContainer->count() gt 0 then begin
            scanobj = (*pstate).scanContainer->get(/all)
            obj_destroy,scanobj
        endif
        obj_destroy,(*pstate).scanContainer
    endif

    if obj_valid((*pstate).harmcheckboxobj) gt 0 then obj_destroy,(*pstate).harmcheckboxobj
    if obj_valid((*pstate).qcheckboxobj) gt 0 then obj_destroy,(*pstate).qcheckboxobj
    if obj_valid((*pstate).spurcheckboxobj) gt 0 then obj_destroy,(*pstate).spurcheckboxobj

    if obj_valid((*pstate).qdrawplotobj) gt 0 then obj_destroy,(*pstate).qdrawplotobj
    if obj_valid((*pstate).edrawplotobj) gt 0 then obj_destroy,(*pstate).edrawplotobj
    if obj_valid((*pstate).scandrawplotobj) gt 0 then obj_destroy,(*pstate).scandrawplotobj
    if obj_valid((*pstate).qzdrawplotobj) gt 0 then obj_destroy,(*pstate).qzdrawplotobj

    if obj_valid((*pstate).qrangeobj)  gt 0 then obj_destroy,(*pstate).qrangeobj
    if obj_valid((*pstate).erangeobj) gt 0 then obj_destroy,(*pstate).erangeobj
    if obj_valid((*pstate).scanrangeobj)  gt 0 then obj_destroy,(*pstate).scanrangeobj

    if ptr_valid(pstate) gt 0 then ptr_free,pstate
end;tas_scan_mapper_cleanup

function tas_scan_mapper_control_values


    s = 0.0


    return,s
end;tas_scan_mapper_control_values
;######################################################
pro tas_scan_mapper_make_basic_controls,tlb,parent
    widget_control,tlb,get_uvalue=pstate
    tab1 = parent
end;tas_scan_mapper_make_basic_controls
;######################################################
pro tas_scan_mapper_make_choice_controls,tlb,parent
end;tas_scan_mapper_make_choice_controls
;######################################################

;; SPURION2_Help
;;
;; PURPOSE:
;;   Event handler. Display SPURION2 manual.
;;
;; PARAMETERS:
;;   event [in] - event structure.
;;
pro SPURION2_Help,event
    widget_control,event.top,get_uvalue = pState
    void = launch_help(!DAVE_AUXILIARY_DIR+'Spurion2Startup.pdf',tlb = event.top)
    ;void = dialog_message('NSE Help file is coming soon!',/info)
    return
end
;-------------------------------------------------------------------------------


pro tas_scan_mapper_partial_update,event,update=update
;print,'tas_scan_mapper_partial_update'
if n_elements(update) eq 0 then update = 0
    ;THIS WILL SAVE THE SCAN INFORMATION BUT RECALCULATE THE
    ;SPURIONS BASED ON THE UPDATED SETTINGS (NOTE: Al, QTol, ETC. ARE NOT SAVED.).

    ;BASICALLY THIS IS THE TREE EVENT HANDLER.

    widget_control,event.handler,get_uvalue=pstate

    tid = widget_info((*pstate).scanTree,/tree_select)
    nmatches = 0
    if widget_info(tid,/valid) gt 0 then begin
        widget_control,tid,get_value=name
        ;print,'tas_scan_mapper_partial_update  name = ',name
        nscans = (*pstate).scanContainer->count()
        for i=0,nscans-1 do begin
            ref = (*pstate).scanContainer->get(position=i)
            ref->getproperty,name=myname,pstr=pstr


            if strcmp(name,myname,/fold_case) ne 0 then begin
                (*pstate).currentscannumber = i      ;SET THE CURRENT SCAN NUMBER BASED ON THE SELECTION
                nmatches++
                tempb = widget_base(title='Please wait, processing loaded scan '+' . . . ',$
                                    xsize=350)
                prog = cw_progress(tempb,title=['File '],value=[1])
                centertlb,tempb
                widget_control,tempb,/realize

                ref->getproperty,pstr=pstr
                str = *pstr

                if update eq 0 then begin
                    widget_control,(*pstate).pointchoiceslider,set_value=0
                    widget_control,(*pstate).pointchoiceslider,set_slider_max=str.npts-1
                    widget_control,(*pstate).selectAllPointsCheckbox,set_value=1;SelectAllPointsCheckboxValue
                endif
;print,'str.npts = ',str.npts


                ;UPDATE SCANPARMS
                tas_scan_mapper_fill_scanparms,event,str
                (*pstate).scandrawplotobj->setproperty,title=file_basename(str.fn)
;print,'tas_scan_mapper_partial_update  updating plots'

                tas_scan_mapper_update_plots,event,str
                if widget_info(tempb,/valid_id) gt 0 then begin
                    widget_control,prog,set_value=[1]
                    wait,0.5
                    widget_control,tempb,/destroy
                endif
                tas_scan_mapper_synch_plot_to_range,(*pstate).qdrawplotobj,(*pstate).qrangeobj
                tas_scan_mapper_synch_plot_to_range,(*pstate).edrawplotobj,(*pstate).erangeobj
                tas_scan_mapper_synch_plot_to_range,(*pstate).scandrawplotobj,(*pstate).scanrangeobj

                break
            endif

        endfor;i
        if nmatches eq 0 then begin
            ;IF THERE ARE NO MATCHES THEN THE USER SELECTED A FOLDER INSTEAD OF A LEAF NODE.
            ;UPDATE THE CURRENT SELECTION TO RECTIFY THE PROBLEM.
            tas_scan_mapper_update_scantree_selection,pstate
        endif;nmatches
;
    endif;valid

end;tas_scan_mapper_partial_update


pro tas_scan_mapper_handle_tree_event,event

;print,'tas_scan_mapper_handle_tree_event'
    tas_scan_mapper_partial_update,event

end;tas_scan_mapper_handle_tree_event



pro tas_scan_mapper_full_update,event
;print,'tas_scan_mapper_full_update'
;MAKES A NEW DATA STR AND ADDS IT TO THE TREE.

    widget_control,event.handler,get_uvalue=pstate

    tempb = widget_base(title='Please wait, processing scan '+' . . . ',$
                xsize=350)
    prog = cw_progress(tempb,title=['Scan '],value=[1])
    centertlb,tempb
    widget_control,tempb,/realize
    tas_scan_mapper_update_plots,event,str


    newscan = obj_new('Spurion2_scan',str,0.0,1)

;print,'TAG_NAMES(str)=',tag_names(str)
;print,str


    (*pstate).scanContainer->add,newscan
    (*pstate).currentScanNumber = (*pstate).scanContainer->count()-1
    tas_scan_mapper_populate_scantree,pstate
    if widget_info(tempb,/valid_id) gt 0 then begin
        widget_control,prog,set_value=[1]
        wait,0.5
        widget_control,tempb,/destroy
    endif
    (*pstate).scandrawplotobj->setproperty,title='Calculated Scan'
    tas_scan_mapper_synch_plot_to_range,(*pstate).qdrawplotobj,(*pstate).qrangeobj
    tas_scan_mapper_synch_plot_to_range,(*pstate).edrawplotobj,(*pstate).erangeobj
    tas_scan_mapper_synch_plot_to_range,(*pstate).scandrawplotobj,(*pstate).scanrangeobj


end;tas_scan_mapper_full_update

pro tas_scan_mapper_event,event
    widget_control,event.handler,get_uvalue=pstate

;print,'EVENT!!!!'
;print,tag_names(event,/structure_name)
;
;print,event.id
;print,(*pstate).scanTree


    ;CATCH TREE EVENTS HERE SINCE scanTree IS NOT THE SOURCE OF THE WIDGET_TREE_SEL EVENT,
    ;RATHER ONE OF ITS CHILDREN IS.
    if strcmp(tag_names(event,/structure_name),'WIDGET_TREE_SEL',/fold_case) ne 0 then begin

        tas_scan_mapper_handle_tree_event,event
        return
    endif

    case event.id of
    (*pstate).tlb:begin
        tas_scan_mapper_redraw,event
        tas_scan_mapper_update_background,event
    end;tlb
    (*pstate).helpbutton:begin

                newevent = {id:event.id,top:(*pstate).dave_id,handler:event.handler}
                if widget_info((*pstate).dave_id,/valid_id) gt 0 then begin
                    SPURION2_Help,newevent
                endif else begin
                    void = dialog_message('Help available when called from DAVE!',/info)
                endelse


    end;helpbutton
    (*pstate).spurcheckbox:begin
        vals = (*pstate).spurcheckboxobj->getchecked()
        eref = (*pstate).edrawplotobj->get(/all)
        sref = (*pstate).scandrawplotobj->get(/all)
        for i=0,n_elements(eref)-1 do begin
            if obj_isa(eref[i],'Spurion2_spurions_data') gt 0 then begin
                eref[i]->setcheckboxes,vals
            endif;obj_isa(eref)
        endfor;i
        sref = (*pstate).scandrawplotobj->get(/all)
        for i=0,n_elements(sref)-1 do begin
            if obj_isa(sref[i],'Spurion2_spurions_data') gt 0 then begin
                sref[i]->setcheckboxes,vals
            endif;obj_isa(sref)
        endfor;i

        (*pstate).edrawplotobj->draw
        (*pstate).scandrawplotobj->draw


    end;spurcheckbox
    (*pstate).qcheckbox:begin
        val = (*pstate).qcheckboxobj->getchecked()

        ref = (*pstate).qdrawplotobj->get(/all)
        for i=0,n_elements(ref)-1 do begin
;            ['Q','ki','kf','yhat','xhat','lattice','harmonics','incoherent',$
;                   'Instr. max','Al Spheres']
            if obj_isa(ref[i],'spurion2_scanqpoint_data') ne 0 then begin
                ref[i]->setproperty,showq=val[0],showki=val[1],showkf=val[2]
            endif
            if obj_isa(ref[i],'spurion2_orientationvecs_data') ne 0 then begin
                ref[i]->setcheckboxproperties,val[3:4]
            endif
            if obj_isa(ref[i],'spurion2_2dlattice_data') ne 0 then begin
                ref[i]->setproperty,showdata=val[5]
            endif
            if obj_isa(ref[i],'spurion2_harmonics_data') ne 0 then begin
                ref[i]->setproperty,showdata=val[6]
            endif
            if obj_isa(ref[i],'spurion2_scanqpoint_incoherent_data') ne 0 then begin
                ref[i]->setproperty,showdata=val[7]
            endif
            if obj_isa(ref[i],'spurion2_instrmax_data') ne 0 then begin
                ref[i]->setproperty,showdata=val[8]
            endif
            if obj_isa(ref[i],'spurion2_alspheres_data') ne 0 then begin
                ref[i]->setproperty,showdata=val[9]
            endif
        endfor;i
        (*pstate).qdrawplotobj->draw
    end;qcheckbox
    (*pstate).harmcheckbox:begin
        ;SELECT HARMONICS
        vals = (*pstate).harmcheckboxobj->getchecked()
        ref = (*pstate).qdrawplotobj->get(/all)
        for i=0,n_elements(ref)-1 do begin
            if obj_isa(ref[i],'spurion2_harmonics_data') ne 0 then begin
                ref[i]->setproperty,showharmonics=vals
            endif
        endfor;i
        ref = (*pstate).edrawplotobj->get(/all)
        for i=0,n_elements(ref)-1 do begin
            if obj_isa(ref[i],'spurion2_energyharmonics_data') ne 0 then begin
                ref[i]->setproperty,showharmonics=vals
            endif
        endfor;i
        (*pstate).qdrawplotobj->draw
        (*pstate).edrawplotobj->draw
    end;harmcheckbox
    (*pstate).qranges:begin
        ;print,'qranges'
        tas_scan_mapper_synch_range_to_plot,(*pstate).qdrawplotobj,(*pstate).qrangeobj
        dum = (*pstate).qrangeobj->getvalues(xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax)
        (*pstate).qdrawplotobj->range,xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax
        (*pstate).qdrawplotobj->draw
    end;qranges
    (*pstate).eranges:begin
        ;print,'eranges'
        tas_scan_mapper_synch_range_to_plot,(*pstate).edrawplotobj,(*pstate).erangeobj
    end;eranges
    (*pstate).scanranges:begin
        ;print,'tas_scan_mapper_event:   scanranges'
        tas_scan_mapper_synch_range_to_plot,(*pstate).scandrawplotobj,(*pstate).scanrangeobj


    end;scanranges
    (*pstate).qdrawplot:begin
        tas_scan_mapper_synch_plot_to_range,(*pstate).qdrawplotobj,(*pstate).qrangeobj
        (*pstate).qdrawplotobj->draw
    end;qdrawplot
    (*pstate).edrawplot:begin
        tas_scan_mapper_synch_plot_to_range,(*pstate).edrawplotobj,(*pstate).erangeobj
        (*pstate).edrawplotobj->draw
    end;qdrawplot
    (*pstate).scandrawplot:begin
        tas_scan_mapper_synch_plot_to_range,(*pstate).scandrawplotobj,(*pstate).scanrangeobj
        (*pstate).scandrawplotobj->draw
    end;qdrawplot
;    (*pstate).qzdrawplot:begin
;        ;print,'qzdrawplot WORKING!!!'
;    end;qdrawplot
    (*pstate).background:begin
        ;print,'background'
    end;background
    (*pstate).scanTree:begin
        ;print,'(*pstate).scanTree'

        ;print,'tas_scan_mapper_event    TREE'


        ename = tag_names(event,/structure_name)
        ;print,tag_names(event)
        ;print,event

        case ename of
        'WIDGET_CONTEXT':begin
            ;print,tag_names(event)
            ;print,event
            widget_displaycontextmenu,(*pstate).scantree,event.x, event.y, $
                                      (*pstate).scanTreeContextMenu

        end;WIDGET_CONTEXT
        else:
        endcase

    end;scantree
    (*pstate).restore:begin
        rfn = dialog_pickfile(path=(*pstate).workdir,/read,filter = ['*.spu'])
        if rfn ne '' then begin

            catch, error_status
            ;This statement begins the error handler:
            if error_status ne 0 then begin
                void = dialog_message('Problem reading file: '+rfn)
                catch,/cancel
                return
            endif

            restore,rfn
            ;help,ref
            old = (*pstate).scanContainer->get(/all)
            (*pstate).scanContainer->remove,/all
            obj_destroy,old
            count = ref->count()
            for i=0,count-1 do begin
                ;print,'populating scanContainer',i
                newref = ref->get(position=i)
                (*pstate).scanContainer->add,newref,position=i
            endfor;i

            tas_scan_mapper_populate_scantree,pstate

            folder = widget_info((*pstate).scantree,/child)
            firsttree = widget_info(folder,/child)
            widget_control,firsttree,set_tree_select=1
            tas_scan_mapper_handle_tree_event,{id:firsttree,top:event.top,handler:event.handler,type:0,clicks:1}
        endif

    end;restore
    (*pstate).save:begin
        ;void = dialog_message('Save not implemented.')


        sfn = dialog_pickfile(path=(*pstate).workdir,/write,filter = ['*.spu'])
        if sfn ne '' then begin
            if file_test(file_dirname(sfn),/write) gt 0 then begin
                len = strlen(sfn)
                if len gt 4 then begin
                    ext = strmid(sfn,3,/reverse_offset)
                    if strcmp(ext,'.spu',/fold_case) eq 0 then sfn = sfn+'.spu'
                    ref = (*pstate).scanContainer
                    save,ref,filename=sfn


                endif else begin
                    fn = fn + '.spu'
                endelse
            endif else begin
                void = dialog_message('Invalid permissions for write operation')
            endelse
        endif


    end;save
    (*pstate).quit:begin
        widget_control,(*pstate).tlb,/destroy
    end;quit
    (*pstate).print_scatplane:begin
            printdir = (*pstate).printdir
            (*pstate).qdrawplotobj->draw,/printwin,/ps,printdir=printdir
            if printdir ne '' then (*pstate).printdir = printdir
    end;print_scatplane
    (*pstate).print_scanplot:begin
            printdir = (*pstate).printdir
            (*pstate).scandrawplotobj->draw,/printwin,/ps,printdir=printdir
            if printdir ne '' then (*pstate).printdir = printdir
    end;print_scatplane
    (*pstate).print_energyplot:begin
            printdir = (*pstate).printdir
            (*pstate).edrawplotobj->draw,/printwin,/ps,printdir=printdir
            if printdir ne '' then (*pstate).printdir = printdir
    end;print_energyplot
    (*pstate).jpg_scatplane:begin
            printdir = (*pstate).printdir
            (*pstate).qdrawplotobj->draw,/printwin,/jpg,printdir=printdir
            if printdir ne '' then (*pstate).printdir = printdir
    end;jpg_scatplane
    (*pstate).jpg_scanplot:begin
            printdir = (*pstate).printdir
            (*pstate).scandrawplotobj->draw,/printwin,/jpg,printdir=printdir
            if printdir ne '' then (*pstate).printdir = printdir
    end;jpg_scanplot
    (*pstate).jpg_energyplot:begin
            printdir = (*pstate).printdir
            (*pstate).edrawplotobj->draw,/printwin,/jpg,printdir=printdir
            if printdir ne '' then (*pstate).printdir = printdir
    end;jpg_energyplot
    (*pstate).color:begin
    end;color
    (*pstate).fixwid:begin
    end;fixwid
    (*pstate).float_controlbase:begin
    end;
    (*pstate).scanaxiscombo:begin
        axisindex = nse_comboindex((*pstate).scanaxiscombo)
        tas_scan_mapper_update_scanplot_axis,(*pstate).scandrawplotobj,(*pstate).edrawplotobj,axisindex
    end;scanaxiscombo
    (*pstate).pointchoiceslider:begin
;        print,'(*pstate).pointchoiceslider',event.id
;        widget_control,(*pstate).pointchoiceslider,get_value=pointchoiceindex
;        print,pointchoiceindex
        ;NEW:
        tas_scan_mapper_partial_update,event,/update

    end;pointchoiceslider
    (*pstate).selectallpointscheckbox:begin
;        widget_control,(*pstate).selectallpointscheckbox,get_value=pointcheckboxvalue
;        print,pointcheckboxvalue
;        print,'(*pstate).selectallpointscheckbox',event.id
        ;NEW:
        tas_scan_mapper_partial_update,event,/update
    end;selectallpointcheckbox
    (*pstate).samplecancombo:begin

        ;AS IS:
        ;tas_scan_mapper_full_update,event

        ;NEW:
        tas_scan_mapper_partial_update,event,/update

    end;sampleCanCombo
    (*pstate).qtolfield:begin
        ;print,'QtolField'

        ;WHEN THIS CHANGES, THE CURRENT str DATA NEEDS TO BE SAVED AND THE
        ;SPURIONS CALCULATED FROM THAT.

        ;AS IS:
        ;tas_scan_mapper_full_update,event

        ;NEW:
        tas_scan_mapper_partial_update,event,/update

    end;qtolfield
    (*pstate).Etolfield:begin
        ;print,'EtolField'
        ;NEED TO DO EVERYTHING HERE SINCE CHANGING TOLERANCES
        ;CHANGES SPURIONS.


        ;AS IS:
        ;tas_scan_mapper_full_update,event

        ;NEW:
        tas_scan_mapper_partial_update,event,/update

    end;EtolField
    (*pstate).a4field:begin
        ;print,'A4Field'
        ;THIS CHANGES ONLY A DISPLAYED ITEM, BUT DOES NOT AFFECT SPURIONS.
        instrmaxpos = -1
        for i = 0,(*pstate).qdrawplotobj->count()-1 do begin
            ref = (*pstate).qdrawplotobj->get(position=i)
            ref->getproperty,id=id
            ;print,id
            if stregex(id,'SPURION2INSTRMAX',/fold_case,/boolean) gt 0 then begin
                instrmaxpos = i
            endif
        endfor;i
        if instrmaxpos ne -1 then begin
;            print,instrmaxpos
            widget_control,(*pstate).a4field,get_value=a4
            ref = (*pstate).qdrawplotobj->get(position=instrmaxpos)
            (*pstate).qdrawplotobj->remove,position=instrmaxpos
            obj_destroy,ref
            vals = (*pstate).scanparmsobj->get_values(str=str)
            ei = vals.ei
            ef = vals.ef
            lims = obj_new('spurion2_instrmax_data',ei,ef,A4,color=0L,$
                            qmax=qmax,q180max=q180max,id='SPURION2INSTRMAX')
            (*pstate).qdrawplotobj->add,lims
            (*pstate).qdrawplotobj->setproperty,xmaxrange=[-q180max,q180max],$
                                                ymaxrange=[-q180max,q180max]
            (*pstate).qdrawplotobj->draw

        endif

    end;a4field
    (*pstate).controlsrestore:begin
        if widget_info((*pstate).float_controlbase,/valid_id) eq 0 then begin
            fc = tas_scan_mapper_make_floating_controls((*pstate).tlb,round([2,1,0]));qh,qk,ql]))
        endif
    end;controlsrestore
    (*pstate).scanparms:begin
;help,/heap,/brief
;print,'tas_scan_mapper_event (*pstate).scanparms'
;print,'tas_scan_mapper_event (*pstate).scanparms'

        tempb = widget_base(title='Please wait, processing scan '+' . . . ',$
                    xsize=350)
        prog = cw_progress(tempb,title=['Scan '],value=[1])
        centertlb,tempb
        widget_control,tempb,/realize

        tas_scan_mapper_update_plots,event,str

        if n_elements(str) gt 0 then begin
            if strcmp(str.fn,'NO DATA READ',/fold_case) eq 0 then begin
                newscan = obj_new('Spurion2_scan',str,0.0,1)
                (*pstate).scanContainer->add,newscan
                (*pstate).currentScanNumber = (*pstate).scanContainer->count()-1
                tas_scan_mapper_populate_scantree,pstate
            endif
        endif;str

;for i=0,(*pstate).scanContainer->count()-1 do begin
;    ref = (*pstate).scanContainer->get(position=i)
;    ref->getproperty,pstr=pstr
;    print,i,(*pstr).da
;    print,i,(*pstr).dm
;endfor;i


        if widget_info(tempb,/valid_id) gt 0 then begin
            widget_control,prog,set_value=[1]
            wait,0.5
            widget_control,tempb,/destroy
        endif
        ;tas_scan_mapper_update_plots,event;,/noqrescale
        (*pstate).scandrawplotobj->setproperty,title='Calculated Scan'
;help,/heap,/brief
        tas_scan_mapper_synch_plot_to_range,(*pstate).qdrawplotobj,(*pstate).qrangeobj
        tas_scan_mapper_synch_plot_to_range,(*pstate).edrawplotobj,(*pstate).erangeobj
        tas_scan_mapper_synch_plot_to_range,(*pstate).scandrawplotobj,(*pstate).scanrangeobj



;print,str.da
;print,str.dm
;print,'end of (*pstate).scanparms event'
    end;scanparms
    (*pstate).scanTreeContextMenu_open:begin
        ;print,'TESTING (*pstate).scanTreeContextMenu_open'

        tas_scan_mapper_event,{id:(*pstate).open,top:(*pstate).tlb,handler:(*pstate).tlb}
    end;(*pstate).scanTreeContextMenu_open
    (*pstate).open:begin
        tas_scan_mapper_open_file,event,str
;        print,n_elements(str)
        ;print,tag_names(str)

        if n_elements(str) gt 0 then begin
            widget_control,(*pstate).pointchoiceslider,set_value=0
            widget_control,(*pstate).pointchoiceslider,set_slider_max=str.npts-1
            widget_control,(*pstate).selectAllPointsCheckbox,set_value=1;SelectAllPointsCheckboxValue

            if str.noscan eq 0 then begin

        ;            print,str.fn
                    if strcmp(str.fn,'NO DATA READ',/fold_case) eq 0 then begin
                        newscan = obj_new('Spurion2_scan',str,0.0,1)
                        (*pstate).scanContainer->add,newscan
                        (*pstate).currentScanNumber = (*pstate).scanContainer->count()-1
                        tas_scan_mapper_populate_scantree,pstate
                        tempb = widget_base(title='Please wait, processing file '+file_basename(str.fn)+' . . . ',$
                                            xsize=350)
                        prog = cw_progress(tempb,title=['File '],value=[1])
                        centertlb,tempb
                        widget_control,tempb,/realize

                        tas_scan_mapper_update_plots,event,str
                        if widget_info(tempb,/valid_id) gt 0 then begin
                            widget_control,prog,set_value=[1]
                            wait,0.5
                            widget_control,tempb,/destroy
                        endif
                    endif
                tas_scan_mapper_synch_plot_to_range,(*pstate).qdrawplotobj,(*pstate).qrangeobj
                tas_scan_mapper_synch_plot_to_range,(*pstate).edrawplotobj,(*pstate).erangeobj
                tas_scan_mapper_synch_plot_to_range,(*pstate).scandrawplotobj,(*pstate).scanrangeobj
            end;str.noscan eq 0
        endif;n_elements(str) gt 0
    end;open
    (*pstate).zqhfield:begin
    end;zqhfield
    (*pstate).zqkfield:begin
    end;zqkfield
    (*pstate).zqlfield:begin
    end;zqlfield
    (*pstate).qzcalculate:begin
        tas_scan_mapper_update_qzplane,event
    end;qzcalculate
    else:
    endcase

end;tas_scan_mapper_event
;######################################################
pro tas_scan_mapper,group_leader=group_leader

    ;RUN CALC Q TO FORCE COMPILATION OF USEFUL ITEMS IN FILE calc_q.pro
    dum = calc_q(1,1,100)
    xsize=800
    ysize=600
    plotxsize = xsize/2 - 40
    plotysize = ysize/2 - 40
    qo = [1,1,0]

    if n_elements(group_leader) eq 1 then begin
        tlb = widget_base(xoffset=200,yoffset=200,kill_notify='tas_scan_mapper_cleanup',mbar=bar,$
                            /tlb_size_events,title='Scan Mapper',group_leader=group_leader)
    endif else begin
        group_leader=0L
        tlb = widget_base(xoffset=200,yoffset=200,kill_notify='tas_scan_mapper_cleanup',mbar=bar,$
                            /tlb_size_events,title='Scan Mapper');title='Spurion2')
    endelse

    scanContainer = obj_new('IDL_Container')

;    if !version.os ne 'Win32' then $
;    background = widget_draw(tlb,xoffset=0,yoffset=0,xsize=xsize,ysize=ysize,/button_events)


    file = widget_button( bar,value='File',/menu)
    open = widget_button(file,value='Open')
    save = widget_button(file,value='Save')
    restore = widget_button(file,value='Restore Session')

    prin = widget_button(file,value='Print',/menu)
    print_Scatplane  = widget_button(prin,value='Scattering Plane')
    print_ScanPlot   = widget_button(prin,value='Scan Plot')
    print_EnergyPlot = widget_button(prin,value='Energy Plot')

    imag = widget_button(file,value='JPEG Output',/menu)
    jpg_Scatplane  = widget_button(imag,value='Scattering Plane')
    jpg_ScanPlot   = widget_button(imag,value='Scan Plot')
    jpg_EnergyPlot = widget_button(imag,value='Energy Plot')

    quit = widget_button(file,value='Quit')
    help = widget_button( bar,value='Help',/menu)
    helpbutton = widget_button(help,value='Spurion2 Help')

    Options   = widget_button( bar,value='Options',/menu)
    controlsrestore = widget_button( options,value='Restore controls')
    color     = 0L;widget_button(Options,value='Change color')

    fixwid    = 0L;widget_button(Options,value='[X] Fix Widgets')

    qdrawplot = Spurion2_drawplot(tlb,xsize=plotxsize,ysize=2*plotysize,$
;    qdrawplot = cwo_drawplot(tlb,xsize=plotxsize,ysize=2*plotysize,$
                             xoffset = 20, yoffset = 50,$;ysize/2,
                             abc = 2*!PI*[1.,1.,1.],$
                             abg = [90.,90.,90.],$
                             o1=[1,0,0.],o2=[0,1,0.],$
                             frame=1,$
                             xtitle = 'X ['+angstrom()+'^-1]',$
                             ytitle = 'Y ['+angstrom()+'^-1]',$
                             title = 'Scattering Plane',$
                             obj=qdrawplotobj)
    statustext = widget_text(tlb,value='Starting Spurion2',xoffset=20,xsize=80,yoffset=2*plotysize+55)

    scandrawplot = cwo_drawplot(tlb,xsize=plotxsize,ysize=plotysize,$
                             xoffset = xsize/2, yoffset = 20,frame=1,$
                             xtitle = 'Point #',$;'Q ['+angstrom()+'^-1]',$
                             ytitle = 'Counts',$
                             title = 'Scan',$
                             obj=scandrawplotobj)

    Edrawplot = cwo_drawplot(tlb,xsize=plotxsize,ysize=plotysize,$
                             xoffset = xsize/2, yoffset = ysize/2,frame=1,$
                             xtitle = 'Point #',$;Q ['+angstrom()+'^-1]',$
                             ytitle = '!7D!XE [meV]',$
                             title = 'Energy Spurions',$
                             obj=edrawplotobj)


    ;PUT THIS HERE SO IT IS IN FRONT OF BACKGROUND
    gorow    = widget_base(tlb,xoffset=16,yoffset=25)


    ;if !version.os eq 'Win32' then $
    background = widget_draw(tlb,xoffset=0,yoffset=0,xsize=xsize,ysize=ysize,/button_events)

    window,/free,/pixmap,xsize=xsize,ysize=ysize
    backgroundpix = !d.window

    black = 0L
    red = 255L
    green = 256L*red
    blue = 256L*green
    white = red + green + blue
    soothing = 120L + 120L*256L + 215L*256L*256L
    erase,color = soothing

    widget_control,tlb,/realize
    widget_control,background,get_value=backgroundvis

    wset,backgroundvis
    device,copy=[0,0,xsize,ysize,0,0,backgroundpix]

    Qcolor = blue
    kicolor = red+200L*256L
    kfcolor = red+green

    if obj_valid(qzdrawplotobj) eq 0 then qzdrawplotobj = obj_new()
    if n_elements(qzdrawplot) eq 0 then begin
        qzdrawplot = 0L
        qzdrawplotbase = 0L
    endif

    spurbase = widget_base(title='Spurion list:',group_leader=tlb)
    spurlist = widget_list(spurbase,xsize=200,ysize=30)


    ;GET DAVE DIR'S IF THEY ARE AVAILABLE
    datadir = ''
    workdir = ''
    printdir = ''

;SEE dave.pro AROUND LINE 390 FOR e.g.
    defsysv,'!dave_defaults',exists=exists
    if exists eq 1 then begin
        if ptr_valid(!dave_defaults) gt 0 then begin
            print,'!dave_defaults exists, setting workdir and datadir.'
            datadir = (*!dave_defaults).datdir
            workdir = (*!dave_defaults).workdir
            printdir = (*!dave_defaults).workdir
        endif
    endif

    state = {tlb:tlb,controlbase:0L,$
            datadir:datadir,$
            workdir:workdir,$
            printdir:printdir,$
            dave_id:group_leader,$
            statustext:statustext,$
            helpbutton:helpbutton,$
            scantree:0L,scanContainer:scanContainer,$
            scantreeContextMenu:0L,$
            scanTreeContextMenu_open:0L,$
            scanListTab:0L,$
            currentscannumber:0,$
            pointchoiceslider:0L,$
            selectallpointscheckbox:0L,$
            spurionoutputlistpix:0,spurionoutputlistvis:0,$
            spurionoutputlistdraw:0L,$
            spurionoutputtext:0L,$
            spurbase:spurbase,spurlist:spurlist,$
            harmcheckbox:0L,harmcheckboxobj:obj_new(),$
            spurcheckbox:0L,spurcheckboxobj:obj_new(),$
            qdrawplot:qdrawplot,qdrawplotobj:qdrawplotobj,$
            edrawplot:edrawplot,edrawplotobj:edrawplotobj,$
            scandrawplot:scandrawplot,scandrawplotobj:scandrawplotobj,$
            qzdrawplot:qzdrawplot,qzdrawplotobj:qzdrawplotobj,$
            qzdrawplotbase:qzdrawplotbase,$
            qrangeobj:obj_new(),erangeobj:obj_new(),scanrangeobj:obj_new(),$
            samplecancombo:0L,$
            scanaxiscombo:0L,$
            qranges:0L,eranges:0L,scanranges:0L,$
            background:background,backgroundpix:backgroundpix,backgroundvis:backgroundvis,$
            green:green,black:black,red:red,blue:blue,white:white,soothing:soothing,$
            qcolor:qcolor,kicolor:kicolor,kfcolor:kfcolor,$
            afield:0L,bfield:0L,cfield:0L,$
            alphafield:0L,betafield:0L,gammafield:0L,$
            hfield:0L,kfield:0L,lfield:0L,$
            hstepfield:0L,kstepfield:0L,lstepfield:0L,$
            Efield:0L,EStepfield:0L,efixfield:0L,eifselect:0L,$
            o1hfield:0L,o1kfield:0L,o1lfield:0L,$
            o2hfield:0L,o2kfield:0L,o2lfield:0L,$
            etolfield:0L,qtolfield:0L,$
            A4field:0L,$
            zqhfield:0L,zqkfield:0L,zqlfield:0L,$
            qzcalculate:0L,nptsfield:0L,$
            open:open,save:save,restore:restore,quit:quit,color:color,fixwid:fixwid,$
            print_Scatplane:print_ScatPlane,$
            print_ScanPlot:print_Scanplot,$
            print_EnergyPlot:print_energyplot,$
            jpg_Scatplane:jpg_scatPlane,$
            jpg_ScanPlot:jpg_Scanplot,$
            jpg_EnergyPlot:jpg_EnergyPlot,$
            controlsrestore:controlsrestore,$
            gobutton:0L,$
            float_controlbase:0L,$
            dmCombo:0L,dmfield:0L,daCombo:0L,dafield:0L,$
            colhor_z:0L,colhor_m:0L,colhor_a:0L,colhor_3:0L,$ ;= cw_field(horcolbase,title='3',value=60,/floating)
            colver_z:0L,colver_m:0L,colver_a:0L,colver_3:0L,$
            mosaic_m:0L,mosaic_a:0L,mosaic_sh:0L,mosaic_sv:0L,$
            sourcecombo:0L,focuscheckbox:0L,instrorient1:0L,instrorient2:0L,$
            scanparmsobj:obj_new(),scanparms:0L,$
            qcheckbox:0L,qcheckboxobj:obj_new()};,controlvalues:tas_scan_mapper_control_values()}

    pstate = ptr_new(state)
    widget_control,tlb,set_uvalue=pstate

    xmanager,'tas_scan_mapper',tlb,event_handler='tas_scan_mapper_event',/no_block

    fc = tas_scan_mapper_make_floating_controls(tlb,qo)

;    ;FIRE TIMER EVENT TO FORCE CALCULATION.
    widget_control,(*pstate).scanparms,timer=0

    tas_scan_mapper_synch_plot_to_range,(*pstate).qdrawplotobj,(*pstate).qrangeobj,/exact
    (*pstate).qdrawplotobj->draw
    (*pstate).edrawplotobj->draw
    (*pstate).scandrawplotobj->draw

;widget_control,(*pstate).scandrawplot,timer=0
;widget_control,(*pstate).scanranges,timer=0

    ;LEGENDS
        qlabel = widget_label(gorow,value='Q',xoffset=50,yoffset=0)
        qleg   = widget_draw(gorow,xsize=30,ysize=4,xoffset=40,yoffset=14)
        kilabel = widget_label(gorow,value='ki',xoffset=90,yoffset=0)
        kileg   = widget_draw(gorow,xsize=30,ysize=4,xoffset=80,yoffset=14)
        kflabel = widget_label(gorow,value='-kf',xoffset=130,yoffset=0)
        kfleg   = widget_draw(gorow,xsize=30,ysize=4,xoffset=120,yoffset=14,$
                                    uvalue=pstate)


    ;THE NEXT STEPS SHOULD REALLY OCCUR AFTER REALIZATION, BUT
    ;THE PREVIOUS STUFF SHOULD BE DONE BEFORE REALIZATION.

        ;COLOR BACKGROUNDS AFTER REALIZATION.
        widget_control,qleg,    get_value=qlegvis
        widget_control,kileg,   get_value=kilegvis
        widget_control,kfleg,   get_value=kflegvis

        black = 0L
        red = 255L
        green = 256L*red
        blue = 256L*green
        Qcolor = blue
        kicolor = red+200L*256L;green;red
        kfcolor = red+green

        wset,qlegvis
        erase,Qcolor
        wset,kilegvis
        erase,kicolor
        wset,kflegvis
        erase,kfcolor

end;tas_scan_mapper

