Bug fixes

Fixed memory leaks and organized code a bit