This seems to work, but it also seems quite clumsy running line 23 and 24 over and over again? Is there a better way of doing this?