#include "def.h"

int ss_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_substring;
	int curPos;
	int newPage; 
	int ss_count;
	PAGENO nextPage;
    Count = 0;
	newPage = 0;
	curPos = 1;

    /* Find insertion position */
    KeyListTraverser = PagePtr->KeyListPtr;
	ss_count = 0;


	while(1) {
		is_substring = CheckSubstring(key, KeyListTraverser->StoredKey);

		if (is_substring == 0) {
			printf("Substring found in %s\n", KeyListTraverser->StoredKey);
			//getpostings(KeyListTraverser->Posting);
			result = KeyListTraverser->Posting;
			Found = TRUE;
			ss_count++;
		}

		if (curPos < PagePtr->NumKeys) {
			curPos++;
			KeyListTraverser = KeyListTraverser->Next;
		} else {
			nextPage = PagePtr->PgNumOfNxtLfPg;
			//printf("next page: %d\n", (int)nextPage);
			if (nextPage < 0) { /* FIX */
				break;
			}
			if(newPage == 1) {
				FreePage(PagePtr);
			} 
			PagePtr = FetchPage(nextPage);
			curPos = 1;
			KeyListTraverser = PagePtr->KeyListPtr;

			newPage = 1;
		}
	}

	return(ss_count);
}
