reduce number of function calls
fold second loop into the first