corrected algorithm