Break this function! This is too long and hard to understand. Make it as several functions. It should be easy to read and understand too much nested if and for.