Smarter handling of files

See line comments for more information