;pro plotbda,filename
;+
; PLOTBDA v1.5 (IDL2) 
;
;  Plot bda file - Menu structure, quick look plotter, can be used to 
;                  select + extract bda datasets. Test_rd compatible.
;		   cursor select on light curve, summation of datasets.
;  if you intend to change anything please read comments.
;
; author:       Andy Phillips , mssl 1991
; in:           filename - name of a BDA file.
; out:          Plots of counts vs time.
; required:     Rd_bsd_header.pro    - read bsd header
;		rd_bsd_rdmap.pro     - read bsd roadmap
;               Rd_bsd_data.pro      - read bsd data sections
;		fmt_tim.pro 	     - format bsd time array into a string
;		range.pro 	     - do a regexp expansion.
;
; syntax:       plotbda[,bdafilename]
;		 (else prompted for [dir]filename[*])
;
; comments: 
;	spectra are selected by certain range criteria.
;	parsing of the selection string (spectstr) is accomplished in range.pro
;	it is not bullet-proof. The selection string contains a comma delinited
;	series of numbers, and/or two wild cards. 
;	* selects all spectra, the rest of the string is ignored.
;	- selects a range. eg 1-3 == 1,2,3.
;	bounds checking is performed, redundancy is not. it is perfectly
;	possible to replot the same spectrum several times eg.
;	1,2,3,1-2,3,3,3 will plot spectra 1,2,3,1,2,3,3,3.
;       Implicit assumption in range option that max(x) = x(max) , min(x) = x(0)
;       error handling uncertain.
;	borrowed mons' code for wild cards.
;
;-
; history:
;  v0.0 atp dump files contents
;  v1.0 atp M.S.S.L 15 - 5 - 91 rewrite, menu structure
;  v1.01 atp hardcopy
;  v1.1 atp idl1 demo version complete, still missing options, mssl specific
;  v1.2 atp idl1 non-mssl specific, missing options, added range.pro,bsdtime
;  v1.3 atp idl2 conversion functionally identical to v1.2 
;  v1.4 atp idl2 inserted error checking reorgainsed default plot variables
;	         into block at start, new bsdtime included.
;  v1.45 atp idl2 Now default plot unit at atart up is as defined externally.
;  v1.5  atp idl2 Fixed bugs/ relating to only one spectrum /channel 
;		 * scans if change channel etc..
;  v1.6  atp idl2 Fixed options 6 and 7. program is now complete aside from
;		  bugfixing.
;  
;  v1.8  atp idl2 Made fixes suggested by rlsac::bjib  - made quit out from
;		  plots easier. Wild card parameters, needs cleaning up
;		  made reset to alpha if tek4010 but see pg e39 idl manual
;	          18/9/91
; RENAMED TO PLOTBDA.PRO 
;  v0.1  atp idl2 Got working with bda files. uses mons database routines
;		  IF IT DOES NOT WORK FIRST CHECK YOUR VERSION OF mons
;		  software matches the files you are trying to read.
;		   This version is very buggy.
;  v0.3   atp idl2  Tidied up several bits, added the light curves bit for an index.
;  v0.3   cdp  Mar 92  de-Vaxed file name handling
;  v0.5   atp 18/3/92 - Rewrite to accomodate test_rd, bring up to date 
;  v0.9   atp 18/3/92 - sequence commands many bug fixes, lightcurve selection
;			can read bda files by self.
;			uses fmt_tim now. 
;  v1.2   atp 23/3/92 - fixed bugs in last version, etc....
;  v1.4   atp 3/4/92  - more bug fixes, few improvements.
;  v1.41  atp 2/8/92  - uses lcbda now. 
;  v1.5   atp 23/11/92 - rationalise with isas
;
;  19709::atp
;
;
;
; initialise local variables
; 1) PLOTTING DEFAULTS - no sanity checking. wrong values == crashed program.
;    plot unit now assumed to be initially defined externally.
;
bcs_struct
gen_struct
 channel = 1;                     (int) Channel to plot.  
 decoyes = 1;                     (int) decompress counts. 
 spectstr = '*';	       (string)	string for range of spectra. see above.
 chstring = '1';	       (string)	 string for range of channels.
 orient = 'portrait';	       (string)  orientation of postscript
;
; 2) variables - do not alter unless support programming
;
 ans = ' ';				Menu variable
 true =1;                              	if !true then quit
 dum = ' '; 				dummy variable for get_kbrd
 ier = 0;				range error variable
 curspect = 0;				plot variable
 j = 0;					internal counter
 version = 'v1.5';			version of this program
 lskip = 0;				plot skipper
 rxlow = 0;				lower plotting x limit
 rxhi = 0;				higher plotting x limit
 got_data = 0;				have already got data via test_rd
 nsumspec = 1;
 nsumstr = '1';
 kplotdirn = 1;
 khcflag = 0;
;
; print program header
;
print,'BDA - PLOTTER ',version,' atp 1991 '
;
;  if !have filename read it in using Mons Morrison's code from test_rd.pro
;  not happy about this.
get_file = 0;
if (n_elements(filnam) eq 0) then begin
   get_file = 1 
   endif else if (filnam eq '' or (strupcase(strmid(filnam,0,3)) ne 'BDA')) then begin
   get_file=1
   endif else begin
   filename = dsk_log+dir+filnam+ext 
   print,'Default filename is :',filename
   print,' Press spacebar to accept, any other key to read in a new file'
   dum = get_kbrd(1)
   if (dum eq '\x0d' or dum eq ' ') then begin 
    if n_elements(dset_str) eq 0 then got_data = 0 else begin
       ndset = n_elements(roadmap)
       if n_elements(dset_str.dset) eq ndset then got_data = 1
       endelse
    endif else get_file = 1 
   endelse

if get_file eq 1 then begin
 ssss = intarr(1) - 1
 bcs_getfile,filename,defstr="BDA*.*"
 if (filename eq '-1') then stop
 endif
;
;
;
print,'Default plot unit - ',!d.name
print,' '
;
; read header info 
;
if (not got_data) then begin
get_lun, lun
openr, lun, filename, /block
;
rd_roadmap, lun, roadmap, ndset, recsize
rd_fheader, filename, fheader, ndset
endif
;
;
; Plotting defaults - do not alter below this line 
; 
  plot_unit=!d.name 
  plot_unit = strlowcase(plot_unit);  +++s+++
  if ((plot_unit eq 'tek') or (plot_unit eq 'regis')) then begin
	tekyes = 1; 
	no_stop = 0; 	                if true then wait for rtn b4 menu
  	endif else begin
	tekyes = 0;
	no_stop = 0;
	endelse
 
 if ((plot_unit eq 'ps')) then begin; +++h+++
	tekyes = 0;
	device,/portrait
	no_stop = 1;                 if true then is hardcopy+dont wait  
        endif
 if (plot_unit eq 'x') then device,retain=2

range,spectstr,ndset-1,spectra,ier; parse default specstr
ntodo = n_elements(spectra); number of spectra to plot in a run
;
; set up plot 
;
set_plot,plot_unit
multiflag=0
;
; output header info
;
;
; strip out file identifier    
;              
break_file,filename,dsk_log,dir,fil,ext,fver
ident = fil+ext
;                                                                               
;
;print,'File - ',filename,' is a version',vernum,' file'
print,'Total number of spectra ',ndset
print,'First Spectrum starts at ',fmt_tim(intextime(roadmap(0).day,roadmap(0).time),/msec)
print,'Last spectrum starts at ',fmt_tim(intextime(roadmap(ndset-1).day,roadmap(ndset-1).time),/msec)
print,' '
if (tekyes eq 1) then begin 
 print,'press any key to continue.'
 if (!d.name eq 'TEK') then device,/reset
 endif
;
; Commence loop
;
while (true eq 1) do begin
 !p.multi=0
 nsumspec=fix(nsumstr)
 print,' '
 print,' '
 print,'PlotBDA ',version,' Options '
 print,'  '
 print,' 1) Select channel (*=all)[',chstring,']'
 print,' 2) Select spectrum, integration (*=all)[',spectstr,',',nsumstr,']'
 print,' 3) Plot Light Curve For all Channels vs Data set number '
 if (!d.name eq 'PS') then begin
  print,' 4) Set plot device [',plot_unit,'-',orient,']'
 endif else begin
  print,' 4) Set plot device [',plot_unit,']'
 endelse
 print,' 5) Plot Decompressed(=1) or Compressed(=0) Counts (toggle) [',decoyes,']'
 print,' 6) Show File_Header and Roadmap structures' 
 print,' 7) Set plot range (0,0)=all [',rxlow,',',rxhi,']'
 print,' Q) Quit '
 print,'  '
 print,' Any other key to plot current selection '
 print,'  Sequence Commands:
 print,'   During a Sequence of Plots press Q or M to return to menu'
 print,'   type ? during plot mode for list of commands '
 print,' '
 ans = get_kbrd(1); 
 case ans of 
  '1': 	begin
	chstring= ' '; reinitialise
	print,'Enter new channel number (1...4)';
	print,'Or enter * for all channels on one page'
	print,format='($,"Channel")'
	

	read,chstring
	if (chstring eq '*') then begin
		channel = 1
		multiflag=1
		endif else begin
		channel = fix(chstring); cast to int
		multiflag=0
		endelse


	if ((channel gt 4) or (channel lt 1)) then begin; assume 4 channels
	    print,'Illegal choice - retry from menu'
	    channel = 1;
	    chstring = string (channel);
	    print,'press any key to continue. '
	    print,' '
	    dum = get_kbrd(1); halt to read error message
	    endif 
       	end
   '2': begin
        ndset = fheader.ndatasets
	print,'Enter new spectrum number(0 ...',string(format='(i5)',ndset-1),')'
	print,' ("*" for all or a comma delimited series "1,3,5" or a range "1-3")'
        print,'Enter C to use the cursor on the light curve.(Xwindows)'
	print,' '
	print,format='($,"Number(s)")'
	read,spectstr
        if spectstr eq '' then spectstr = '*'
        print,format='($,"Number of Spectra to Integrate [1]")'
        read,nsumstr
        if (nsumstr eq '') then nsumstr = '1'
        nsumspec = fix(nsumstr)

        if strmid(strupcase(spectstr),0,1) eq 'C' then begin
         if multiflag eq 1 then begin
          idiot = true;
          while idiot eq true do begin
           print,format='($,"Use light curve from which channel ")'
           read,channel
           if (channel gt 4) or (channel lt 1) then idiot = true else idiot=0
           endwhile
          endif
         !p.multi=0
         if (!d.name eq "X") then begin
          clear_utplot
          ptitle = "Channel "+string(format='(i1)',channel)
          spectra = plot_lcur(roadmap,roadmap.total_cnts(channel-1)>0,/nohard,title=ptitle,psym=0)
          ptitle = ''
          if (size(spectra))(0) eq 0 then spectra = indgen(ndset)
          ier=0
          endif else begin
          print,'Not Xwindows'
          spectstr = "*"
          range,spectstr,ndset-1,spectra,ier
          endelse
         endif else range,spectstr,ndset-1,spectra,ier

	if (ier eq 2) then begin 
		print,'Error in choice - try again from menu'
		print,'press any key to continue. '
		print,' '
                spectra = ndset-1
		spectstr = string(spectra)
		ntodo = 1
		dun = get_kbrd(1);
		endif else begin
		ntodo = n_elements(spectra)
		if (ntodo gt 1) then begin
			; more than one in sequence
			print,' During sequence press return for next plot '
			print,'  or M or Q for menu unless plotting to file '
			print,' '
			print,' press any key to continue.'
			dum = get_kbrd(1);
			endif else begin
			; only one in sequence
			endelse			
		endelse
       	end
   '3':	begin
        ;
	; The window used by lcbda is idl7. save current + pop back later
	;
	if (!d.name eq 'X') then begin 
		; if X and !d.Window == -1 then no windows active. Def=0
		winsav = !d.Window
		if (winsav eq -1) then winsav = 0 
		endif
	print,'Plotting Light Curve in ',orient,' orientation' 
	if (orient eq 'portrait') then lcbda,roadmap,chan=chstring else $
	 lcbda,roadmap,chan=chstring,/landscape
	; restore winsav
	if (!d.name eq 'X') then wset,winsav
	end
   '4':	begin
	no_stop = 0; 	reset no_stop
	if (strlowcase(plot_unit) eq 'ps') then device,/close; +++h+++
	print,'Plot device      TEK - Tektronix type display e.g. kermit '
	print,'                 X - X workstations '
	print,'                 PS - PostScript file, for creating hardcopies'
	print,'                 REGIS - Regis terminals '
	print,' ';+++s+++h+++
	print,format='($,"Plot Device")'
	read,plot_unit
	plot_unit=strlowcase(plot_unit)
	case (plot_unit) of
	  'tek':begin; 
		tekyes = 1
		print,'Tektronix Type display - After plot press any key for menu'
		print,' '
		print,' press any key to continue.'
                dum = get_kbrd(1)
		end
	    'x':begin
		tekyes = 0
                set_plot,plot_unit
		device,retain=2 ; enable backing store.
		print,'X Workstation display'
		print,' '
		print,' press any key to continue.'
		dum = get_kbrd(1)
		end
	   'ps':begin
		tekyes = 0
		no_stop = 1; dont stop in hardcopy output
		print,format='($,"Landscape or Portrait [P]")'
		read,dum
		if (dum eq '') then orient = 'portrait' 
		if (strlowcase(strmid(dum,0,1)) eq 'l') then orient='landscape' else orient = 'portrait'
		print,'PostScript file - plot(s) will be output without waiting'
		print,'  for keyboard input, selecting option 4 or quitting will '
		print,'  close the current file. Print with command pprint'
		print,' '
		print,' press any key to continue.'
		dum = get_kbrd(1)
		end
	'regis':begin
		tekyes = 1
		print,'Regis type display - After plot press key for menu'
		print,' ' 
		print,' press any key to continue.'
		dum = get_kbrd(1)
		end

;    +++s+++h+++ insert documentation and tekyes/nostop
;	flag conditions here

	ELSE:   begin
		print,'Error in choice - try again from menu'
		print,' resetting to default plot unit '
		print,' press any key to continue. '
		print,' '
		dum = get_kbrd(1)
		plot_unit = !d.name
		end
	endcase
	set_plot,plot_unit
	if (plot_unit eq 'ps') then $
			if orient eq 'landscape' then device,/landscape $
			 else device,/portrait
	end
   '5': begin
	if (decoyes eq 0) then begin 
		print,'Plotting decompressed counts '
		decoyes = 1
		endif else begin
		print,'Plotting compressed counts '
		decoyes = 0
		endelse
		print,'  '
		print,' press any key to continue.'
		dum = get_kbrd(1)
	end
   '6': begin
	print,'dump of header info '
	print,'  '
	help,/struct,fheader
	help,/struct,roadmap
	
        print,'--Return-to-menu----'&dum = get_kbrd(1);
	end
   '7': begin
 	 print,' '
	  rxlow = ' '; reinitialise
	  rxhi = ' '
	  print,'Enter plot range between 0 and 255'
	  print,'(Enter 0 and 0 to reset to all)'
	  print,format='($,"Low ")'
	  read,rxlow
	  print,format='($,"High")'
	  read,rxhi
	  rxlow = float(rxlow); cast to float
	  rxhi = float(rxhi)
	  if (rxlow gt rxhi) then begin ; lowest -> rxlow
	    kktoggle = rxlow;
 	    rxlow = rxhi
	    rxhi = kktoggle
	    endif		
		
	  if ((rxlow lt 0) or (rxhi gt 255)) then begin; bound check
	   if ((rxlow eq 0) and (rxhi eq 0)) then begin
	     print,'Resetting plot range'
	     endif else begin
	     print,'Illegal choice - retry from menu'
             rxlow = 0&rxhi = 0
	     print,'press any key to continue. '
	     print,' '
	     dum = get_kbrd(1); halt to read error message
	     endelse
	    endif
	end
   'Q': begin
	print,'ok - quitting'
        kktoggle = !d.name
        set_plot,'ps'
        device,/close
        set_plot,kktoggle
        filnam = fil
	true = 0
	end
   'q': begin
	print,'ok - quitting'
        kktoggle = !d.name
        set_plot,'ps'
        device,/close
        set_plot,kktoggle
        filnam = fil
	true = 0
	end

   ELSE:begin

        j = 0
;
; set plot range / clear plot range
;
;
; start plotting loop
;
	if (multiflag eq 1) then begin
		!p.multi = [0,2,2,0,0]
		chstart=1
		chend = 4
		endif else begin
		chstart = channel
		chend = channel
		!p.multi=0
		endelse

       if (not got_data) then begin
        ; first find if need to read
        kkc = -1 &kkkk = 0&kktoggle = 0
        if ssss(0) eq -1 then kkkk =1 
        if ((n_elements(ssss) eq 0) or (kkkk eq 1)) then begin
          kkc=spectra 
          kktoggle = 1
         endif else begin
         for iih = 0,n_elements(spectra)-1 do begin 
            kfred = where(ssss eq spectra(iih),knumber)
            if (knumber eq 0) then $ 
              if kktoggle eq 0 then begin
                kkc = spectra(iih)
                kktoggle = 1 
                endif else kkc = [kkc,spectra(iih)]
            endfor
         endelse
         ;
         ; filter out crap blockids
         ; 
        if kktoggle eq 1 then begin
         if n_elements(kkc) eq 1 then kkc = intarr(2)+kkc 
         for iih = 0,n_elements(kkc)-1 do if (roadmap(kkc(iih)).blockid gt 1) $
          then kkc(iih) = -1
         dum = where(kkc ge 0,knumber)
         if knumber eq 0 then kkc = 0 else kkc = [1,kkc(dum)]
         endif
        if n_elements(kkc) gt 1 then begin
         kkc = kkc(1:n_elements(kkc)-1)
         print,'reading data....'
         tdset_str = mk_dset_str(filename,kkc)
         rd_bda,filename,tdset_str,tindex,tdata,roadmap,dset_str=tdset_str
         if (n_elements(ssss) eq 0) or (kkkk eq 1) then begin
          ; make ssss, data index
          dset_str = mk_dset_str(filename,kkc)
          ssss = kkc
          data = tdata
          tdata=0
          index = tindex
          endif else begin
          ; add ssss data index
          datsiz = size(data)
          tdatsiz = size(tdata)
          if (tdatsiz(1) ne datsiz(1)) then begin
             print,'ERROR - mismatch in data block sizes.'
             if tdatsiz(1) gt datsiz(1) then begin
               print,'New data array is ',tdatsiz(1),' wide'
               print,'Old data array is ',datsiz(1),' wide'
               print,'Truncating new data array'
               tdata = tdata(0:datsiz(1)-1,*)
               endif else begin
               print,'New data array is ',tdatsiz(1),' wide'
               print,'Old data array is ',datsiz(1),' wide'
               print,'Truncating old data array'
               data = data(0:tdatsiz(1)-1,*)
               endelse
             print,'This is probably going to fall over...'
             endif
          ssss = [ssss,kkc]
          data = [[data],[tdata]]
          tdata = 0
          index = [index,tindex]
          addr = sort(ssss)
          ssss = ssss(addr)
          dset_str=mk_dset_str(filename,ssss)
          data = data(*,addr)
          index = index(addr)
          endelse
         print,'finished...'
         ndset = n_elements(spectra)
          endif
        endif

        kplotdirn = 1
	repeat begin 
          lskip =0;
          if (j ge ndset) then lskip=1
	  if (lskip eq 0) then begin	
	  if (ntodo gt 1) then curspect = spectra(j) else curspect =fix(spectra,0)
 
          for chloop = chstart, chend do begin
           kktoggle = 0
           nsumspec = fix(nsumstr)
	   for iih = 0,nsumspec-1 do begin
            addr = where(ssss eq curspect+iih,knumber)
            if (knumber eq 0) then nsumspec = nsumspec - 1 else begin
             if kktoggle eq 0 then begin 
              pdata = data(*,addr(0))
              kktoggle = 1 
              endif else pdata=[[pdata],[data(*,addr)]]
              modeid = index(addr(0)).bcs.modeid
             endelse
            endfor
 
         if kktoggle eq 1 then begin 
	  if ( (modeid lt 0) or (modeid gt 4) ) then begin
	     print,' modeid(group plan) ',modeid,' not recognised...'
	     print,' Will dump entire data array  to screen'
	     wait,1
	     nsamppchan = intarr (4)
	     nsamppchan(*) = n_elements(pdata)
	     y = pdata
	     endif else begin

             bcs_grp_plan,modeid,ngroup,group,nsamppchan
	     ;/* scan along the grouper plan */
             if (total(nsamppchan) gt n_elements(pdata)) then begin
		print,'ERROR - data groupings do not match grouper plan'
		print,'
		print,'modeid - ',modeid
		print,'grouper plan - ',group
		print,'terminating program'
		stop
		endif
 
          x = indgen(nsamppchan(chloop-1))
    	
	  if (decoyes eq 1) then begin
                if nsumspec ne 1 then begin
                 pdata = bcs_decomp(pdata,0)
                 pdatiz = size(pdata)
                 if pdatiz(0) eq 1 then nsummed = 1 else nsummed = pdatiz(2)
                 pdatmp = intarr(pdatiz(1))
                 for iih = 0,nsummed-1 do pdatmp = pdatmp + pdata(*,iih)
                 pdata=pdatmp
                 endif else begin
                 pdata = bcs_decomp(pdata,0)
                 nsummed = 1
                 endelse
   		px = x
		endif else begin
                if nsumspec ne 1 then begin
                  pdatiz = size(pdata)
                  if pdatiz(0) eq 1 then nsummed = 1 else nsummed = pdatiz(2)
                  pdatmp = intarr(pdatiz(1))
                  for iih = 0,nsummed-1 do pdatmp = pdatmp + pdata(*,iih)
                  pdata = pdatmp
                  endif else begin
                  nsummed = 1
                  endelse
		px = x
		endelse

           gplanoffs = total(nsamppchan(0:chloop-1)) - total(nsamppchan(chloop-1))
						 ; /* initial index 
						 ;  * for the y array under this 
	        			                                 ;  * grouper plan */
	     y = 0
             for i = 0,(ngroup(chloop-1)-1) do begin
	       ; expand the grouper plan .....
	       ; At the moment not bothered with dealing with grouper 
	       ; plans that have a multiple number of in put bins binned 
	       ; into an output bin. eg. [4,8,192,1,4,8]
	       ;
               if (i eq 0) then begin
                     y = pdata(gplanoffs:gplanoffs+group(i*2,(chloop-1))-1) 
		     endif else begin
		     y = [y,pdata(gplanoffs:gplanoffs+group(i*2,(chloop-1))-1)]
		     endelse
               gplanoffs = gplanoffs + group(i*2,(chloop-1))
               endfor

             endelse

       if (multiflag eq 1) then begin
         if (chloop eq 1) then    $
	  kptitle = 'Chan '+string(format='(i2)',chloop)+ $
		' Spect '+string(format='(i5)',curspect)+'   '+ $
                 'Nsum '+string(format='(i4)',nsummed);

         if (chloop eq 2) then     $
          kptitle = 'Chan '+string(format='(i2)',chloop)+ $
                ' Time '+fmt_tim(intextime(roadmap(curspect).day, $
                  roadmap(curspect).time),/msec)

         if (chloop gt 2) then     $
          kptitle = 'Chan '+string(format='(i2)',chloop)

        endif else begin

	  kptitle = 'Chan '+string(format='(i2)',chloop)+ $
		' Spect '+string(format='(i5)',curspect)+'   '+ $
                 'Nsum '+string(format='(i4)',nsummed) + $
                ' Time '+fmt_tim(intextime(roadmap(curspect).day, $
                  roadmap(curspect).time),/msec)
          endelse

          interval = roadmap(curspect).dgi * nsummed / 8.0
	  kytitle = 'Counts/bin per '+string(format='(f4.1)',interval)+' secs'
          kxtitle = 'Bin Number'
          plot,px,y    ,Xrange=[rxlow,rxhi], font =-1, psym=10, $
                       xstyle=1,yrange=[0,0],linestyle=0,title=kptitle, $
                       xtitle=kxtitle,ytitle=kytitle

       endif else begin
             print,'no valid data for spectrum',curspect
              kptitle='Chan '+string(format='(i2)',chloop)+ $
		' Spect '+string(format='(i5)',curspect)+'   '+ $
                 'Nsum '+string(format='(i4)',nsummed) 
	     j = j + kplotdirn
             endelse
	endfor
	  if (!d.name eq 'PS') then print,'Output of spectrum',j,'complete'
	  if (khcflag eq 1) then begin
                    khcflag = 0
                    pprint
                    set_plot,kolddev
                    endif
		
	  if (ntodo gt 1)  then begin
            if (!d.name eq 'X') then print,kptitle
            if (no_stop eq 0) then dum = get_kbrd(1) else dum = get_kbrd(0);
                case strlowcase(dum) of 
                'c':  no_stop=1
                's':  no_stop=0
                'd':  kplotdirn=kplotdirn*(-1)
		'b':  j = j - 2*nsumspec*kplotdirn
		'!':  begin
			cmdstr = ''
			read,cmdstr
			dum = execute(cmdstr)
		        j = j - nsumspec*kplotdirn
			print,'+ [done]'
			;just in case ....
			set_plot,plot_unit
			end
		'm':  begin
			j = ntodo
                        kplotdirn=1
			end
                'q':  begin
			j = ntodo
			kplotdirn=1
			end
                'h': begin
                      khcflag = 1
                      kolddev = !d.name
                      set_plot,'ps'
		      j = j - nsumspec*kplotdirn
                     end
		'?': begin 
			print,'Plot Mode commands'
			print,' '
			print,'c for continous mode'
			print,'s for step by step'
			print,'q or m return to main menu '
			print,'d reverses time direction of plots'
			print,'b goes back one spectrum (depends on "d")'
			print,'h for hardcopy'
			print,'! for an IDL escape (can be used to call other programs)'
			print,'? for help'
			print,' '
		        j = j - nsumspec*kplotdirn
			end
                else:
                endcase
	     endif
	  endif; /*skip */
	  j = j + nsumspec*kplotdirn
          if (j lt 0) then j = ntodo
	  endrep until j ge ntodo

	if ((tekyes eq 1) and (ntodo eq 1)) then dum = get_kbrd(1);
       	end
   endcase
 endwhile
end
