Changed position of cookies.set to avoid repeated setting of cookie

This is my first pull request ever , please review thoroughly and merge : )