#Begin copy-and-paste usefulness

import os
import re
import string
import sys

PROGRAM_NAME=''

class CGI:

    def __init__(self, vars=[]):
        "Initialize variables and run this script."
        self.printedHeader = 0
        self.workingDir = self.getWorkingDir()
        self.programName = PROGRAM_NAME
        self.setContextFromEnvironment()
        try:
            self.run()
        except SystemExit:
            #If we exit normally, don't print a traceback.
            pass
        except Exception, arg: #Something went wrong. Print a traceback.
            self.printHeader()
            print "\n\n<pre>"   
            print "Exception: %s" % arg
            import traceback
            traceback.print_exc()
            print "</pre>"

    def getWorkingDir(self):
        "Get the working directory for this script."

        workingDir = './'
        if len(sys.argv):
            invoked = sys.argv[0]
            i = string.rfind(invoked, '/')
            if i > 0:
                extraPath = invoked[:i+1]
                workingDir = os.path.join(os.getcwd(), extraPath)
        return workingDir    

    def setContextFromEnvironment(self):
        self.baseURL = '/cgi-bin/msm/'
        self.scriptName = None
        self.host = None
        for var in ['SCRIPT_NAME', '_']:
            if not self.baseURL:
                path = os.environ.get(var, '')
                i = string.rfind(path, '/')
                if i > -1 and not (var == '_' and string.find(path[i+1:], 'python') == 0):
                    #If the executable name begins with 'python', then it's a
                    #red herring; they fed this script into a Python
                    #executable and we have no way of getting path information.
                    self.baseURL = path[:i+1]
                    self.scriptName = path[i+1:]
        if not self.baseURL:
            #Uh-oh. Well, they're probably running something from the
            #command line (with Python as the interpreter), so they
            #probably won't be checking URLs.  Let's make the horribly
            #misinformed assumption that the URL is '/msm/'.
            self.baseURL = '/msm/'
        if not self.scriptName:
            #Probably 'map.cgi'
            self.scriptName = 'map.cgi'

    def printHeader(self, type='text/html'):
        if not self.printedHeader:
            print 'Content-type: %s\n' % type
            self.printedHeader = 1

    def startPage(self, title='', printTitleAsHeader=0):
        self.printHeader()
        if title:
            title = self.programName + ': ' + title
        else:
            title = self.programName
        print '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/transitional.dtd">'
        print '<html><head><title>%s</title></head><body>' % title  
        if printTitleAsHeader:
            print '<h1>%s</h1>' % title

    def endPage(self):
        print '</body></html>'

    def error(self, error):
        self.startPage('Error')
        print '<h1>Error: %s</h1>' % error
        self.endPage()
        sys.exit()

    def run(self):    
        "Override this in a subclass."
        self.startPage('Nothing Happens')
        print "You instantiated CGI directly, or you didn't override run() in your subclass."
        self.endPage()

#End copy-and-paste usefulness
