Added a subroutine that simpified the code.