implementation of the algorithm - debugging needed, probably will not
work now :)