Copied and amended functionality from georgedrexler.grant