!==============================================================================
! Find key record in sorted list of unknown length.
! Dean Gienger, 1993
!==============================================================================

integer FIND_KEY(the_key)

!==============================================================================
! Perform a modified binary search (since we don't know where end of list is!)
! Using step values of 1,2,4,8,16,... until we pass the value or pass
! the end of the list.  When we pass the value or get to end of list, start
! cutting the step in half.
! Return 0 if key not found, else place in list where key is found.
!==============================================================================

integer lo,hi,step,maximum_hi

lo = 1
hi = 1
step = 1
maximum_hi = MAX_INT

! Get first record and bail out if there isn't one
record = GET_RECORD(lo)
IF record.number = 0 THEN RETURN 0

! If desired key is before first message, bail out
IF the_key < record.key THEN RETURN 0

LOOP

   ! fetch record [hi]
   record = GET_RECORD(hi)

   ! double the step
   step = step+step

   ! if there is no such message or we passed the desired key, step back
   IF (record.number = 0) OR (the_key < record.key) THEN
      step = step/4

      IF step = 0 THEN RETURN 0 ! either we found it or it's beyond eof

      maximum_hi = hi
      hi = lo
      ENDIF

   ! choose next probe point (hi)
   lo = hi
   hi = hi + step

   ! don't go beyond the highest reasonable boundary known to date
   IF hi > maximum_hi THEN
      hi = maximum_hi
      ! cut step back to reasonable value
      LOOP
         WHILE (lo+step) > hi
         step = step/2
         ENDLOOP
      ENDIF

   ENDLOOP

RETURN lo

END PROCEDURE
