improved gateway script