Algorithm 2 fully commented.