Fixed a memory leak and a added some other code optimizations.