Checked memory management, leaks and errors fixed