PRO editbox, x0, y0, x1, y1, flag

; Procedure to drag an edit box within a plot. Can be used for zooming, 
;  editing, etc.  IDL direct graphics does not have a flag for a mouse button
;  release, so the mouse must be moved slightly after box is completed for
;  the procedure to return the coordinates (although the coordinates will be
;  the correct coordinates before the mouse was moved, if that makes any 
;  sense).
;
; So, to use position the cursor over the first corner; press and hold the left
;  mouse button and move the mouse to the second, opposite corner of the 
;  desired box; release the button and move the mouse slightly.  The mouse
;  button pressed is returned in 'flag'.

DEVICE, GET_GRAPHICS = old, SET_GRAPHICS = 6  ;Set xor

button = 0
old_button = 0
x0 = 0.  ;init origin of box
y0 = 0.
nx = 0.  ;init box size
ny = 0.

GOTO, middle

WHILE (1) DO BEGIN

  old_button = button
  CURSOR, x, y, 2, /DEV
  button = !mouse.button

  IF (old_button EQ 0 AND button EQ 1) THEN BEGIN  ;mark first corner
    x0 = x
    y0 = y 
  ENDIF

  IF (button EQ 1) THEN BEGIN
    IF (old_button EQ 0) THEN BEGIN
      nx0 = nx   ;save size
      ny0 = ny
    ENDIF
    dx = x-x0    ;distance dragged
    dy = y-y0
    nx = nx0 + dx
    ny = ny0 + dy
  ENDIF

  IF (old_button NE 0 OR button NE 0) THEN BEGIN   ;erase old box
    plots, px, py, /dev, THICK=1, LINESTYLE=0
  ENDIF

  IF (button EQ 0 AND old_button EQ 1) THEN BEGIN  ;ret.data after buton rel.
    result0 = convert_coord(x0, y0, /DEVICE, /TO_DATA)
    result1 = convert_coord(x, y, /DEVICE, /TO_DATA)
    x0 = result0[0] 
    y0 = result0[1]
    x1 = result1[0] 
    y1 = result1[1]
    flag = 1
    DEVICE, SET_GRAPHICS = old
    RETURN
  ENDIF

  IF (!mouse.button EQ 4) THEN BEGIN  ; This is used for returning from editing
    DEVICE, SET_GRAPHICS = old    
    flag = 4
    RETURN
  ENDIF

  IF (!mouse.button EQ 2) THEN BEGIN  ; This can be used for something else
    DEVICE, SET_GRAPHICS = old    
    flag = 2
    RETURN
  ENDIF


middle:

  px = [x0, x0, x0+nx, x0+nx, x0]
  py = [y0, y0+ny, y0+ny, y0, y0]

  IF (old_button NE 0 AND button EQ 1) THEN BEGIN  ;draw box
    plots, px, py, /dev, THICK=1, LINESTYLE=0
  ENDIF

  WAIT, .05

ENDWHILE
END