Several speedups to the code