refactoring and  security fixes