Minor style changes; optimized nested loops at end to avoid some redundant computation