ex9 with cleaner code