Revised code using ideas from search.cgi