/*

  P-Code interpreter (to run the apple pascal system)
  Copyright (C) 2000 Mario Klebsch

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

  $Log: TreeSearch.c,v $
  Revision 1.2  2001/05/20 13:12:02  mario
  CVS-Idents und Logs eingefügt


*/

#ident "$Id: TreeSearch.c,v 1.2 2001/05/20 13:12:02 mario Exp $";

#include <stdio.h>

#include "psystem.h"
#include "Memory.h"
#include "Array.h"

#undef DEBUG

word csp_TreeSearch(word TokenBuf, word ResultPtr, word NodePtr)
{
  word	Link;

#ifdef DEBUG
  int i;

  for (i=0; i<8;i++)
    putchar(MemRdByte(TokenBuf, i));
  printf(": ");
#endif

  while (1)
    {
      int cmp=ByteCmp(TokenBuf, NodePtr, 8);
      if (cmp<0)
	if ((Link=MemRd(WordIndexed(NodePtr,5))))
	  NodePtr=Link;			/* follow RightLink		    */
	else
	  {
#ifdef DEBUG
	    printf("not found, should be on right node\n");
#endif
	    MemWr(ResultPtr, NodePtr);
	    return(0xffff);
	  }
      else if (cmp>0)
	if ((Link=MemRd(WordIndexed(NodePtr,4))))
	  NodePtr=Link;			/* follow LeftLink		    */
	else
	  {
#ifdef DEBUG
	    printf("not found, should be on left node\n");
#endif
	    MemWr(ResultPtr, NodePtr);
	    return(1);
	  }
      else
	{
#ifdef DEBUG
	  printf("found\n");
#endif
	  MemWr(ResultPtr, NodePtr);
	  return(0);
	}
    }
}
