{<<<< KeySearch >>>>}
{ From: COMPLETE TURBO PASCAL by Jeff Duntemann  }
{ Scott, Foresman & Co. 1986  ISBN 0-673-18600-8 }
{ Described in section 18.10 -- Last mod 2/1/86  }

FUNCTION KeySearch(VAR Keys     : KeyFile;
                   VAR KeyRef   : Integer;
                       MatchIt  : String80) : Boolean;

VAR High,Low,Mid : Integer;
    SearchRec    : KeyRec;
    Found        : Boolean;
    Collided     : Boolean;
    RecCount     : Integer;

BEGIN
  KeyRef := 0;                 { Initialize variables      }
  RecCount := FileSize(Keys);
  High := RecCount;
  Low := 0;
  KeySearch := False; Found := False; Collided := False;
  Mid := (Low + High) DIV 2;   { Calc first midpoint       }

  IF RecCount > 0 THEN         { Don't search if file empty}
    REPEAT
      Seek(Keys,Mid);          { Read midpoint record      }
      Read(Keys,SearchRec);
      { Collision between Mid & Low or Mid & High?   }
      IF (Low = Mid) OR (High = Mid) THEN Collided := True;
      IF MatchIt = SearchRec.KeyData THEN  { Found it! }
        BEGIN
          Found := True;           { Set found flag...    }
          KeySearch := True;       { ...function value... }
          KeyRef := SearchRec.Ref  { ...and file key      }
        END
      ELSE            { No luck...divide & try again  }
        BEGIN
          IF MatchIt > SearchRec.KeyData THEN Low := Mid
            ELSE High := Mid; { Halve the field  }
          Mid := (Low + High + 1) DIV 2;    { Recalc midpoint }
          KeyRef := Mid { Save Mid in parm }
        END
    UNTIL Collided OR Found
END;  
