Fixed memory leak and some other logic that was causing incorrect behavior.