; $Id: oodisplayecho__savesession.pro,v 1.10 2005/11/16 16:46:06 kneller Exp $
;###############################################################################
;
;CLASS NAME:
;    pro ooDisplayEcho__savesession
;
;PURPOSE:
;               To save the sessions and individual objects.
;CATEGORY:
;               Data Visualization, Analysis and Manipulation.
;SUPERCLASSES:
;               myProperties
;
;METHODS:
;    ooDisplayEcho::saveSession
;
; AUTHOR:
; Larry Kneller
; NIST Center for Neutron Research
; 100 Bureau Drive, Gaithersburg, MD 20899
; United States
; kneller@nist.gov  301-975-8839
; July 25,2005
;
; 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 of if the code in this file is
; included in another product.
;
;###############################################################################
function ooDisplayEcho::saveSession,xml=xml,sav=sav,index=index,$
                                    prerestore=prerestore,$
                                    exitflag=exitflag,_Extra=extra
;
;NAME:
;        ooDisplayEcho::saveSession
;
;PURPOSE:
;           Encapsulate all save session functionality into one method
;           to be used from file menu and on final exit.
;PARAMETERS:
;
;KEYWORDS:
;           xml     Flag to save as .xml
;           sav     Flag to save as .sav
;           index   If index is present, only the object at self.qchoiceindex will be saved.
;           exit    flag to indicate that this is being called on exit.
;           prerestore  flag to indicate that a session is being restored and this will save
;                       the current session before continuing
;RETURN VALUE
;           1/0 TO INDICATE SUCCESS/FAILURE

            if n_elements(xml) eq 0 then xml = 0
            if n_elements(sav) eq 0 then sav = 0
            if n_elements(index) eq 0 then index = -1
            if n_elements(exitflag) eq 0 then exitflag = 0
            if n_elements(prerestore) eq 0 then prerestore = 0

            ;SET DEFAULT AS .sav
            if xml eq 0 and sav eq 0 then sav = 1

            count = self.datacontainer->count()
            if count gt 0 then begin
                if xml eq 1 then begin


                        print,'ooDisplayEcho::menuEvents SAVESESSION.'
                        print,'<nobj>  '+strtrim(string(count),2)+'  </nobj>'


                        CATCH, Error_status

                           ;This statement begins the error handler:
                           IF Error_status NE 0 THEN BEGIN
                              PRINT, 'Error index: ', Error_status
                              PRINT, 'Error message: ', !ERROR_STATE.MSG
                              ; Handle the error
                                fn = self.work_dir+'nse_default_save_file.xml'
                              CATCH, /CANCEL
                           ENDIF


;                        fn = dialog_pickfile(/write,/overwrite_prompt,filter='*.xml',default_extension='xml')
                        fn = dialog_pickfile(/write,/overwrite_prompt,path = self.work_dir,$
                                    filter='*.xml',default_extension='xml')




                        fnlen = strlen(fn)
                        if fnlen ge 4 then begin
                            fn_ext = strmid(fn,fnlen-4,4)
                            print,'fn_ext',fn_ext
                            if strupcase(fn_ext) ne '.XML' then begin
                                fn = fn+'.xml'
                            endif
                        endif else begin
                            if fn ne '' then begin
                                fn = fn+'.xml'
                            endif else begin
                                inq = dialog_message('NO OUTPUT FILE OR INVALID OUTPUT FILE SELECTED. Try again?',/question)

                                if inq eq 'Yes' then begin
                                    ret = self->saveSession(xml=xml,sav=sav,index=index,$
                                                        prerestore=prerestore,$
                                                        exitflag=exitflag,_Extra=extra)
                                endif else begin
                                    return,0
                                endelse

                            endelse
                        endelse

                        if (fn eq '') or (fnlen le 4) then begin
                                inq = dialog_message('NO OUTPUT FILE OR INVALID OUTPUT FILE SELECTED. Try again?',/question)

                                if inq eq 'Yes' then begin
                                    ret = self->saveSession(xml=xml,sav=sav,index=index,$
                                                        prerestore=prerestore,$
                                                        exitflag=exitflag,_Extra=extra)
                                endif else begin
                                    return,0
                                endelse
                        endif else begin

                            self.work_dir = file_dirname(fn,/mark_directory)
                            openw,lun,fn,/get_lun

                            ;REMEMBER TO READ OFF THESE NEXT TWO LINES
                            ;IN THE readSession PROCEDURE AND TO
                            ;AVOID THEM IN THE ooEcho::readState METHOD.
                            ;
                            printf,lun,'<xml>'
                            printf,lun,'<!-- PLEASE DO NOT EDIT THIS FILE!!!-->'
                            printf,lun,'<!-- CHANGES MAY DESTROY THE SAVED STATE.-->'
                            printf,lun,'<session>'
                            printf,lun,'<nobj>  '+ $
                                        strtrim(string(count),2)+ $
                                        '  </nobj>'

;;033105
;;PROGRAM CRASHES HERE!!!!!
;help,self

;FIXED WITH IF STATEMENTS.

                            if widget_info(self.atwwidth,/valid_id) ne 0 then begin
                                widget_control,self.atwwidth,get_value=currentwidth
                            endif else begin
                                currentwidth = self.gaussianwidth
                            endelse

                            swidth = strtrim(string(currentwidth),2)


                            ;print,'swidth = ',swidth
                            printf,lun,'<gaussianwidth>  '+swidth+'  </gaussianwidth>'

                            if widget_info(self.atwperiod,/valid_id) ne 0 then begin
                                widget_control,self.atwperiod,get_value=currentperiod
                            endif else begin
                                currentperiod = self.periodvalue
                            endelse


                            speriod = strtrim(string(currentperiod),2)
                            printf,lun,'<period>   '+speriod+'   </period>'
                            printf,lun,'<data_dir>  '+self.data_dir+'   </data_dir>
                            printf,lun,'<work_dir>  '+self.work_dir+'   </work_dir>



                            ;120304
                            ;PROGRESS BAR
                            if widget_info(self.atlb,/valid_id) ne 0 then begin
                                b1 = widget_base(title='Session Save',xsize=200, $
                                    xoffset=400,yoffset=400,/floating,group_leader=self.atlb)
                            endif else begin
                                b1 = widget_base(title='Session Save',xsize=200);, $
                                    ;xoffset=400,yoffset=400)
                            endelse

;print,'b1=',b1
                            p1 = cw_progress(b1,value=[count], $
                                                    title=['Obj # ='])

;print,'p1=',p1
                            myErrorStatus = 0
                            print,Error_status
                            CATCH, Error_status

                               ;This statement begins the error handler:
                               IF Error_status NE 0 THEN BEGIN
                                  PRINT, 'Error index: ', Error_status
                                  PRINT, 'Error message: ', !ERROR_STATE.MSG
                                  ; Handle the error
                                    ;fn = self.work_dir+'nse_default_save_file.xml'
                                    void = dialog_message('Saving without showing progress.',/info)
                                    myErrorStatus = -1
                                  CATCH, /CANCEL
                               ENDIF
                            print,Error_status

                            if myErrorStatus ne -1 then $
                                widget_control,b1,/realize


                            for io = 0,count-1 do begin
                                ref=(self.dataContainer->get(position=io))
                                dum=ref->writestate(lun=lun);print,ref->writestate(lun=lun)
                                widget_control,p1,set_value=[io+1]
                            endfor;io
                            printf,lun,'</session>'
                            printf,lun,'</xml>'
                            widget_control,b1,/destroy
                            free_lun,lun
                            return,1
                        endelse
                endif else begin    ;END OF .xml BLOCK

                    print,'SAVE THE FILE IN THE .sav FORMAT'
                        if prerestore eq 0 then begin
                            if index ne -1 then begin
                                title = 'Save Object'
                            endif else begin
                                title = 'Save Session'
                            endelse
                        endif else begin
                            ;void = dialog_message('PLEASE SAVE YOUR CURRENT SESSION BEFORE RESTORING',/information)
                            inq = dialog_message('CURRENT DATA WILL BE DELETED ON RESTORE. Save Now?',/question)

                            if inq eq 'Yes' then begin
                                ret = self->saveSession(xml=xml,sav=sav,index=index,$
                                                    prerestore=0,$
                                                    exitflag=exitflag,_Extra=extra)
                                return,ret
                            endif else begin
                                return,0
                            endelse

                            title = 'SAVE NOW!!! Data will be deleted upon restore.'
                        endelse

                        if exitflag eq 1 then begin
                            inq = dialog_message('WOULD YOU LIKE TO SAVE YOUR SESSION BEFORE QUITTING?',/question)
                            if inq eq 'No' then return,0
                        endif;exitting

                        fn = dialog_pickfile(/write,/overwrite_prompt,path = self.work_dir,$
                                    filter='*.sav',default_extension='sav',title=title)


;                        void = dialog_message('savesession TESTING 1: filename = '+fn)

                        fnlen = strlen(fn)
                        if fnlen ge 4 then begin
                            fn_ext = strmid(fn,fnlen-4,4)
                            print,'fn_ext',fn_ext
                            if strupcase(fn_ext) ne '.SAV' then begin
                                fn = fn+'.sav'
                            endif
                        endif else begin
                            if fn ne '' then begin
                                fn = fn+'.sav'
                            endif else begin
                                inq = dialog_message('NO OUTPUT FILE OR INVALID OUTPUT FILE SELECTED. Try again?',/question)

                                if inq eq 'Yes' then begin
                                    ret = self->saveSession(xml=xml,sav=sav,index=index,$
                                                        prerestore=prerestore,$
                                                        exitflag=exitflag,_Extra=extra)
                                endif else begin
                                    return,0
                                endelse
                            endelse
                        endelse
                        if (fn eq '') or (fnlen le 4) then begin
                                inq = dialog_message('NO OUTPUT FILE OR INVALID OUTPUT FILE SELECTED. Try again?',/question)
                                if inq eq 'Yes' then begin
                                    ret = self->saveSession(xml=xml,sav=sav,index=index,$
                                                        prerestore=prerestore,$
                                                        exitflag=exitflag,_Extra=extra)
                                endif else begin
                                    return,0
                                endelse
                        endif else begin

;                        void = dialog_message('savesession TESTING 2: filename = '+fn)


;                        if widget_info(self.atlb,/valid_id) ne 0 then begin
;                            print,'GROUP LEADER VALID'
;                            b1 = widget_base(title='Session Save',xsize=200, $
;                                xoffset=400,yoffset=400,/floating,group_leader=self.atlb)
;                        endif else begin
;                            print,'GROUP LEADER NOT VALID'
                            b1 = widget_base(title='Session Save',xsize=300, $
                                                        xoffset=400,yoffset=400)
;                        endelse


;print,'b1=',b1
                        p1 = cw_progress(b1,value=[count],$;count], $
                                                title=['Please wait '])
                        widget_control,p1,set_value=[count]

                        widget_control,b1,/realize



                            self.work_dir = file_dirname(fn,/mark_directory)


                            if widget_info(self.atwwidth,/valid_id) ne 0 then begin
                                widget_control,self.atwwidth,get_value=currentwidth
                            endif else begin
                                currentwidth = self.gaussianwidth
                            endelse

                            if widget_info(self.atwperiod,/valid_id) ne 0 then begin
                                widget_control,self.atwperiod,get_value=currentperiod
                            endif else begin
                                currentperiod = self.periodvalue
                            endelse
                            data_dir = self.data_dir
                            work_dir = self.work_dir
                            if index eq -1 then begin
                                nse_container = self.datacontainer
                            endif else begin
                                nse_container = obj_new('idl_container')
                                ref = self.datacontainer->get(position=index)
                                nse_container->add,ref
                            endelse

                            qchoiceindex = self.qchoiceindex
                            xindex = self.xindex
                            yindex = self.yindex


;                        void = dialog_message('savesession LAST TESTING BEFORE save: filename = '+fn)

                            if !version.release ge 6.1 then begin
                                save,xindex,yindex,qchoiceindex,data_dir,work_dir,nse_container,$
                                        filename = fn,/compress;,$
                                        ;description = 'NSE DATA REDUCTION'
                            endif else begin
                                ;print,'TESTING 6.1'
                                save,xindex,yindex,qchoiceindex,data_dir,work_dir,nse_container,$
                                        filename = fn,/compress
                            endelse



                            if widget_info(b1,/valid_id) gt 0 then widget_control,p1,set_value=[1]
                            ;ELIMINATE THE NEWLY CREATED CONTAINER OBJECT IF SAVING ONLY A SINGLE OBJECT
                            if index ne -1 then begin
                                nse_container->remove,/all
                                obj_destroy,nse_container
                            endif

                            if widget_info(b1,/valid_id) gt 0 then widget_control,b1,/destroy

                            return,1
                        endelse;valid filename
                endelse;END OF .sav BLOCK
            endif else begin
                ;092805
                ;ELIMINATE THE NEXT MESSAGE SINCE IT PROVIDES NO ADDITIONAL INFORMATION.
                if prerestore ne 1 and exitflag ne 1 then begin
                    void = dialog_message('THERE ARE NO DATA TO SAVE.')
                endif
                return,1
            endelse
end;saveSession
