; $Id: resgui2.pro,v 1.7 2007/05/01 20:09:38 kneller Exp $
;###############################################################################
;
;FILENAME:
;        resgui2.pro
;
;PURPOSE:
;
;CATEGORY:
;
;
;METHODS IN FILE:
;
;METHODS:
;    resGUI2_draw
;    resGUI2_makeParmImage
;    resGUI2_makeImage
;    resGUI2_writePS
;    resGUI2_jpg
;    resGUI2_ps
;    resGUI2_calculate
;    resGUI2_updatevalues
;    resGUI2_event
;    resGUI2_help
;    resGUI2_cleanup
;    resGUI2
;
;
; AUTHOR:
; Larry Kneller
; NIST Center for Neutron Research
; 100 Bureau Drive, Gaithersburg, MD 20899
; United States
; kneller@nist.gov  301-975-8839
; Thu May 18 15:20:57 2006
;
; LICENSE:
; The software in this file is written by an employee of
; National Institute of Standards and Technology
; as part of the DAVE software project.
;
; The DAVE software package is not subject to copyright protection
; and is in the public domain. It should be considered as an
; experimental neutron scattering data reduction, visualization, and
; analysis system. As such, the authors assume no responsibility
; whatsoever for its use, and make no guarantees, expressed or
; implied, about its quality, reliability, or any other
; characteristic. The use of certain trade names or commercial
; products does not imply any endorsement of a particular product,
; nor does it imply that the named product is necessarily the best
; product for the stated purpose. We would appreciate acknowledgment
; if the DAVE software is used or if the code in this file is
; included in another product.
;
;###############################################################################


;###############################################################################
;
;NAME:
;        resGUI2_makeParmImage
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;RETURN VALUE:
;
;###############################################################################
function resGUI2_makeParmImage,event,xyimage,printout=printout,stringout=stringout

    widget_control,event.handler,get_uvalue=pstate

    if n_elements(printout) eq 0 then printout = 0

    device,get_decomposed=dc
    device,decomposed=1
    ;WRITE PARAMETERS IN THE CORNER IMAGE
    sz = size(xyimage)


    window,/free,/pixmap,xsize=sz[1],ysize=sz[2]
    wtemp = !d.window


    red   = 255L
    green = 256L*red
    blue  = 256L*green
    erase,color = red+green+blue

    ;print,tag_names(*pstate)

    resvals = (*pstate).resvals
    latvals = (*pstate).latvals
    form  = '(f3.0)'
    form2 = '(f9.5)'

    str = strarr(18)

    str[1] = 'Qh='  +strtrim(string(resvals.qetrans[0],format=form2),2)
    xyouts,0.1,0.90,str[1],/normal,color=red
    str[2] = 'Qk='  +strtrim(string(resvals.qetrans[1],format=form2),2)
    xyouts,0.1,0.85,str[2],/normal,color=red
    str[3] = 'Ql='  +strtrim(string(resvals.qetrans[2],format=form2),2)
    xyouts,0.1,0.80,str[3],/normal,color=red
    str[4] = 'dE='  +strtrim(string(resvals.qetrans[3],format=form2),2)
    xyouts,0.1,0.75,str[4],/normal,color=red
    str[5] = 'Efix='+strtrim(string(resvals.qetrans[4],format=form2),2)
    xyouts,0.1,0.70,str[5],/normal,color=red
    str[6] = 'orient1=['+strtrim(string(latvals.orient1[0],format=form),2)+',' $
                    +strtrim(string(latvals.orient1[1],format=form),2)+',' $
                    +strtrim(string(latvals.orient1[2],format=form),2)+']'
    xyouts,0.1,0.65,str[6],/normal,color=green
    str[7] = 'orient2=['+strtrim(string(latvals.orient2[0],format=form),2)+',' $
                    +strtrim(string(latvals.orient2[1],format=form),2)+',' $
                    +strtrim(string(latvals.orient2[2],format=form),2)+']'
    xyouts,0.1,0.60,str[7],/normal,color=green



    rm = strtrim(string((*pstate).rm,format='(f10.2)'),2)
    ;help,rm
    rm = reform(rm,4,4)

    str[8] = 'rm=[['+rm[0,0]+','+rm[1,0]+','+rm[2,0]+','+rm[3,0]+'],'
    str[9] = '     ['+rm[0,1]+','+rm[1,1]+','+rm[2,1]+','+rm[3,1]+'],'
    str[10]= '     ['+rm[0,2]+','+rm[1,2]+','+rm[2,2]+','+rm[3,2]+'],'
    str[11]= '     ['+rm[0,3]+','+rm[1,3]+','+rm[2,3]+','+rm[3,3]+']]'

    xyouts,0.1,0.55,str[8],/normal,color=0L
    xyouts,0.1,0.50,str[9],/normal,color=0L
    xyouts,0.1,0.45,str[10],/normal,color=0L
    xyouts,0.1,0.40,str[11],/normal,color=0L


(*pstate).xydata->calculate,majxyhalfwidth=xymajhalfwidth,minxyhalfwidth=xyminhalfwidth
(*pstate).xwdata->calculate,majExhalfwidth=xEmajhalfwidth,minExhalfwidth=xEminhalfwidth
(*pstate).ywdata->calculate,majEyhalfwidth=yEmajhalfwidth,minEyhalfwidth=yEminhalfwidth

    str[12] = 'x-y major axis halfwidth='+ $
                strtrim(string(xymajhalfwidth,format='(f8.6)'),2)
    xyouts,0.1,0.35,str[12],/normal,color=0L

    str[13] = 'x-y minor axis halfwidth='+ $
                    strtrim(string(xyminhalfwidth,format='(f8.6)'),2)
    xyouts,0.1,0.30,str[13],/normal,color=0L


    str[14] = 'x-E major axis halfwidth='+ $
                strtrim(string(xEmajhalfwidth,format='(f8.6)'),2)
    xyouts,0.1,0.25,str[14],/normal,color=0L

    str[15] = 'x-E minor axis halfwidth='+ $
                    strtrim(string(xEminhalfwidth,format='(f8.6)'),2)
    xyouts,0.1,0.20,str[15],/normal,color=0L


    str[16] = 'y-E major axis halfwidth='+ $
                strtrim(string(yEmajhalfwidth,format='(f8.6)'),2)
    xyouts,0.1,0.15,str[16],/normal,color=0L

    str[17] = 'y-E minor axis halfwidth='+ $
                    strtrim(string(yEminhalfwidth,format='(f8.6)'),2)
    xyouts,0.1,0.10,str[17],/normal,color=0L

    stringout = str

    if printout eq 1 then print,tranpose(str)
;print,(*pstate).r0

    image = tvrd(true=3)
    wdelete,wtemp
    device,decomposed=dc

    return,image
end;resGUI2_makeParmImage



;###############################################################################
;
;NAME:
;        resGUI2_draw
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
pro resGUI2_draw,event

    widget_control,event.handler,get_uvalue=pstate


;    (*pstate).xyplot->draw

(*pstate).xyplot->defaultDraw,/xy,/nodraw
(*pstate).xyplot->unzoom
(*pstate).xyplot->draw,/xy

;(*pstate).xydata->calculate,majxyhalfwidth=xymajhalfwidth,minxyhalfwidth=xyminhalfwidth
;print,'xymajhalfwidth=',xymajhalfwidth
;print,'xyminhalfwidth=',xyminhalfwidth
;print,(*pstate).r0
;    (*pstate).xwplot->draw
(*pstate).xwplot->defaultDraw,/xw,/nodraw
(*pstate).xwplot->unzoom
(*pstate).xwplot->draw,/xw

;    (*pstate).ywplot->draw
(*pstate).ywplot->defaultDraw,/yw,/nodraw
(*pstate).ywplot->unzoom
(*pstate).ywplot->draw,/yw

dum = resgui2_makeparmimage(event,indgen(4,4),stringout=stringout)
widget_control,(*pstate).textoutput,set_value=stringout


end;resGUI2_draw


;;###############################################################################
;;
;;NAME:
;;        resGUI2_makeParmImage
;;
;;PURPOSE:
;;
;;PARAMETERS:
;;
;;KEYWORDS:
;;
;;_EXTRA - is used to pass keywords meant for the superclass.
;;
;;RETURN VALUE:
;;
;;###############################################################################
;function resGUI2_makeParmImage,event,xyimage,printout=printout,stringout=stringout
;
;    widget_control,event.handler,get_uvalue=pstate
;
;    if n_elements(printout) eq 0 then printout = 0
;
;    device,get_decomposed=dc
;    device,decomposed=1
;    ;WRITE PARAMETERS IN THE CORNER IMAGE
;    sz = size(xyimage)
;
;
;    window,/free,/pixmap,xsize=sz[1],ysize=sz[2]
;    wtemp = !d.window
;
;
;    red   = 255L
;    green = 256L*red
;    blue  = 256L*green
;    erase,color = red+green+blue
;
;    ;print,tag_names(*pstate)
;
;    resvals = (*pstate).resvals
;    latvals = (*pstate).latvals
;    form  = '(f3.0)'
;    form2 = '(f9.5)'
;
;    str = strarr(18)
;
;    str[1] = 'Qh='  +strtrim(string(resvals.qetrans[0],format=form2),2)
;    xyouts,0.1,0.90,str[1],/normal,color=red
;    str[2] = 'Qk='  +strtrim(string(resvals.qetrans[1],format=form2),2)
;    xyouts,0.1,0.85,str[2],/normal,color=red
;    str[3] = 'Ql='  +strtrim(string(resvals.qetrans[2],format=form2),2)
;    xyouts,0.1,0.80,str[3],/normal,color=red
;    str[4] = 'dE='  +strtrim(string(resvals.qetrans[3],format=form2),2)
;    xyouts,0.1,0.75,str[4],/normal,color=red
;    str[5] = 'Efix='+strtrim(string(resvals.qetrans[4],format=form2),2)
;    xyouts,0.1,0.70,str[5],/normal,color=red
;    str[6] = 'orient1=['+strtrim(string(latvals.orient1[0],format=form),2)+',' $
;                    +strtrim(string(latvals.orient1[1],format=form),2)+',' $
;                    +strtrim(string(latvals.orient1[2],format=form),2)+']'
;    xyouts,0.1,0.65,str[6],/normal,color=green
;    str[7] = 'orient2=['+strtrim(string(latvals.orient2[0],format=form),2)+',' $
;                    +strtrim(string(latvals.orient2[1],format=form),2)+',' $
;                    +strtrim(string(latvals.orient2[2],format=form),2)+']'
;    xyouts,0.1,0.60,str[7],/normal,color=green
;
;
;
;    rm = strtrim(string((*pstate).rm,format='(f10.2)'),2)
;    ;help,rm
;    rm = reform(rm,4,4)
;
;    str[8] = 'rm=[['+rm[0,0]+','+rm[1,0]+','+rm[2,0]+','+rm[3,0]+'],'
;    str[9] = '     ['+rm[0,1]+','+rm[1,1]+','+rm[2,1]+','+rm[3,1]+'],'
;    str[10]= '     ['+rm[0,2]+','+rm[1,2]+','+rm[2,2]+','+rm[3,2]+'],'
;    str[11]= '     ['+rm[0,3]+','+rm[1,3]+','+rm[2,3]+','+rm[3,3]+']]'
;
;    xyouts,0.1,0.55,str[8],/normal,color=0L
;    xyouts,0.1,0.50,str[9],/normal,color=0L
;    xyouts,0.1,0.45,str[10],/normal,color=0L
;    xyouts,0.1,0.40,str[11],/normal,color=0L
;
;
;(*pstate).xydata->calculate,majxyhalfwidth=xymajhalfwidth,minxyhalfwidth=xyminhalfwidth
;(*pstate).xwdata->calculate,majExhalfwidth=xEmajhalfwidth,minExhalfwidth=xEminhalfwidth
;(*pstate).ywdata->calculate,majEyhalfwidth=yEmajhalfwidth,minEyhalfwidth=yEminhalfwidth
;
;    str[12] = 'x-y major axis halfwidth='+ $
;                strtrim(string(xymajhalfwidth,format='(f8.6)'),2)
;    xyouts,0.1,0.35,str[12],/normal,color=0L
;
;    str[13] = 'x-y minor axis halfwidth='+ $
;                    strtrim(string(xyminhalfwidth,format='(f8.6)'),2)
;    xyouts,0.1,0.30,str[13],/normal,color=0L
;
;
;    str[14] = 'x-E major axis halfwidth='+ $
;                strtrim(string(xEmajhalfwidth,format='(f8.6)'),2)
;    xyouts,0.1,0.25,str[14],/normal,color=0L
;
;    str[15] = 'x-E minor axis halfwidth='+ $
;                    strtrim(string(xEminhalfwidth,format='(f8.6)'),2)
;    xyouts,0.1,0.20,str[15],/normal,color=0L
;
;
;    str[16] = 'y-E major axis halfwidth='+ $
;                strtrim(string(yEmajhalfwidth,format='(f8.6)'),2)
;    xyouts,0.1,0.15,str[16],/normal,color=0L
;
;    str[17] = 'y-E minor axis halfwidth='+ $
;                    strtrim(string(yEminhalfwidth,format='(f8.6)'),2)
;    xyouts,0.1,0.10,str[17],/normal,color=0L
;
;    stringout = str
;
;    if printout eq 1 then print,tranpose(str)
;;print,(*pstate).r0
;
;    image = tvrd(true=3)
;    wdelete,wtemp
;    device,decomposed=dc
;
;    return,image
;end;resGUI2_makeParmImage

;###############################################################################
;
;NAME:
;        resGUI2_makeImage
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;RETURN VALUE:
;
;###############################################################################
function resGUI2_makeImage,event
    widget_control,event.handler,get_uvalue=pstate

    xyimage = (*pstate).xyplot->getColorImage()
    xwimage = (*pstate).xwplot->getColorImage()
    ywimage = (*pstate).ywplot->getColorImage()

    corner = resGUI2_makeParmImage(event,xyimage)

    image1r = [[xyimage[*,*,0], corner[*,*,0]],$
              [xwimage[*,*,0],ywimage[*,*,0]]]
    image1g = [[xyimage[*,*,1], corner[*,*,1]],$
              [xwimage[*,*,1],ywimage[*,*,1]]]
    image1b = [[xyimage[*,*,2], corner[*,*,2]],$
              [xwimage[*,*,2],ywimage[*,*,2]]]

    sz = size(image1r)
    image = reform([[image1r],[image1g],[image1b]],sz[1],sz[2],3)

    sz = size(image)
    image = rebin(image,sz[1]*2,sz[2]*2,sz[3])
    return,image

end;resGUI2_makeImage

;###############################################################################
;
;NAME:
;        resGUI2_writePS
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
pro resGUI2_writePS,image,fn

    len = strlen(fn)


    if fn ne '' then begin
        if len gt 3 then begin
            ext = strmid(fn,2,/reverse_offset)
            if strcmp(ext,'.ps',/fold_case) eq 0 then fn = fn+'.ps'
        endif else begin
            fn = fn + '.ps'
        endelse

    ;THIS IS PRETTY GENERAL!
        sz = size(image)
        set_plot,'PS'
        device,/color,file=fn
        ;plotimage,image,/no_axes
        if sz[0] eq 3 then begin
            tv,image,true=3
        endif else begin
            tv,image
        endelse
        device,/close

        if !version.os eq 'Win32' then begin
            set_plot,'WIN'
        endif else begin
            set_plot,'X'
        endelse
    endif else begin
        void = dialog_message('File name is invalid.')
    endelse

end;resGUI2_writePS

;###############################################################################
;
;NAME:
;        resGUI2_jpg
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
pro resGUI2_jpg,event

    fn = dialog_pickfile(/overwrite_prompt,filter='*.jpg')
    if fn ne '' then begin
        len = strlen(fn)
        if len gt 3 then begin
            ext = strmid(fn,3,/reverse_offset)
            if strcmp(ext,'.jpg',/fold_case) eq 0 then fn = fn+'.jpg'
        endif else begin
            fn = fn + '.jpg'
        endelse

        image = resGUI2_makeImage(event)
        write_jpeg,fn,image,true=3
    endif else begin
        void = dialog_message('No .jpg file chosen.')
    endelse

end;resGUI2_jpg

;###############################################################################
;
;NAME:
;        resGUI2_ps
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
pro resGUI2_ps,event
    fn = dialog_pickfile(/overwrite_prompt,filter='*.ps')

    if fn ne '' then begin
        image = resGUI2_makeImage(event)
        resGUI2_writePS,image,fn
    endif else begin
        void = dialog_message('No .ps file chosen.')
    endelse

end;resGUI2_ps



;###############################################################################
;
;NAME:
;        resGUI2_calculate
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;RETURN VALUE:
;
;###############################################################################
function resGUI2_calculate,event

    widget_control,event.handler,get_uvalue=pstate

    ;GET VALUES FROM PARMS WIDGETS
    lats = (*pstate).latvals;.latparms->get_values()
    res  = (*pstate).resvals;.resparms->get_values()

    ;UPDATE THE LATTICE OBJECT
    (*pstate).lattice->setproperty,$
                            la=lats.a,lb=lats.b,lc=lats.c,$
                            alpha=lats.alpha,beta=lats.beta,gamma=lats.gamma


    ;CALCULATE THE RESOLUTION
    (*pstate).rescalculator->calculate,rm,r0,$
                                  horizontal=res.horizontal,$
                                  collimatorh=res.collimatorh,$
                                  collimatorv=res.collimatorv,$
                                  mosaic=res.mosaic,$
                                  dspacing=res.dspacing,$
                                  instrument_orient=res.instrument_orient,$
                                  qetrans=res.qetrans,$
                                  lattice=(*pstate).lattice,closed=closed



    ;UPDATE THE STATE VALUES
    (*pstate).rm = rm
    (*pstate).r0 = r0
    (*pstate).qetrans = res.qetrans
    (*pstate).mosaic = res.mosaic
    (*pstate).collimatorv = res.collimatorv
    (*pstate).collimatorh = res.collimatorh
    (*pstate).horizontal = res.horizontal


if total(finite(rm,/nan)) ne 0 then return,0



    ;CALCULATE THE a,b,c VALUES AND THE 3x3 ROTATION MATRIX FOR THE
    ;ELLIPSOID.
       rmtransformed=(*pstate).lattice->rtransform(lats.orient1,lats.orient2,$
                                                     res.qetrans,(*pstate).rm)

if total(finite(rmtransformed,/nan)) gt 0 then rmtransformed = double([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]])
;print,'rmtransformed=',rmtransformed

       eigenvalues = float(LA_EIGENPROBLEM(rmtransformed, EIGENVECTORS = eigenvectors))
       eigenvectors=float(eigenvectors)
       eiginv=invert(eigenvectors)
        ;diagonal=float(eiginv#f#eigenvectors)


;#################################################
;RESET rm TO BE rmtransformed!!!!
;#################################################
rm = rmtransformed


       ;GET a,b,c = AXES OF ELLIPSOID IN ITS NATURAL COORD SYSTEM WHERE R matrix is diagonalized
       d=sqrt(2.0*alog(2.0))

       a=d/sqrt(eigenvalues[0]);*100.0
       b=d/sqrt(eigenvalues[1]);*100.0
       c=d/sqrt(eigenvalues[2]);*10.0
       transmatrix=eigenvectors; note that this is a 4x4 matrix since it comes from the R-matrix
       ; delete the last row
       transmatrix=transmatrix[*,[0,1,2]]
       ; delete the last column
       transmatrix=transmatrix[[0,1,2],*]


    ;######################################################
    ;NOTE THAT THIS IS SIMPLY FOR TESTING
;    qx = total(res.qetrans[0:2]*lats.orient1)
;    qy = total(res.qetrans[0:2]*lats.orient2)



latticevalues = (*pstate).lattice->getvalues()
qxyz = hkl_to_qxy(res.qetrans[0],$
                  res.qetrans[1],$
                  res.qetrans[2],$
                  latticevalues.a,$
                  latticevalues.b,$
                  latticevalues.c,$
                  latticevalues.alpha,$
                  latticevalues.beta,$
                  latticevalues.gamma,$
                  lats.orient1,$
                  lats.orient2,$
                  hklunits=1,$
                  invang=0)

qx = qxyz[0]
qy = qxyz[1]





        ;UPDATE DATA OBJECTS WITH CALCULATION RESULTS.
        (*pstate).xydata->setproperty,$
                                rm=rm,$
                                r0=r0,$
                                qx=qx,$
                                qy=qy,$
                                E=res.qetrans[3];,$
;                                Q=res.qetrans[0:2],$
;                                orient1=lats.orient1,$
;                                orient2=lats.orient2,$
;                                astar=lats.astar,$
;                                bstar=lats.bstar,$
;                                cstar=lats.cstar,$
;                                alphastar=lats.alphastar,$
;                                betastar= lats.betastar,$
;                                gammastar=lats.gammastar

        (*pstate).xwdata->setproperty,$
                                rm=rm,$
                                r0=r0,$
                                qx=qx,$
                                qy=qy,$
                                E=res.qetrans[3];,$
;                                Q=res.qetrans[0:2],$
;                                orient1=lats.orient1,$
;                                orient2=lats.orient2,$
;                                astar=lats.astar,$
;                                bstar=lats.bstar,$
;                                cstar=lats.cstar,$
;                                alphastar=lats.alphastar,$
;                                betastar= lats.betastar,$
;                                gammastar=lats.gammastar

        (*pstate).ywdata->setproperty,$
                                rm=rm,$
                                r0=r0,$
                                qx=qx,$
                                qy=qy,$
                                E=res.qetrans[3];,$
;                                Q=res.qetrans[0:2],$
;                                orient1=lats.orient1,$
;                                orient2=lats.orient2,$
;                                E=res.qetrans[3],$
;                                astar=lats.astar,$
;                                bstar=lats.bstar,$
;                                cstar=lats.cstar,$
;                                alphastar=lats.alphastar,$
;                                betastar= lats.betastar,$
;                                gammastar=lats.gammastar


    return,1

end;resGUI2_calculate

;###############################################################################
;
;NAME:
;        resGUI2_updatevalues
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
pro resGUI2_updatevalues,event

    widget_control,event.handler,get_uvalue=pstate

    resvals = (*pstate).resparms->get_values()
    latvals = (*pstate).latparms->get_values()


    (*pstate).resvals = resvals
    (*pstate).latvals = latvals

    (*pstate).qetrans = resvals.qetrans
    (*pstate).mosaic = resvals.mosaic
    (*pstate).collimatorv = resvals.collimatorv
    (*pstate).collimatorh = resvals.collimatorh
    (*pstate).horizontal = resvals.horizontal


end;resGUI2_updatevalues

;###############################################################################
;
;NAME:
;        resGUI2_event
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
pro resGUI2_event,event

    catch,es
    if es ne 0 then begin
        vaoid = dialog_message('Error occurred in resGUI2_event, please report the following:'+!error_state.msg)
        catch,/cancel
        return
    endif

    widget_control,event.handler,get_uvalue=pstate

    case event.id of
    (*pstate).tlb:begin

        ;print,'resGUI2_event'
        ;print,event.x,event.y

        if !version.os eq 'Win32' then begin
            xpad = 20
            ypad = 8
        endif else begin
            xpad = 40
            ypad = 40
        endelse
        xtabsize = 385
        ytabsize = 470



        xsize = (event.x-xtabsize)
        if xsize gt xtabsize then xsize = (event.x-xpad)/2
        ysize = (event.y-ytabsize)
        if ysize gt ytabsize then ysize = (event.y-ypad)/2

        if xsize lt 150 or ysize lt 150 then begin
            xsize = 150
            ysize = 150
        endif

        (*pstate).xyplot->resize,xsize,ysize
        (*pstate).xwplot->resize,xsize,ysize
        (*pstate).ywplot->resize,xsize,ysize

    end;tlb
    (*pstate).resparmsid:begin

        resGUI2_updatevalues,event

        ;SYNCHRONIZE latparms and resparms
        ret = (*pstate).latparms->set_q((*pstate).resparms->get_q())
        if ret ne 0 then begin
            if resGUI2_calculate(event) ne 0 then resGUI2_draw,event
        endif
    end
    (*pstate).latparmsid:begin

        resGUI2_updatevalues,event

        ;SYNCHRONIZE latparms and resparms
        (*pstate).resparms->set_q,(*pstate).latparms->get_q()
        if resGUI2_calculate(event) ne 0 then resGUI2_draw,event
    end
    (*pstate).quit:begin
        widget_control,(*pstate).tlb,/destroy
    end
    (*pstate).writeJPG:begin
        resGUI2_jpg,event
    end;writeJPG
    (*pstate).printbutton:begin
        resGUI2_ps,event
    end;printbutton
    (*pstate).helpbutton:begin
        resGUI2_help,event
    end;printbutton
    else:
    endcase

end;resGUI2_event
;###############################################################################
;
;NAME:
;        resGUI2_help
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
pro resGUI2_help,event
    widget_control,event.handler,get_uvalue=pstate

    helpbase   = widget_base(group_leader = (*pstate).tlb,title='Rescal2 Info',$
                                xoffset=200,yoffset=200)



    helpstring = [  'Rescal2',$
                    ' ',$
                    'Written by Larry Kneller Jr. and William Ratcliff II.',$
                    '',$
                    'Calculations adapted from code by Andrey Zheludev (ResLib)',$
                    'and Collin Broholm (reselps).',$
                    '',$
                    'Rescal 2 uses the Cooper-Nathans approach to calculate the resolution ',$
                    'ellipse in three selected planes:',$
                    '1) The scattering plane (defined by vectors orient1 and orient2 ',$
                    '   (under the Crystal Lattice/Orientation tab),',$
                    '2) The Qx-E plane and ',$
                    '3) The Qy-E plane.',$
                    '',$
                    'The solid red ellipses are the projection of the resolution',$
                    'ellipsoid onto the plane and the black ellipses are the cut',$
                    'of the plane throught the ellipsoid.',$
                    '',$
                    'The parameters for the instrument configuration are modified',$
                    'under the Resolution/Instrument tab.',$
                    '' $
                    ]


    list = widget_list(helpbase,value=helpstring,ysize = 20)

    widget_control,helpbase,/realize

end;resGUI_help



;###############################################################################
;
;NAME:
;        resGUI2_cleanup
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
pro resGUI2_cleanup,id
    print,'resGUI2_cleanup'
    widget_control,id,get_uvalue=pstate


    xwdata = (*pstate).xwdata
    ywdata = (*pstate).ywdata
    xydata = (*pstate).xydata

    xwplot = (*pstate).xwplot
    ywplot = (*pstate).ywplot
    xyplot = (*pstate).xyplot

;    lattice = (*pstate).lattice
;
;    rescalculator = (*pstate).rescalculator

print,'{{RESGUI2_CLEANUP}}'
print,'{1) CLEAN UP DATA}'
    if obj_valid(xwdata) then obj_destroy,xwdata
    if obj_valid(xwdata) then obj_destroy,xwdata
    if obj_valid(xwdata) then obj_destroy,xwdata

print,'{2) CLEAN UP PLOTS}'
    if obj_valid(xwplot) then obj_destroy,xwplot
    if obj_valid(xwplot) then obj_destroy,xwplot
    if obj_valid(xwplot) then obj_destroy,xwplot

print,'{3) CLEAN UP CALCULATORS}'
    if obj_valid((*pstate).lattice) then obj_destroy,(*pstate).lattice
    if obj_valid((*pstate).rescalculator) then obj_destroy,(*pstate).rescalculator

print,'{4) CLEAN UP PARM WIDGETS}'
    if obj_valid((*pstate).resparms) then obj_destroy,(*pstate).resparms
    if obj_valid((*pstate).latparms) then obj_destroy,(*pstate).latparms

print,'{5) CLEAN UP STATE POINTER}'
    ptr_free,pstate


end;resGUI2_cleanup



;###############################################################################
;
;NAME:
;        resGUI2
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
pro resGUI2,group_leader = group_leader


    catch,es
    if es ne 0 then begin
        vaoid = dialog_message('Error occurred in resGUI2.pro, please report the following:'+!error_state.msg)
        catch,/cancel
        return
    endif

    if n_elements(group_leader) eq 1 then begin
        tlb = widget_base(xoffset=150,yoffset=150,title='RESCAL2',/col,mbar=bar,$
                            /tlb_size_events,group_leader=group_leader,$
                            kill_notify='resGUI2_cleanup')
    endif else begin
        tlb = widget_base(xoffset=150,yoffset=150,title='RESCAL2',/col,mbar=bar,$
                            /tlb_size_events,kill_notify='resGUI2_cleanup')
    endelse



    filemenu = widget_button(bar,value='File',/menu)
    printbutton    = widget_button(filemenu,value='Print to File')
    writejpg = widget_button(filemenu,value='Write .jpg')
    quit     = widget_button(filemenu,value='Quit')
    helpmenu = widget_button(bar,value='Help',/menu)
    helpbutton = widget_button(helpmenu,value='About Rescal2')


    row1 = widget_base(tlb,/row)
    row2 = widget_base(tlb,/row)

    xwplotid = cwo_drawplot(row1,obj=xwplot,xsize=300,ysize=300,uname='XWPLOT',$
                                frame=1,title='X-E',ytitle='E',xtitle='Qx')
    ywplotid = cwo_drawplot(row1,obj=ywplot,xsize=300,ysize=300,uname='YWPLOT',$
                                frame=1,title='Y-E',ytitle='E',xtitle='Qy')
    xyplotid = cwo_drawplot(row2,obj=xyplot,xsize=300,ysize=300,uname='XYPLOT',$
                                frame=1,title='X-Y',ytitle='Qy',xtitle='Qx')

    tabs = widget_tab(row2)

    resparmsid = cwo_resparms(tabs, title='Resolution Parms',uname='RESPARMS',obj=resparms)
    resvals = resparms->get_values()

    hq = resvals.qetrans[0]
    kq = resvals.qetrans[1]
    lq = resvals.qetrans[2]

    latparmsid = cwo_latparms(tabs, a,b,c,alpha,beta,gamma,$
                                    astar,bstar,cstar,alphastar,betastar,gammastar,$
                                    h1,k1,l1,h2,k2,l2,hq,kq,lq,$
                                    title='Lattice Parms',uname='LATPARMS',obj=latparms)
    latvals = latparms->get_values()

    textoutputtab = widget_base(tabs,title='Text Output')
    textoutput = widget_text(textoutputtab,xsize=45,ysize = 30,value=strarr(30))

    lattice = obj_new('lattice',latvals.a,latvals.b,latvals.c,latvals.alpha,latvals.beta,latvals.gamma)

    rescalculator = obj_new('Rescal2_calculator',$
                                   lattice,$;a, b, c, alpha, beta, gamma,$           ;LATTICE PARAMETERS
                                   resvals.horizontal,resvals.collimatorh,resvals.collimatorv,$    ;RESOLUTION PARAMETERS
                                   resvals.mosaic,resvals.dspacing,resvals.instrument_orient,$
                                   resvals.qetrans)

    rescalculator->calculate,rm,r0, horizontal=resvals.horizontal,$
                                    collimatorh=resvals.collimatorh,$
                                    collimatorv=resvals.collimatorv,$
                                    mosaic=resvals.mosaic,$
                                    dspacing=resvals.dspacing,$
                                    instrument_orient=resvals.instrument_orient,$
                                    qetrans=resvals.qetrans,$
                                    lattice=lattice,closed=closed


    rmtransformed=lattice->rtransform(latvals.orient1,latvals.orient2,$
                                                     resvals.qetrans,rm)


    ;SET rm TO rmtransformed FOR THE DATA OBJECTS
    rm = rmtransformed
    ;print, rm


    ;SET UP DUMMY DATA FOR PLOTS
    x = [0] & y = [0] & sy = [0]

    ;######################################################
    ;NOTE THAT THIS IS SIMPLY FOR TESTING
    qx = 0.0;total(resvals.qetrans[0:2]*latvals.orient1)
    qy = 0.0;total(resvals.qetrans[0:2]*latvals.orient2)

;OMIT UNTIL A PROPER CALCULATION CAN BE MADE.

;    xydata = obj_new('rescut_data',x,y,sy,legend='XY',$
    xydata = obj_new('scanqpoint_data',x,y,sy,legend='XY',$
                                         showdata=1,$
                                         showlegend=1,$;0,$
                                         rm=rm,$
                                         ro=ro,$
                                         /xy)

    latticevalues = lattice->getvalues()
    qxyz = hkl_to_qxy(resvals.qetrans[0],$
                      resvals.qetrans[1],$
                      resvals.qetrans[2],$
                      latticevalues.a,$
                      latticevalues.b,$
                      latticevalues.c,$
                      latticevalues.alpha,$
                      latticevalues.beta,$
                      latticevalues.gamma,$
                      latvals.orient1,$
                      latvals.orient2,$
                      hklunits=1,$
                      invang=0)

    qx = qxyz[0]
    qy = qxyz[1]


    xydata->setproperty,$
                rm=rm,$
                r0=r0,$
                qx=qx,$
                qy=qy,$
;                Q=resvals.qetrans[0:2],$
;                orient1=latvals.orient1,$
;                orient2=latvals.orient2,$
                E=resvals.qetrans[3];,$
;                astar=latvals.astar,$
;                bstar=latvals.bstar,$
;                cstar=latvals.cstar,$
;                alphastar=latvals.alphastar,$
;                betastar= latvals.betastar,$
;                gammastar=latvals.gammastar

    xyplot->add,xydata

;    xwdata = obj_new('rescut_data',x,y,sy,legend='XW',$
    xwdata = obj_new('scanqpoint_data',x,y,sy,legend='XW',$
                                         showdata=1,$
                                         showlegend=0,$
                                         rm=rm,$
                                         ro=ro,$
                                         /xw)


    xwdata->setproperty,$
                rm=rm,$
                r0=r0,$
                qx=qx,$
                qy=qy,$
;                Q=resvals.qetrans[0:2],$
;                orient1=latvals.orient1,$
;                orient2=latvals.orient2,$
                E=resvals.qetrans[3];,$
;                astar=latvals.astar,$
;                bstar=latvals.bstar,$
;                cstar=latvals.cstar,$
;                alphastar=latvals.alphastar,$
;                betastar= latvals.betastar,$
;                gammastar=latvals.gammastar

    xwplot->add,xwdata

;    ywdata = obj_new('rescut_data',x,y,sy,legend='YW',$
    ywdata = obj_new('scanqpoint_data',x,y,sy,legend='YW',$
                                         showdata=1,$
                                         showlegend=0,$
                                         rm=rm,$
                                         ro=ro,$
                                         /yw)


    ywdata->setproperty,$
                rm=rm,$
                r0=r0,$
                qx=qx,$
                qy=qy,$
;                Q=resvals.qetrans[0:2],$
;                orient1=latvals.orient1,$
;                orient2=latvals.orient2,$
                E=resvals.qetrans[3];,$
;                astar=latvals.astar,$
;                bstar=latvals.bstar,$
;                cstar=latvals.cstar,$
;                alphastar=latvals.alphastar,$
;                betastar= latvals.betastar,$
;                gammastar=latvals.gammastar


    ywplot->add,ywdata

    state = {tlb:tlb,quit:quit,writejpg:writejpg,printbutton:printbutton,$
             helpbutton:helpbutton,$
             xwplot:xwplot,ywplot:ywplot,xyplot:xyplot,$
             xwdata:xwdata,ywdata:ywdata,xydata:xydata,$
             textoutput:textoutput,$
             resparms:resparms,latparms:latparms,$              ;OBJECTS
             resparmsid:resparmsid,latparmsid:latparmsid,$      ;WIDGET ID'S
             lattice:lattice,rescalculator:rescalculator,$
             resvals:resvals,latvals:latvals,$                  ;VALUE STRUCTURES
             rm:rm,r0:r0,$
             qetrans:resvals.qetrans,$
             mosaic:resvals.mosaic,$
             collimatorv:resvals.collimatorv,$
             collimatorh:resvals.collimatorh,$
             horizontal:resvals.horizontal}

    pstate = ptr_new(state)

    widget_control,tlb,/realize,set_uvalue=pstate

    resgui2_draw,{id:tlb,top:tlb,handler:tlb}

    xmanager,'resGUI2',tlb,/no_block

end;resGUI2


