optimized some loops, improved formatting and clarity