Total rewrite of the code, with better closure and performance.