;+
;===========================================================================
;
; file CPDISPLAY.PRO -- includes routines CPTV, CPDIFF, CPDISPLAY
;
;===========================================================================
;
;
; NAME:
;	CPTV
;
; PURPOSE:
; 	Send a single (not movie) image, housekeeping info and 
;	requested drawing option output to screen or printer.
;
; CATEGORY:  
;	CP display
;
; CALLING SEQUENCE:
;	CPTV, DATA=DATA, HK=HK, XPOS=XPOS, YPOS=YPOS, X_SIZ=X_SIZ, 
;		Y_SIZ=Y_SIZ, XWINSIZ=XWINSIZ, YWINSIZ=YWINSIZ, COLO=COLO, $
;		IMSIZ=IMSIZ, DONORTH=DONORTH, DODISK=DODISK, $
;		DORADII=DORADII, DORADIAL=DORADIAL, HOUSEKP=HOUSEKP, $
;		RULETIMES=RULETIMES, RULECONDITION=RULECONDITION, $
;		SIN_MOV=SIN_MOV, NORM_DIFF=NORM_DIFF, PROCESSED=PROCESSED, $
;		FILENAME=FILENAME, DIFFNAME1=DIFFNAME1, DIFFNAME2=DIFFNAME2, $
;		SAVEME=SAVEME, WMOVIE=W, NFILES=NFILES
;
; CALLED BY:
;	CPDISPLAY
;
; CALLS TO:  
;	CPHOUSE, CPSUNCEN, PSPLOT, CPINTERANIMATE, RESPOND_WIDG
;         
; INPUTS:
;	DATA    : Byte array of size equal to CP image.
;	HK	: Array of size (224 x N) where N is 1 for single images
;		  and 2 for difference images. Contains the housekeeping
;		  information for the current image(s)
;	XPOS  : X direction screen coordinate (device pixels), to place window
;	YPOS  : Y direction screen coordinate (device pixels), to place window
;	X_SIZ : Image X size
;	Y_SIZ : Image Y size
;	XWINSIZ :  X direction width of window w/ housekeeping
;	YWINSIZ :  Y direction width of window 
;	COLO  : -1 means no hard copy allowed
;		 0 means hard copy device is B/W
;		 1 means hard copy device is color
;	IMSIZ : Size of one dimension of CP image, CP images are square.  
;	DONORTH : 0 means don't draw solar north
;		  1 means do draw solar north on image
;	DODISK  : 0 means don't draw solar disk
;		  1 means do draw solar disk
;	DORADII : 0 means don't draw radius lines
;		  1 means do draw radius lines
;	DORADIAL : 0 means don't draw radial lines
;		   1 means do draw radial lines
;	HOUSEKP : X direction size reserved for house keeping information
;	RULETIMES : 0 means don't do pick any R/theta
;		    1 means pick 1 R/theta
;		    2 means pick multiple R/theta
;		    3 means enter R/theta
;		    4 means use r/theta already in memory
;	RULECONDITION : 0 means draw ruler s/c thru R/theta
;			1 means mark R/theta click w/ circle
;			2 means don't draw ruler or mark
;	SIN_MOV  : 0 means current display mode is for single images
;	           1 means current display mode is for movies
;	NORM_DIFF : 0 means do a normal image
;                   1 means do a difference image
;	PROCESSED : for movies a number indicating the current movie frame
;	FILENAME  : string filename normal images	
;	DIFFNAME1 : string filename for base image 
;	DIFFNAME2 : string filename for subtraction image 
;	SAVEME    : for movies 0 means don't save movie to a file
;			       1 means do save movie to a file
;	W 	: associated record array for file output
;	NFILES  : for movies the number of frames in movie
;
; OPTIONAL INPUTS: 
;	none
;
; OUTPUTS:
;	PROCESSED : for movies a number indicating the next movie frame
;
; OPTIONAL OUTPUTS: 
;	none
;
; COMMON BLOCKS:
;	CPLASTPASS  for plot scan values 
;	CPNEW_WINDOW  for parameters relating to a new window
;	CPWIDGBASES for the widget IDs of the informational windows
;
; SIDE EFFECTS:
;	If hardcopy is set, creates postscript fiiles.
;	If SAVEME is set then creates a file containing the images and
;	housekeeping information of a movie.
;	If doing radial or azmuthal scans, a window is created.
;
; RESTRICTIONS: 
;	none
;
; PROCEDURE:  
;	Output image to selected device and call CPSUNCEN to draw line options.
;	If doing radial or azmuthal scans, they are plotted now.
;	For movies to be saved write necessary arrays to an already opened file.
;
; MODIFICATION HISTORY:
;	1991 - Elaine Einfalt (HSTX)
;
;-


pro cptv, data=data, hk=hk, xpos=xpos, ypos=ypos, x_siz=x_siz, y_siz=y_siz, $
		xwinsiz=xwinsiz, ywinsiz=ywinsiz, colo=colo, $
		imsiz=imsiz, donorth=donorth, dodisk=dodisk, $
		doradii=doradii, doradial=doradial, housekp=housekp, $
		ruletimes=ruletimes, rulecondition=rulecondition, $
		sin_mov=sin_mov, norm_diff=norm_diff, processed=processed, $
		filename=filename, diffname1=diffname1, diffname2=diffname2, $
		saveme=saveme, wmovie=w, nfiles=nfiles

@cplastpass.common
@cpnew_window.common
@cpwidgbases.common


    if sin_mov eq 1 then colo = -1		; can't print movies

    scan_cond = 2				; 0=scan only
						; 1=image only
						; 2=both

    if colo ge 0 then begin			; making a hardcopy
	if rulecondition ge 3 then $
	   scan_cond = respond_widg(title='Scan related option', $
					 mess='Select one of the following,'+$
					       ' to be printed.', $
					 butt=['Print the scan only', $
					       'Print the image only', $
					       'Print scan and image'], $
					 /column)

	if scan_cond ne 0 then begin
           set_plot,'ps',/copy   &   !p.font=0
           if norm_diff eq 0 then oxsiz=21. else oxsiz=23.  ; output size
           oysiz = oxsiz * (ywinsiz/xwinsiz)   		 ; square up output
           xoff  = 3.0 + norm_diff  &  yoff=25.5

           device, /landscape, bits_per_pixel=8, xsize=oxsiz, ysize=oysiz, $
	        xoffset=xoff, yoffset=yoff, color=colo, /helvetica, $
	        FILENAME='CPIMAGE.PS'
	endif	

    endif

    xpos = xpos / xwinsiz    &  ypos = ypos / ywinsiz	; covnert to normalized
    x_siz = x_siz / xwinsiz  &  y_siz = y_siz / ywinsiz	; covnert to normalized
    housekp = housekp / xwinsiz  

    ;
    ; Put up the image
    ;

    if scan_cond ne 0 then begin
       ;
       ; Will be showing the image
       ;

	
	tv, data, xpos, ypos, /normal  

       ;
       ; Write the housekeepping information, (do twice if a difference)
       ;

       for ntime = 0,norm_diff do cphouse, hk=hk(*,ntime), ntime=ntime, colo=colo

       ;
       ; Draw the requested lines.
       ;

       cpsuncen, data=data, imsiz=imsiz, hk=hk(*,0), donorth=donorth, $
		dodisk=dodisk, $
		doradii=doradii, doradial=doradial, colo=colo, $
		ruletimes=ruletimes, rulecondition=rulecondition, $
		housekp=housekp, $
		sin_mov=sin_mov, norm_diff=norm_diff, $
		xpos=xpos, ypos=ypos, x_siz=x_siz, y_siz=y_siz 


       if colo ge 0 then begin			
	  ;
	  ; Close and print image
	  ;

	  device,/close  
          psplot, FILENAME='CPIMAGE.PS', color=colo, /delete

          set_plot,'x'  &  !p.font=-1 
          widget_control, comment, set_value='Printing image.', /append

       endif
    endif

    if (rulecondition ge 3) and (ruletimes ne 0) and $
	(scan_cond ne 1) then begin

      ;
      ;
      ; Plot radial or azmuthal scans.
      ;
      ;
         
      num_of_scans = where(cpnum_vals_n_scans ne (-1)) 
      if num_of_scans(0) ne -1 then num_of_scans = n_elements(num_of_scans)-1 $
			       else num_of_scans = -1

      if num_of_scans gt -1 then begin      		
	
         ;
         ; Have some valid data scans, so open appropriate device
         ;

         if colo eq -1 then begin		; to the screen 
            ;
            ; Get a window to display the plot
            ;

   	    imag_window = !d.window          	; remember image window
	    savreuse  = reuse

	    ;
	    ; Need to switch to a plotting window
	    ; 

	    if n_elements(plot_window) eq 0 then plot_window = -1

	    if plot_window ne -1  then begin  		; there is a window
	       device, window=w_up                         ; existing windows
	       if w_up(plot_window) eq 0 then reuse=0      ; not there anymore
	    endif else reuse = 0			; there is no window
            
	    if reuse then begin  			; reuse window
		wset, plot_window			; locate plot window
	        device, get_window = winpos             ; but keep in same place
		xwinpos = winpos(0)  &   ywinpos = winpos(1)
	        wdelete, plot_window
	    endif else begin  
		lastmark = 1 - lastmark			; alternate position
                xwinpos = sc(0)-448-10
                ywinpos = (sc(1)-448) * lastmark + (lastmark * (-20) + 10)
	    endelse
	
	    if rulecondition eq 3 then title='CP Radial Scan' $
				  else title='CP Azmuthal Scan'
	    winup, /free, title=title, xsiz=448+150, ysiz=600, $
			  retain=2, xpos=xwinpos, ypos=ywinpos

	    plot_window = !d.window
	    reuse = savreuse			; restore original setting


         endif else begin		; making a hardcopy

           set_plot,'ps',/copy   &   !p.font=0

           device, /landscape, bits_per_pixel=8, color=colo, /helvetica, $
	        		FILENAME='CPSCAN.PS'

         endelse

	 idoy = 256*hk(1,0) + hk(2,0)
	 title = strtrim(fix(hk(0,0)),2) + ':' +string(idoy,format='(i3.3)') +$
		 ':' + string(fix(hk(20,0)),format='(i2.2)') + ':' + $
 	         string(fix(hk(21,0)),'(i2.2)') + ':' + $
		 string(fix(hk(24,0)),'(i2.2)')


	 if norm_diff eq 0 then ydata = [0, 255]  $
	 else begin   			
    	    idoy = 256*hk(1,1) + hk(2,1)
	    title = title + ' - ' + strtrim(fix(hk(0,1)),2) + ':' + 	$
		    string(idoy,format='(i3.3)') + ':' +  		$
		    string(fix(hk(20,1)),format='(i2.2)') + ':' +   	$
 	            string(fix(hk(21,1)),'(i2.2)') + ':' + 		$
		    string(fix(hk(24,1)),'(i2.2)')
	    ydata = [-255, 255] 
	 endelse

	 ;
	 ; Plotting setup
	 ;

 	 if rulecondition eq 3 then begin
	
	   ;
	   ; Radial scan
	   ;
 
	   xdata = [0,6]
	   xticks = 6
	   xstyle = 1 
	   xtickname = ['0','1','2','3','4','5','6']
 
	   xaxis = cpabscissa
	   yaxis = cpintensity

	 endif else begin  
            	
           ;
	   ; Azmuthal scan
           ;

	   xaxis = fltarr(max(cpnum_vals_n_scans)+1, num_of_scans+1)
	   yaxis = fltarr(max(cpnum_vals_n_scans)+1, num_of_scans+1)
                                       	
	   minval=400.  &   maxval=-400.

	   for i = 0, num_of_scans do begin

		xaxis(0,i) =  cpabscissa(  0:cpnum_vals_n_scans(i),i)
		yaxis(0,i) =  cpintensity( 0:cpnum_vals_n_scans(i),i)

                if (xaxis(cpnum_vals_n_scan(i),i)-(xaxis(0,i))) gt 300 $
	        then begin
	           ;
		   ; Because we are crossing over the 359 to 0 boundary,
		   ; make values gt 180 into negatives for plotting 
		   ;

		   shiftneg = where(xaxis(0:cpnum_vals_n_scans(i),i) gt 180)
		   xaxis(shiftneg,i) = xaxis(shiftneg,i) - 360	
		   order = sort(xaxis(0:cpnum_vals_n_scans(i),i))
		   xaxis(0,i) = xaxis(order, i)
		   yaxis(0,i) = yaxis(order, i)
		endif

		minval = min([minval, xaxis(0:cpnum_vals_n_scans(i),i)])
		maxval = max([maxval, xaxis(0:cpnum_vals_n_scans(i),i)])

	   endfor

           xdata  = [minval,maxval]             ; largest range
	   xstyle = 0				; default
	   xticks = 0                 		; default

	   ;
	   ; Need to label negative numbers as 180 to 360 degrees
 	   ;

       	   plot, xdata, ydata, /nodata, xstyle=4, ystyle=4, $
			xtick_get=xname			; get !X.TICKNAMES
 	   xtickname = strtrim(fix(xname),2)
 	   negativ = where(xname lt 0)
 	   if negativ(0) ne -1 $     		; convert negative to 180-360
 	      then xtickname(negativ) = strtrim(fix(xname(negativ) + 360), 2)

	 endelse



    	 ; 
    	 ; Plot each scan 
    	 ; 

	 csize  = 1.25                   
	 ycsize = csize
	 if num_of_scans+1 gt 4 then ycsize = ycsize * .5

	 space = 0.95 / (num_of_scans+1)

	 for i = 0, num_of_scans do begin

		if i eq 0 then title=title else title=''
  
 	       	if rulecondition eq 3 then xtitle = 'Radial distance (solar '+$
			      'radii) at ' + $
			      'position angle ' + strtrim(cptheta(i+1),2) $
	       	else xtitle = 'Position Angle at ' + strtrim(cprsun(i+1),2) + $
			      ' solar radii'
	
		position=[0.14,  0.95-space*(i+1)+0.1,  0.95, 0.95-space*i]

 	        plot, xaxis(0:cpnum_vals_n_scans(i),i),   	$
		      yaxis(0:cpnum_vals_n_scans(i),i),   	$
			position=position,  /noerase,		$
			xrange=xdata,        yrange=ydata,	$
			charsize=csize,				$
			ycharsize=ycsize,			$
			xtickname=xtickname,			$
			xticks = xticks,			$
			xstyle=xstyle,       ystyle=1,		$	
			title=title, 				$
			xtitle=xtitle,       ytitle='Intensity'

         endfor


         ;
         ; Close print device if necessary
         ;

         if colo ge 0 then begin			
   	   ;
	   ; Close and print image
	   ;

           device,/close  
           psplot, filename='CPSCAN.PS', color=colo, /delete

           set_plot,'x'  &  !p.font=-1 
           widget_control, comment, set_value='Printing scan plot.', /append

         endif

         wset, imag_window		; return control to the image window

      endif

    endif

    ;
    ; When doing a movie
    ;

    if sin_mov ne 0 then begin          
	   ;
	   ; load a movie frame to movie widget
	   ;

      	   cpinteranimate, frame=processed, window=!d.window

	   if saveme then begin			
		;
		; Save a movie frame by writing it to a file
		;
		ndata = bytarr(imsiz,imsiz+2)	; 2 headers and image

		; write header(s) to file 
		for ntime = 0,norm_diff do $	; do twice if difference
			ndata(0,ntime) = [hk(*,ntime),nfiles-1b, $
					 xpos*100b, ypos*100b]	
		; write information needed by CPSUNCEN.PRO once the movie	
		;	is restored
                ndata(227) = donorth
		ndata(228) = dodisk
		ndata(229) = doradii
		ndata(230) = doradial
		ndata(231) = colo
		ndata(232) = ruletimes
		ndata(233) = rulecondition
		ndata(234) = norm_diff          ; normal / difference image
		ndata(235) = housekp*100	; percent space left for info
		ndata(236) = x_siz*100		; percent image X size
		ndata(237) = y_siz*100		; percent image Y size

		
		; starting at 239 assign the rsun, and at 785 the theta values
		; rsun values use 1st byte for the whole part of Rsun
		;      then 3 bytes for each of 3 more digits in fractional part
		; theta values use 1st byte for 100s, 2nd byte for 10s,
		;	3rd for ones place, then 1 byte for a fractional deg
		;
		; saving ten, but there is room for more or better precion
		; for saving R/theta strip out initial bogus value of "-1"
		;

		num_r_t = ((n_elements(cptheta) - 1) < 10)

        	r_bytloc = 239
        	t_bytloc = 350
	
		for r_t = 1, num_r_t do begin

		  ones 	  = fix(cprsun(R_T))
		  tenth   = fix((cprsun(R_T) - ones) * 10)
		  hundth  = fix((cprsun(R_T) - ones) * 100) - (tenth * 10)
		  thousth = fix((cprsun(R_T) - ones) * 1000) - $
						(tenth*100 + hundth*10)
		
		  ndata(r_bytloc)   = ones
		  ndata(r_bytloc+1) = tenth
		  ndata(r_bytloc+2) = hundth
		  ndata(r_bytloc+3) = thousth

		  hund  = fix(cptheta(R_T)/ 100.)
                  tens  = fix(cptheta(R_T)/ 10.) - hund*10
		  ones	= fix(cptheta(R_T)) - (hund*100 + tens*10)
		  tenth = fix((cptheta(R_T) - $
				(hund*100 + tens*10 + ones)) * 10)

		  ndata(t_bytloc)   = hund
		  ndata(t_bytloc+1) = tens
		  ndata(t_bytloc+2) = ones
		  ndata(t_bytloc+3) = tenth

        	  r_bytloc = r_bytloc + 4
        	  t_bytloc = t_bytloc + 4

                  ;
  		  ; holds the number of R/Theta being saved
		  ;
		  ndata(238) = ndata(238) + 1

	        endfor

		; add image of size IMSIZ x IMSIZ
; 4/93		ndata(*,2:*) = data
		ndata(*,2:*) = cpdata
		
		w(processed)=ndata	; saving movie frame w/ headers to file
		ndata = 0b		; clear memory
	   endif

           processed = processed + 1


	   mes = 'Proccessed frame ' + strtrim(processed,2) + ': ' 
	   if norm_diff eq 0 then mes = mes + filename $
	    		     else mes = mes + diffname1 + ' sub ' + diffname2
           widget_control, news, set_value= mes, /append 

           erase
    endif

end

;===========================================================================

;+
;
; NAME: 
;	CPDIFF
;
; PURPOSE:
; 	Scale the difference images to align with the difference color table.
;
; CATEGORY:  
;	CP diplay
;
; CALLING SEQUENCE: 
;      	CPDIFF, DATA=DATA, POSFAC=POSFAC, NEGFAC=NEGFAC
;
; CALLED BY:  
;	CPDISPLAY
;
; CALLS TO: 
;	none
;
; INPUTS:
;	DATA  : Array of size equal to CP image.  Array values
;		range from -255 to +255.
;
; OPTIONAL INPUTS:  
;	none
;
; OUTPUTS:
;	DATA   : Array of size equal to CP image.  Array values
;		 range from 1 to the value of !D.N_COLORS-3
;	POSFAC : image red color scale factor
;	NEGFAC : image blue color scale factor
;
; OPTIONAL OUTPUTS: 
;	none
;
; COMMON BLOCKS: 
; 	CPLASTPASS	for color table scale information
;
; SIDE EFFECTS: 
;	none
;
; RESTRICTIONS: 
;	none
;
; PROCEDURE:
;	Align data array values to match the difference color table and
;	the users (or default) values for scaling the negative and positive
;	values resulting from the image subtraction.
;
; MODIFICATION HISTORY:
;	1991 - Elaine Einfalt (HSTX)
;
;-

pro cpdiff, data=data, posfac=posfac, negfac=negfac

@cplastpass.common

       ;
       ; Find the mid point of the data display area. 
       ;   

;       blk=(!p.color)/2.                    ; middle value(s) of blue/red scale
;       if (blk mod 1) ne 0 then begin loblk=fix(blk)  &  hiblk=loblk+1
;     	             endif else begin loblk=blk       &  hiblk=blk    & endelse

	 loblk = fix(cpmidscale)   &    hiblk = fix(cpmidscale + 0.5)

       ;
       ; Difference data ranges from -255 to +255
       ;

       neg = where(data lt 0)  &  sizn = size(neg)   ; where are the negatives
       pos = where(data ge 0)  &  sizp = size(pos)   ; where are the positives

       ;
       ; Try to scale the negative data values from 1 to the mid point index 
       ; minus 1, this is the blue area of the color table.  
       ; If NEGFAC is less than 255 (default is 65), then the more negative 
       ; data values will not be scaled enough to get into valid color table 
       ; range. Later, those values will be set to index 1.
       ;

       fntb = loblk-1.		; the faintest blue, 1 index from black

       if sizn(0) ne 0 then data(neg) = (data(neg) * (fntb/negfac)) + loblk


       ; scale the positives from faintest red color to darkest red

       fntr = hiblk+1.		; the faintest red, 1 index from black
       if sizp(0) ne 0 then data(pos) = (data(pos) * ((!p.color-fntr)/posfac))$
						+ hiblk

       ;                                     
       ; Truncate those data values that didn't get scaled, to a legal value
       ;   so they are between to 1 (index 0 is a black line) and
       ;   !p.color-3 (there are 3 white indexes at top)
       ;

       data = 1 > byte(data) < !p.color-3 
     
end

;====================================================================

;+
;
; NAME: 
;	CPDISPLAY
;
; PURPOSE:
;	Setup image for display
;
; CATEGORY:  
;	CP display
;
; CALLING SEQUENCE:
; 	CPDISPLAY, NORM_DIFF=NORM_DIFF, DONORTH=DONORTH, $
;	         DODISK=DODISK, DORADII=DORADII, DORADIAL=DORADIAL,  $
;		 RULETIMES=RULETIMES, RULECONDITION=RULECONDITION, $
;		 POSFAC=POSFAC, NEGFAC=NEGFAC, SIN_MOV=SIN_MOV, $
;		 PROCESSED=PROCESSED, SAVEME=SAVEME, WMOVIE=W, $
;		 NFILES=NFILES, OK=OK
;
; CALLED BY:
;	CPONE, CPMOVIE
;
; CALLS TO: 
;	CPDISK, CPDIFF, WINUP, CPTV
;
; INPUTS:
;	NORM_DIFF     : 0 means do a normal image
;                       1 means do a difference image
;	DONORTH       : just passing through, on it's way to CPTV
; 	DODISK        : just passing through, on it's way to CPTV
;	DORADII       : just passing through, on it's way to CPTV
;	DORADIAL      : just passing through, on it's way to CPTV
;	RULETIMES     : just passing through, on it's way to CPTV 
; 	RULECONDITION : just passing through, on it's way to CPTV
;	POSFAC        : just passing through, on it's way to CPDIFF 
;	NEGFAC        : just passing through, on it's way to CPDIFF 
;	SIN_MOV       : 0 means current display mode is for single images
;	           	1 means current display mode is for movies
;	PROCESSED     : just passing through, on it's way to CPTV
;	SAVEME 	      : just passing through, on it's way to CPTV
;	W 	      : just passing through, on it's way to CPTV
;	NFILES        : just passing through, on it's way to CPTV
;
; OPTIONAL INPUTS: 
;	none
;
; OUTPUTS:
;	OK : 0 means failed to successfully read the input file
;	     1 means successfully read the input file
;	PROCESSED : just passing through, on it's back to CPMOVIE
;
; OPTIONAL OUTPUTS: 
;	none
;
; COMMON BLOCKS :
;	CPCOLORS to load color tables
;	COLORS to change values in R_CURR, G_CURR, B_CURR to desired table
;	CPDISPFILE for files to read and output device color condition
;	CPNEW_WINDOW  for window display variables
;	CPWIDGBASES for widget IDs to write out informational messages
;
; SIDE EFFECTS : 
;	Changes values in IDL common block COLORS
;
; RESTRICTIONS: 
;	none
;
; PROCEDURE:
;	Read in data file(s) and if a difference image do the subtraction.
;	If the data file is the same as last pass then the file is not reread. 
;	Scale the data to the appropriate color table and load that table.
;	Call to CPTV to output the CP display.
;
; MODIFICATION HISTORY:
;	1991 - Elaine Einfalt (HSTX)
;	MAR 1993 - modified to save data array to common.
;		   modified the CP window manager to be user friendly.
;
;-

pro cpdisplay, norm_diff=norm_diff, donorth=donorth, $
	         dodisk=dodisk, doradii=doradii, doradial=doradial,  $
		 ruletimes=ruletimes, rulecondition=rulecondition, $
		 posfac=posfac, negfac=negfac, sin_mov=sin_mov, $
		 processed=processed, saveme=saveme, wmovie=w, $
		 nfiles=nfiles, ok=ok

@cpcolors.common
@cpdispfiles.common
@cplastpass.common
@cpnew_window.common
@cpwidgbases.common

common colors, r_orig, g_orig, b_orig, r_curr, g_curr, b_curr

print,'this is the SDAC::[SDAC] account cpdisplay'

 if n_elements(last_filename)  eq 0 then last_filename='nothing'
 if n_elements(last_diffname1) eq 0 then last_diffname1='nothing'
 if n_elements(last_diffname2) eq 0 then last_diffname2='nothing'


 if n_elements(processed) eq 0 then processed=0  ; define if no value 

 hk = bytarr(224, norm_diff+1)          ; house keeping, 2D for differences

 if norm_diff eq 0 then begin    	; normal image, not a difference

   if filename ne last_filename then begin   	; not the same file as last time

      cpdisk, data=data, hk=houskeep, file=filename, ok=ok, $
			imsiz=imsiz, sin_mov=sin_mov

      if not(ok) then begin
        explain = 'Error with file ' + filename 
        if sin_mov eq 0 then widget_control,comment,set_value=explain,/append $
		        else widget_control,news,set_value=explain,/append 
        last_filename  = 'error_with_file'
	return
      endif

      hk(0,0) = houskeep
      ih = ishft(hk(9,0) and 'f0'x, -4)
      iv = hk(9,0) and 'f'x                	; horizontal position parameter
      reso = ishft((hk(3,0) and '4'x),-2)  	; vertical position parameter
      if reso eq 0 then begin
	data=rebin(data, imsiz/2, imsiz/2)  	; high res to low res
	imsiz = imsiz/2
      endif
  
      new_file = 1				; new file, new data
      cpdata  = data				; save in memory
      cphk    = hk
      cpimsiz = imsiz
      cpih    = ih
      cpiv    = iv
      last_filename  = filename
      last_diffname1 = 'nothing'	; don't remember difference filenames
      last_diffname2 = 'nothing'

   endif else begin

	new_file = 0			; same file, same data
	data   = cpdata			; get array from memory
	hk     = cphk
	imsiz  = cpimsiz
	ih     = cpih
	iv     = cpiv

   endelse

 endif else begin                   	; difference image

   if (diffname1 ne last_diffname1) or  $        ; one of these is not the same
      (diffname2 ne last_diffname2) then begin   ;    file as last time


      ; go get the base image data
      cpdisk, data=data1, hk=houskeep, file=diffname1, ok=ok, $
				imsiz=imsiz,sin_mov=sin_mov
      if not(ok) then begin
        explain = 'Error with file ' + filename 
        if sin_mov eq 0 then widget_control,comment,set_value=explain,/append $
		        else widget_control,news,set_value=explain,/append 

        explain = 'Requires both images for a difference '
        if sin_mov eq 0 then widget_control,comment,set_value=explain,/append $
		        else widget_control,news,set_value=explain,/append 

        last_diffname1 = 'error_with_file'
	return
      endif

      hk(0,0) = houskeep                   ; base image's housekeeping info
      ih = ishft(hk(9,0) and 'f0'x, -4)
      iv = hk(9,0) and 'f'x                	; horizontal position parameter
      reso = ishft((hk(3,0) and '4'x),-2)    	; vertical position parameter
      if reso eq 0 then begin
	data1=rebin(data1, imsiz/2, imsiz/2)  	; high res to low
	imsiz = imsiz/2
      endif

      ; now get the subtraction image data
      cpdisk, data=data2, hk=houskeep, file=diffname2, ok=ok, $
				imsiz=imsiz, sin_mov=sin_mov
      if not(ok) then begin
        explain = 'Error with file ' + filename 
        if sin_mov eq 0 then widget_control,comment,set_value=explain,/append $
		        else widget_control,news,set_value=explain,/append 
        explain = 'Requires both images for a difference '
        if sin_mov eq 0 then widget_control,comment,set_value=explain,/append $
		        else widget_control,news,set_value=explain,/append 

        last_diffname2 = 'error_with_file'
	return
      endif

      hk(0,1) = houskeep             	; subtraction image's housekeeping info
      ih2 = ishft(hk(9,1) and 'f0'x, -4)
      iv2 = hk(9,1) and 'f'x                	; horizontal position parameter
      reso = ishft((hk(3,1) and '4'x),-2)    	; vertical position parameter
      if reso eq 0 then begin
	data2=rebin(data2, imsiz/2, imsiz/2)  	; high res to low
	imsiz = imsiz/2
      endif
 

      ; size testing, images must be same
      siz1 = size(data1)  &  siz2 = size(data2)
      if siz1(1) ne siz2(1) then begin
        explain = 'Base and Subtraction images are different sizes'
	if sin_mov eq 0 then widget_control,comment,set_value=explain,/append $
	                else widget_control,news,set_value=explain,/append 

        last_diffname1 = 'error_with_file'
        last_diffname2 = 'error_with_file'
 	return
      endif

      ;
      ; Subtract "BASE IMAGE" from "SUBTRACTION IMAGE"
      ;

      data1 = fix(data1)  &  data2 = fix(data2)  
      data = data2 - data1 

      new_file = 1				; new files, new data
      cpdata  = data				; save in memory
      cphk    = hk
      cpimsiz = imsiz                             
      cpih    = ih
      cpiv    = iv

      last_diffname1 = diffname1
      last_diffname2 = diffname2
      last_filename  = 'nothing'	; don't remember normal image filename

   endif else begin

	new_file = 0			; same file, same data
	data   = cpdata			; get array from memory
	hk     = cphk
	imsiz  = cpimsiz
	ih     = cpih
	iv     = cpiv

   endelse 

 endelse               		; end of difference image clause
 

  

 housekp = 150.			; room to write out house keeping info
 x_siz=448.  &  y_siz = 448.	; width and height of image windowing area 
 xwinsiz = housekp*(norm_diff+1.) + x_siz	; width window w/ housekeeping 
 ywinsiz = y_siz				; height window w/ housekeeping 

 square = x_siz/4.              ; size of one of the 16 position squares

 case 1 of 
    (ih eq 7) or (ih eq 6) : xpos = square + housekp	; 1 square to right
    (ih eq 3) : xpos = square*2 + housekp               ; 2 squares to right
    else : xpos = 0 + housekp				; left edge w/ house
 endcase
 case 1 of
    (iv eq 14) or (iv eq 6) : ypos = square		; 1 square up 
    (iv eq 12) : ypos = square*2			; 2 sqaures up
    else : ypos = 0                                     ; bottom edge
 endcase

 case coltyp of
    0: begin	; normal display so use b/w, data values within 0 to +255

       if colreset then begin    ; reset to standard c/p normal color table
          r_curr=norm_r  &  g_curr=norm_g  &  b_curr=norm_b  
       endif

       ;
       ; Scale the data to match the data part of the color table.
       ; Don't use top 3 color for data.
       ;

       data = (!p.color-3)/255. * data		; scale data to !p.color-3
                                        	;   3 values reserved for lines

       end                               

    1: begin    ; difference images, data values within -255 to +255

       if colreset then begin    ; reset to standard c/p difference color table
          r_curr=diff_r  &  g_curr=diff_g  &  b_curr=diff_b 
       endif

       cpdiff, data=data, posfac=posfac, negfac=negfac
       end
 endcase

;;;;  modified march 23 1993  --  for better window management  ;;;;;;;;;;;;;
; if sin_mov eq 0 and colo eq -1 then begin  
; ; if a single image (movies make their own) and if output going to screen
;
;          if reuse and not(first_pass) then begin	; reuse windows
;		wdelete, current_window
;	   endif else begin
;		lastmark = 1 - lastmark			; alternate position
;		first_pass = 0 				; now have at least 1
; 	   endelse
;           if not(norm_diff) then title = 'CP '+ filename $
;		             else title = 'CP '+ diffname1 + ' / ' + diffname2
;
;           winup, /free, title=title, $
;	        xsiz=xwinsiz, ysiz=ywinsiz, retain=2, $
;		xpos=sc(0)-xwinsiz-10, $  
;		ypos=(sc(1)-ywinsiz) * lastmark + (lastmark * (-20) + 10)
;
;	   current_window = !d.window
; endif
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

 if sin_mov eq 0 and colo eq -1 then begin  
 ; if a single image (movies make their own) and if output going to screen

    savreuse = reuse

    if n_elements(current_window) eq 0 then current_window = -1

    if current_window ne -1 then begin  	   ; there is a window
       device, window=w_up                         ; get all existing windows
       if w_up(current_window) eq 0 then reuse=0   ; window is not there anymore
    endif else reuse = 0   			   ; there was no window
     
;    if not(norm_diff) then title = 'CP '+ filename $
;		      else title = 'CP '+ diffname1 + ' / ' + diffname2

    idoy = 256*hk(1,0) + hk(2,0)
    title = 'CP  ' + strtrim(fix(hk(0,0)),2) + ':' + $
		 string(idoy,format='(i3.3)') + $
  		 ':' + string(fix(hk(20,0)),format='(i2.2)') + ':' + $
 	         string(fix(hk(21,0)),'(i2.2)') + ':' + $
		 string(fix(hk(24,0)),'(i2.2)')


    if norm_diff eq 1 then begin   			
    	    idoy = 256*hk(1,1) + hk(2,1)
	    title = title + ' - ' + strtrim(fix(hk(0,1)),2) + ':' + 	$
		    string(idoy,format='(i3.3)') + ':' +  		$
		    string(fix(hk(20,1)),format='(i2.2)') + ':' +   	$
 	            string(fix(hk(21,1)),'(i2.2)') + ':' + 		$
		    string(fix(hk(24,1)),'(i2.2)')
    endif

    if reuse then begin				; reuse windows

       if not(new_file) then begin                 ; same file, same banner
           wshow, current_window
           erase
       endif else begin                            ; new file needs new banner
           device, get_window = winpos             ; but keep in same place
           wdelete, current_window
           winup, /free, title=title, xsiz=xwinsiz, ysiz=ywinsiz, retain=2, $
                         xpos=winpos(0), ypos=winpos(1)
           current_window = !d.window              ; get new window's index
       endelse

    endif else begin  
	   lastmark = 1 - lastmark			; alternate position
           winup, /free, title=title, $
	        xsiz=xwinsiz, ysiz=ywinsiz, retain=2, $
		xpos=sc(0)-xwinsiz-10, $  
		ypos=(sc(1)-ywinsiz) * lastmark + (lastmark * (-20) + 10)

	   current_window = !d.window
    endelse
   
    reuse = savreuse
    new_file = 0
 endif

 tvlct, r_curr, g_curr, b_curr   	; reload color table 

 cptv, data=data, hk=hk, xpos=xpos, ypos=ypos, x_siz=x_siz, y_siz=y_siz, $
		xwinsiz=xwinsiz, ywinsiz=ywinsiz, colo=colo, $
		imsiz=imsiz, donorth=donorth, dodisk=dodisk, $
		doradii=doradii, doradial=doradial, housekp=housekp, $
		ruletimes=ruletimes, rulecondition=rulecondition, $
		sin_mov=sin_mov, norm_diff=norm_diff, processed=processed, $
		filename=filename, diffname1=diffname1, diffname2=diffname2, $
	        saveme=saveme, wmovie=w, nfiles=nfiles

end


