moved some stuff around to only use one foreach loop