Major refactoring to allow easier integration with ICP