Added permission check and minor error handling