Code quality improvements

The improvements mostly include fixed warnings from JSHint and some refactoring of complex code blocks.