Several improvements suggested by @WouterJ