minor refactoring to avoid too many nested loops