Major refactoring to support new functionality