Refactor use of tmp files and dirs