A small comment. This check is done twice, here, and then a few lines below when copying the file. You might want to do everything at once.