rather verbose solution to problem 4