pro selbox,arr,sx1,sx2,sy1,sy2
;
; Interactive selection of a subfield with a cursor.
; If a 2D array ARR is specified, a new window is created to fit
; the dimensions of the array.
; The first corner is defined by pressing the left mouse button.
; Dragging the mouse, a box of selection is plotted.
; The second corner is defined at the release of the left mouse button.
; Output: coordinates of the corners are printed in the form
;         (x1:x2,y1:y2)
;         and passed by optional output parameters sx1,sx2,sy1,sy2.
;
;                                       25.5.1998, Michal
on_error,1

if n_params() gt 0 then begin		; ARR specified
  dim=size(arr)
  if dim(0) ne 2 then message,' ERROR - Not a 2-D array'
  window,6,xsize=dim(1),ysize=dim(2),title='SELBOX (6)'
  tvscl,arr
endif

print,'On window, press left button and drag, quit by release'

device,get_graphics = oldmode
device,set_graphics = 6			; XOR write mode

cursor,x1,y1,/device,/down		; 1st corner
x2=x1
y2=y1

while !err eq 1 do begin
   plots,[x1,x2,x2,x1,x1],[y1,y1,y2,y2,y1],/device ; plot box
   ox=x2
   oy=y2
   cursor,x2,y2,/device,/change			   ; new box
   plots,[x1,ox,ox,x1,x1],[y1,y1,oy,oy,y1],/device ; erase old box
endwhile

plots,[x1,x2,x2,x1,x1],[y1,y1,y2,y2,y1],/device    ; final plot

sx1=strtrim(min([x1,x2]),1)
sx2=strtrim(max([x1,x2]),1)
sy1=strtrim(min([y1,y2]),1)
sy2=strtrim(max([y1,y2]),1)

print,''
print,'Selection:  (',sx1,':',sx2,',',sy1,':',sy2,')'

device,set_graphics = oldmode
end