refactor a bit, 3x speedup