Fixed some memory leaks and misc bugs