Just to add, this function should be broken into smaller functions to reduce the nesting as well.