After much table banging and swearing I finally finished the code and got the right answer. Yayyyyyy!