Large refactoring to avoid lots of duplication
Also implement couple of fixes/improvements spotted by Mark Improve Doxygen comments