Modified algorithm and implementation.