Thank you very much to both of you, fumei and macropod for your precious help!
I just managed to get something working without going too far from your original algorithms, but I will study closely all your advise and loops to see what would be the best.
I obviously do not want to get my code more complex than it should, and the whole point is not to go against common sense, but more to process the data I am given the best possible way.

Again, big applause to both of you. I will mark the case as solved shortly, once I have gone through all your points again, and I will probably leave my "final" code in here as well if it may be useful to anyone else.