memory leak and other bugs fixed and refactored