Profiled the code a bit and fixed major bottlenecks.