Improved error handling and invalid file handling