from __future__ import with_statement

import cairo
import csv
import sys

headings = None
data = []
idealrow = None
idealness = []

def is_ideal(heading, value):
    v = idealrow[heading].lower()
    if v[:3] == 'opt':
        if value[:3].lower() == 'opt':
            return True
        v = 'y'
    return (v[0] == value[0].lower())

def dump_headings(labelheading, headings):
    print '<table class="comparison-table" cellspacing="0" cellpadding="0">'
    print '<tr class="headings">'
    print '<th>%s</th>' % (labelheading,)
    for h in headings:
        print '<th>%s</th>' % (h.replace(' / ', '&nbsp;/ '),)
    print '</tr>'

def dump_row(rowlabel, row, headings):
    if rowlabel == 'IDEAL':
        print '<tr class="idealrow">'
    else:
        print '<tr>'
    print '<th>%s</th>' % (rowlabel,)
    for h in headings:
        if is_ideal(h, row[h]):
            print '<td class="ideal">%s</td>' % (row[h],)
        else:
            print '<td>%s</td>' % (row[h],)
    print '</tr>'

def dump_footer():
    print '</table>'

with open(sys.argv[1]) as filehandle:
    for row in csv.reader(filehandle):
        if row[0] == '----':
            break
        if not headings:
            headings = row
        elif row[0]:
            m = {}
            for i in range(1, min(len(row), len(headings))):
                m[headings[i]] = row[i]
            data.append((row[0], m))
            if row[0] == 'IDEAL':
                idealrow = m
for (rowlabel, row) in data:
    count = 0
    for heading in headings[1:]:
        if is_ideal(heading, row[heading]):
            count = count + 1
    row['_idealness'] = count
data.sort(lambda a, b: a[1]['_idealness'] - b[1]['_idealness'], reverse=True)

print '''<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <style type="text/css">
    .comparison-table {
      margin-top: 1em;
      border: 1px solid black;
      width: 100%;
    }
    .comparison-table td, .comparison-table th {
      text-align: left;
      border: 0.1px solid #dddddd;
      margin: 0px;
      padding: 0px;
    }
    .comparison-table td {
      width: 100px;
    }
    tr.idealrow th, tr.idealrow td {
      border-top: 0.1px solid black;
      border-bottom: 0.1px solid black;
    }
    .ideal {
      background-color: #bbffbb;
    }
    tr.idealrow th, tr.idealrow .ideal {
      background-color: #ffdddd;
    }
    body, p, table, td {
      font-size: 10pt;
    }
  </style>
</head>
<body>
'''
slicepoint = 7
for offset in range(1, len(headings), slicepoint):
    hs = headings[offset:offset+slicepoint]
    dump_headings(headings[0], hs)
    for (label, row) in data:
        dump_row(label, row, hs)
    dump_footer()
print '</body></html>'
