This is function is really long. If it were broken up into manageable chunks then it would be easier to read and understand.