Added some error-checking to help diagnose input formats. This code needs refactoring though.