All of the advice you've received so far is fantastic, but
I'm kind of surprised that nobody has mentioned (although
it is implied in
tilly's response) that when you start
nesting large amounts of code into conditional blocks you
should immediately think
modularize. Break some of
those chunks into subroutines and it will be much easier on
the eyes.
--Jim
Note: apologies if someone else has already mentioned this
and I missed it.