Hmmm... I wonder if "Premature end of script headers" might
be what happens when the script dies with an error message
it has written any valid html header or data.
Maybe if you make sure to print your header first, in some
way, before that bunch of
instructions -- or else make up a subroutine that you call
instead of "die", so that you generate some sort of sensible
output for the browser (including the error message),
then exit.