refactor so we only need to loop twice instead of three times