some code formatting and sql optimizations