#!/usr/bin/python

import cgitb; cgitb.enable()
import sys, os, cgi, pickle

FILE = '.postcount.pickle'

def getnum():
    try:
        f = open(FILE)
    except IOError:
        savenum(0)
        return getnum() #infinite loop!
    try:
        return pickle.load(f)
    except EOFError:
        savenum(0)
        return getnum() #infinite loop!
        

def savenum(n):
    f = open(FILE, "w")
    pickle.dump(n, f)

env = os.environ
method = env['REQUEST_METHOD'].lower()
if method == 'get':
    print "Content-type: text/html"
    print 
    print """<!DOCTYPE html>
<form method=POST><button type=submit>Do it!</button></form>
"""
elif method == 'post':
    n = getnum()
    n += 1
    savenum(n)
    print "Content-type: text/html"
    print 
    print """<p>Count: %d</p>""" % n
else:
    print "Status: 405 Method Not Allowed"
    print "Accept: GET, POST"
    print
    
