Complete code for NMA Chapter 27 with some changes