Fixed memory leak and bug