Copied an algorithm off the interwebs. It is much much better than mine.