Divide and Conquer - Selectively comment out sections of the function until you can isolate it to a particular line.
The problem might be with the for loops. I believe that you must use a row or record type for the for loop variable.