#include "areaPool.h"
#include "area.h"
#include "page.h"
#include "vmHeaderBlock.h"
#include "pageManager.h"

extern vmHeaderBlock *vmBlock;

// If we can get one from an existing block, cool. If not, get a new block, create as many as will fit in the block, put them on the free list and call ourself recursively
area *poolarea::get(void) {
	area *ret=NULL;
	if (unused.count()) {
		//error ("poolarea::get: Getting an unused one!\n");
		ret=(area *)unused.next();
		}
	if (ret) {
		//error ("poolarea::get: Returning address:%x \n",ret);
		return ret;
		}
	else {
		page *newPage=vmBlock->pageMan->getPage();
		//error ("poolarea::get: Getting new page %lx!\n",newPage->getAddress());
		if (!newPage)
			throw ("Out of pages to allocate a pool!");
		int newCount=PAGE_SIZE/sizeof(area);
		//error ("poolarea::get: Adding %d new elements to the pool!\n",newCount);
		for (int i=0;i<newCount;i++)
			unused.add(((node *)(newPage->getAddress()+(i*sizeof(area)))));	
		return (get()); // A little cheat - call self again to get the first one from stack...
		}
	}
