Refactored some functions, extracted some functionality, added exceptions to deal with insufficient privileges