some speed optimizations from profiling