Fixed memory leak, cleaned up code, added performance improvements, refactored some more

Resubmitted request with all changes in order to avoid merge conflicts