Although this is way to complicated, it should be refactored into several helper methods that are dealing with singular things. Give those methods good names and this will read light years better.