
; file UVSPSEPER.PRO

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

pro sep_event, event
common sepers, S_doppto, S_savdefdopp, S_newdopp,       $
	       S_pixlto, S_savdefpix,  S_newpix,   S_pmag, S_msize
                                                         
common order1, diskexp, control, generic, comment

 widget_control, event.id, get_uvalue=input
 if n_elements(input) eq 0 then input=''

 type = strmid(tag_names(event, /structure_name),7, 4)

 case type of
    'BUTT'   : case input of
        'DOPPCAN' : begin
	   S_doppto = S_savdefdopp
	   widget_control, event.top, /destroy  ; kill top widget
           end
        'DOPP_GO'  : begin
	   S_doppto = S_newdopp                    ; assign new doppler balance
	   widget_control, event.top, /destroy ; kill top widget
           end

        'PIXLMAX' : S_newpix = S_msize
	'PIXLAST' : S_newpix = S_savdefpix 

        'PIXLCAN' : begin
	   S_pixlto = S_savdefpix
	   widget_control, event.top, /destroy  ; kill top widget
           end
        'PIXL_GO'  : begin
	   S_pixlto = S_newpix                     ; assign new pixel size
	   widget_control, event.top, /destroy ; kill top widget
           end
        else:
     endcase

     'TEXT' : begin
   	widget_control, event.id, get_value=value, set_value=''
	case input of
	   'SEPRTXT' : begin
	   	on_ioerror, TRYAGAIN
          	  if value(0) eq '' then begin
	   	    newscal = savdefmax 			; back to default
		    return
		  endif
		  newscal = double(value(0))
	       	on_ioerror, null
	
		; what to do with values over input
	        if newscal lt savdefmax then widget_control, clippn, sensitive=1 
		end

	   'DOPPTXT' : begin
	   	on_ioerror, TRYAGAIN
          	  if value(0) eq '' then begin
	   		S_newdopp = S_savdefdopp   	; back to default
			return
                  endif
		  S_newdopp = double(value(0))
	       	on_ioerror, null
                end

	   'PIXLTXT' : begin
	   	on_ioerror, TRYAGAIN
          	  if value(0) eq '' then begin
	   		S_newpix = S_savdefpix
			return
	          endif
		  S_newpix = double(value(0))
	       	on_ioerror, null
                S_newpix = S_newpix / S_pmag
 	        if S_newpix gt S_msize then begin     ; "no can do"
		   widget_control, comment, set_value='UVSP-W-UVSPSEPER, ' + $ 
				'Input pixel size too large.', /append
		   S_newpix = S_msize		       ; maxed out
                endif
                end
           else:
	endcase
TRYAGAIN:
        end
 endcase
end

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

PRO UVSPSEPER, struc=struc, data=CEXP, hd=HD, exp=EXP_TYPE, solgrid=solgrid, $
		point=point, rollo=ROLLO, $
		smuth=SMUTH, contur=CONTUR, silent=SILENT, $
		top_scale=top_scale, templev=templev, hard=hard
common order1, diskexp, control, generic, comment
common uvspsav, savexp, exptyp, saviwin, banner, savwinfile, $
		 widstatus, savsilent
common sepers, S_doppto, S_savdefdopp, S_newdopp,       $
	       S_pixlto, S_savdefpix,  S_newpix,   S_pmag, S_msize

@uvspcolors.common

	

 ;
 ;  Calculate just how many rows and columns are there
 ;

;6/93 if (struc.st4.all or struc.st4.vel) $
;	then rpf = 2 $ 
;   	else rpf = struc.st3.tempnd 			; rows of detectors

 nfr = struc.st1.tempnfr			; number of repeats to use
 frst = struc.st1.tempfrst			; starting with this repeat
 rpf = struc.st3.tempnd 			; rows of detectors

 if (struc.st4.jdet ne 0) then rpf = 1			; only one det
 if (exp_type eq 18) then rpf = struc.st3.tempnd * struc.st7.wava  ; rows of wavelengths

 nfpr = fix(sqrt(nfr*rpf))                      ; number frames / row
 nrow = rpf*(nfr/nfpr)                          ; number of rows
 if nfpr*nrow lt rpf*nfr then nrow = nrow + rpf


 base_win_size = 512

 ;
 ;   Given the window size how big can a pixel be, user can make image smaller
 ;

 mvert = 1d &  mhorz = 1d 		; normalized size double
                                                    
; S_msize = double(0.85)/max([(struc.st7.nx+2.)*nfpr, (struc.st7.ny+2)*nrow])
; S_pmag = double(.85) * base_win_size

 S_msize = 0.85d / max([(struc.st7.nx+2.)*nfpr, (struc.st7.ny+2)*nrow])
 S_pmag =  0.85d * base_win_size


 ;
 ; Default is max size else user's last size.
 ;

 if (struc.st1.temppixS gt S_msize) or (struc.st1.temppixS eq 0.d) $
   then defpix = S_msize else defpix = struc.st1.temppixS    
	
 if silent or hard then psize = defpix	$		; don't bother user	
 else begin		                        ; bother user for size
	   S_savdefpix = defpix  & S_newpix=defpix	; current size
	    sepr = widget_base(title='Pixel size in window units', /frame, $
				 /column, xpad=20, ypad=20, space=10)
              sppick = widget_base(sepr, /exclusive, /frame, /column)
               sbmax  = widget_button(sppick, value='Maximum size possible ' +$
		        '(' + strtrim(S_msize*S_pmag,2) +')', uvalue='PIXLMAX') 
               sblast = widget_button(sppick, value='Default size [' + $
			strtrim(S_savdefpix*S_pmag,2) + ']', uvalue='PIXLAST')

              lab = widget_label(sepr, value='Or enter a value ')
	      txt = widget_text(sepr, /editable, uvalue='PIXLTXT')

	      canit = widget_button(sepr, value='CANCEL', uvalue='PIXLCAN')
	      doit  = widget_button(sepr, value='READY', uvalue='PIXL_GO')
	    widget_control, sepr, /realize
            widget_control, sblast, set_button=1
	    xmanager, 'uvspseper', sepr, event_handler='sep_event', $
			/modal, just_reg=0

            psize = S_pixlto 			; assign user's input
	    struc.st1.temppixS = psize       	; input becomes default
            widget_control, comment, set_value= $
			'Pixel size ' + strtrim(psize*S_pmag,2), /append

 endelse

 struc.st2.xfact = struc.st7.nx * psize                 ; x magnification
 struc.st2.yfact = struc.st7.ny * psize 		; y magnification


 ;
 ;  Will the all of the separate images fit
 ;

 !c = 0
 image_size = max([struc.st2.xfact,struc.st2.yfact])
 space = .039   &  space = min([space,image_size/10 + .00195])

 desired_h_size = nfpr*(struc.st2.xfact + space)
 desired_v_size = nrow*(struc.st2.yfact + space)

 h_size = min([desired_h_size,mhorz])    
 v_size = min([desired_v_size,mvert])
 nfpr_max = h_size/(struc.st7.nx*psize + space)         
 nrow_max = v_size/(struc.st7.ny*psize + space)
 nfr_max = nfpr_max*nrow_max

 if nfr gt nfr_max then begin          ; more frames than there is room
	  continue_extend = 1     
	  while continue_extend do begin     ; go until max frames will fit
	      new_h_size = h_size + struc.st7.nx*psize + space     ; add raster to row
	      if new_h_size gt mhorz then begin
		 ; no room to expand this way. 
		 continue_extend = 0
	      endif else begin		 ; possible to add a raster to the row
	         h_size = new_h_size     	; total width is 1 raster wider
		 nfpr_max = nfpr_max + 1        ; can have 1 more frame per row
		 nfpr = nfpr + 1                ; do have 1 more frame per row
	         nfr_max = nfr_max + nrow_max   ; room for 1 at end of every row
	         if nfr_max le nfr then continue_extend = 0   ; passes the test
	      endelse
	   endwhile

	   if nfr_max lt nfr then begin   ; still no room
	      nfr = nfr_max
	      widget_control, comment, set_value='Warning: ' + $
			'Can only fit ' + strtrim(nfr,2) + ' frames.', /append
	   endif
 endif


 ;
 ; Only chosen frames and det. are used,  dimensions assigned 
 ;	accordingly.   Separated image cannot be roll corrected.
 ;


 if rollo then widget_control, comment, set_value='UVSP-W-UVSPSEPER, ' + $
		'Separated image are not roll corrected.', /append

 ndet = struc.st3.d2-struc.st3.d1+1       	; not same as tempnd for SUM

;6/93 a = fltarr(struc.st7.nx,struc.st7.ny,struc.st7.wava,struc.st7.polo,nfr,ndet)   
;
; if not(smuth) then $
;	      for d = struc.st3.d1,struc.st3.d2 do $ ; for each detector choosen
;	       for r = frst-1, frst+nfr-2 do $	; for each frame user chose
;	        for p = 0,struc.st7.polo-1 do $       	; for each polarimeter
;	         for w = 0,struc.st7.wava-1 do $       	; for each wavelength
;	            a(0,0,w,0,r-(frst-1),d-struc.st3.d1) = $
;				cexp(*,*,w,p,r,d)  $
; else  for d = struc.st3.d1,struc.st3.d2 do $	; for each detector choosen
;	       for r = frst-1, frst+nfr-2 do $	; for each frame user chose
;	        for p = 0,struc.st7.polo-1 do $       	; for each polarimeter
;	         for w = 0, struc.st7.wava-1 do $       	; for each wavelength
;	            a(0,0,w,0,r-(frst-1),d-struc.st3.d1) = $
;					smooth(cexp(*,*,w,p,r,d),3)
;

 a = rebin(cexp(*,*,*,*,frst-1:frst+nfr-2, struc.st3.d1:struc.st3.d2), $
	   struc.st7.nx, struc.st7.ny, struc.st7.wava, 1, nfr, ndet)	
 omax = max(a)

 uvspsave, data=a, hd=hd, type='SEPARATE'
  

 ;
 ; Scale display.	One or more detectors,	individually displayed
 ;

;6/93  b = a          			; define B

 if not(struc.st4.sum) then begin                 
    ;
    ;   Scaling for most experiments.  Only exp not scaled here
    ;   have set variable SUM. Not sum includes NOT VEL also.
    ;
                               

; 6/93   for d = 0,struc.st3.tempnd-1 do begin   	; for each detector
;     case struc.st1.tempscal of
;      1: begin		;         square-root scaling
;          scl = top_scale/sqrt(omax)
;          for r = 0,nfr-1 do $			; for each frame choosen
;             for w = 0,struc.st7.wava-1 do $       	; for each wavelength
;                    b(0,0,w,0,r,d) = byte(scl*sqrt(a(*,*,w,0,r,d)))
;         end
;      2: begin		;         log scaling
;          scl = top_scale/alog10(omax)
;          for r = 0,nfr-1 do $			; for each frame choosen
;             for w = 0,struc.st7.wava-1 do $       	; for each wavelength
;                   b(0,0,w,0,r,d)=  byte(scl*alog10(a(*,*,w,0,r,d)>1))
;         end
;      else: begin	 			; linear scaling
;            scl = top_scale/omax
;            for r = 0,nfr-1 do $	        ; for each frame choosen
;               for w = 0,struc.st7.wava-1 do $       	; for each wavelength
;                      b(0,0,w,0,r,d) = byte(scl*a(*,*,w,0,r,d))
;            end
;     endcase
;    endfor			; each det.
;
;    a = 0  &  a = b  &  b = 0	; clear and assign to output variable

    if struc.st1.tempscal eq 1 then  a = sqrt(a) $
    else if struc.st1.tempscal eq 2 then a = alog10(a>1)  

    a = bytscl(a, top=top_scale-distinct) + distinct

 endif else begin       
    ;
    ; Scaling when SUM is set, VEL may also be set.
    ; 	Add detectors and divide by 2 det.  Notice 6th dimension is lost.
    ;

    if struc.st4.vel and (struc.st3.tempnd eq 4) $  	; do 3 and 4 later
	then asum = a(*,*,*,*,*,0) + a(*,*,*,*,*,1) $ 
	else begin
		asum = a(*,*,*,*,*,0)
		for dloop = 1, hd(60)-1 do  asum = asum + a(*,*,*,*,*,dloop) 
	endelse

    omax = max(asum)

    if struc.st1.tempscal eq 1 then asum = sqrt(asum) $
    else if struc.st1.tempscal eq 2 then asum = alog10(asum>1.) 

     ; 
     ; Load into first array spot, if velocity it will take second spot
     ;

     if not(struc.st4.vel) then begin  
        a(0,0,0,0,0,0) = bytscl(asum, top=top_scale-distinct) + distinct
        struc.st3.tempnd = 1 		; all summed, looks like one det now
     endif else a(0,0,0,0,0,0) = bytscl(asum, top=middopp-1-distinct)+distinct 

     ; velocities with 4 det, 3rd and 4th det sum into 3rd aray spot
     if struc.st4.vel and (struc.st3.tempnd eq 4) then begin
        asum = a(*,*,*,*,*,2) + a(*,*,*,*,*,3) 
        a(0,0,0,0,0,2) = bytscl(asum, top=middopp-1-distinct)+distinct 
     endif

    asum = 0   				; clear variable
 endelse

 if struc.st4.vel then begin
   ;
   ; Scale velocity
   ;

;7/93   S_doppto = 1.
;
;   if silent or hard then dist = S_doppto else begin
;	    S_savdefdopp = S_doppto   &  S_newdopp = S_doppto
;	    sepr = widget_base(title='Doppler Red and Blue', /frame, /column, $
;				xpad=20, ypad=20, space=10)
;              lab = widget_label(sepr, value='Enter that number to get ' + $
;				 'amount of Red to Blue')
;              lab = widget_label(sepr, value='Enter red/blue compression.')
;              lab2 = widget_label(sepr, value='Default ['+strtrim(s_doppto,2)+'.]')
;	      avr = widget_text(sepr, /editable, uvalue='DOPPTXT')
;
;	      canit = widget_button(sepr, value='CANCEL', uvalue='DOPPCAN')
;	      doit  = widget_button(sepr, value='READY', uvalue='DOPP_GO')
;	    widget_control, sepr, /realize
;	    xmanager, 'uvspseper', sepr, event_handler='sep_event', $
;			/modal, just_reg=0
;
;
;            dist = S_doppto			; assign user's value
;            widget_control, comment, set_value= $
;			'Distribution red/blue ' + strtrim(dist,2), /append
;
;   endelse


   for velloop = 0, fix((struc.st3.tempnd-1)/2) do begin  
   	  ;
   	  ; 2 or 4 det vel. get scaled to top part of dopp color table 
   	  ; and put into array spot 2 or 4
   	  ;

     	   redfrst = 0   
;7/93	   v_scl = float(middopp)/dist
	   v_scl = float(middopp)/ struc.st4.doppto

     	   seg = velloop * 2 			
	   if ((hd(137+seg) eq 1) and (hd(138+seg) eq 2)) or $
	      ((hd(137+seg) eq 4) and (hd(138+seg) eq 3)) then redfrst = 1
	   if redfrst then begin 
		dr = 0 & db = 1 ; 1st det is red, 2nd blue
 	   endif else begin 
		dr = 1 & db = 0 ; 1st det is blue, 2nd red
	   endelse  

	    rs = cexp(*,*,0,0,frst-1:frst+nfr-2,dr+seg)  	; red shift
	    bs = cexp(*,*,0,0,frst-1:frst+nfr-2,db+seg)  	; blue shift

	    bal_fac = total(rs)/total(bs)  &  bs = bal_fac*bs
	    v_sum = rs + bs  		   &  v_dif = rs - bs
	    brght_pix = byte(v_sum gt 20)  &  v_sum = v_sum + (v_sum eq 0)
	    midscl = (!d.n_colors - middopp)/2. + middopp   ; middle index
	    v_sig = byte(midscl + v_scl*(v_dif/v_sum))
	    v_sig = (v_sig > byte(middopp)) < byte(!p.color-1)
            v_sig = v_sig*brght_pix

	    a(0,0,0,0,0,1+seg) = byte(v_sig)   ; velocites into 2nd or 4th array spot

	    rs = 0  &  bs = 0  &  v_sig = 0  &  v_dif = 0  ; clear variables
            brght_pix = 0      &  v_sum = 0

  endfor 

 endif				; if VEL


 ; 
 ; Positioning and outputing the separate images to TV device
 ; 

 if not(hard) then begin  	; will need a window

    if struc.st5.imagewin ge 0 and not(savexp) then wdelete, struc.st5.imagewin 

    uvspwin, struc=struc, xwin=base_win_size, ywin=base_win_size
    struc.st5.imagewin = !d.window

 endif

 dx = struc.st2.xfact + space       
 dy = struc.st2.yfact + space
 xb = [0, 0, struc.st2.xfact,struc.st2.xfact, 0] 
 yb = [0, struc.st2.yfact, struc.st2.yfact, 0, 0]
 xfree = (mhorz - dx * nfpr)/2 	   ; to center image(s) left and right
 yfree = (mvert - dy * nrow)/2 	   ; to center up and down

 if not(struc.st4.twodet) then begin
   ;                 
   ; Almost all experiments.  Only experiments not covered here
   ;			      are types 2 and 4, w/ 2 or 4 dets. 
   ;

   for i_row = 0, nrow-1, struc.st7.wava*struc.st3.tempnd do begin   ; each set of rows

      for i_fpr = 0, nfpr - 1 do begin         ; for each frame/row
         r = nfpr*(i_row/struc.st7.wava/struc.st3.tempnd) + i_fpr           
         if r lt nfr then begin                    ; if < # of reps.
            struc.st2.xpos = space/2 + i_fpr*dx + xfree
            y0 = v_size + space/2 - (i_row + 1)*dy + yfree
	    for d = 0, struc.st3.tempnd-1 do begin             ; for each det
            	for w = 0,struc.st7.wava-1 do begin             ; for each WL
	     	   b = 0                              ; clear variable
                   b =congrid(a(*,*,w,0,r,d), 				$
			      struc.st2.xfact*base_win_size,	$
			      struc.st2.yfact*base_win_size)
		   if smuth then b=smooth(b,3)

                   struc.st2.ypos = y0 - ((d*dy*struc.st7.wava)+(w*dy))

  	           tv,b,struc.st2.xpos,struc.st2.ypos,xsize=struc.st2.xfact, $
			 		 ysize=struc.st2.yfact,/normal
    		   plots,[struc.st2.xpos + xb],[struc.st2.ypos + yb],/normal
		   if solgrid then $ 
     			uvsphelio, point=point, hd=hd, nx=struc.st7.nx, $
				   ny=struc.st7.ny, expnu=struc.st6.expnu, $
				   catplace=struc.st6.cat, glabel=0,	$
				   comment=comment, $
	        		   posit=[ struc.st2.xpos, struc.st2.ypos, $
			           struc.st2.xpos+struc.st2.xfact, $
		                   struc.st2.ypos+struc.st2.yfact]

                   if contur then uvspcondur,struc=struc, arr=a(*,*,w,0,r,d), $
					 silent=silent, hard=hard, $
				         velis=struc.st4.vel, $
					 top_scale=top_scale,templev=templev
               	endfor   ; WL
	    endfor	; det.
	 endif		      
      endfor	; frames across
   endfor       ; row sets down

 endif else begin

   ;                 
   ;  Set conditions for given case of twodet
   ;                 

   dopp = intarr(5)				   ; not dopp unless VEL

   if struc.st4.all then begin                     ; all det display
      to = struc.st3.tempnd-1   &  step = struc.st3.tempnd
   endif else if (not struc.st4.sum) and (not struc.st4.vel) then begin     
      to = 0   &  step = 1                          ; 1st or 2nd channel
   endif else if struc.st4.vel then begin                         
      to = struc.st3.tempnd-1   &  step = struc.st3.tempnd
      dopp = [0,1,0,1,0]		; 2nd and 3rd are dopplergram colors
   endif else if struc.st4.sum and (not struc.st4.vel) then begin 
      to = 0   &  step = 1                          ; just sum w/out vel.
   endif else begin
      widget_control, comment, set_value='UVSPSEPER: '+ $
		'strange situation output', /append
      to = 0  &  step = 1
   endelse

   for i_row = 0, nrow - 1, step do begin    ; each set of rows w/ 'step' det
      for i_fpr = 0, nfpr - 1 do begin      ; each frame / ro
	 r = nfpr*(i_row/step) + i_fpr
	 if r lt nfr then begin               ; if < # of reps.
	    struc.st2.xpos = space/2 + i_fpr*dx + xfree
	    y0 = v_size + space/2 - (i_row + 1)*dy + yfree
	    for d = 0,to do begin                ; ea. of 'to'+1 det
                b=congrid(a(*,*,0,0,r,d),struc.st2.xfact*base_win_size, $
			  struc.st2.yfact*base_win_size)
                struc.st2.ypos = y0 - d*dy              ; adjust for multi. det.

		if smuth then $
		  if not(dopp(d)) then b= smooth(b,3) $          ; vel smooth
		  else b= smooth(b,3) * (smooth(b,3) gt middopp) ; color check

                tv,b,struc.st2.xpos,struc.st2.ypos,xsize=struc.st2.xfact, $
					           ysize=struc.st2.yfact,/normal

                b = 0                         ; clear variable
    		plots,[struc.st2.xpos + xb],[struc.st2.ypos + yb],/normal, $
					color=!p.color
		if solgrid then $ 
     			uvsphelio, point=point, hd=hd, nx=struc.st7.nx, $
				   ny=struc.st7.ny, expnu=struc.st6.expnu, $
				   catplace=struc.st6.cat, glabel=0,	$
				   comment=comment, $
	        		   posit=[ struc.st2.xpos, struc.st2.ypos, $
			           struc.st2.xpos+struc.st2.xfact, $
		                   struc.st2.ypos+struc.st2.yfact]

                if contur then uvspcondur,struc=struc,arr=a(*,*,0,0,r,d), $
				      silent=silent, $
				      velis=struc.st4.vel, $
				      templev=templev, hard=hard
            endfor   ; det
         endif
      endfor         ; frames arcoss
   endfor             ; row sets down

 endelse


return		; return from seper to image
end		; seper

