Refactored code, also added user permission checking.