  pro azam_hmi, directory, winfree=winfree
  ;+
  ; procedure:  wrapper for azam to select sub-areas of large maps
  ;
  ; purpose:  use interactive cursor to disambiguate azimuth in
  ;     directories with a_* files
  ;
  ; author:  lites@ucar 4/10, modified from codes by paul@ncar, 6/93
  ;-
  
    ; Check number parameters.
    if(n_params() gt 1) then begin
      print
      print, "usage:	azam_hinodesp [, dir ]"
      print
      print, "	Use interactive cursor to disambiguate azimuth in"
      print, "	directories with a_* files."
      print
      print, "	Arguments"
      print, "		directory	- directory path (string;"
      print, "			  def=use current working directory)"
      print
      print, "	Keywords"
      print, "		winfree	- set to open windows position free"
      return
    endif

;  common com_azamspectra passes some variables needed in other routines
;  besides azam_spectra
    common com_azamspectra, xllo,xuro,yllo,yuro,full_directory, $
        iwstrt,iwend,dispers,wavlngth,basewav,etaratio,vbroad, $
        maxsz,ntran,mscatt


	;  set variable full_directory to the directory for the ASP files for
	;	the full map
	full_directory = directory
    
    ; If no directory given, use current working directory.
    if(n_elements(directory) eq 0) then cd, current = directory
    
    ; Append directory path with '/'.
    if(strmid(directory, strlen(directory)-1, 1) ne '/') then begin
      directory = directory + '/'
    endif
    
    ; Read header, check for existence.
    header = read_floats(directory+'a___header', error)
    if(error ne 0)  then begin
      print, !err_string
      print, 'a_* files may not exit or directory path wrong'
      return
    endif
    
    ; Get the size of the map.
    cct = azam_a_image(directory+'a__cct', kk, r='i')
    szimg = size(cct)

	;  set the default image sizes to the map size
	xllo = 0 & yllo = 0
	xuro = szimg(1)-1 & yuro = szimg(2)-1
    
    ; Get the screen resolution.
    szscr = get_screen_size()
    
    ; Test to see if map will fit within available screen size, leave edge margin
    ; for taskbars, plot headers etc.
    pedge = 0.90

    
	jump13: loadct,0
    if(azam_fitsOnScreen(szimg[1], szimg[2]) eq 'true') then begin
	;  determine if necessary to re-select window
		clk = pop_cult(/string, xpos=100,ypos=100 $
			, title = 'Process a Sub-Area?' $
			,['^rProcess Subarea','^gEntire Area'])
		if clk eq 'Process Subarea' then goto,jump14
		if clk eq 'Entire Area' then goto,jump15
     endif else begin
	clk = pop_cult(/string, xpos=100,ypos=100 $
		, title = ' Sub-Area Processing Mandatory ' $
		,['^gSelect a Sub-Area','^rExit AZAM'])
		if clk eq 'Select a Sub-Area' then goto,jump14
		if clk eq 'Exit AZAM' then goto,jump17
     endelse

	jump14:
		
	;  Processing of subarea manditory if whole area does not fit on screen
      ; Open a temporary directory for reduced image a_files
      tdir = 'tempazamdir'
      tempDirectory = directory + tdir
      file_mkdir, tempDirectory, /noexpand_path

      ; Display the LOS flux image on an appropriately reduced scale.
	  ; First use the ASP software to read in the appropriate images
      fld = azam_a_image(directory+'a_fld', kk, r='i')
      psi = azam_a_image(directory+'a_psi', kk, r='i')
      alpha = azam_a_image(directory+'a_alpha', kk, r='i')
      ;flux = fld*cos(psi*!dtor)*(1.-alpha)
	  ; NOTE!!!  HMI inversions use fill fraction for alpha!!
	  ; NOTE!!!  for HMI inversions, fld assumes alpha =1
      ;flux = fld
      flux = fld*cos(psi*!dtor)
      cen1 = azam_a_image(directory+'a_cen1', kk, r='i')
      azm1 = azam_a_image(directory+'a_1azm', kk, r='i')
      incl1 = azam_a_image(directory+'a_1incl', kk, r='i')
      azm2 = azam_a_image(directory+'a_2azm', kk, r='i')
      incl2 = azam_a_image(directory+'a_2incl', kk, r='i')
      azm0 = azam_a_image(directory+'a_azm0', kk, r='i')
      azm = azam_a_image(directory+'a_azm', kk, r='i')
      eta0 = azam_a_image(directory+'a_eta0', kk, r='i')
      dop = azam_a_image(directory+'a_dop', kk, r='i')
      dmp = azam_a_image(directory+'a_dmp', kk, r='i')
      bzero = azam_a_image(directory+'a_bzero', kk, r='i')
      b1mu = azam_a_image(directory+'a_b1mu', kk, r='i')

;  find locations outside of the disk and regularize the varibles
	whrout = where(dop le 0., complement=whrin,countdop)
	if countdop ne 0 then begin
		dop(whrout) = 0.
		flux(whrout) = min(flux(whrin))
		cen1(whrout) = median(cen1(whrin))
		fld(whrout) = 0.
		psi(whrout) = 0.
		dmp(whrout) = 0.
		bzero(whrout) = 0.
		b1mu(whrout) = 0.
		alpha(whrout) = 1.
		cct(whrout) = 0.
	endif

      
      ; Get where-array of fitted points.
      whrfit = kk.sxy
      
      ; Determine factor to reduce size of flux image in order to display entire
      ; image on screen with 10% margin.
      redfac = min([pedge * szscr(0) / szimg(1), pedge * szscr(1) / szimg(2)])
      ; Reduced size flux image.
      redflux = congrid(flux,szimg(1) * redfac, szimg(2) * redfac, /interp)
      ; Display the flux image.
      redflux = bytscl(redflux, min=-1500., max=1500.)
      ; Select sub-area.
      jump53: azam_area_sel, redflux, redfac, xll, yll, xur, yur
      
      ; Get the reduced image coordinates in original image pixels.
      xllo = round(xll/redfac) & yllo = round(yll/redfac)
      xuro = round(xur/redfac) & yuro = round(yur/redfac)
      
      ; Restrain values to within original range.
      if(xllo lt 0) then xllo = 0
      if(yllo lt 0) then yllo = 0
      if(xuro gt szimg(1) - 1) then xuro = szimg(1) - 1
      if(yuro gt szimg(2) - 1) then yuro = szimg(2) - 1
      
      ; Check to see if sub-area fits in the available screen area.
      xwdth = xuro-xllo+1
      if(xwdth gt szscr(0)) then begin
        print,'x-dimension of sub-area (',xwdth,')  exceeds screen area (',szscr(0),'), select again'
        goto, jump53
      endif
      ywdth = yuro-yllo+1
      if(ywdth gt szscr(1)) then begin
        print,'y-dimension of sub-area (',ywdth,') exceeds screen area (',szscr(0),'), select again'
        goto, jump53
      endif
      
      ; Write the ASP-style header to the temporary directory.
      nspansav = header(57)
      header(57) = yuro - yllo + 1 ; Set nspan in header
      err = write_floats(tempDirectory + '/a___header', header)
      header(57) = nspansav
      
      ; Find the solved where array for the the sub-area.
      temp = azam_a_image(directory + 'a_solved', kk, r='i')
      temp(*,*) = -1.
      temp(whrfit) = 1.
      temp = temp(xllo:xuro, yllo:yuro)
      whrfnew = where(temp gt 0.)
      
      ; Reformulate the a__points array for the sub-area.
      nxn = xuro - xllo + 1
      nyn = yuro - yllo + 1
      fnxn = float(nxn) & fnyn = float(nyn)
      tsolv = fltarr(nxn, nyn)
      for ix = 0, nxn-1 do for iy = 0, nyn-1 do begin
        tsolv(ix,iy) = float(ix)*fnyn + float(iy)
      endfor
      kk.sxy = whrfnew
      err = write_floats(tempDirectory+'/a__points', tsolv)
      
      ; Reformulate the a_solved array for the sub-area.
      asolnew = tsolv(whrfnew)
      ;kk.sxy = whrfnew
      err = write_floats(tempDirectory+'/a_solved', asolnew)
      
      ; Now go through all the variables used by AZAM, reducing the
      ; size and writing them to a_* files in the temporary directory
      ; first do the variables already read in.
      temp = fld(xllo:xuro, yllo:yuro) & temp = temp(whrfnew)
      err = write_floats(tempDirectory+'/a_fld', temp)
      temp = psi(xllo:xuro, yllo:yuro) & temp = temp(whrfnew)
      err = write_floats(tempDirectory+'/a_psi', temp)
      temp = alpha(xllo:xuro, yllo:yuro) & temp = temp(whrfnew)
      err = write_floats(tempDirectory+'/a_alpha', temp)
      ;  variables defined for fitted points only
      temp = cen1(xllo:xuro, yllo:yuro) & temp = temp(whrfnew)
      err = write_floats(tempDirectory+'/a_cen1', temp)
      temp = azm0(xllo:xuro, yllo:yuro) & temp = temp(whrfnew)
      err = write_floats(tempDirectory+'/a_azm0', temp)
      temp = azm(xllo:xuro, yllo:yuro) & temp = temp(whrfnew)
      err = write_floats(tempDirectory+'/a_azm', temp)
      temp = azm1(xllo:xuro, yllo:yuro) & temp = temp(whrfnew)
      err = write_floats(tempDirectory+'/a_1azm', temp)
      temp = azm2(xllo:xuro, yllo:yuro) & temp = temp(whrfnew)
      err = write_floats(tempDirectory+'/a_2azm', temp)
      temp = incl1(xllo:xuro, yllo:yuro) & temp = temp(whrfnew)
      err = write_floats(tempDirectory+'/a_1incl', temp)
      temp = incl2(xllo:xuro, yllo:yuro) & temp = temp(whrfnew)
      err = write_floats(tempDirectory+'/a_2incl', temp)

	  ;  variables used by ME profile generation
      temp = eta0(xllo:xuro, yllo:yuro) & temp = temp(whrfnew)
      err = write_floats(tempDirectory+'/a_eta0', temp)
      temp = dop(xllo:xuro, yllo:yuro) & temp = temp(whrfnew)
      err = write_floats(tempDirectory+'/a_dop', temp)
      temp = dmp(xllo:xuro, yllo:yuro) & temp = temp(whrfnew)
      err = write_floats(tempDirectory+'/a_dmp', temp)
      temp = bzero(xllo:xuro, yllo:yuro) & temp = temp(whrfnew)
      err = write_floats(tempDirectory+'/a_bzero', temp)
      temp = b1mu(xllo:xuro, yllo:yuro) & temp = temp(whrfnew)
      err = write_floats(tempDirectory+'/a_b1mu', temp)
      
      ;  Continue with other needed variables not yet read in
      ;  variables defined over whole area.
      temp = azam_a_image(directory+'a__cct', kk, r='i') & temp = temp(xllo:xuro, yllo:yuro)
      err = write_floats(tempDirectory+'/a__cct', temp)
      temp = azam_a_image(directory+'a__utime', kk, r='i') & temp = temp(xllo:xuro, yllo:yuro)
      err = write_floats(tempDirectory+'/a__utime', temp)
      temp = azam_a_image(directory+'a__mu', kk, r='i') & temp = temp(xllo:xuro, yllo:yuro)
      err = write_floats(tempDirectory+'/a__mu', temp)
     ; temp = azam_a_image(directory+'a__pip', kk, r='i') & temp = temp(xllo:xuro, yllo:yuro)
     ; err = write_floats(tempDirectory+'/a__pip', temp)
      temp = azam_a_image(directory+'a__longitude', kk, r='i') & temp = temp(xllo:xuro, yllo:yuro)
      err = write_floats(tempDirectory+'/a__longitude', temp)
      temp = azam_a_image(directory+'a__latitude', kk, r='i') & temp = temp(xllo:xuro, yllo:yuro)
      err = write_floats(tempDirectory+'/a__latitude', temp)
	  temp = azam_a_image(directory+'a__rgtasn',kk,r='i') & temp = temp(xllo:xuro,yllo:yuro)
	  err = write_floats(tempDirectory+'/a__rgtasn',temp)
	  temp = azam_a_image(directory+'a__dclntn',kk,r='i') & temp = temp(xllo:xuro,yllo:yuro)
	  err = write_floats(tempDirectory+'/a__dclntn',temp)

      delwin
      
      ; Perform AZAM function on reduced area.
      hmi_azam, tempDirectory
    
      delwin
      
      ; After AZAM function on reduced area, replace affected files into original.    

      n_azm = azam_a_image(tempDirectory+'/a_azm', r='i')
      azm(xllo:xuro,yllo:yuro) = n_azm & azm = azm(whrfit)
      err = write_floats(directory+'n_a_azm',  azm)

      n_1azm = azam_a_image(tempDirectory+'/a_1azm', r='i')
      azm1(xllo:xuro,yllo:yuro) = n_1azm & azm1 = azm1(whrfit)
      err = write_floats(directory+'n_a_1azm',  azm1)
      
      n_2azm = azam_a_image(tempDirectory+'/a_2azm', r='i')
      azm2(xllo:xuro,yllo:yuro) = n_2azm & azm2 = azm2(whrfit)
      err = write_floats(directory+'n_a_2azm', azm2)
      
      n_1incl = azam_a_image(tempDirectory+'/a_1incl', r='i')
      incl1(xllo:xuro,yllo:yuro) = n_1incl & incl1 = incl1(whrfit)
      err = write_floats(directory+'n_a_1incl', incl1)
      
      n_2incl = azam_a_image(tempDirectory+'/a_2incl', r='i')
      incl2(xllo:xuro,yllo:yuro) = n_2incl & incl2 = incl2(whrfit)
      err = write_floats(directory+'n_a_2incl', incl2)
      
      ; Cleanup the temporary directory and delete it, move the altered disambiguation files.
      azam_cleanup_hmi, directory, tempDirectory
	  goto,jump16

      ; Run the normal AZAM routine if image fits within the display.
	  jump15:
	  ;  FOR HMI, SPECIAL AZAM THAT CALLS AZAM_OP_HMI.PRO
      hmi_azam, directory
      delwin

  	  jump16:

  ;  check to process another area
	  clk = pop_cult(/string, xpos=100,ypos=200 $
	  , title = 'Process another Area?' $
	  ,['^rYES, Process Area','^gNO, CONTINUE'])
  	  if clk eq 'YES, Process Area' then goto,jump13
  	  if clk eq 'NO, CONTINUE' then goto,jump17
    
  jump17:

  ;  reset the color table to B/W
  loadct,0

  	;  prompt to output a FITS ambiguity resolution file
	  clk = pop_cult(/string, xpos=100,ypos=200 $
	  , title = 'Write an AZAM ambiguity resolution FITS file?' $
	  ,['^rYES, Write FITS file','^gNO, END AZAM'])
  	  if clk eq 'YES, Write FITS file' then goto,jump18
  	  if clk eq 'NO, END AZAM' then goto,jump19
    


	jump18:

  	;  output the ambiguity solution to a FITS file.  This will be a
	;  byte array containing 0 where the resolution matches the original
	;  inversion output, and 1 where it differs from the original.

	azzorig = a_image(directory+'a_azm0')	;  read in original azimuth
	azz = a_image(directory+'a_azm')	;  read in original azimuth
	sz = size(azz)
	nnx = sz(1) & nny = sz(2)
	azam_ambig_resol = bytarr(nnx,nny)
	azam_ambig_resol(*,*) = 0 
	temp = azzorig-azz
	whr = where(abs(temp) gt 1.)
	azam_ambig_resol(whr) = 1

	;  read in the original Hinode FITS header
	restore,directory+'HMI_FITSheader.save'
	;  write FITS file
	fits_write,'AZAM_ambig_resol.fits',azam_ambig_resol,header

	jump19:

  return

  end
