Code cleanup
Improved speed and removed memory leak