Updated the algorithm in comments