Improve code logic
Merge pull request #1 from eduard-sukharev/optimizations

Improve code logic