Some improvements for code speed and refactoring