Huge refactor to make things more testable