Rewritten with the help of @joedj, @uroboro, @rpetrich, @DHowett.