Fixing several small bugs / refactoring