Added some ugly error checking code to deal with bad data (turned out to be only 3 cases)