wrote a bunch of the algorithm