]> git.sesse.net Git - pkanalytics/blobdiff - ultimate.js
Make it possible to have separate videos per match, instead of hardcoding one specifi...
[pkanalytics] / ultimate.js
index 798c582bea99043607bb0a89abbc7f8d2365a5dd..32dd2493d539260fd12a2df4e77600e3cdd53bf1 100644 (file)
@@ -3,26 +3,40 @@
 // No frameworks, no compilers, no npm, just JavaScript. :-)
 
 let global_json;
+let global_filters = [];
 
-addEventListener('hashchange', () => { console.log('heei'); process_matches(global_json); });
+addEventListener('hashchange', () => { process_matches(global_json, global_filters); });
+addEventListener('click', possibly_close_menu);
 fetch('ultimate.json')
    .then(response => response.json())
-   .then(response => { global_json = response; process_matches(global_json); });
+   .then(response => { global_json = response; process_matches(global_json, global_filters); });
 
-function attribute_player_time(player, to, from) {
+function attribute_player_time(player, to, from, offense) {
+       let delta_time;
        if (player.on_field_since > from) {
                // Player came in while play happened (without a stoppage!?).
-               player.playing_time_ms += to - player.on_field_since;
+               delta_time = to - player.on_field_since;
        } else {
-               player.playing_time_ms += to - from;
+               delta_time = to - from;
+       }
+       player.playing_time_ms += delta_time;
+       if (offense === true) {
+               player.offensive_playing_time_ms += delta_time;
+       } else if (offense === false) {
+               player.defensive_playing_time_ms += delta_time;
        }
 }
 
-function take_off_field(player, t, live_since) {
-       if (live_since === null) {
-               // Play isn't live, so nothing to do.
-       } else {
-               attribute_player_time(player, t, live_since);
+function take_off_field(player, t, live_since, offense, keep) {
+       if (keep) {
+               if (live_since === null) {
+                       // Play isn't live, so nothing to do.
+               } else {
+                       attribute_player_time(player, t, live_since, offense);
+               }
+               if (player.on_field_since !== null) {  // Just a safeguard; out without in should never happen.
+                       player.field_time_ms += t - player.on_field_since;
+               }
        }
        player.on_field_since = null;
 }
@@ -31,9 +45,121 @@ function add_cell(tr, element_type, text) {
        let element = document.createElement(element_type);
        element.textContent = text;
        tr.appendChild(element);
+       return element;
+}
+
+function add_th(tr, text, colspan) {
+       let element = document.createElement('th');
+       let link = document.createElement('a');
+       link.style.cursor = 'pointer';
+       link.addEventListener('click', (e) => {
+               sort_by(element);
+               process_matches(global_json, global_filters);
+       });
+       link.textContent = text;
+       element.appendChild(link);
+       tr.appendChild(element);
+
+       if (colspan > 0) {
+               element.setAttribute('colspan', colspan);
+       } else {
+               element.setAttribute('colspan', '3');
+       }
+       return element;
 }
 
-function process_matches(json) {
+function add_3cell(tr, text, cls) {
+       let p1 = add_cell(tr, 'td', '');
+       let element = add_cell(tr, 'td', text);
+       let p2 = add_cell(tr, 'td', '');
+
+       p1.classList.add('pad');
+       p2.classList.add('pad');
+       if (cls === undefined) {
+               element.classList.add('num');
+       } else {
+               element.classList.add(cls);
+       }
+       return element;
+}
+
+function add_3cell_with_filler_ci(tr, text, cls) {
+       let element = add_3cell(tr, text, cls);
+
+       let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+       svg.classList.add('fillerci');
+       svg.setAttribute('width', ci_width);
+       svg.setAttribute('height', ci_height);
+       element.appendChild(svg);
+
+       return element;
+}
+
+function add_3cell_ci(tr, ci) {
+       if (isNaN(ci.val)) {
+               add_3cell_with_filler_ci(tr, 'N/A');
+               return;
+       }
+
+       let text;
+       if (ci.format === 'percentage') {
+               text = (100 * ci.val).toFixed(0) + '%';
+       } else {
+               text = ci.val.toFixed(2);
+       }
+       let element = add_3cell(tr, text);
+       let to_x = (val) => { return ci_width * (val - ci.min) / (ci.max - ci.min); };
+
+       // Container.
+       let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+       if (ci.inverted === true) {
+               svg.classList.add('invertedci');
+       } else {
+               svg.classList.add('ci');
+       }
+       svg.setAttribute('width', ci_width);
+       svg.setAttribute('height', ci_height);
+
+       // The good (green) and red (bad) ranges.
+       let s0 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
+       s0.classList.add('range');
+       s0.classList.add('s0');
+       s0.setAttribute('width', to_x(ci.desired));
+       s0.setAttribute('height', ci_height);
+       s0.setAttribute('x', '0');
+
+       let s1 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
+       s1.classList.add('range');
+       s1.classList.add('s1');
+       s1.setAttribute('width', ci_width - to_x(ci.desired));
+       s1.setAttribute('height', ci_height);
+       s1.setAttribute('x', to_x(ci.desired));
+
+       // Confidence bar.
+       let bar = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
+       bar.classList.add('bar');
+       bar.setAttribute('width', to_x(ci.upper_ci) - to_x(ci.lower_ci));
+       bar.setAttribute('height', ci_height / 3);
+       bar.setAttribute('x', to_x(ci.lower_ci));
+       bar.setAttribute('y', ci_height / 3);
+
+       // Marker line for average.
+       let marker = document.createElementNS('http://www.w3.org/2000/svg', 'line');
+       marker.classList.add('marker');
+       marker.setAttribute('x1', to_x(ci.val));
+       marker.setAttribute('x2', to_x(ci.val));
+       marker.setAttribute('y1', ci_height / 6);
+       marker.setAttribute('y2', ci_height * 5 / 6);
+
+       svg.appendChild(s0);
+       svg.appendChild(s1);
+       svg.appendChild(bar);
+       svg.appendChild(marker);
+
+       element.appendChild(svg);
+}
+
+function process_matches(json, filters) {
        let players = {};
        for (const player of json['players']) {
                players[player['player_id']] = {
@@ -48,11 +174,21 @@ function process_matches(json) {
                        'num_throws': 0,
                        'throwaways': 0,
                        'drops': 0,
+                       'was_ds': 0,
 
                        'defenses': 0,
                        'interceptions': 0,
                        'points_played': 0,
                        'playing_time_ms': 0,
+                       'offensive_playing_time_ms': 0,
+                       'defensive_playing_time_ms': 0,
+                       'field_time_ms': 0,
+
+                       // For efficiency.
+                       'offensive_points_completed': 0,
+                       'offensive_points_won': 0,
+                       'defensive_points_completed': 0,
+                       'defensive_points_won': 0,
 
                        'offensive_soft_plus': 0,
                        'offensive_soft_minus': 0,
@@ -69,14 +205,53 @@ function process_matches(json) {
                };
        }
 
+       // Globals.
+       players['globals'] = {
+               'points_played': 0,
+               'playing_time_ms': 0,
+               'offensive_playing_time_ms': 0,
+               'defensive_playing_time_ms': 0,
+               'field_time_ms': 0,
+
+               'offensive_points_completed': 0,
+               'offensive_points_won': 0,
+               'defensive_points_completed': 0,
+               'defensive_points_won': 0,
+       };
+       let globals = players['globals'];
+
        for (const match of json['matches']) {
+               if (!keep_match(match['match_id'], filters)) {
+                       continue;
+               }
+
+               let our_score = 0;
+               let their_score = 0;
                let handler = null;
                let prev_handler = null;
                let live_since = null;
-               let offense = null;
+               let offense = null;  // True/false/null (unknown).
                let puller = null;
                let pull_started = null;
+               let last_pull_was_ours = null;  // Effectively whether we're playing an O or D point (not affected by turnovers).
                let point_num = 0;
+               let game_started = null;
+               let last_goal = null;
+
+               // The last used formations of the given kind, if any; they may be reused
+               // when the point starts, if nothing else is set.
+               let last_offensive_formation = null;
+               let last_defensive_formation = null;
+
+               // Formations we've set, but haven't really had the chance to use yet
+               // (e.g., we get a “use zone defense” event while we're still on offense).
+               let pending_offensive_formation = null;
+               let pending_defensive_formation = null;
+
+               // Formations that we have played at least once this point, after all
+               // heuristics and similar.
+               let formations_used_this_point = new Set();
+
                for (const [q,p] of Object.entries(players)) {
                        p.on_field_since = null;
                        p.last_point_seen = null;
@@ -86,73 +261,247 @@ function process_matches(json) {
                        let type = e['type'];
                        let p = players[e['player']];
 
-                       // Point count management
-                       if (p !== undefined && type !== 'out' && p.last_point_seen !== point_num) {
-                               p.last_point_seen = point_num;
-                               ++p.points_played;
-                       }
-                       if (type === 'goal' || type === 'their_goal') {
-                               ++point_num;
-                       }
-
                        // Sub management
+                       let keep = keep_event(players, formations_used_this_point, filters);
                        if (type === 'in' && p.on_field_since === null) {
                                p.on_field_since = t;
+                               if (!keep && keep_event(players, formations_used_this_point, filters)) {
+                                       // A player needed for the filters went onto the field,
+                                       // so pretend people walked on right now (to start their
+                                       // counting time).
+                                       for (const [q,p2] of Object.entries(players)) {
+                                               if (p2.on_field_since !== null) {
+                                                       p2.on_field_since = t;
+                                               }
+                                       }
+                               }
                        } else if (type === 'out') {
-                               take_off_field(p, t, live_since);
+                               take_off_field(p, t, live_since, offense, keep);
+                               if (keep && !keep_event(players, formations_used_this_point, filters)) {
+                                       // A player needed for the filters went off the field,
+                                       // so we need to attribute time for all the others.
+                                       // Pretend they walked off and then immediately on again.
+                                       //
+                                       // TODO: We also need to take care of this to get the globals right.
+                                       for (const [q,p2] of Object.entries(players)) {
+                                               if (p2.on_field_since !== null) {
+                                                       take_off_field(p2, t, live_since, offense, keep);
+                                                       p2.on_field_since = t;
+                                               }
+                                       }
+                               }
                        }
 
+                       keep = keep_event(players, formations_used_this_point, filters);  // Recompute after in/out.
+
                        // Liveness management
                        if (type === 'pull' || type === 'their_pull' || type === 'restart') {
                                live_since = t;
+                       } else if (type === 'catch' && last_pull_was_ours === null) {
+                               // Someone forgot to add the pull, so we'll need to wing it.
+                               console.log('Missing pull on ' + our_score + '\u2013' + their_score + ' in ' + match['description'] + '; pretending to have one.');
+                               live_since = t;
+                               last_pull_was_ours = !offense;
                        } else if (type === 'goal' || type === 'their_goal' || type === 'stoppage') {
                                for (const [q,p] of Object.entries(players)) {
-                                       if (p.on_field_since !== null) {
-                                               attribute_player_time(p, t, live_since);
+                                       if (p.on_field_since === null) {
+                                               continue;
+                                       }
+                                       if (type !== 'stoppage' && p.last_point_seen !== point_num) {
+                                               if (keep) {
+                                                       // In case the player did nothing this point,
+                                                       // not even subbing in.
+                                                       p.last_point_seen = point_num;
+                                                       ++p.points_played;
+                                               }
+                                       }
+                                       if (keep) attribute_player_time(p, t, live_since, offense);
+
+                                       if (type !== 'stoppage') {
+                                               if (keep) {
+                                                       if (last_pull_was_ours === true) {  // D point.
+                                                               ++p.defensive_points_completed;
+                                                               if (type === 'goal') {
+                                                                       ++p.defensive_points_won;
+                                                               }
+                                                       } else if (last_pull_was_ours === false) {  // O point.
+                                                               ++p.offensive_points_completed;
+                                                               if (type === 'goal') {
+                                                                       ++p.offensive_points_won;
+                                                               }
+                                                       }
+                                               }
+                                       }
+                               }
+
+                               if (keep) {
+                                       if (type !== 'stoppage') {
+                                               // Update globals.
+                                               ++globals.points_played;
+                                               if (last_pull_was_ours === true) {  // D point.
+                                                       ++globals.defensive_points_completed;
+                                                       if (type === 'goal') {
+                                                               ++globals.defensive_points_won;
+                                                       }
+                                               } else if (last_pull_was_ours === false) {  // O point.
+                                                       ++globals.offensive_points_completed;
+                                                       if (type === 'goal') {
+                                                               ++globals.offensive_points_won;
+                                                       }
+                                               }
+                                       }
+                                       if (live_since !== null) {
+                                               globals.playing_time_ms += t - live_since;
+                                               if (offense === true) {
+                                                       globals.offensive_playing_time_ms += t - live_since;
+                                               } else if (offense === false) {
+                                                       globals.defensive_playing_time_ms += t - live_since;
+                                               }
                                        }
                                }
+
                                live_since = null;
                        }
 
+                       // Score management
+                       if (type === 'goal') {
+                               ++our_score;
+                       } else if (type === 'their_goal') {
+                               ++their_score;
+                       }
+
+                       // Point count management
+                       if (p !== undefined && type !== 'out' && p.last_point_seen !== point_num) {
+                               if (keep) {
+                                       p.last_point_seen = point_num;
+                                       ++p.points_played;
+                               }
+                       }
+                       if (type === 'goal' || type === 'their_goal') {
+                               ++point_num;
+                               last_goal = t;
+                       }
+                       if (type !== 'out' && game_started === null) {
+                               game_started = t;
+                       }
+
                        // Pull management
                        if (type === 'pull') {
                                puller = e['player'];
                                pull_started = t;
-                               ++p.pulls;
+                               if (keep) ++p.pulls;
                        } else if (type === 'in' || type === 'out' || type === 'stoppage' || type === 'restart' || type === 'unknown' || type === 'set_defense' || type === 'set_offense') {
                                // No effect on pull.
                        } else if (type === 'pull_landed' && puller !== null) {
-                               players[puller].pull_times.push(t - pull_started);
+                               if (keep) players[puller].pull_times.push(t - pull_started);
                        } else if (type === 'pull_oob' && puller !== null) {
-                               ++players[puller].oob_pulls;
+                               if (keep) ++players[puller].oob_pulls;
                        } else {
                                // Not pulling (if there was one, we never recorded its outcome, but still count it).
                                puller = pull_started = null;
                        }
 
-                       // Offense/defense management (TODO: use it for actual counting)
-                       if (type === 'set_defense' || type === 'goal' || type === 'throwaway' || type === 'drop') {
+                       // Offense/defense management
+                       let last_offense = offense;
+                       if (type === 'set_defense' || type === 'goal' || type === 'throwaway' || type === 'drop' || type === 'was_d') {
                                offense = false;
                        } else if (type === 'set_offense' || type === 'their_goal' || type === 'their_throwaway' || type === 'defense' || type === 'interception') {
                                offense = true;
                        }
+                       if (last_offense !== offense && live_since !== null) {
+                               // Switched offense/defense status, so attribute this drive as needed,
+                               // and update live_since to take that into account.
+                               if (keep) {
+                                       for (const [q,p] of Object.entries(players)) {
+                                               if (p.on_field_since === null) {
+                                                       continue;
+                                               }
+                                               attribute_player_time(p, t, live_since, last_offense);
+                                       }
+                                       globals.playing_time_ms += t - live_since;
+                                       if (offense === true) {
+                                               globals.offensive_playing_time_ms += t - live_since;
+                                       } else if (offense === false) {
+                                               globals.defensive_playing_time_ms += t - live_since;
+                                       }
+                               }
+                               live_since = t;
+                       }
+
+                       if (type === 'pull') {
+                               last_pull_was_ours = true;
+                       } else if (type === 'their_pull') {
+                               last_pull_was_ours = false;
+                       } else if (type === 'set_offense' && last_pull_was_ours === null) {
+                               // set_offense could either be “changed to offense for some reason
+                               // we could not express”, or “we started in the middle of a point,
+                               // and we are offense”. We assume that if we already saw the pull,
+                               // it's the former, and if not, it's the latter; thus, the === null
+                               // test above. (It could also be “we set offense before the pull,
+                               // so that we get the right button enabled”, in which case it will
+                               // be overwritten by the next pull/their_pull event anyway.)
+                               last_pull_was_ours = false;
+                       } else if (type === 'set_defense' && last_pull_was_ours === null) {
+                               // Similar.
+                               last_pull_was_ours = true;
+                       } else if (type === 'goal' || type === 'their_goal') {
+                               last_pull_was_ours = null;
+                       }
+
+                       // Formation management
+                       if (type === 'formation_offense' || type === 'formation_defense') {
+                               let id = e.formation === null ? 0 : e.formation;
+                               let for_offense = (type === 'formation_offense');
+                               if (offense === for_offense) {
+                                       formations_used_this_point.add(id);
+                               } else if (for_offense) {
+                                       pending_offensive_formation = id;
+                               } else {
+                                       pending_defensive_formation = id;
+                               }
+                               if (for_offense) {
+                                       last_offensive_formation = id;
+                               } else {
+                                       last_defensive_formation = id;
+                               }
+                       } else if (last_offense !== offense) {
+                               if (offense === true && pending_offensive_formation !== null) {
+                                       formations_used_this_point.add(pending_offensive_formation);
+                                       pending_offensive_formation = null;
+                               } else if (offense === false && pending_defensive_formation !== null) {
+                                       formations_used_this_point.add(pending_defensive_formation);
+                                       pending_defensive_formation = null;
+                               } else if (offense === true && last_defensive_formation !== null) {
+                                       if (should_reuse_last_formation(match['events'], t)) {
+                                               formations_used_this_point.add(last_defensive_formation);
+                                       }
+                               } else if (offense === false && last_offensive_formation !== null) {
+                                       if (should_reuse_last_formation(match['events'], t)) {
+                                               formations_used_this_point.add(last_offensive_formation);
+                                       }
+                               }
+                       }
 
                        // Event management
                        if (type === 'catch' || type === 'goal') {
                                if (handler !== null) {
-                                       ++players[handler].num_throws;
-                                       ++p.catches;
+                                       if (keep) {
+                                               ++players[handler].num_throws;
+                                               ++p.catches;
+                                       }
                                }
 
-                               ++p.touches;
+                               if (keep) ++p.touches;
                                if (type === 'goal') {
-                                       if (prev_handler !== null) {
-                                               ++players[prev_handler].hockey_assists;
+                                       if (keep) {
+                                               if (prev_handler !== null) {
+                                                       ++players[prev_handler].hockey_assists;
+                                               }
+                                               if (handler !== null) {
+                                                       ++players[handler].assists;
+                                               }
+                                               ++p.goals;
                                        }
-                                       if (handler !== null) {
-                                               ++players[handler].assists;
-                                       }
-                                       ++p.goals;
                                        handler = prev_handler = null;
                                } else {
                                        // Update hold history.
@@ -160,29 +509,63 @@ function process_matches(json) {
                                        handler = e['player'];
                                }
                        } else if (type === 'throwaway') {
-                               ++p.throwaways;
+                               if (keep) {
+                                       ++p.num_throws;
+                                       ++p.throwaways;
+                               }
                                handler = prev_handler = null;
                        } else if (type === 'drop') {
-                               ++p.drops;
+                               if (keep) ++p.drops;
+                               handler = prev_handler = null;
+                       } else if (type === 'was_d') {
+                               if (keep) ++p.was_ds;
                                handler = prev_handler = null;
                        } else if (type === 'defense') {
-                               ++p.defenses;
+                               if (keep) ++p.defenses;
                        } else if (type === 'interception') {
-                               ++p.interceptions;
-                               ++p.defenses;
-                               ++p.touches;
+                               if (keep) {
+                                       ++p.interceptions;
+                                       ++p.defenses;
+                                       ++p.touches;
+                               }
                                prev_handler = null;
                                handler = e['player'];
                        } else if (type === 'offensive_soft_plus' || type === 'offensive_soft_minus' || type === 'defensive_soft_plus' || type === 'defensive_soft_minus') {
-                               ++p[type];
+                               if (keep) ++p[type];
                        } else if (type !== 'in' && type !== 'out' && type !== 'pull' &&
-                                  type !== 'their_goal' && type !== 'stoppage' && type !== 'unknown' &&
+                                  type !== 'their_goal' && type !== 'stoppage' && type !== 'restart' && type !== 'unknown' &&
                                   type !== 'set_defense' && type !== 'goal' && type !== 'throwaway' &&
-                                  type !== 'drop' && type !== 'set_offense' && type !== 'their_goal' &&
-                                  type !== 'pull' && type !== 'pull_landed' && type !== 'pull_oob' &&
-                                  type !== 'their_throwaway' && type !== 'defense' && type !== 'interception') {
+                                  type !== 'drop' && type !== 'was_d' && type !== 'set_offense' && type !== 'their_goal' &&
+                                  type !== 'pull' && type !== 'pull_landed' && type !== 'pull_oob' && type !== 'their_pull' &&
+                                  type !== 'their_throwaway' && type !== 'defense' && type !== 'interception' &&
+                                  type !== 'formation_offense' && type !== 'formation_defense') {
                                console.log("Unknown event:", e);
                        }
+
+                       if (type === 'goal' || type === 'their_goal') {
+                               formations_used_this_point.clear();
+                       }
+               }
+
+               // Add field time for all players still left at match end.
+               const keep = keep_event(players, formations_used_this_point, filters);
+               if (keep) {
+                       for (const [q,p] of Object.entries(players)) {
+                               if (p.on_field_since !== null && last_goal !== null) {
+                                       p.field_time_ms += last_goal - p.on_field_since;
+                               }
+                       }
+                       if (game_started !== null && last_goal !== null) {
+                               globals.field_time_ms += last_goal - game_started;
+                       }
+                       if (live_since !== null && last_goal !== null) {
+                               globals.playing_time_ms += last_goal - live_since;
+                               if (offense === true) {
+                                       globals.offensive_playing_time_ms += last_goal - live_since;
+                               } else if (offense === false) {
+                                       globals.defensive_playing_time_ms += last_goal - live_since;
+                               }
+                       }
                }
        }
 
@@ -192,15 +575,27 @@ function process_matches(json) {
        let rows = [];
        if (chosen_category === 'general') {
                rows = make_table_general(players);
-       } else if (chosen_category === 'pulls') {
-               rows = make_table_pulls(players);
+       } else if (chosen_category === 'offense') {
+               rows = make_table_offense(players);
+       } else if (chosen_category === 'defense') {
+               rows = make_table_defense(players);
+       } else if (chosen_category === 'playing_time') {
+               rows = make_table_playing_time(players);
+       } else if (chosen_category === 'per_point') {
+               rows = make_table_per_point(players);
        }
        document.getElementById('stats').replaceChildren(...rows);
 }
 
 function get_chosen_category() {
-       if (window.location.hash === '#pulls') {
-               return 'pulls';
+       if (window.location.hash === '#offense') {
+               return 'offense';
+       } else if (window.location.hash === '#defense') {
+               return 'defense';
+       } else if (window.location.hash === '#playing_time') {
+               return 'playing_time';
+       } else if (window.location.hash === '#per_point') {
+               return 'per_point';
        } else {
                return 'general';
        }
@@ -209,83 +604,913 @@ function get_chosen_category() {
 function write_main_menu(chosen_category) {
        let elems = [];
        if (chosen_category === 'general') {
-               elems.push(document.createTextNode('General'));
+               let span = document.createElement('span');
+               span.innerText = 'General';
+               elems.push(span);
        } else {
                let a = document.createElement('a');
                a.appendChild(document.createTextNode('General'));
                a.setAttribute('href', '#general');
                elems.push(a);
        }
-       elems.push(document.createTextNode(' | '));
-       if (chosen_category === 'pulls') {
-               elems.push(document.createTextNode('Pulls'));
+
+       if (chosen_category === 'offense') {
+               let span = document.createElement('span');
+               span.innerText = 'Offense';
+               elems.push(span);
        } else {
                let a = document.createElement('a');
-               a.appendChild(document.createTextNode('Pulls'));
-               a.setAttribute('href', '#pulls');
+               a.appendChild(document.createTextNode('Offense'));
+               a.setAttribute('href', '#offense');
                elems.push(a);
        }
+
+       if (chosen_category === 'defense') {
+               let span = document.createElement('span');
+               span.innerText = 'Defense';
+               elems.push(span);
+       } else {
+               let a = document.createElement('a');
+               a.appendChild(document.createTextNode('Defense'));
+               a.setAttribute('href', '#defense');
+               elems.push(a);
+       }
+
+       if (chosen_category === 'playing_time') {
+               let span = document.createElement('span');
+               span.innerText = 'Playing time';
+               elems.push(span);
+       } else {
+               let a = document.createElement('a');
+               a.appendChild(document.createTextNode('Playing time'));
+               a.setAttribute('href', '#playing_time');
+               elems.push(a);
+       }
+
+       if (chosen_category === 'per_point') {
+               let span = document.createElement('span');
+               span.innerText = 'Per point';
+               elems.push(span);
+       } else {
+               let a = document.createElement('a');
+               a.appendChild(document.createTextNode('Per point'));
+               a.setAttribute('href', '#per_point');
+               elems.push(a);
+       }
+
        document.getElementById('mainmenu').replaceChildren(...elems);
 }
 
+// https://en.wikipedia.org/wiki/1.96#History
+const z = 1.959964;
+
+const ci_width = 100;
+const ci_height = 20;
+
+function make_binomial_ci(val, num, z) {
+       let avg = val / num;
+
+       // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval
+       let low  = (avg + z*z/(2*num) - z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);   
+       let high = (avg + z*z/(2*num) + z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num); 
+
+       // Fix the signs so that we don't get -0.00.
+       low = Math.max(low, 0.0);
+       return {
+               'val': avg,
+               'lower_ci': low,
+               'upper_ci': high,
+               'min': 0.0,
+               'max': 1.0,
+       };
+}
+
+// These can only happen once per point, but you get -1 and +1
+// instead of 0 and +1. After we rewrite to 0 and 1, it's a binomial,
+// and then we can rewrite back.
+function make_efficiency_ci(points_won, points_completed, z)
+{
+       let ci = make_binomial_ci(points_won, points_completed, z);
+       ci.val = 2.0 * ci.val - 1.0;
+       ci.lower_ci = 2.0 * ci.lower_ci - 1.0;
+       ci.upper_ci = 2.0 * ci.upper_ci - 1.0;
+       ci.min = -1.0;
+       ci.max = 1.0;
+       ci.desired = 0.0;  // Desired = positive efficiency.
+       return ci;
+}
+
+// Ds, throwaways and drops can happen multiple times per point,
+// so they are Poisson distributed.
+//
+// Modified Wald (recommended by http://www.ine.pt/revstat/pdf/rs120203.pdf
+// since our rates are definitely below 2 per point).
+function make_poisson_ci(val, num, z, inverted)
+{
+       let low  = (val == 0) ? 0.0 : ((val - 0.5) - Math.sqrt(val - 0.5)) / num;
+       let high = (val == 0) ? -Math.log(0.025) / num : ((val + 0.5) + Math.sqrt(val + 0.5)) / num;
+
+       // Fix the signs so that we don't get -0.00.
+       low = Math.max(low, 0.0);
+
+       // The display range of 0 to 0.25 is fairly arbitrary. So is the desired 0.05 per point.
+       let avg = val / num;
+       return {
+               'val': avg,
+               'lower_ci': low,
+               'upper_ci': high,
+               'min': 0.0,
+               'max': 0.25,
+               'desired': 0.05,
+               'inverted': inverted,
+       };
+}
+
 function make_table_general(players) {
        let rows = [];
        {
                let header = document.createElement('tr');
-               add_cell(header, 'th', 'Player');
-               add_cell(header, 'th', '+/-');
-               add_cell(header, 'th', 'Soft +/-');
-               add_cell(header, 'th', 'Points played');
-               add_cell(header, 'th', 'Time played');
+               add_th(header, 'Player');
+               add_th(header, '+/-');
+               add_th(header, 'Soft +/-');
+               add_th(header, 'O efficiency');
+               add_th(header, 'D efficiency');
+               add_th(header, 'Points played');
                rows.push(header);
        }
 
-       for (const [q,p] of Object.entries(players)) {
+       for (const [q,p] of get_sorted_players(players)) {
+               if (q === 'globals') continue;
                let row = document.createElement('tr');
-               let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops;
+               let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops - p.was_ds;
                let soft_pm = p.offensive_soft_plus + p.defensive_soft_plus - p.offensive_soft_minus - p.defensive_soft_minus;
-               add_cell(row, 'td', p.name);  // TODO: number?
-               add_cell(row, 'td', pm > 0 ? ('+' + pm) : pm);
-               add_cell(row, 'td', soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
-               add_cell(row, 'td', p.points_played);
-               add_cell(row, 'td', Math.floor(p.playing_time_ms / 60000) + ' min');
+               let o_efficiency = make_efficiency_ci(p.offensive_points_won, p.offensive_points_completed, z);
+               let d_efficiency = make_efficiency_ci(p.defensive_points_won, p.defensive_points_completed, z);
+               let name = add_3cell(row, p.name, 'name');  // TODO: number?
+               add_3cell(row, pm > 0 ? ('+' + pm) : pm);
+               add_3cell(row, soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
+               add_3cell_ci(row, o_efficiency);
+               add_3cell_ci(row, d_efficiency);
+               add_3cell(row, p.points_played);
+               row.dataset.player = q;
                rows.push(row);
-               console.log(p.name + " played " + p.points_played + " points (" + Math.floor(p.playing_time_ms / 60000) + " min), " + p.goals + " goals, " + p.assists + " assists, plus/minus: " + pm);
        }
+
+       // Globals.
+       let globals = players['globals'];
+       let o_efficiency = make_efficiency_ci(globals.offensive_points_won, globals.offensive_points_completed, z);
+       let d_efficiency = make_efficiency_ci(globals.defensive_points_won, globals.defensive_points_completed, z);
+       let row = document.createElement('tr');
+       add_3cell(row, '');
+       add_3cell(row, '');
+       add_3cell(row, '');
+       add_3cell_ci(row, o_efficiency);
+       add_3cell_ci(row, d_efficiency);
+       add_3cell(row, globals.points_played);
+       rows.push(row);
+
        return rows;
 }
 
-function make_table_pulls(players) {
+function make_table_offense(players) {
        let rows = [];
        {
                let header = document.createElement('tr');
-               add_cell(header, 'th', 'Player');
-               add_cell(header, 'th', 'Pulls');
-               add_cell(header, 'th', 'OOB pulls');
-               add_cell(header, 'th', 'Avg. hang time (IB)');
+               add_th(header, 'Player');
+               add_th(header, 'Goals');
+               add_th(header, 'Assists');
+               add_th(header, 'Hockey assists');
+               add_th(header, 'Throws');
+               add_th(header, 'Throwaways');
+               add_th(header, '%OK');
+               add_th(header, 'Catches');
+               add_th(header, 'Drops');
+               add_th(header, 'D-ed');
+               add_th(header, '%OK');
+               add_th(header, 'Soft +/-', 6);
                rows.push(header);
        }
-       for (const [q,p] of Object.entries(players)) {
-               if (p.pulls === 0) {
-                       continue;
-               }
+
+       let num_throws = 0;
+       let throwaways = 0;
+       let catches = 0;
+       let drops = 0;
+       let was_ds = 0;
+       for (const [q,p] of get_sorted_players(players)) {
+               if (q === 'globals') continue;
+               let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
+               let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
+
+               throw_ok.format = 'percentage';
+               catch_ok.format = 'percentage';
+
+               // Desire at least 90% percentage. Fairly arbitrary.
+               throw_ok.desired = 0.9;
+               catch_ok.desired = 0.9;
+
+               let row = document.createElement('tr');
+               add_3cell(row, p.name, 'name');  // TODO: number?
+               add_3cell(row, p.goals);
+               add_3cell(row, p.assists);
+               add_3cell(row, p.hockey_assists);
+               add_3cell(row, p.num_throws);
+               add_3cell(row, p.throwaways);
+               add_3cell_ci(row, throw_ok);
+               add_3cell(row, p.catches);
+               add_3cell(row, p.drops);
+               add_3cell(row, p.was_ds);
+               add_3cell_ci(row, catch_ok);
+               add_3cell(row, '+' + p.offensive_soft_plus);
+               add_3cell(row, '-' + p.offensive_soft_minus);
+               row.dataset.player = q;
+               rows.push(row);
+
+               num_throws += p.num_throws;
+               throwaways += p.throwaways;
+               catches += p.catches;
+               drops += p.drops;
+               was_ds += p.was_ds;
+       }
+
+       // Globals.
+       let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
+       let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
+       throw_ok.format = 'percentage';
+       catch_ok.format = 'percentage';
+       throw_ok.desired = 0.9;
+       catch_ok.desired = 0.9;
+
+       let row = document.createElement('tr');
+       add_3cell(row, '');
+       add_3cell(row, '');
+       add_3cell(row, '');
+       add_3cell(row, '');
+       add_3cell(row, num_throws);
+       add_3cell(row, throwaways);
+       add_3cell_ci(row, throw_ok);
+       add_3cell(row, catches);
+       add_3cell(row, drops);
+       add_3cell(row, was_ds);
+       add_3cell_ci(row, catch_ok);
+       add_3cell(row, '');
+       add_3cell(row, '');
+       rows.push(row);
+
+       return rows;
+}
+
+function make_table_defense(players) {
+       let rows = [];
+       {
+               let header = document.createElement('tr');
+               add_th(header, 'Player');
+               add_th(header, 'Ds');
+               add_th(header, 'Pulls');
+               add_th(header, 'OOB pulls');
+               add_th(header, 'OOB%');
+               add_th(header, 'Avg. hang time (IB)');
+               add_th(header, 'Soft +/-', 6);
+               rows.push(header);
+       }
+       for (const [q,p] of get_sorted_players(players)) {
+               if (q === 'globals') continue;
                let sum_time = 0;
                for (const t of p.pull_times) {
                        sum_time += t;
                }
-               let avg_time = 1e-3 * sum_time / p.pulls;
+               let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
                let oob_pct = 100 * p.oob_pulls / p.pulls;
 
+               let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
+               ci_oob.format = 'percentage';
+               ci_oob.desired = 0.2;  // Arbitrary.
+               ci_oob.inverted = true;
+
                let row = document.createElement('tr');
-               add_cell(row, 'td', p.name);  // TODO: number?
-               add_cell(row, 'td', p.pulls);
-               add_cell(row, 'td', p.oob_pulls + ' (' + oob_pct.toFixed(0) + '%)');
+               add_3cell(row, p.name, 'name');  // TODO: number?
+               add_3cell(row, p.defenses);
+               add_3cell(row, p.pulls);
+               add_3cell(row, p.oob_pulls);
+               add_3cell_ci(row, ci_oob);
                if (p.pulls > p.oob_pulls) {
-                       add_cell(row, 'td', avg_time.toFixed(1) + ' sec');
+                       add_3cell(row, avg_time.toFixed(1) + ' sec');
+               } else {
+                       add_3cell(row, 'N/A');
+               }
+               add_3cell(row, '+' + p.defensive_soft_plus);
+               add_3cell(row, '-' + p.defensive_soft_minus);
+               row.dataset.player = q;
+               rows.push(row);
+       }
+       return rows;
+}
+
+function make_table_playing_time(players) {
+       let rows = [];
+       {
+               let header = document.createElement('tr');
+               add_th(header, 'Player');
+               add_th(header, 'Points played');
+               add_th(header, 'Time played');
+               add_th(header, 'O time');
+               add_th(header, 'D time');
+               add_th(header, 'Time on field');
+               add_th(header, 'O points');
+               add_th(header, 'D points');
+               rows.push(header);
+       }
+
+       for (const [q,p] of get_sorted_players(players)) {
+               if (q === 'globals') continue;
+               let row = document.createElement('tr');
+               add_3cell(row, p.name, 'name');  // TODO: number?
+               add_3cell(row, p.points_played);
+               add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
+               add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
+               add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
+               add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
+               add_3cell(row, p.offensive_points_completed);
+               add_3cell(row, p.defensive_points_completed);
+               row.dataset.player = q;
+               rows.push(row);
+       }
+
+       // Globals.
+       let globals = players['globals'];
+       let row = document.createElement('tr');
+       add_3cell(row, '');
+       add_3cell(row, globals.points_played);
+       add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
+       add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
+       add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
+       add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
+       add_3cell(row, globals.offensive_points_completed);
+       add_3cell(row, globals.defensive_points_completed);
+       rows.push(row);
+
+       return rows;
+}
+
+function make_table_per_point(players) {
+       let rows = [];
+       {
+               let header = document.createElement('tr');
+               add_th(header, 'Player');
+               add_th(header, 'Goals');
+               add_th(header, 'Assists');
+               add_th(header, 'Hockey assists');
+               add_th(header, 'Ds');
+               add_th(header, 'Throwaways');
+               add_th(header, 'Recv. errors');
+               add_th(header, 'Touches');
+               rows.push(header);
+       }
+
+       let goals = 0;
+       let assists = 0;
+       let hockey_assists = 0;
+       let defenses = 0;
+       let throwaways = 0;
+       let receiver_errors = 0;
+       let touches = 0;
+       for (const [q,p] of get_sorted_players(players)) {
+               if (q === 'globals') continue;
+
+               // Can only happen once per point, so these are binomials.
+               let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
+               let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
+               let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
+               // Arbitrarily desire at least 10% (not everybody can score or assist).
+               ci_goals.desired = 0.1;
+               ci_assists.desired = 0.1;
+               ci_hockey_assists.desired = 0.1;
+
+               let row = document.createElement('tr');
+               add_3cell(row, p.name, 'name');  // TODO: number?
+               add_3cell_ci(row, ci_goals);
+               add_3cell_ci(row, ci_assists);
+               add_3cell_ci(row, ci_hockey_assists);
+               add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
+               add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
+               add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
+               if (p.points_played > 0) {
+                       add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
                } else {
-                       add_cell(row, 'td', 'N/A');
+                       add_3cell(row, 'N/A');
                }
+               row.dataset.player = q;
                rows.push(row);
+
+               goals += p.goals;
+               assists += p.assists;
+               hockey_assists += p.hockey_assists;
+               defenses += p.defenses;
+               throwaways += p.throwaways;
+               receiver_errors += p.drops + p.was_ds;
+               touches += p.touches;
        }
+
+       // Globals.
+       let globals = players['globals'];
+       let row = document.createElement('tr');
+       add_3cell(row, '');
+       if (globals.points_played > 0) {
+               add_3cell_with_filler_ci(row, goals == 0 ? 0 : (goals / globals.points_played).toFixed(2));
+               add_3cell_with_filler_ci(row, assists == 0 ? 0 : (assists / globals.points_played).toFixed(2));
+               add_3cell_with_filler_ci(row, hockey_assists == 0 ? 0 : (hockey_assists / globals.points_played).toFixed(2));
+               add_3cell_with_filler_ci(row, defenses == 0 ? 0 : (defenses / globals.points_played).toFixed(2));
+               add_3cell_with_filler_ci(row, throwaways == 0 ? 0 : (throwaways / globals.points_played).toFixed(2));
+               add_3cell_with_filler_ci(row, receiver_errors == 0 ? 0 : (receiver_errors / globals.points_played).toFixed(2));
+               add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
+       } else {
+               add_3cell_with_filler_ci(row, 'N/A');
+               add_3cell_with_filler_ci(row, 'N/A');
+               add_3cell_with_filler_ci(row, 'N/A');
+               add_3cell_with_filler_ci(row, 'N/A');
+               add_3cell_with_filler_ci(row, 'N/A');
+               add_3cell_with_filler_ci(row, 'N/A');
+               add_3cell(row, 'N/A');
+       }
+       rows.push(row);
+
        return rows;
 }
+
+function open_filter_menu() {
+       document.getElementById('filter-submenu').style.display = 'none';
+
+       let menu = document.getElementById('filter-add-menu');
+       menu.style.display = 'block';
+       menu.replaceChildren();
+
+       // Place the menu directly under the “click to add” label;
+       // we don't anchor it since that label will move around
+       // and the menu shouldn't.
+       let rect = document.getElementById('filter-click-to-add').getBoundingClientRect();
+       menu.style.left = rect.left + 'px';
+       menu.style.top = (rect.bottom + 10) + 'px';
+
+       add_menu_item(menu, 0, 'match', 'Match (any)');
+       add_menu_item(menu, 1, 'player_any', 'Player on field (any)');
+       add_menu_item(menu, 2, 'player_all', 'Player on field (all)');
+       add_menu_item(menu, 3, 'formation_offense', 'Offense played (any)');
+       add_menu_item(menu, 4, 'formation_defense', 'Defense played (any)');
+}
+
+function add_menu_item(menu, menu_idx, filter_type, title) {
+       let item = document.createElement('div');
+       item.classList.add('option');
+       item.appendChild(document.createTextNode(title));
+
+       let arrow = document.createElement('div');
+       arrow.classList.add('arrow');
+       arrow.textContent = '▸';
+       item.appendChild(arrow);
+
+       menu.appendChild(item);
+
+       item.addEventListener('click', (e) => { show_submenu(menu_idx, null, filter_type); });
+}
+
+function show_submenu(menu_idx, pill, filter_type) {
+       let submenu = document.getElementById('filter-submenu');
+       let subitems = [];
+       const filter = find_filter(filter_type);
+
+       let choices = [];
+       if (filter_type === 'match') {
+               for (const match of global_json['matches']) {
+                       choices.push({
+                               'title': match['description'],
+                               'id': match['match_id']
+                       });
+               }
+       } else if (filter_type === 'player_any' || filter_type === 'player_all') {
+               for (const player of global_json['players']) {
+                       choices.push({
+                               'title': player['name'],
+                               'id': player['player_id']
+                       });
+               }
+       } else if (filter_type === 'formation_offense') {
+               choices.push({
+                       'title': '(None/unknown)',
+                       'id': 0,
+               });
+               for (const formation of global_json['formations']) {
+                       if (formation['offense']) {
+                               choices.push({
+                                       'title': formation['name'],
+                                       'id': formation['formation_id']
+                               });
+                       }
+               }
+       } else if (filter_type === 'formation_defense') {
+               choices.push({
+                       'title': '(None/unknown)',
+                       'id': 0,
+               });
+               for (const formation of global_json['formations']) {
+                       if (!formation['offense']) {
+                               choices.push({
+                                       'title': formation['name'],
+                                       'id': formation['formation_id']
+                               });
+                       }
+               }
+       }
+
+       for (const choice of choices) {
+               let label = document.createElement('label');
+
+               let subitem = document.createElement('div');
+               subitem.classList.add('option');
+
+               let check = document.createElement('input');
+               check.setAttribute('type', 'checkbox');
+               check.setAttribute('id', 'choice' + choice.id);
+               if (filter !== null && filter.elements.has(choice.id)) {
+                       check.setAttribute('checked', 'checked');
+               }
+               check.addEventListener('change', (e) => { checkbox_changed(e, filter_type, choice.id); });
+
+               subitem.appendChild(check);
+               subitem.appendChild(document.createTextNode(choice.title));
+
+               label.appendChild(subitem);
+               subitems.push(label);
+       }
+       submenu.replaceChildren(...subitems);
+       submenu.style.display = 'block';
+
+       if (pill !== null) {
+               let rect = pill.getBoundingClientRect();
+               submenu.style.top = (rect.bottom + 10) + 'px';
+               submenu.style.left = rect.left + 'px';
+       } else {
+               // Position just outside the selected menu.
+               let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
+               submenu.style.top = (rect.top + menu_idx * 35) + 'px';
+               submenu.style.left = (rect.right - 1) + 'px';
+       }
+}
+
+// Find the right filter, if it exists.
+function find_filter(filter_type) {
+       for (let f of global_filters) {
+               if (f.type === filter_type) {
+                       return f;
+               }
+       }
+       return null;
+}
+
+function checkbox_changed(e, filter_type, id) {
+       let filter = find_filter(filter_type);
+       if (e.target.checked) {
+               // See if we must add a new filter to the list.
+               if (filter === null) {
+                       filter = {
+                               'type': filter_type,
+                               'elements': new Set([ id ]),
+                       };
+                       filter.pill = make_filter_pill(filter);
+                       global_filters.push(filter);
+                       document.getElementById('filters').appendChild(filter.pill);
+               } else {
+                       filter.elements.add(id);
+                       let new_pill = make_filter_pill(filter);
+                       document.getElementById('filters').replaceChild(new_pill, filter.pill);
+                       filter.pill = new_pill;
+               }
+       } else {
+               filter.elements.delete(id);
+               if (filter.elements.size === 0) {
+                       document.getElementById('filters').removeChild(filter.pill);
+                       global_filters = global_filters.filter(f => f !== filter);
+               } else {
+                       let new_pill = make_filter_pill(filter);
+                       document.getElementById('filters').replaceChild(new_pill, filter.pill);
+                       filter.pill = new_pill;
+               }
+       }
+
+       process_matches(global_json, global_filters);
+}
+
+function make_filter_pill(filter) {
+       let pill = document.createElement('div');
+       pill.classList.add('filter-pill');
+       let text;
+       if (filter.type === 'match') {
+               text = 'Match: ';
+
+               let all_names = [];
+               for (const match_id of filter.elements) {
+                       all_names.push(find_match(match_id)['description']);
+               }
+               let common_prefix = find_common_prefix_of_all(all_names);
+               if (common_prefix !== null) {
+                       text += common_prefix + '(';
+               }
+
+               let first = true;
+               let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
+               for (const match_id of sorted_match_id) {
+                       if (!first) {
+                               text += ', ';
+                       }
+                       let desc = find_match(match_id)['description'];
+                       if (common_prefix === null) {
+                               text += desc;
+                       } else {
+                               text += desc.substr(common_prefix.length);
+                       }
+                       first = false;
+               }
+
+               if (common_prefix !== null) {
+                       text += ')';
+               }
+       } else if (filter.type === 'player_any') {
+               text = 'Player (any): ';
+               let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
+               let first = true;
+               for (const player_id of sorted_players) {
+                       if (!first) {
+                               text += ', ';
+                       }
+                       text += find_player(player_id)['name'];
+                       first = false;
+               }
+       } else if (filter.type === 'player_all') {
+               text = 'Players: ';
+               let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
+               let first = true;
+               for (const player_id of sorted_players) {
+                       if (!first) {
+                               text += ' AND ';
+                       }
+                       text += find_player(player_id)['name'];
+                       first = false;
+               }
+       } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
+               const offense = (filter.type === 'formation_offense');
+               if (offense) {
+                       text = 'Offense: ';
+               } else {
+                       text = 'Defense: ';
+               }
+
+               let all_names = [];
+               for (const formation_id of filter.elements) {
+                       all_names.push(find_formation(formation_id)['name']);
+               }
+               let common_prefix = find_common_prefix_of_all(all_names);
+               if (common_prefix !== null) {
+                       text += common_prefix + '(';
+               }
+
+               let first = true;
+               let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
+               for (const formation_id of sorted_formation_id) {
+                       if (!first) {
+                               text += ', ';
+                       }
+                       let desc = find_formation(formation_id)['name'];
+                       if (common_prefix === null) {
+                               text += desc;
+                       } else {
+                               text += desc.substr(common_prefix.length);
+                       }
+                       first = false;
+               }
+
+               if (common_prefix !== null) {
+                       text += ')';
+               }
+       }
+
+       let text_node = document.createElement('span');
+       text_node.innerText = text;
+       text_node.addEventListener('click', (e) => show_submenu(null, pill, filter.type));
+       pill.appendChild(text_node);
+
+       pill.appendChild(document.createTextNode(' '));
+
+       let delete_node = document.createElement('span');
+       delete_node.innerText = '✖';
+       delete_node.addEventListener('click', (e) => {
+               // Delete this filter entirely.
+               document.getElementById('filters').removeChild(pill);
+               global_filters = global_filters.filter(f => f !== filter);
+               process_matches(global_json, global_filters);
+
+               let add_menu = document.getElementById('filter-add-menu');
+               let add_submenu = document.getElementById('filter-submenu');
+               add_menu.style.display = 'none';
+               add_submenu.style.display = 'none';
+       });
+       pill.appendChild(delete_node);
+       pill.style.cursor = 'pointer';
+
+       return pill;
+}
+
+function find_common_prefix(a, b) {
+       let ret = '';
+       for (let i = 0; i < Math.min(a.length, b.length); ++i) {
+               if (a[i] === b[i]) {
+                       ret += a[i];
+               } else {
+                       break;
+               }
+       }
+       return ret;
+}
+
+function find_common_prefix_of_all(values) {
+       if (values.length < 2) {
+               return null;
+       }
+       let common_prefix = null;
+       for (const desc of values) {
+               if (common_prefix === null) {
+                       common_prefix = desc;
+               } else {
+                       common_prefix = find_common_prefix(common_prefix, desc);
+               }
+       }
+       if (common_prefix.length >= 3) {
+               return common_prefix;
+       } else {
+               return null;
+       }
+}
+
+function find_match(match_id) {
+       for (const match of global_json['matches']) {
+               if (match['match_id'] === match_id) {
+                       return match;
+               }
+       }
+       return null;
+}
+
+function find_formation(formation_id) {
+       for (const formation of global_json['formations']) {
+               if (formation['formation_id'] === formation_id) {
+                       return formation;
+               }
+       }
+       return null;
+}
+
+function find_player(player_id) {
+       for (const player of global_json['players']) {
+               if (player['player_id'] === player_id) {
+                       return player;
+               }
+       }
+       return null;
+}
+
+function player_pos(player_id) {
+       let i = 0;
+       for (const player of global_json['players']) {
+               if (player['player_id'] === player_id) {
+                       return i;
+               }
+               ++i;
+       }
+       return null;
+}
+
+function keep_match(match_id, filters) {
+       for (const filter of filters) {
+               if (filter.type === 'match') {
+                       return filter.elements.has(match_id);
+               }
+       }
+       return true;
+}
+
+function filter_passes(players, formations_used_this_point, filter) {
+       if (filter.type === 'player_any') {
+               for (const p of Array.from(filter.elements)) {
+                       if (players[p].on_field_since !== null) {
+                               return true;
+                       }
+               }
+               return false;
+       } else if (filter.type === 'player_all') {
+               for (const p of Array.from(filter.elements)) {
+                       if (players[p].on_field_since === null) {
+                               return false;
+                       }
+               }
+               return true;
+       } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
+               for (const f of Array.from(filter.elements)) {
+                       if (formations_used_this_point.has(f)) {
+                               return true;
+                       }
+               }
+               return false;
+       }
+       return true;
+}
+
+function keep_event(players, formations_used_this_point, filters) {
+       for (const filter of filters) {
+               if (!filter_passes(players, formations_used_this_point, filter)) {
+                       return false;
+               }
+       }
+       return true;
+}
+
+// Heuristic: If we go at least ten seconds without the possession changing
+// or the operator specifying some other formation, we probably play the
+// same formation as the last point.
+function should_reuse_last_formation(events, t) {
+       for (const e of events) {
+               if (e.t <= t) {
+                       continue;
+               }
+               if (e.t > t + 10000) {
+                       break;
+               }
+               const type = e.type;
+               if (type === 'their_goal' || type === 'goal' ||
+                   type === 'set_defense' || type === 'set_offense' ||
+                   type === 'throwaway' || type === 'their_throwaway' ||
+                   type === 'drop' || type === 'defense' || type === 'interception' ||
+                   type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
+                   type === 'formation_offense' || type === 'formation_defense') {
+                       return false;
+               }
+       }
+       return true;
+}
+
+function possibly_close_menu(e) {
+       if (e.target.closest('#filter-click-to-add') === null &&
+           e.target.closest('#filter-add-menu') === null &&
+           e.target.closest('#filter-submenu') === null &&
+           e.target.closest('.filter-pill') === null) {
+               let add_menu = document.getElementById('filter-add-menu');
+               let add_submenu = document.getElementById('filter-submenu');
+               add_menu.style.display = 'none';
+               add_submenu.style.display = 'none';
+       }
+}
+
+let global_sort = {};
+
+function sort_by(th) {
+       let tr = th.parentElement;
+       let child_idx = 0;
+       for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
+               let element = tr.children[column_idx];
+               if (element === th) {
+                       ++child_idx;  // Pad.
+                       break;
+               }
+               if (element.hasAttribute('colspan')) {
+                       child_idx += parseInt(element.getAttribute('colspan'));
+               } else {
+                       ++child_idx;
+               }
+       }
+
+       global_sort = {};
+       let table = tr.parentElement;
+       for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) {  // Skip header and globals.
+               let row = table.children[row_idx];
+               let player = parseInt(row.dataset.player);
+               let value = row.children[child_idx].textContent;
+               global_sort[player] = value;
+       }
+}
+
+function get_sorted_players(players)
+{
+       let p = Object.entries(players);
+       if (global_sort.length !== 0) {
+               p.sort((a,b) => {
+                       let ai = parseFloat(global_sort[a[0]]);
+                       let bi = parseFloat(global_sort[b[0]]);
+                       if (ai == ai && bi == bi) {
+                               return bi - ai;  // Reverse numeric.
+                       } else if (global_sort[a[0]] < global_sort[b[0]]) {
+                               return -1;
+                       } else if (global_sort[a[0]] > global_sort[b[0]]) {
+                               return 1;
+                       } else {
+                               return 0;
+                       }
+               });
+       }
+       return p;
+}