Fixed the unfreed memory issues
Clean up code