Refactored some repetitive loops for performance