Fixed error checking and file type detection