Use unsigned ints to silence comparison warning. Cache loop condition
where feasible.
Optimized more loops