Some code cleanup and optimizations