Heavy refactoring and improvements