Final solution, although there is some nasty bug, which I'm looking for.