Fixes #8

Still needs testing, and probably tweaking, but all the functionality is
there now.