chapter 5 code, ugly hack at the end