;+
;
; FILE CP.PRO  the display program for Coronagraph/Polarimeter data.
;
;
; REQUIREMENTS :  IDL Version 2 with widgets, or better.
;		  X windows graphics device.
;			
;   To test to see if widgets are available :
;
;   IDL> if (!D.FLAGS AND 65536) NE 0 THEN PRINT, 'WIDGETS ARE AVAILABLE.'
;		
;
; The CP data must be written from the CP achive media using the IDL
; routine CPTAPE.PRO.  This is a VMS specific procedure and will place
; the data into subdirectories, one per day.  These file can then be copied
; to a UNIX machine, if desired. 
;
; - The program has two main modes: "Display one image" (single image) mode or 
;   "Show a movie" (movie) mode.  
; - The mode is selected from the main options widget, but first select the
;   desired option for "Normal display" (not a difference image) and 
;   "Make a difference" (difference image).  
; - Once single or movie modes are selected, each will create it's own
;   widget menues.
; - These menues are designed to display either normal or difference images
; - The remain option are independant and may be selected interactively 
;   during processing.
; NOTE: All widget menues are placed at the top left corner of the screen.
;	This may result in smaller menues, such as the main options menu,
; 	being completely hidden.  Move the offending menu as you would
;	any window on your system.
;
;
;                         /--- CPONE---CPONE_EV*-------------------\
;    CP--------CP_EVENT---                                         ---**
;    (cpcolor)            \--- CPMOVIE--CPMOVIE_EV*---CPMOVIE_DO---/   
;
;                                                                * returns to 
;            **---CPDISPLAY---------------------CPTV---CPSUNCEN    cpone_ev or
;                 (cpdisk)   \----CPDIFF---/                       to cpmovie_ev
;
;
;    Programs for C/P have the naming convention of CP*.PRO :
;       CP.PRO, CPCOLOR.PRO, CPDISK.PRO, CPDISPLAY.PRO, CPHOUSE.PRO,
;       CPINTERANIMATE.PRO, CPMOVIE.PRO, CPONE.PRO, CPSUNCEN.PRO
;
;    Common block for these programs are named CP*.COMMON :
;       CPCOLORS.COMMON, CPDISPFILES.COMMON, CPGET_R_T.COMMON,
;       CPKEYWORDS.COMMON, CPLOGIC_ENVRON.COMMON, CPMOVIDISPLAY.COMMON,
;       CPMOVIETIME.COMMON, CPMOV_DIR.COMMON, CPNEW_WINDOW.COMMON, 
;       CPONE_DIR.COMMON, CPPROLOCAL.COMMON, CPUSERINP.COMMON
;       CPWIDGBASES.COMMON
;
;    Required program that don't use the naming convention of CP*.* :
;       any widget library routines, ACKNOWLEDGE.PRO, OPSYS_LGCL.PRO,
;	PSPLOT.PRO, RESPOND_WIDG.PRO, WINUP.PRO, 
;	WINUP_COMMON.PRO, LINECOLORS.PRO
;
;
;-                                                     
                                                    

;+
;
; NAME:  		
;	CP_EVENT
;
; PURPOSE: 
;	The event handler for main CP option menu widget
;
; CATEGORY: 	
;	CP display
;
; CALLING SEQUENCE: 	
;	CP_EVENT, EVENT
;
; CALLED BY: 	
;	CP.PRO
;
; CALLS TO:  		
;	WINUP, ACKNOWLEDGE, CPONE, CPMOVIE
;
; INPUTS:
;	EV : the event structure, variable depending on type of item clicked
;	also, values in commons
;
; OPTIONAL INPUTS: 
;	none
;
; OUTPUTS: 
;	none explicit, only through commons
;
; OPTIONAL OUTPUTS: 
;	none
;
; COMMON BLOCKS: 	
;	CPCOLORS 	to set color tables states
;	CPDISPFILES 	to pass printer status
;	CPKEYWORDS 	for current options conditions
;	CPNEW_WINDOW 	for reuse state
;	CPPROLOCAL 	for the widget IDs of option buttons
;	CPWIDGBASES 	for the widget IDs of parents and informational 
;
; SIDE EFFECTS: 		
;	none
;              	
; RESTRICTIONS: 		
;	none
;
; PROCEDURE: 		
;	Process the events from the main options menu widget.  Continue 
;	recieving events until "QUIT" is clicked, thus sending 
;	return control to calling routine.  Or until "Display one image" or
;	"Show a movie" are selected. Each of these will call the appropriate
;	routines to contine processing.
;
; MODIFICATION HISTORY:
;	1991 - Elaine Einfalt (HSTX)
;	MAR 93 - removed unneccessary comments window, from main widget.
;	       - added handlers for radial and azmuthal scans
;
;-

pro cp_event, event

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

;e 2/19/93 @cplogic_envron.common 

 widget_control, event.id, get_uvalue=input	; which widget was clicked
 if n_elements(input) eq 0 then input = ''

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

 case type of 
    'BUTT' : case input of
	'QUITPRO': widget_control, event.top, /destroy 	; kill all widgets
        'KILLSCL': begin
	             widget_control, event.top, /destroy  ; kill top widget
                     widget_control, base, sensitive=1    ; can use BASE again
                   end

	'DELWIN' : winup, group_leader=event.top, message=message

	'REUSE'	  : reuse = 1
	'NOREUSE' : reuse = 0

	'SAVE'    : begin
			save, /xdr, /ver, FILE='CPSAVE.DAT',  $
				last_filename, 	$       ; normal image filename
				last_diffname1, $	; base image filename
				last_diffname2, $	; subtraction image filename
				cpmaxscale,	$	; the !p.color value for color table
				cpmidscale,	$	; mid point of data area in difference
				cpnegfac,	$	; the diff image neg scaling factor
				cpposfac,	$	; the diff image pos scaling factor
				cpdata,         $	; The data array.  NOTE: these values
							;   are not scaled for the color table.
				cphk, 		$	; the house keeping
				cpimsiz, 	$	; original image size
				cpih, 		$	; FOV positional value for image
				cpiv, 		$	; FOV positional value for image
				cptheta, 	$	; the value of theta entered by user,
							;  	in degrees
				cprsun,  	$	; the Rsun value entered by user
				cpnum_vals_n_scans, $   ; vector w/ # of valid data for each
							; 	scan
				cpintensity,	$	; the intensity values
				cpabscissa		; for RULECONDITION 3 it is the Rsun 
							;        values for the intensity array
		                                        ; for RULECONDITION 4 it is the angle
							;        values for the intensity array
		    end

	'HELP'    : cphelp, group=event.top

	; the user set options
	'NORMAL'   :  if event.select ne 0 then begin	  ; ignore offs

                         if norm_diff eq 1 then begin	; difference was active
			    if xregistered('cpone') or $	  ; have wrong
				xregistered('cpmovie') then begin ;   option
								  ;   display 
								  ;   active
			        acknowledge, message=([ $
				        'Cancel active top widget,',$
					'either "Display one image"',$
					'or "Show a movie". ', $
					'It is incompatible ', $
					'with "Normal display.'])

				; undo normal event, put back to difference
			        widget_control, norm, set_button=0   ; undo 
			        widget_control, diff, set_button=1   ;   event
				return
			    endif

			 endif

			 coltyp=0  &  norm_diff=0
			 widget_control, scal, sensitive=0  ; not applicable
		      endif

	'DIFFERE'  :  if event.select ne 0 then begin	; ignore offs

                         if norm_diff eq 0 then begin	; normal was active
			    if xregistered('cpone') or $	  ; have wrong
				xregistered('cpmovie') then begin ;   option
								  ;   display 
								  ;   active
			        acknowledge, message=([ $
				        'Cancel active top widget,',$
					'either "Display one image"',$
					'or "Show a movie". ', $
					'It is incompatible ', $
					'with "Make a difference".'])

				; undo difference event, put back to normal
			        widget_control, norm, set_button=1  
			        widget_control, diff, set_button=0 
				return
			    endif

			 endif

			 coltyp=1  &  norm_diff=1  
			 widget_control, scal, sensitive=1  ; now an option
		      endif

	'SOLNORTH' :  if event.select eq 0 then donorth=0 else donorth=1
	'SOLDISK'  :  if event.select eq 0 then dodisk=0  else dodisk=1
	'SOLRADII' :  if event.select ne 0 then doradii=1 else doradii=0
	'SOLRADIAL':  if event.select ne 0 then doradial=1 else doradial=0

	'RULNONE'  :  if event.select ne 0 then begin
			ruletimes = 0
		        widget_control, ruleopt2, sensitive=0
                      endif
	'RULONCE'  :  if event.select ne 0 then begin
			ruletimes = 1
		        widget_control, ruleopt2, sensitive=1
                      endif
	'RULMANY'  :  if event.select ne 0 then begin
			ruletimes = 2
		        widget_control, ruleopt2, sensitive=1
                      endif
	'RULINPT'  :  if event.select ne 0 then begin
			ruletimes = 3
		        widget_control, ruleopt2, sensitive=1
                      endif
	'MEMRUL'   :  if event.select ne 0 then begin
			ruletimes = 4
		        widget_control, ruleopt2, sensitive=1
                      endif

	'RULIT'     	:  if event.select ne 0 then rulecondition=0
	'MARKIT'    	:  if event.select ne 0 then rulecondition=1
	'NORULMARK' 	:  if event.select ne 0 then rulecondition=2
	'RADIALSCAN'    :  if event.select ne 0 then rulecondition=3
	'AZMUTHSCAN'	:  if event.select ne 0 then rulecondition=4

        'AUTOSCL'   :  if event.select ne 0 then begin   ; default clip
                         negfac = 65.  &  posfac = 65.
                         cpnegfac = 65.  &  cpposfac = 65.
		       endif 	
	'MANUSCL'   :  if event.select ne 0 then begin
			widget_control, base, sensitive=0 ; no BASE inputs now
                        negfac = 65.  &  posfac = 65.   	; default clip
                        cpnegfac = 65.  &  cpposfac = 65.

                        ; make a widget to ask for the scaling factors
          		inpscl = widget_base(title='C/P difference image ' +$
				 'scaling',/column, space=10,   $
			          xpad=20, ypad=20)

          		lab = widget_label(inpscl, value='Select the ' + $
			      'difference image scaling factors.')

          		lab = widget_label(inpscl, value='Difference data '+$
			      'has a possible value range of -255 to +255.')
			
          		lab = widget_label(inpscl, value='Values outside '+$
			      'of the scaled range are set to the scaling ' +$
			      'factor value.')
			      
	    		lab = widget_label(inpscl, value='Defaults are -65 '+$
			      'and +65.')

		    	tex = widget_slider(inpscl, title='Negative (blue) '+$
			      'clipping value', minimum=-256, maximum=-1, $
			      value=-65, xsize=700, uvalue = 'NEGINP')
	    		tex = widget_slider(inpscl, title='Positive (red) '+$
			      'clipping value', minimum=1, maximum=255, $
			      value=65, xsize=700, uvalue = 'POSINP') 

	    		go_on = widget_button(inpscl, value='READY', $
					              uvalue='KILLSCL')
	    		widget_control, inpscl, /realize
	    		xmanager,'cp', inpscl, /modal, group_leader=event.top
		       endif           

	'ONEIMAG' : begin
           sin_mov=0				; single image
	   onewin = -99				; no cp display window yet
	   widget_control, event.top, sensitive=0     ; no user for a while
	   cpone, group_leader=event.top 	; go display single image
	   end

        'MOVIEIM' : begin
	   sin_mov=1				; doing a movie
	   widget_control, event.top, sensitive=0       ; no user for a while
	   cpmovie, group_leader=event.top 		; go make a movie
           end
	else : print, 'Invalid BUTTON value in CP:' + input
	endcase   	; of input            

    'SLID': case input of 		; only if diff and manual scale factor
	'POSINP' : begin
	              widget_control, event.id, get_value=value
		      posfac = float(value)
		      cpposfac = posfac 
                   end
	'NEGINP' : begin
	              widget_control, event.id, get_value=value
		      negfac = float(value)
		      cpnegfac = negfac
                   end                            
	else : print, 'Invalid SLIDER value' + input
	endcase   	; of input

    else : print, 'Invalid type of widget ' + type

   endcase      	; of type
end

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

;+
;
; NAME: 
;	CP
;
; PURPOSE:
;	Create the main options menu widget
;
; CATEGORY:  
;	CP display
;
; CALLING SEQUENCE:
;	CP, [GROUP_LEADER=GROUP]
;
; CALLED BY: 
;	none
;
; CALLS TO: 
;	CPCOLOR, CP_event (via XMANAGER)
;
; INPUTS: 
;	none
;
; OPTIONAL INPUTS:
;	GROUP :  The widget ID of the parent widget.
;
; OUTPUTS: 
;	none explicit, only through commons
;
; OPTIONAL OUTPUTS: 
;	none
;
; COMMON BLOCKS:
;	CPCOLORS     	assigns the CP color tables
;	CPKEYWORDS  	assigns the initial values for option conditions
;	CPLOGIC_ENVRON	assigns the location of data
;	CPNEW_WINMDOW  	assigns initial values for window management
;	CPPROLOCAL 	creates the widget IDs of menu buttons
;	CPWIDGBASES 	creates the widget IDs of parents and informational 
;
; SIDE EFFECTS:  
;	none
;
; RESTRICTIONS:  
;	none
;
; PROCEDURE:
;	Verifiy data loction and create CP color tables then create the 
;	main options menu widget. 
;
; MODIFICATION HISTORY:
; 	1991 - Elaine Einfalt (HSTX)
;	MAR 93 - Added radial and azmuthal scan buttons
;
;-

pro cp,group_leader=group

@cpcolors.common
@cpkeywords.common
@cplastpass.common
@cplogic_envron.common
@cpnew_window.common
@cpprolocal.common
@cpwidgbases.common
 
 if xregistered('cp') then return	 ; only want one running at a time

 ; see if logical/environment name is defined
 opsys_lgcl, part1='CP', discern='_', part2='DATA', separate=1, 	$
	dataplace=dataplace, ok=ok, 					      $
  	instructme=['Enter your designation for the data location and return',$
  		    '     VMS    ex: SDAC::CP$DATA, $1$DIA4:[CP]',          $
  		    '     UNIX   ex: $CP_DATA, /usr/users/Data']

 if not(ok) then begin
	acknowledge, message=(['Progam is returning', $
			       'because of cancel'])
	return		; no input given to look for the data
 endif

; windowing setup
  device, get_screen_size=sc
  lastmark = 0
  reuse = 1

; Create C/P color table

cpcolor, diff_r=diff_r, diff_g=diff_g, diff_b=diff_b, $
	 norm_r=norm_r, norm_g=norm_g, norm_b=norm_b

; initialize keywords
coltyp=0     &  colreset = 1 
norm_diff=0  &  donorth=1  &  dodisk=1  &  doradii=0   &  doradial=0
ruletimes=0  &  rulecondition=0         
posfac=65.  &  negfac=65.   &  cpposfac=65.  &  cpnegfac=65.

cpintensity = bytarr(800, 5) - 1    	; data intensities of scans
cpabscissa  = fltarr(800, 5) - 1    	; theta or Rsun of scans
cptheta = [-1,0]			; initial value and a terminator
cprsun  = [-1,0]			; initial value and a terminator
cpnum_vals_n_scans = intarr(5)-1    	; in each of up to 5 repeats 

base = widget_base(title='C/P Workbench  Version 1.1', /column, space=20, $
					xpad=20, ypad=20)

 combos = widget_base(base, /row, space=30) 
  dispway = widget_base(combos, /column, space=10)
   oneim = widget_button(dispway, value='  Display one image  ', $
							uvalue='ONEIMAG')
   movie = widget_button(dispway, value='  Show a movie  ', uvalue='MOVIEIM')
 
  normdiffopt = widget_base(combos, /column, /frame, /exclusive)
   norm = widget_button(normdiffopt, value='Normal display ', uvalue='NORMAL')
   diff = widget_button(normdiffopt, value='Make a difference', uvalue='DIFFERE')

  endit = widget_button(combos, value='QUIT', uvalue='QUITPRO')

 drawopt = widget_base(base, /column, /frame, xpad=20, /nonexclusive)
   snorth = widget_button(drawopt, value='Draw solar north', uvalue='SOLNORTH')
   sdisk = widget_button(drawopt, value='Draw solar disk', uvalue='SOLDISK')
   sradii = widget_button(drawopt, value='Draw solar radii lines', $
						uvalue='SOLRADII')
   sradial = widget_button(drawopt, value='Draw radial lines', $
						 uvalue='SOLRADIAL')

 rulopts = widget_base(base, /row, /frame)
 ruleopt1 = widget_base(rulopts, /column, /frame, /exclusive)
   rulenone = widget_button(ruleopt1, value='No R and theta', uvalue='RULNONE')
   ruleone = widget_button(ruleopt1, value='Pick one R and theta', $
				     uvalue='RULONCE')
   rulemulti = widget_button(ruleopt1, value='Pick multiple R and theta', $
				     uvalue='RULMANY')
   ruleinput = widget_button(ruleopt1, value='User input R and theta', $
				     uvalue='RULINPT')
   memoryrule = widget_button(ruleopt1, value='Use R and theta in memory', $
				     uvalue='MEMRUL')

 ruleopt2 = widget_base(rulopts, /column, /frame, /exclusive)
   rulerit = widget_button(ruleopt2, value='Draw R and theta ruler', $
				     uvalue='RULIT')
   markit = widget_button(ruleopt2, value='Mark R and theta click', $
				     uvalue='MARKIT')
   norule = widget_button(ruleopt2, value='No R and theta ruler or mark', $
				     uvalue='NORULMARK')
   radscan = widget_button(ruleopt2, value='Plot radial scan', $
				     uvalue='RADIALSCAN')
   azmscan = widget_button(ruleopt2, value='Plot azmuthal scan', $
				     uvalue='AZMUTHSCAN')
   
 aux = widget_base(base, /row, space=20)
  scal = widget_base(aux, /column, /frame, /exclusive)
   auto = widget_button(scal, value='Auto-Scale data', uvalue='AUTOSCL')
   inscl = widget_button(scal, value='Input data scaling', uvalue='MANUSCL')

  tools = widget_base(aux, /row, space=20)
    xpdmenu, ['"Windowing" {', $
		'"Delete windows" DELWIN', $
		'"Reuse display window" REUSE',$
		'"New display windows" NOREUSE', '}' ], tools

    save = widget_button(tools, value='SAVE', uvalue='SAVE')
    hlp = widget_button(tools, value='HELP', uvalue='HELP')

 widget_control, base, /realize

 widget_control, norm, set_button=1
 widget_control, snorth, set_button=1
 widget_control, sdisk, set_button=1
 widget_control, rulenone, set_button=1
 widget_control, ruleopt2, sensitive=0
 widget_control, rulerit, set_button=1
 widget_control, scal, sensitive=0
 widget_control, auto, set_button=1
 

 xmanager,'cp', base, group_leader=group

 current_window = -1		; can't be sure these windows will still be
 plot_window    = -1		; valid CP windows, once we leave this code

end