Merged some things from Mads's solution