Made a few changes to limit the possibility of a "file locked" error occurring.