#include "def.h"

int prefix_searchLeaf( PagePtr, key)
struct PageHdr *PagePtr;
char *key;
{

    int result;
	struct PageHdr   *FetchPage();
    struct KeyRecord *KeyListTraverser;
    int               InsertionPosition;     /* Position for insertion */
    int     FindInsertionPosition();
    int               Count, Found, i;
	int is_prefix;
	//struct PageHdr *PagePtr2;
	int newPage; 
	PAGENO nextPage;
    Count = 0;
	newPage = 0;

    /* Find insertion position */
    KeyListTraverser = PagePtr->KeyListPtr;
    InsertionPosition = FindPrefixPosition(KeyListTraverser,key,&Found,
                        PagePtr->NumKeys,Count);

    /* key is already in the B-Tree */
	result = 0;
    if (Found == TRUE) {
        for (i = 0; i < InsertionPosition - 1; i++) {
			//printf("skip key: %s\n",  KeyListTraverser->StoredKey);
            KeyListTraverser = KeyListTraverser->Next;
		}

		//result = KeyListTraverser->Posting;
		is_prefix = CheckPrefix(key, KeyListTraverser->StoredKey);
		while (is_prefix == 0) {
			printf("Prefix found in %s\n", KeyListTraverser->StoredKey);
			result++;
			//getpostings(KeyListTraverser->Posting);

			if (InsertionPosition < PagePtr->NumKeys) {
				InsertionPosition++;
				KeyListTraverser = KeyListTraverser->Next;
			} else {
				nextPage = PagePtr->PgNumOfNxtLfPg;
				if(newPage == 1) {
					FreePage(PagePtr);
				} 
				if (nextPage < 0) { /* FIX */
					break;
				}
				PagePtr = FetchPage(nextPage);
				InsertionPosition = 1;
				KeyListTraverser = PagePtr->KeyListPtr;

				newPage = 1;
				//is_prefix = 1;
			}
			is_prefix = CheckPrefix(key, KeyListTraverser->StoredKey);
		}
    } 
	return(result);
}
