Refactor temp file handling (fix #348)

@krimdomu: could you please review this before merging? Most of the diff is from the first perltidy run, so you can find the more interesting changes in the commits after that.