With the help of zpmorgan, here is a more streamlined version of my code