Integrate Dan's algorithm changes