Added leak detection, fixed bugs