Performance refactoring

Cleaning up loops, saving common references to variables and removing repeated logic to functions. Let me know what you think?