Small optimization & cleanups + fixes a potential bug.