Some refactoring and a bug fix for #545

I originally wanted to just merge the bug fix for #545 , but am a git noob, and it would be good to merge in the refactorings anyway, as they remove some duplication from the code.

Having said that, the refactors are from january, so might be out of date.  If this pull request doesn't merge or breaks tests, then just disregard it and i'll try work out how to submit just the bug fix in it's own PR.