Tweak import order
Additional code formatting improvements
Remove dead variable
Add simple fixture
Big refactor to avoid leaving tempfiles accidentally

The new behaviour is to ensure that we only overwrite
the old files if the new ones were generated without
an exception being raised.

The new structure is more amenable to testing, too.