Massive code reorg and refactor