cleaned up version, 47x speedup