Improve open file handling

Also re-instate test directory cleanup.