Can we factor out this code in smaller functions?  With this split addtion, the function is almost 500 LOC...