Algorithm 4 improved