Suggestion: set up an environment that lets you run the script from the command line (e.g., by wrapping it inside of another script that sets up environment variables to simulate CGI). Run the script -w

Also, though this may not be your immediate problem, always check error returns from system calls.