Cleaned up. Tested with valgrind.