Along the lines of MrViggy's second suggestion, I suspect that your code could do with more extensive use of functions that do one thing and do it well.