Implement book's pseudocode (fixes #1).