Big refactoring

Designed to simplify the code.
The logic of the code has not changed, the work was carried out only to reduce nesting code.