Added some memory management, changed algorithm to work with our new node structure.