Refactor a bunch of stuff for cgi fork