edited final algorithm