Code refactoring + some small fixes