Optimized code

Optimized code for readability and a few performance improvements.