updated algorithm (2)