ex 6.27, and modularized many functions