Viewing contents of file '../idllib/astron/contrib/varosi/code/allpro/analyze_mosaics.pro'
;+
; NAME:
;	analyze_mosaics
; PURPOSE:
;	Interactively create a mosaic of arbitrary size images
;	(called "mosaic" images, which are created in pro mosaic) and:
;	compute algebraic expression involving fluxes in overlayed pixels,
;	(after appropriately scaling fluxes in the images),
;	or compute average of the mosaic.
;	Can also just arrange a collection of images for
;	deconvolution of mosaic & PSF image pairs,
;	or modeling the IR spectrum at each pixel with heated dust emission
;	and line-of-sight absorption.
; CALLING:
;	analyze_mosaics, math_result, math_spec, Return_Task
; INPUTS:
;	All INPUT and most of OUTPUT is thru
;
;	common math_mosaics:
;
;		math_List = array of structures containing image locations and
;			pointers into the arrays: math_images & math_imscaled.
;		math_images = array of image data, pointed to by math_List.
;		math_imscaled = image data scaled into bytes for display.
;
;	common mosaic_array:
;
;		mosaics = array of image data, pointed to by mosaic_specs.
;		mosaic_specs = array of structures containing specs. and
;					pointers into the array: mosaics.
;		mosaic_infos = array of structures containing info about
;				how each mosaic image was formed.
;
;	Elements of math_images are extracted from array mosaics.
; OUTPUTS:
;	math_result = 2D array (image) result of computations.
;	math_spec = structure defining the math_result.
;	Return_Task = string, next task requested by user.
; COMMON BLOCKS:
;	common math_mosaics, math_List, math_images, math_imscaled
;	common mosaic_array, mosaics, mosaic_specs, mosaic_infos
;	common analyze_mosaics, math_window,result_window,contour_window,border
;	common analyze_mosaic2, mathmos_colors
;	common dir_names, dirinv, dirmos_raw, dirmos_aver
;	common dir_name2, dirmos_math
; EXTERNAL CALLS:
;	functions:	calc_im_stack	DeConv_images	average_mosaics
;	pros:	restore_MathMos	restore_mosaic	display_images	centroid_images
;		align_mosaics	contour_mosaic	scale_mosaics	pop_mosaics
;		mosaic_correls	mosaic_coordin	mosaic_task	get_window...
; PROCEDURE:
;	Menu with loop around big CASE statement,
;	and pro mosaic_task gets leftovers.
; HISTORY:
;	Written, Frank Varosi NASA/Goddard 1990  (started as: ratio_mosaics).
;	F.V.1991, generalized into mosaic Math & Analysis.
;	F.V.1991, added option: Match_Levels.
;	F.V.1992, added options: align by centroids, De-Convolve mosaics.
;	F.V.1994, call mosaic_correls for more cross-correlation options.
;	F.V.1998, option to display images in wavelength/maximum order.
;-

pro analyze_mosaics, math_result, math_spec, Return_Task

  common math_mosaics, math_List, math_images, math_imscaled
  common mosaic_array, mosaics, mosaic_specs, mosaic_infos
  common analyze_mosaics, math_window, result_window, contour_window, border
  common analyze_mosaic2, mathmos_colors
  common dir_names, dirinv, dirmos_raw, dirmos_aver
  common dir_name2, dirmos_math
  common menus, menu_window

	if N_elements( border ) NE 1 then border=1
	if N_struct( math_List ) GT 0 then math_wtit = math_List(0).winame $
				      else math_wtit = "MosMath"

	menu_math_p1 = ["Analysis / Math Functions:"	,$
			" "				,$
			"goto IDL>"			,$
			"goto MOSAIC"			,$
			"goto DISPLAY mosaics"		,$
			" "				,$
			"restore Math mosaic"		,$
			" "				,$
			"select mosaics"		,$
			"remove a mosaic"		,$
			"restore a mosaic"		,$
			" "				,$
			"mosaic by correlations"	,$
			"mosaic by offsets"		,$
			" "				,$
			"align by centroids"		,$
			"align by cursor"		,$
			" "				,$
			"move image"			,$
			"pop image"			,$
			"push image"			,$
			"order images"			,$
			" "				,$
			"Match Levels"			,$
			"filter images"			,$
			"reset to original images"	,$
			" "				,$
			"set source fluxes"		,$
			"mark source Locations"		,$
			" "				]

	if (!version.arch EQ '386i') then $
		menu_math_p1 = [ menu_math_p1			,$
				"COMPUTE ALGEBRA"		,$
				"COMPUTE average"		,$
				"De-Convolve  mosaics"	]	$
	  else	menu_math_p1 = [ menu_math_p1			,$
				"COMPUTE ALGEBRA"		,$
				" "				,$
				"COMPUTE average"		,$
				" "				,$
				"De-Convolve  mosaics"		]

	menu_math_p2 = ["show info"			,$
			"show fluxes"			,$
			"show borders"			,$
			"show statistics"		,$
			"show histograms"		,$
			" "				,$
			"define ORIGIN"			,$
			" "				,$
			"scale & smooth display"	,$
			"magnify or reduce"		,$
			" "				,$
			"color tables"			,$
			"adjust colors"			,$
			" "				,$
			"resize window"			,$
			"redisplay images"		,$
			"reorganize images"		,$
			"shift window center"		,$
			" "				,$
			"plot PROFILES"			,$
			"plot SPECTRUM"			,$
			" "				]

	if (!version.arch EQ '386i') then $
		menu_math_p2 = [ menu_math_p2			,$
				"CONTOUR computed image"	,$
				"SAVE results"			,$
				"SAVE Math Mosaic"	]	$
	  else	menu_math_p2 = [ menu_math_p2			,$
				"CONTOUR computed image"	,$
				" "				,$
				"SAVE results"			,$
				" "				,$
				"SAVE Math Mosaic"		,$
				" "				,$
				"zoom window"			]

	if (!D.name EQ "SUN") then menu_blank = [replicate( " ", 5 ),$
						"pause  (to use mouse)"," "] $
	  else if (!D.name EQ "X") AND (!version.os EQ "sunos") then $
		menu_blank = replicate( " ", 26 )  else  menu_blank = " "

	menu_math = [ menu_math_p1, menu_blank, menu_math_p2 ]
	check_menu_size, menu_math
	menu_window, XPOS=0, YPOS=!DEVY-128
	BELL = string( 7b )
	LF = string( 13b )
	task = ""
	select = 6
	if N_struct( mathmos_colors ) EQ 1 then color_ST_Load, mathmos_colors

	if N_elements( math_window ) EQ 1 then begin
	   device,WIN=win_flags
	   if (math_window GE 0) AND $
	      (math_window LT N_elements( win_flags )) then begin
		if win_flags(math_window) then begin
			wset, math_window
			wshow, math_window, ICON=0
		  endif else display_images, math_List, math_imscaled,/RESIZE
	     endif
	  endif else begin
		get_window, math_window, TITLE=math_wtit, XSIZ=8, XPOS=0, $
							  YSIZ=8, YPOS=0
		wshow, math_window, 0
		wait,0.5
	   endelse

while task NE "goto" do begin

	window_set_show, menu_window
	printw,[ "operating in Mosaic Math window", replicate(" ",3) ],/ERASE

  MENU:	select = wmenu( menu_math, INIT=select, TITLE=0 )

	if (select LT 0) then begin
		select = 6
		goto, MENU
	   endif

	request = menu_math(select)
	printw, ["function = " + strupcase( request ), " "], Line=-3, /ERASE
	task = next_word( request )

	CASE task OF

	"mosaic": BEGIN
		req = get_words( request )
		CASE req(1) OF
		  "correlations": mosaic_correls, math_List, IMAG=math_images, $
							IMSCALED=math_imscaled
	 	  "offsets":	mosaic_coordin, math_List, math_imscaled
		  else:
		 ENDCASE
		END

	"align": BEGIN

		what = next_word( request )
		if (what EQ "by") then  what = next_word( request )

		CASE what OF

		  "centroids":	centroids = centroid_images( math_List,   $
							     math_images, $
							     math_imscaled )

		     "cursor":	align_mosaics, math_List, math_imscaled

			 else:
		  ENDCASE
		END

	"pop":		pop_mosaics, math_List, math_imscaled

	"select": BEGIN
			analysis_select, change

			if (change) then begin
				math_List.windo = math_window
				math_wtit = math_List(0).winame
				display_images, math_List, math_imscaled,/RESIZ
			   endif
		    END

	"restore": BEGIN

		if next_word( request ) EQ "Math" then begin

			restore_MathMos, change, DIR=dirmos_math

			if (change) then scale_mosaics, math_List, math_images,$
							math_imscaled, /COLORSC
		  endif else begin

			restore_mosaic, imos, mosaic, change, DIR=dirmos_aver

			if (change) then $
				analysis_addmos, imos, N_struct( math_List )
		   endelse

		if (change) then begin
			math_List.windo = math_window
			math_wtit = math_List(0).winame
			display_images, math_List, math_imscaled,/RESIZE
		   endif
		END

	"duplicate": BEGIN
			if ( analysis_dupmos() GT 0 ) then $
				display_images, math_List, math_imscaled,/ERASE
		     END

	"remove":	remove_mosaics, math_List, math_images, math_imscaled

	"magnify":	magnify_mosaics, math_List, math_images, math_imscaled

	"scale": BEGIN
			scale_mosaics, math_List, math_images, math_imscaled, $
						  change, /MENU, /COLORSCALE
			if (change) then $
			   display_images, math_List, math_imscaled,/RESIZE
		   END

	"order": BEGIN
			order_images, math_List
			display_images, math_List, math_imscaled
		   END

	"delete":	delete_window, mosaic_specs

	"filter": BEGIN
			filter_mosaics, math_List, math_images, INUMS=inums

			if N_elements( inums ) GT 0 then begin
			   if (inums(0) GE 0) then begin
				scale_mosaics, math_List, math_images, $
						math_imscaled, /COLORSCALE
				display_images, math_List, math_imscaled,/ERASE
			    endif
			  endif
		    END

	"Match":	match_mosaics, math_List, math_images, math_imscaled

	"reset": BEGIN
			Nmath = N_struct( math_List )
			if (Nmath LE 0) then goto,MENU

			match, math_List.name, mosaic_specs.name, mm,ms,COUN=Nim

			if (Nim LE 0) then begin
				message,"original mosaics not found",/INFO
				goto,MENU
			  endif else if (Nim LT Nmath) then begin
				message,"not all original mosaics found",/INFO
			   endif

			math_sizes = math_List.size_image

			for i=0,Nim-1 do begin
	
				mmL = math_List(mm(i))
				mospec = mosaic_specs(ms(i))
				arcs_pixel = [ mospec.RA_pix, mospec.DEC_pix ]
				Magfs = arcs_pixel/math_List(0).arcs_pixel
				Magf = total( Magfs )/2

				print," reset of mosaic [", $
						mmL.name,"] in Math List"
				if (Magf NE 1) then print," Magfs =",Magfs

				mosaic = image_extract( ms(i), mosaics, $
						    mosaic_specs.size_image )

				image_replace, Rotate( RotMag( mosaic, /PIVOT, $
							XC=mmL.origin(0), $
							YC=mmL.origin(1), $
							ANG=mmL.rot_ang_deg, $
							INT=mmL.rot_interp, $
							MISS=min(mosaic), $
						 MAG=Magf ), mmL.rotation ), $
						mm(i), math_images, math_sizes
			  endfor

			math_List.size_image = math_sizes
			if (Nim EQ 1) then ms = ms(0)
			math_List(mm).Factor = 1
			math_List(mm).offset = 0
			math_List(mm).max = mosaic_specs(ms).max
			math_List(mm).min = mosaic_specs(ms).min
			math_List(mm).index = ms
			math_List(mm).history = ""

			scale_mosaics, math_List, math_images, $
						math_imscaled, /COLORSCALE
			display_images, math_List, math_imscaled,/ERASE
		  END

	"set": 		analyze_fluxset

	"mark":		analyze_markset

	"define":	define_origin, math_List

	"COMPUTE": BEGIN

		if (next_word( request ) EQ "average") then begin

			menu = [ "Width of border to neglect ?", $
						string(indgen(10)) ]
			sel = wmenu( menu, INIT=border+1, TITLE=0 )
			border = (sel-1) > 0

			math_result = average_mosaics( math_List, math_images, $
							BORDER=border, /BACK )
			Nmath = N_elements( math_List )
			math_info = mosaic_struct( Nmath, TYPE="info" )
			copy_struct, math_List, math_info
			math_info.border = border

			Mcalc = "Average(B=" + strtrim( border,2 ) + ")"
			Mdefs = math_List.name

		  endif else begin

			math_result = calc_im_stack( math_List, Mcalc,$
						 	Mdefs,DATA=math_images )
			math_info = 0
		   endelse

		szmr = size( math_result )

		if (szmr(0) EQ 2) then begin

			deconv_info = 0
			maxr = max( math_result, MIN=minr )

			Mdefs = [Mdefs,"MAX = " + strtrim( maxr, 2 ), $
					"MIN = " + strtrim( minr, 2 )  ]

			if N_struct( math_spec ) NE 1 then begin
				math_spec = mosaic_struct( 1, TYPE="spec" )
				copy_struct, math_List(0), math_spec, $
					EXC=["factor","offset","filter",$
						"filt_width","windo"]
				math_spec.rotation = 0
				math_spec.scaling = "Linear"
				math_spec.winame = "Contour of Computation"
				math_spec.RA_pix = math_List(0).arcs_pixel(0)
				math_spec.DEC_pix = math_List(0).arcs_pixel(1)
			   endif

			math_spec.size_image = szmr
			math_spec.max = maxr
			math_spec.min = minr
			math_spec.minF = math_spec.min
			math_spec.maxF = math_spec.max
			math_spec.minT = math_spec.min
			math_spec.maxT = math_spec.max
			math_spec.Truncate = 0
			math_rescl = scale_mosaic( math_result, math_spec )

			Nchar = strlen( Mcalc ) > max( [strlen( Mdefs )] )
			s = size( math_rescl )
			xsiz = s(1) > (!D.x_ch_size * (Nchar+2) )
			ysiz = s(2) + (N_elements( Mdefs )+2) * !D.y_ch_size

			get_window, result_window, TIT="Computation", $
				XSIZ=xsiz, YSIZ=ysiz, XPOS=!DEVX-xsiz, YPOS=300
			erase
			tv, math_rescl
			printw,[Mcalc,Mdefs]

			math_spec.title = Mcalc
			Mcalc = "MosMath: " + Mcalc
			math_spec.name = Mcalc
			math_spec.file = ""

			s = float( s )
			posxyr = [ [0,0], [s(1)/xsiz, s(2)/ysiz] ]
			contour_marks, posxyr, "MosMath",/SHOW_SOURCES
			empty
			wshow, result_window, ICON=0
			color_scale, SPEC=math_spec
		   endif
		END

	"De-Convolve": BEGIN
			deconv_info = 0
			math_result = DeConv_images( math_List, deconv_info, $
							     DATA=math_images )

			if N_struct( deconv_info ) GT 0 then begin
				math_spec = mosaic_struct( 1, TYPE="spec" )
				copy_struct, math_List(0), math_spec, $
					EXC=["factor","offset","filter",$
						"filt_width","windo"]
				math_spec.name = deconv_info.file
				math_spec.title = deconv_info.file
				math_spec.file = ""
				math_spec.size_image = size( math_result )
				math_spec.filter = "none"
				math_spec.filt_width = 0
				math_spec.scaling = "Linear"
				math_spec.max = deconv_info.maxdc
				math_spec.min = deconv_info.mindc
				math_spec.minF = math_spec.min
				math_spec.maxF = math_spec.max
				math_spec.minT = math_spec.min
				math_spec.maxT = math_spec.max
				math_spec.Truncate = 0
				math_spec.winame = "Contour of De-Convolution"
				math_spec.windo = -1
				math_spec.rotation = 0
				math_spec.RA_pix = math_List(0).arcs_pixel(0)
				math_spec.DEC_pix = math_List(0).arcs_pixel(1)
				math_info = 0
				Mcalc = ""
				Mdefs = ""
			   endif
			END

	"CONTOUR": BEGIN
			if N_elements( math_result ) LE 1 then begin
				print,LF+" must COMPUTE first"+BELL
				wait,0.5
				goto,MENU
			   endif

			if N_elements( contour_window ) EQ 1 then $
					math_spec.windo = contour_window

			contour_mosaic, math_result, math_spec,CAL="Mosaic Math"
			contour_window = math_spec.windo
		     END

	"SAVE":	BEGIN
		     CASE next_word( request ) OF

		      "results": save_analysis, math_result, Mcalc, Mdefs, $
					math_info, math_spec, deconv_info, $
					DIR=dirmos_aver

			 "Math": save_MathMos, DIR=dirmos_math
		      ENDCASE
		  END

	"pause": BEGIN
			pause_mouse, "Mosaic Math"
			if !DEBUG then stop
		   END

	"zoom":		zoomw, math_window

	   else:	mosaic_task, task, request, math_List, $
					DATA=math_images, SCALED=math_imscaled

	ENDCASE
endwhile

	mathmos_colors = color_struct( math_wtit )
	Return_Task = next_word( request )
end