Refactor code to organize functions (should probably use objects, but I'm lazy)