Fleshed out algorithm a bit.