Library refactoring

This is code for review.

[Here] you can find extended explanation of idea of usage 2 semaphores.
[Here]: https://docs.google.com/document/d/19W8b9xvFRrfktYB9zr1V0zrh2zuVAxADyPBioEunzZI/pub "Library refactoring: 2 semaphores idea"