Merged refactored code.  Not sure if stable.