Fixed memomy management, added tests.