General refactoring and several small-bugs fixes