@ ./miver.pro
;!path = expand_path('+/sanhome1/asainz/iris2_official')+':'+!path

; restore, '/Users/asainz/ciencia/IRIS/20160114_230409_3630008076/data_info_iris_l2_20160114_230409_3630008076_raster_t000_r00000.sav'

;data = 'factor.DATA_MG_II_K_2796


function tvg, data, show_fit=show_fit, step=step, aux_ima=aux_ima, show_var=show_var, $
	show_chi2 = show_chi2, show_pos = show_pos, show_mu = show_mu, put_threshold=put_threshold, $
    color_index=color_index, zoom=zoom, arcsec=arcsec, show_obs=show_obs, raster_sel=raster_sel, $
    symmetric_lim=symmetric_lim, max_sel=max_sel, verbose=verbose
;+
;
; NAME:
;   tvg (for tvguay)
;
; PURPOSE:
;      To display a 4D data cube.
;
; CATEGORY:
;;  Visualization.
;
; SAMPLE CALLS:
;   Inputing file list:
;   IDL> sel = tvg(data)
;
; INPUTS:
;   A 2D, 3D or 4D data cube
;
; OUTPUTS (OPTIONAL):
;   If position(s) is stored by the user, the output is a structure with the position(s)
;   in the displayed (selected) data, the original data, the filenames of the data, and
;   other information.
;
; KEYWORDS:
;    zoom: If zoom is just a number, the data to be displayed are zoom in/out by a factor of zoom.
;         in both axes (X and Y). If zoom is a tuple, the data to be displayed are zoom in/out by a
;         factor zoom[0] in X axis, and by a factor zoom[1] in Y axis.
;         
; COMMANDS:
;    Several commands are encoded in some letters (case-insensitive). This a list of letters and commands and
;    a description of their actions:
;
;    - To display the discription of these commands:"
;      'I' -> Shows the help information."
;
;    - Moving along the 3rd dimension in the model atmosphere (optical depth) or the original calibrated data"
;      (spectral information). A vertical line pointing out the current position is displayed in the optical"
;      depth in the model variables plots or in thes spectral postion in the profile plots. It changes as:"
;      'Z' -> Moves back along the 3rd dimension of the data cube."
;      'X' -> Moves forward along 3rd dimension of the data cube."
;
;    - Changes between the variables in the model atmosphere:"
;      'V' -> Changes the variable displayed following this order: T -> vlos -> vturb -> elec. density -> T ..."
;
;    - Storing the position and other information:"
;      'S' -> Stores the position, the corresponding values of model atmosphere and uncertainty in that"
;      position and other values depending on the level_info in the iris2model structure. The position"
;      is stored as it is displayed in the image (in the orignal scale of the data, i.e. without taking into"
;      account the zoom) and as it is in the original raster."
;
;    - Changing the size of the displayed image:"
;      '+/=' -> Makes the displayed image 10% larger."
;      '-' -> Makes the displayed image 10% smaller."
;
;    - Quit show_iris2model:"
;      'Q' -> Quits show_iris2model."
;
; AUTHOR: 
;    A. Sainz Dalda (asainz.solarphysics@gmail.com)
; VERSION DATE:
;    20190610 - v1.0
;
;-

;;; WARNING: DO NOT REMOVE/CHANGE THIS LINE ;;;
device, True=24, Decomposed=0, Retain=2
;;; WARNING: DO NOT REMOVE/CHANGE THIS LINE ;;;
;;; Your life will become misarable if you do it.


dim = size(data)	
;data = reform(data)
n_dim = dim[0]

;restore, './colors_iris2model.sav'
;;; Colors are hard-coded at colors_iris2model.pro

var = 0

j= 0 
var = 0
flag_pmulti =0 
case n_dim of
   2: begin
        maxi=max(data[*,*])
        mini=min(data[*,*])
      end	
   3: begin
        ;maxi=max(data[*,*,j])
        ;mini=min(data[*,*,j])
        maxi =  max(max(data, dim=1), dim=1)
        mini =  min(min(data, dim=1), dim=1)
      end	
   4: begin
        ;maxi=max(data[*,*,j,var])
        ;mini=min(data[*,*,j,var])
        maxi =  max(max(max(data, dim=1), dim=1), dim=1)
        mini =  min(min(min(data, dim=1), dim=1), dim=1)
      end	
  else: begin
        sel = -1
        return, sel
      end       
endcase      
lim_inf = float(mini)
lim_sup = float(maxi)

lims_ima = [[lim_inf], [lim_sup]]

if keyword_set(symmetric_lim) then begin
    max_lim = max(abs(lims_ima), dim=2)
    lim_inf = float(-max_lim)
    lim_sup = float(max_lim)
    lims_ima = [[-max_lim], [max_lim]]
endif 



n=0
step = 1 
if keyword_set(inc) then step = inc>0 

tampan = GET_SCREEN_SIZE(RESOLUTION=resolution)
title0='tvguay'
if keyword_set(title) then  title0=title

; Default size plotting window 
xsp=700 & ysp=500  
; Position for "Colorbar" window
width_window2 = ysp/4. & xpos3=0 & ypos3=tampan(1)-width_window2
; Position for plotting window
;xpos0=0 & ypos0=tampan(1)-ysp 
xpos0=0 & ypos0=tampan(1)-ysp-width_window2-20
; Position for datawindow
xpos1=xpos0 + xsp + 10 & ypos1= ypos0+(ysp/2.)-dim[2]/2.

window,0, xs=xsp, ys=ysp, xpos=xpos0, ypos=ypos0,  title='Data Cube Dimension Inspector'
if keyword_set(zoom) eq 0 then zoom=[1.,1.]
window,1, xs=dim[1]*zoom[0], ys=dim[2]*zoom[1], xpos=xpos1, ypos=ypos1, title=title0
window,2, xs=xsp, ys=width_window2,  xpos=xpos3, ypos=ypos3,  title='Colorbar'


old_mouse = !mouse.button
!p.multi=[0,1,0]
!mouse.button=1
c=0
;print, ini, fin, step, cond , opc
ini=n
j=0
tc=""
enmouse=1
control_mouse=1
dev_kw  = 1
data_kw = 0
size_font_plot = 1.5
x_crs =0
y_crs =0
active_box=0
count_box =0
x_before_box = 0
y_before_box = 0
zoom_before_box = [1,1]
nxb = dim[1]
nyb = dim[2]
dim_ima2show = dim 
x_crs =0
y_crs =0
x_scr =0
y_scr =0
data_flag=0
dev_flag=1
chr = 'Z'
string_show = ''
var_text = ''
inaxis = dindgen(dim[1])
list_points = LIST()

xi=0
xf=dim[1]-1
yi=0
yf=dim[2]-1
zi=0
zf=dim[3]-1
dim2display=0
label_dim = ['X', 'Y', 'Z', 'V']
colorbar_area = 1.

flag_max_sel = 0

;while ( (!mouse.button eq 1 or !mouse.button eq 4 or  !mouse.button eq 0 ) and tc ne "q") do begin
while (chr ne "Q" and flag_max_sel eq 0) do begin

   ;;;; Command-line control options	
   chr = strupcase(get_kbrd(0.1)) ;Read character

   show_help = 0
   if keyword_set(verbose) then show_help = 1
   
   ; Information about the key shortcuts
   if chr eq "?" or  ( c eq 0 and show_help eq 1 ) then begin
      print,""
      print,"==================== Key shortcuts for show_iris2model ===================="
      print,""
      print,"    - To display the discription of these commands:"
      print,"      '?' -> Shows the help information."
      print,""
      print,"    - Moving along the 3rd dimension in the model atmosphere (optical depth) or the original calibrated data"
      print,"      (spectral information). A vertical line pointing out the current position is displayed in the optical"
      print,"      depth in the model variables plots or in thes spectral postion in the profile plots. It changes as:"
      print,"      'Z' -> Moves back along the 3rd dimension of the data cube."
      print,"      'X' -> Moves forward along 3rd dimension of the data cube."
      print,""
      print,"    - Toggles between the model atmosphere and the original (calibrated) data, only if level_info is 2:"
      print,"      'M' -> Changes between the  model atmosphere and the data cube."
      print,""
      print,"    - Changes between the variables in the model atmosphere:"
      print,"      'V' -> Changes the variable displayed following this order: T -> vlos -> vturb -> elec. density -> T ..."
      print,""
      print,"    - Changing the threshold of the image displayed (not of the values in the data):"
      print,"      'H' -> Turns DOWN the LOWER limit of displayed image."
      print,"      'J' -> Turns UP the LOWER limit of displayed image."
      print,"      'L' -> Turns UP the UPPER limit of displayed image."
      print,"      'K' -> Turns DOWN the UPPER limit of displayed image."
      print,"      'R' -> Resets the lower and upper limts of the displayed image."
      print,""
      print,"    - Activate/Deactivate the profile+fit window:"
      print,"      'F' -> Shows/Hides the profile+fit window."
      print,""
      print,"    - Storing the position and other information:"
      print,"      'S' -> Stores the position, the corresponding values of model atmosphere and uncertainty in that"
      print,"      position and other values depending on the level_info in the iris2model structure. The position"
      print,"      is stored as it is displayed in the image (in the orignal scale of the data, i.e. without taking into"
      print,"      account the zoom) and as it is in the original raster."
      print,""
      print,"    - Changing the size of the displayed image:"
      print,"      '+/=' -> Makes the displayed image 10% larger."
      print,"      '-' -> Makes the displayed image 10% smaller."
      print,"      'a' -> Changes the displayed image to 1px/arcsec"
      print,""
      print,"    - Quit show_iris2model:"
      print,"      'Q' -> Quits show_iris2model."
      print,""
      print,"==========================================================================="
      print,""
      c = 1
   endif

   ; Quitting 
   if chr eq 'Q' then print, " -> Quitting."

   ; Erasing colorbar dynamically
   if chr eq 'H' or chr eq 'J' or chr eq 'L' or chr eq 'K' or chr eq 'R' or chr eq 'V' or chr eq 'M' then begin
      wset, 2  & COYOTE_COLORBAR, POSITION=[0.1, 0.65, 0.90, 0.80], MAXRANGE=lim_sup_cb, MINRANGE=lim_inf_cb, title=tit_cb, color=0, format=format_cb
      wset, 1 
   endif 
  
   ; Enlarge/shrink the image displayed
   if chr eq '+' or chr eq '-' or chr eq '=' then begin
      if chr eq '+' or chr eq '=' then begin
	     incr_zoom = 1.1	   
	     print, ' -> Making the displayed image 10% larger.'
      endif	 
      if chr eq '-' then begin
	     incr_zoom = 0.9	   
	     print, ' -> Making the displayed image 10% smaller.'
      endif	 
      if keyword_set(zoom) eq 0 then zoom=[1.,1.]
      zoom=float(zoom)
      zoom[0] = (zoom[0]*incr_zoom)>0.1
      zoom[1] = (zoom[1]*incr_zoom)>0.1
      print, 'New...', zoom
      ;eraser = intarr(dim[1]*zoom[0], dim[2]*zoom[1]*(colorbar_area-1.10))
      ;eraser = eraser+1.
      ;eraser[0,0]=0.
      wdelete, 1
      window,1, xs=dim_ima2show[1]*zoom[0], ys=dim_ima2show[2]*zoom[1]*colorbar_area, xpos=xpos1, ypos=ypos1, title=title0
      ;tvcrs, x_crs*zoom[0], y_crs*zoom[1]
      ;x_crs = x_crs*zoom[0]
      ;y_crs = y_crs*zoom[1]
   endif 

   ; Moves down aling the 3rd dimension. In the model atmosphere that means to move 
   ; to higher layers in the solar atmosphere.
   if chr eq 'Z' then begin
	   print, '-> Moving back along the 3rd dimension of the data cube...'
	   j = j-step
       if j lt 0 then j = dim[3]-1
   endif
   ; Moves up down aling the 3rd dimension. In the model atmosphere that means to move 
   ; to lower layers in the solar atmosphere.
   if chr eq "X" then begin
	   print, '-> Moving forward along 3rd dimension of the data cube...'
	   j = j+step
       if j gt dim[3]-1 then j=0
   endif 	   

   ;if keyword_set(show_monochromatic) and control_mouse eq 1 then begin
   lim_mouse = dim[3]
   if (j ge lim_mouse) then begin
	   j_wl = j
                  print, "WARNING: There are "+strcompress(lim_mouse,/remove_all)+" images only"
                  ;j=dim[3]-1
                  j=0
                  ;if keyword_set(show_monochromatic) and control_mouse eq 1 then begin
                  ; if show_monochromatic eq 1 then begin
                  ;        j_wl = j
                  ;endif else begin
                  ;        j_tau = j
                  ;endelse
   endif


   ; ; Toggle between variables in the model atmosphere.
   ; if chr eq 'V' and n_dim gt 3 then begin
   ;    var = var + 1
   ;    if var gt 3 then var = 0      
   ;    print, '-> Changing displayed variable to ', var   
   ;    inaxis = indgen(dim[dim2display+1<3])
   ; endif 

   ; Toggle between variables in the model atmosphere.
   if (chr eq 'N' or chr eq 'M') and n_dim gt 3 then begin
      if chr eq 'N' then var = var - 1
      if chr eq 'M' then var = var + 1
      if var gt 3 or var lt 0 then var = 0      
      print, '-> Changing displayed variable to ', var   
      inaxis = indgen(dim[dim2display+1<3])
   endif 

   ; Changing the lower limit of the image displayed
   if chr eq 'H' then print, '-> Turning DOWN the LOWER limit of displayed image.'
   if chr eq 'J' then print, '-> Turning UP the LOWER limit of displayed image.'
   ; Changing the upper limit of the image displayed
   if chr eq 'L' then print, '-> Turning UP the UPPER limit of displayed image.'
   if chr eq 'K' then print, '-> Turning DOWN the UPPER limit of displayed image.'
   ; Resetting the limit values to the nominal values
   if chr eq 'R' then print, '-> Resetting the lower and upper limts of the displayed image.'
   if 1 then begin
      case n_dim of
         2: index_minmax = 0
         3: index_minmax = j
         4: index_minmax = var 
      endcase
      if chr eq 'H' then lim_inf[index_minmax] = (lim_inf[index_minmax]-abs(lim_inf[index_minmax])*.02) ;<lim_sup
      if chr eq 'J' then lim_inf[index_minmax] = (lim_inf[index_minmax]+abs(lim_inf[index_minmax])*.02)<lim_sup[index_minmax]
      if chr eq 'L' then lim_sup[index_minmax] = (lim_sup[index_minmax]+abs(lim_sup[index_minmax])*.02) ;<lim_sup
      if chr eq 'K' then lim_sup[index_minmax] = (lim_sup[index_minmax]-abs(lim_sup[index_minmax])*.02)>lim_inf[index_minmax]
      if chr eq 'R' then begin
	     lim_inf[index_minmax] = lims_ima[index_minmax,0]
         lim_sup[index_minmax] = lims_ima[index_minmax,1]
      endif	 
      if lim_inf[index_minmax] eq lim_sup[index_minmax] then lim_inf[index_minmax] = (lim_inf[index_minmax]-lim_inf[index_minmax]*.03)
      ;print, 'Lim inf.', lim_inf[index_minmax]
      ;print, 'Lim sup.', lim_sup[index_minmax]
   end
  
    

   case n_dim of
      2: begin & ima2show = data[*,*] & end
      3: begin & ima2show = data[*,*,j] & end
      4: begin & ima2show = data[*,*,j,var] & end
   endcase

   if lim_inf[index_minmax] eq 0.0 then begin
      w = (where(ima2show>0.))[0]
      if w ne -1 then lim_inf[index_minmax] = ima2show[w]
      w = (where(ima2show<0.))[0]
      if w ne -1 then lim_inf[index_minmax] = ima2show[w]
   endif    
   if lim_sup[index_minmax] eq 0.0 then begin
      w = (where(ima2show>0.))[0]
      if w ne -1 then lim_sup[index_minmax] = ima2show[w]
      w = (where(ima2show<0.))[0]
      if w ne -1 then lim_sup[index_minmax] = ima2show[w]
   endif    

   if keyword_set(symmetric_lim) then begin
      if chr eq 'K' or chr eq 'L' then lim_inf[index_minmax] = -lim_sup[index_minmax]
      if chr eq 'H' or chr eq 'J' then lim_sup[index_minmax] = -lim_inf[index_minmax]
   endif    

   ; Zoom manual box 
   if chr eq 'I' then begin
      if count_box eq 0 then active_box = ~active_box	   
      if active_box eq 1 then begin
	 count_box+=1
	 if count_box eq 1 then begin
	    xb_1 = x_crs 
	    yb_1 = y_crs 
	    dim_ima2show = dim
	    print, ' -> First corner of the zoom-in box selected in: ', xb_1, yb_1
	 endif     
	 if count_box eq 2 then begin
	    xb_2 = x_crs 
	    yb_2 = y_crs 
	    print, ' -> Second corner of the zoom-in box selected in: ', xb_2, yb_2
	    nxb = abs(xb_2 - xb_1)/zoom[0] 
	    nyb = abs(yb_2 - yb_1)/zoom[1] 
	    nxb = abs(xb_2 - xb_1)
	    nyb = abs(yb_2 - yb_1)
	    nxb = ceil(nxb)
	    nyb = ceil(nyb)
	    dim_before_box = dim_ima2show
	    x_crs_before_box = xb_1<xb_2
	    y_crs_before_box = yb_1<yb_2
	    x_before_box = fix(x_crs_before_box/zoom[0])
	    y_before_box = fix(y_crs_before_box/zoom[1])
	    x_before_box = fix(x_crs_before_box)
	    y_before_box = fix(y_crs_before_box)
	    zoom_before_box = zoom
            ;dim = [1,nxb+1, nyb+1]
	    ;stop
	    print, 'Zoom-in box: ', x_before_box,(x_before_box+nxb+1)<dim[1]-1,y_before_box,(y_before_box+nyb+1)<dim[2]-1
        aux = ima2show[x_before_box:(x_before_box+nxb+1)<dim[1]-1,y_before_box:(y_before_box+nyb+1)<dim[2]-1]
	    ;stop
	    ;ima2show[x_before_box+2,y_before_box+2] = ima2show[0,0]
	    ;ima2show[x_before_box+1,y_before_box+1] = ima2show[0,1]
        dim_ima2show = size(aux)
        x_crs = 0 ;(x_crs - xb) < dim[1]
        y_crs = 0 ;(y_crs - yb) < dim[2]
	    zoom = zoom*5.
	 endif     
      endif else begin 	 
     	dim_ima2show = dim
	zoom = zoom_before_box
	;x_crs = x_crs_before_box
	;y_crs = y_crs_before_box
	x_before_box = 0
	y_before_box = 0
	x = x_before_box
	y = y_before_box
	nxb = dim[1]
	nyb = dim[2]
      endelse
      wdelete, 1
      window,1, xs=dim_ima2show[1]*zoom[0], ys=dim_ima2show[2]*zoom[1]*colorbar_area, xpos=xpos1, ypos=ypos1, title=title0
   endif 

   ; Zoom-out to the whole FoV (keeping the previous zoom/arcsec factor)
   if chr eq 'O' then begin
      dim_ima2show = dim
      x_before_box = 0
      y_before_box = 0
      nxb = dim[1]
      nyb = dim[2]
      zoom=zoom_before_box
      if count_box ge 1 then active_box = ~active_box
      count_box = 0
      wdelete, 1
      window,1, xs=dim_ima2show[1]*zoom[0], ys=dim_ima2show[2]*zoom[1]*colorbar_area, xpos=xpos1, ypos=ypos1, title=title0
   endif


   ;print, lim_inf, lim_sup

   ; Re-defining ima2show
   ima2show = ima2show[x_before_box:(x_before_box+nxb)<dim[1]-1,y_before_box:(y_before_box+nyb)<dim[2]-1]

   ; Applying the zoom to ima2show     
   if keyword_set(zoom) then ima2show = congrid(ima2show, dim_ima2show[1]*zoom[0], dim_ima2show[2]*zoom[1])


   ; Feeding the thresholds for the proper image display
   case n_dim of
         2: index_minmax = 0
         3: index_minmax = j
         4: index_minmax = var 
   endcase
   lim_sup_cb = lim_sup[index_minmax]
   lim_inf_cb = lim_inf[index_minmax]
   format_cb = '(F0.1)'
   ima2show[0,0] = lim_inf_cb
   ima2show[0,1] = lim_sup_cb
   

   ; Cross-hair locator
   ima2show[*,(y_scr)<(dim_ima2show[2]*zoom[1]-1)>0]=max(ima2show)
   ima2show[(x_scr)<(dim_ima2show[1]*zoom[0]-1)>0,*]=max(ima2show)

   ;lim_inf = min(ima2show>lim_inf)
   ;lim_sup = max(ima2show<lim_sup)
   ; Displays/Shows ima2show 
   wset, 1 & tvscl, ima2show<lim_sup_cb>lim_inf_cb

   ; Erasing/cleaning  the colorbar properly, either because of an update in the limits or because a resize of the window
   if chr eq 'H' or chr eq 'J' or chr eq 'L' or chr eq 'K' or chr eq 'O' or chr eq 'V' or chr eq 'M' or chr eq 'C' or chr eq 'Z' or chr eq 'X' or chr eq 'D' or control_mouse eq 0 then begin
      if chr eq 'C' then print, ' -> Cleaning IRIS2 Physical Variable Information window'
      wset, 2
      eraser = intarr(!d.x_size, !d.y_size/2) ;+1.
      ;eraser[0,0] = 0
      erase
   endif

   if lim_inf_cb eq lim_sup_cb then lim_inf_cb = lim_sup_cb*0.99
   wset, 2 & COYOTE_COLORBAR, POSITION=[0.1, 0.65, 0.90, 0.80], MAXRANGE=lim_sup_cb, MINRANGE=lim_inf_cb, title=tit_cb, format=format_cb
;;   wset, 3 & COLORBAR, POSITION=[0.1, 0.65, 0.90, 0.80], MAXRANGE=lim_sup_cb, MINRANGE=lim_inf_cb, title=tit_cb, format=format_cb
   ;print, control_mouse, data_kw, dev_kw
   ;wset, control_mouse  & cursor, x_crs,y_crs, 0, data=data_kw, dev=dev_kw
   ; Reading the coordinates in pixels

       
   ;if chr eq 'P' then begin
   ;   control_mouse =  ~control_mouse 
   ;   if control_mouse eq 0 then begin
   ;       data_flag=1
   ;       dev_flag=0
   ;       x_scr_before_p = x_scr
   ;       y_scr_before_p = y_scr
   ;  endif else begin 
   ;       data_flag=0
   ;       dev_flag=1
   ;  endelse       
   ;endif   

   if chr eq 'W' then begin
      control_mouse =  control_mouse - 1
      if control_mouse lt 0 then control_mouse = 1
      if control_mouse eq 0 then begin
          data_flag=1
          dev_flag=0
          x_scr_before_p = x_scr
          y_scr_before_p = y_scr
      endif    
      ;if control_mouse eq 2 then begin
      ;    data_flag=0
      ;    dev_flag=1
      ;    x_scr_before_p = lim_sup[index_minmax]
      ;    wset, 2
      ;endif    
      if control_mouse eq 1 then begin 
          data_flag=0
          dev_flag=1
      end
   endif   

   if control_mouse eq 0 then begin
       wset, control_mouse  & cursor, x_p,y_p, 0, data=data_flag, dev=dev_flag
       if dim2display eq 0 then begin
           y_scr = y_scr
           x_scr = x_p<(dim[dim2display+1]-1)
       endif    
       if dim2display eq 1 then begin
           x_scr = x_scr
           y_scr = x_p<(dim[dim2display+1]-1)
           ;print, y_scr
       endif    
       if dim2display eq 2 or dim2display eq 3 then begin
          ;if dim2display eq 2 or dim2display eq 3 then x_p = j
           if x_p gt 0 then j = x_p<(dim[(dim2display+1)<3]-1)>0    ; In the 4th dimension the plots will run over the 3rd dimension.
           x_scr = x_scr
           y_scr = y_scr
       endif    
       ;print, j
   endif else begin  
       wset, control_mouse  & cursor, x_scr,y_scr, 0, data=data_flag, dev=dev_flag
       ;if control_mouse eq 2 then begin
       ;   if x_scr > (lim_sup_cb - lim_inf_cb)/2. then lim_sup[index_minmax] = x_scr 
       ;   if x_scr < (lim_sup_cb - lim_inf_cb)/2. then lim_inf[index_minmax] = x_scr 
       ;   print, control_mouse, lim_sup[index_minmax]
       ;endif 
   endelse

   ; Transforming the coordinates in pixels to the data scale because of the zoom/arcsec factor
   ; if control_mouse eq 1 then begin
   x_crs = floor(x_scr/float(zoom[0]))
   y_crs = floor(y_scr/float(zoom[1]))
   x_crs_ant = x_crs
   y_crs_ant = y_crs
   ; Taking into account the origin of the zoom-in box 
      if active_box eq 1 then begin
           x = (x_crs+x_before_box)<(dim[1]-1)>0 
           y = (y_crs+y_before_box)<(dim[2]-1)>0 
      endif else begin  
	   x = x_crs<(dim[1]-1)>0
	   y = y_crs<(dim[2]-1)>0
      endelse 	   
   ;endif



   ; Plotting the model atmosphere  
   if ( x lt dim[1] and y lt dim[2] and x ge 0 and y ge 0 ) then begin
      ;print, x, y, dim[1], dim[2]
      wset, 0
      ;yv = [ima(x,y,n)]
      ;if keyword_set(show_monochromatic) and control_mouse eq 1  then j_tau = 18 ;;; log(tau) = -4 
      if chr eq 'D' then begin
        dim2display += 1
	    if dim2display gt n_dim-1 then dim2display = 0
	    inaxis = indgen(dim[dim2display+1<3])
	    print, ' -> Showning dimension #'+strcompress(dim2display+1), dim[dim2display+1]
        if dim2display eq 3 then flag_pmulti = 0
      endif

      xi = x & xf = x
      yi = y & yf = y
      zi = j & zf = j
      x_text = strcompress(x)
      y_text = strcompress(y)
      z_text = strcompress(j)
      v_text = strcompress(var)
      case dim2display of
	      0: begin & xi=0 & xf = dim[1]-1 & end
	      1: begin & yi=0 & yf = dim[2]-1 & end
	      2: begin & zi=0 & zf = dim[3]-1 & end
	      ;3: begin & zi=j & zf = j & end
	      3: begin & zi=0 & zf = dim[3]-1 & end
      endcase  		      

      case n_dim of
         2: begin
		        data_xy = data[xi:xf,yi:yf]
                j = 0
                var = 0
                text_val = [x_text+','+y_text]
                string_pos = string('data[X,Y] = '+text_val+' = ', data[x,y], format = '(a, E-0.2)')
                coordinates = [x,y]
            end	
         3: begin
		        data_xy = data[xi:xf,yi:yf,zi:zf]
                var = 0
                text_val = [x_text+','+y_text+','+z_text]
                string_pos = string('data[X,Y,Z] = '+text_val+' = ', data[x,y,j], format = '(a, E-0.2)')
                coordinates = [x,y,j]
            end	
         4: begin
		        data_xy = data[xi:xf,yi:yf,zi:zf,var]
		        if dim2display eq 3 then data_xy = data[xi:xf,yi:yf,zi:zf,*]
                text_val = [x_text+','+y_text+','+z_text+','+v_text]
                string_pos = string('data[X,Y,Z,V] = '+text_val+' = ', data[x,y,j,var], format = '(a, E-0.2)')
                coordinates = [x,y,j,var]
            end	
        else: begin
              sel = -1
              return, sel
      end       

      endcase      
      var_txt_show = ''
      wset, 0 
      if dim2display ne 3 then begin
          !p.multi = 0
          plot,  inaxis, reform(data_xy), psym=0, title=string_pos, /data, /yno, charsize=size_font_plot, xtitle=label_dim[dim2display]+' [px]', ylog=ylog
          wset, 0 
          if dim2display eq 0 then miver, x, line=2
          if dim2display eq 1 then miver, y, line=2
          if dim2display eq 2 or dim2display eq 3 then miver, j, line=2
      endif else begin
          ;print, ceil(dim[4]/2.), 2
          if flag_pmulti eq 0 then !p.multi = [0,ceil(dim[4]/2.), 2, 0] 
          wset, 0
          for var_plot = 0, dim[4]-1 do begin
              color_4d=!d.n_colors-1.
              if var_plot eq var then color_4d=12.*16
              plot, inaxis, reform(data_xy[*,*,*,var_plot]), psym=0, $
                 ;title=string_pos, /data, /yno, charsize=size_font_plot, $
                 xtitle=label_dim[dim2display]+' [px]', ylog=ylog
              miver, j, line=2, color=color_4d
          endfor    
          ;if var eq 3 then stop
          xyouts, 0.5, 0.5, /norm, string_pos, align=.5, size=size_font_plot
          resto = dim[4] mod 2
          if resto gt 0 then plot, indgen(100), xstyle=4, ystyle=4, color=0 ; plots nothing
          flag_pmulti =1
      endelse 
      wset, 0 
      ;xyouts, 0.5, 0.05, string_pos, /norm, align=0.5, size=size_font_plot
   endif

   if chr eq 'S' or chr eq 'Q' then begin
        selected_flag = 0
        if chr eq 'S' then begin
           text_pos = ''		
           if keyword_set(max_sel) then begin		
             text_pos = strcompress(fix(list_points.Length+1), /rem)+ ' out of '+ $
                        strcompress(fix(max_sel), /rem)		     
           endif 
           print, '-> Storing position '+text_pos+' '+string_pos+' and its corresponding data.'
           selected_flag = 1
        endif    
        ;point = {x_display:x, y_display:y, $ 
               ;data_xy:reform(data[x, y,*,*]), coordinates:coordinates}
        point = {coordinates:coordinates, $
                 data_xy:reform(data[x, y,*,*]), selected_flag:selected_flag}
        if list_points.Length eq 0 then begin
	        list_points = LIST(point) 
        endif else begin 
	        if chr eq 'S' then list_points.Add,point
        endelse 	      
	if keyword_set(max_sel) then begin 
           if list_points.Length eq max_sel then flag_max_sel = 1
        endif 
   endif 
endwhile

while !d.window ne -1 do wdelete, !d.window

return, list_points.toarray()

end

