update to algorithm, it almost works