Cleanup code - reorder checks and make variable declaration scope narrower.
Merge pull request #334 from Dmitry-Me/ReorderChecksAndCleanupDeclarations

Cleanup code - reorder checks and make variable declaration scope narrower