#!/usr/bin/python

import re
import cgi

# Specify the location of the files
folder = "C:\\Programmer\\python\\cgi-bin\\"

# specify the filename of the template file
TemplateFile = "template.html"

# specify the filename of the form to show the user
FormFile = "form.html"

# Display  takes one parameter - a string to Display
def Display(Content):
    TemplateHandle = open(folder+TemplateFile, "r")  # open in read only mode
    # read the entire file as a string
    TemplateInput = TemplateHandle.read() 
    TemplateHandle.close()                    # close the file

    # this defines an exception string in case our
    # template file is messed up
    BadTemplateException = "There was a problem with the HTML template."

    SubResult = re.subn("<!--REPLACE_CONTENT-->",  
        Content,TemplateInput)
    if SubResult[1] == 0:
        raise BadTemplateException

    print "Content-Type: text/html\n\n"
    print SubResult[0]

### what follows are our two main 'action' functions, one to show the
### form, and another to process it

# this is a really simple function
def DisplayForm():
    FormHandle = open(folder+FormFile, "r")
    FormInput = FormHandle.read()
    FormHandle.close()

    Display(FormInput)

def ProcessForm(form):    
    # extract the information from the form in easily digestible format
    try:
        name = form["name"].value
    except:
        # name is required, so output an error if 
        # not given and exit script
        Display("You need to at least supply a name. Please go back.")
        raise SystemExit
    try:
        email = form["email"].value
    except:
        email = None
    try:
        color = form["color"].value
    except:
        color = None
    try:
        comment = form["comment"].value
    except:
        comment = None

    Output = ""  # our output buffer, empty at first

    Output = Output + "Hello, "

    if email != None:
        Output = Output + '<A HREF="mailto:' + email + '">' + name + "</A>.<P>"
    else:
        Output = Output + name + ".<P>"

    if color == "swallow":
        Output = Output + "You must be a Monty Python fan.<P>"
    elif color != None:
        Output = Output + "Your favorite color was " + color + "<P>"
    else:
        Output = Output + "You cheated!  You didn't specify a color!<P>"

    if comment != None:
        Output = Output + "In addition, you said:<BR>" + comment + "<P>"

    Display(Output)


###
### Begin actual script
###

### evaluate CGI request
form = cgi.FieldStorage()

### "key" is a hidden form element with an 
### action command such as "process"
try:
    key = form["key"].value
except:
    key = None

if key == "process":
    ProcessForm(form)
else:
    DisplayForm()

