Improved file handling from commit e33debcb.