First working solution of the simple version, with the dirtiest code imaginable, refactoring urgent.