Fixed some memory leaks and sloppy behavior; close #292