This is the code associated with algorithms 1