Refactored code.Hopefully, it's more readable now

TODO: synchronization, fix bugs