#!/bin/bash
set -euo pipefail
IFS=

tsvread() {
	IFS='	' read -r "$@"
}

warn() {
	echo >&2 "$@"
}

dt() {
	date -d "${*:-}" +%Y-%m-%d\ %a
}

showday() {
	local date=$1 win=$2
	case $date in
	*\ Mon)
		echo ; echo -n "<tr><th>${date% *} " ;;
	esac
	echo -n "<td class=c$win> "
}

fill_dates() {
	while [ $date_expect != $date -a $date_expect \< $date -a $date_expect \< $future ]; do
		showday $date_expect ''
		date_expect=`dt $date_expect 1 day`
	done
}

convert() {
echo "<html>
<head>
<title>focus</title>
<style>
table.wins { border: 1px solid black; }
table.wins td { width: 50px; }
table.wins td.c0 { background-color: red; }
table.wins td.c1 { background-color: green; }
</style>
</head>"

while tsvread focus && [ -n "$focus" ]; do

echo -n "<h1>$focus</h1>
<table class=wins>"

future=`dt 7 days`
date_expect=
while tsvread date win && [ -n "$date" ]; do
	date=`dt $date`
	if [ -z $date_expect ]; then
		dow=`date -d $date +%u`
		delta=$[1-dow]
		date_expect=`dt $date $delta days`
	fi
	fill_dates
	showday $date "$win"
	date_expect=`dt $date 1 day`
done
date=`dt sun 1 day`
fill_dates

echo ; echo '</table>'

done

echo '<span id="end">
<script>
window.onload = function() {
	location.hash="end";
};
</script>'

}

convert
