still not compiling, but the outline of the algorithm is essentially right