This function is unnecessarily large and could be cleaned up quite a bit by breaking it into multiple functions