more refactoring and some security tweaks