Added a flag to switch between old and new behavior, code reorg and clean-up