Code and tests from second half of chapeter 5