Code Refactor

Cleaned up some reusable code into helper functions and added
corresponding comments