Final revision of algorithm