corrected and updated algorithm