improve speed and small refactoring