Now works for messy data sets. Potental off by one error in indexing