#!/usr/local/bin/python2.4 --

import cgi
import cgitb
import os.path
import re
import smtplib
import string

cgitb.enable()  # for debugging tracebacks

digit_names = [ 'zero', 'one', 'two', 'three', 'four',
                'five', 'six', 'seven', 'eight', 'nine',
                'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
                'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' ]
ten_names = [ 'zero', 'ten', 'twenty', 'thirty', 'forty',
              'fifty', 'sixty', 'seventy', 'eighty', 'ninety' ]

def Append(s, t):
  if len(s) and len(t):
    return '%s %s' % (s, t)
  else:
    return s + t

def TwoDigitNumber(num):
  if not num:
    return ''
  if num < 20:
    return digit_names[num]
  
  digits = num % 10
  num /= 10
  if digits:
    return '%s-%s' % (ten_names[num], digit_names[digits])
  else:
    return ten_names[num]

def NumberToText(num):
  result = ''

  thousands = num / 1000
  if thousands:
    result = '%s thousand' % TwoDigitNumber(thousands)
    
  hundreds = (num % 1000) / 100
  if hundreds:
    result = Append(result, '%s hundred' % digit_names[hundreds])
    
  tens = num % 100
  if tens:
    result = Append(result, TwoDigitNumber(tens))
  elif not result:
    result = digit_names[0]
  return result    

def NumbersToText(num):
  numbers = [NumberToText(i + 1) for i in range(num)]
  numbers.sort()
  return numbers

def FullPage(title, body):
  """Given the body of an HTML page, wraps it to make a full HTML page"""
  return """Content-type: text/html

<html><head><title>%s</title></head><body>%s
</body></html>

""" % (title, body)

def Form():
  return FullPage("Enter a count", """
  <form name="theForm" method="GET" action="http://ax.to/numbers.cgi">
  Enter a count from 1 to 99,999:
  <input name="count" value="1000" type="text" maxlength="50" size="50"></form>""")


# Read the CGI values before we do anything else.
cgi_values = cgi.FieldStorage()

if not cgi_values.has_key('count'):
  print Form()
else:
  count = int(cgi_values.getfirst("count"))
  if count > 19999:
    print FullPage("Maximum value of count=19999",
                   "Maximum value of count=19999")
  else:
    print FullPage("Sorted numbers for %d" % count,
                   '<br>'.join(NumbersToText(count)))
  
