First version of algorithm seems to be working.