Total rewrite of the code