Refactor cgi code