#!/Library/Frameworks/Python.framework/Versions/Current/bin/python
# L-34 MCS 275 Wed 9 Apr 2008 : show_hello_world3.py

# This CGI script prints the HTML code like in show_hello_world2.html
# and as in show_hello_world2.py display the code.

import cgi

Lv = {'0':'C', '1':'Java', '2':'Python'}

def code(L):
   """
   Returns the string for code in
   the language L.
   """
   if L == '0':
      c = '#include <stdio.h>\n\n' \
        + 'int main(void)\n' \
        + '{\n' \
        + '   printf(\"Hello World!\\n\");\n' \
        + '   return 0;\n' \
        + '}\n'
   elif L == '1':
      c = 'public class HelloWorld\n' \
        + '{\n' \
        + '   public static void main(String[] args)\n' \
        + '   {\n' \
        + '      System.out.print(\"Hello World!\");\n' \
        + '      System.out.println();\n' \
        + '   }\n' \
        + '}\n'
   else:
      c = 'print \"Hello World!\"'
   return c

def PrintHeader():
   """
   Prints header of web page.
   """
   print """
<HTML>
<HEAD>
<TITLE> MCS 275 Review 2: show hello world </TITLE>
</HEAD>

<BODY>
"""

def PrintForm():
   """
   Prints the input form to screen.
   """
   print "<h1> Show Hello World!</h1>"
   print """
<form action=\"http://localhost/cgi-bin/show_hello_world3.py\">
<p>
See the code to show <TT>Hello World!</TT> displayed in
<select name=\"language\">
<option value = 0>C
<option value = 1>Java
<option selected value = 2>Python
</select>
<p> <input type = \"submit\" value = \"press to see the code\"> </p>
"""

def PrintCode(L):
   """
   Prints the code to screen.
   """
   print "<h1> Hello World! in %s </h1>" % Lv[L]
   print "<textarea rows = 4 columns = 30>"
   print code(L)
   print "</textarea>"
   print "<p> <input type = \"submit\" " \
      + " value = \"execute the code\"> </p>"

def main():
   """
   prints the form or the code
   """
   print "Content-Type: text/html\n"
   PrintHeader()
   form = cgi.FieldStorage()
   if form.has_key('language'):
      L = form['language'].value
      PrintCode(L)
   else:
      PrintForm()
   print "</body></html>"

if __name__=="__main__": main()
