instead of looping, can't you gather all information in only one pass over the whole file?