Cleaned up code using auto and for in loops
Fix memory-related bug