#!/usr/bin/env python

import cgi
import cgitb
import glob

cgitb.enable()
form = cgi.FieldStorage()
print 'Content-Type: text/html\n'

# Functions
def unit_selector():
	"""Return an HTML snippet to select units with."""
	if units == 'metric':
		return '<p>Units: metric|<a href="?units=sae">sae</a></p>'
	else:
		return '<p>Units: <a href="?units=metric">metric</a>|sae</p>'

# Determine units to display
units = 'metric'
if 'units' in form:
	if form.getfirst('units') == 'sae':
		units = 'sae'

# Figure out the latest image
graph_list=glob.glob('graph_%s_*.png' % units)
graph_list.sort()
latest=graph_list[-1]
previous=[]
for graph in graph_list[:50]:
	previous.append('    <li><a href="%s">%s</a></li>' % (graph, graph[:-4]))
previous='\n'.join(previous)

# Figure out the latest comparison image
graph_list=glob.glob('graph_comparison_%s_*.png' % units)
graph_list.sort()
latest_comparison=graph_list[-1]

print """<html>
<title>My Weight Loss Progression</title>
%(unit_selector)s

<table>
 <tr>
  <td>
   <img src="%(latest)s" /><br />
   <img src="%(latest_comparison)s" />
  </td>
  <td>
   <p>Previous Graphs:</p>
   <ul>
%(previous)s
   </ul>
  </td>
 </tr>
</table>

<h1>News</h1>

<p><strong>2011 Nov 23</strong></p>
<p>
 I added a chart showing my average daily gain/loss rate.
</p>

<p><strong>2011 Oct 2</strong></p>
<p>
 While cleaning out an old hard drive I found two datapoints from last March.
 I've added them to the record to show that my weight used to stay fairly 
 stable, if a bit high.
</p>

<h1>Source</h1>
<p>The raw data and scripts that generate the above graph are here:</p>

<ul>
 <li><a href="weightlog.csv">weightlog.csv</a></li>
 <li><a href="weightlog.sh">weightlog.sh</a></li>
 <li><a href="weightlog.%(units)s.gnuplot">weightlog.%(units)s.gnuplot</a></li>
 <li><a href="index.txt">index.cgi</a> (The source for this page)</li>
</ul>
</html>
""" % {'latest_comparison': latest_comparison, 'latest': latest, 'previous': previous, 'units': units, 'unit_selector': unit_selector()}
