Fixed bugs and memory leak