Okay, I basically rewrote the whole thing. May it be useful.