Fixed mem leak and other bugs