Merge code refactor into the mainstream

Brings master repo upto date with current development version of code.