Major refactoring. Moved functions into closed function scope, only exposing functions used by web app.