Refactor code

Make dependencies local rather than global, and reduce code duplication.