added security checks and refactoring