Moved gateway code into a function