Fix horrible code and memory leak