Your code has processed several iterations correctly. The error message suggests that the next 'end' is beyond the end of the string. Are you sure that you are printing the range
before you try to use it? Try printing your debug messages to STDERR. There must be either an error in your data or a special case that you are not considering. Use your editor to search for the last 'good' end. Parse the next few records by hand. If you cannot find the problem, you can write and post a simple program that demonstrates the problem with these offending records.