Modified from https://gist.github.com/fcoury/1074348 to run safety checks; added tests on safety tests as well.