changed flow control to make better use of logicals