Some refactored changes. Moved a few functions around for scope visibility