Algorithm seems to work fine. It is quite slow though.