Code cleanup - fix some minor issues

This pull request addresses the following:
1. too deep nesting
2. "as" where a cast should be
3. "is" followed by "as"
4. redundant code