complete solution to ex3, some reorganization