]> git.sesse.net Git - pkanalytics/blob - ultimate.js
Remove some repetition.
[pkanalytics] / ultimate.js
1 'use strict';
2
3 // No frameworks, no compilers, no npm, just JavaScript. :-)
4
5 let global_json;
6 let global_filters = {};
7 let next_filterset_id = 2;  // Arbitrary IDs are fine as long as they never collide.
8
9 addEventListener('hashchange', () => { process_matches(global_json, global_filters); });
10 addEventListener('click', possibly_close_menu);
11 fetch('ultimate.json')
12    .then(response => response.json())
13    .then(response => { global_json = response; process_matches(global_json, global_filters); });
14
15 function format_time(t)
16 {
17         const ms = t % 1000 + '';
18         t = Math.floor(t / 1000);
19         const sec = t % 60 + '';
20         t = Math.floor(t / 60);
21         const min = t % 60 + '';
22         const hour = Math.floor(t / 60) + '';
23         return hour + ':' + min.padStart(2, '0') + ':' + sec.padStart(2, '0') + '.' + ms.padStart(3, '0');
24 }
25
26 function attribute_player_time(player, to, from, offense) {
27         let delta_time;
28         if (player.on_field_since > from) {
29                 // Player came in while play happened (without a stoppage!?).
30                 delta_time = to - player.on_field_since;
31         } else {
32                 delta_time = to - from;
33         }
34         player.playing_time_ms += delta_time;
35         if (offense === true) {
36                 player.offensive_playing_time_ms += delta_time;
37         } else if (offense === false) {
38                 player.defensive_playing_time_ms += delta_time;
39         }
40 }
41
42 function take_off_field(player, t, live_since, offense, keep) {
43         if (keep) {
44                 if (live_since === null) {
45                         // Play isn't live, so nothing to do.
46                 } else {
47                         attribute_player_time(player, t, live_since, offense);
48                 }
49                 if (player.on_field_since !== null) {  // Just a safeguard; out without in should never happen.
50                         player.field_time_ms += t - player.on_field_since;
51                 }
52         }
53         player.on_field_since = null;
54 }
55
56 function add_cell(tr, element_type, text) {
57         let element = document.createElement(element_type);
58         element.textContent = text;
59         tr.appendChild(element);
60         return element;
61 }
62
63 function add_th(tr, text, colspan) {
64         let element = document.createElement('th');
65         let link = document.createElement('a');
66         link.style.cursor = 'pointer';
67         link.addEventListener('click', (e) => {
68                 sort_by(element);
69                 process_matches(global_json, global_filters);
70         });
71         link.textContent = text;
72         element.appendChild(link);
73         tr.appendChild(element);
74
75         if (colspan > 0) {
76                 element.setAttribute('colspan', colspan);
77         } else {
78                 element.setAttribute('colspan', '3');
79         }
80         return element;
81 }
82
83 function add_3cell(tr, text, cls) {
84         let p1 = add_cell(tr, 'td', '');
85         let element = add_cell(tr, 'td', text);
86         let p2 = add_cell(tr, 'td', '');
87
88         p1.classList.add('pad');
89         p2.classList.add('pad');
90         if (cls === undefined) {
91                 element.classList.add('num');
92         } else {
93                 element.classList.add(cls);
94         }
95         return element;
96 }
97
98 function add_3cell_with_filler_ci(tr, text, cls) {
99         let element = add_3cell(tr, text, cls);
100
101         let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
102         svg.classList.add('fillerci');
103         svg.setAttribute('width', ci_width);
104         svg.setAttribute('height', ci_height);
105         element.appendChild(svg);
106
107         return element;
108 }
109
110 function add_3cell_ci(tr, ci) {
111         if (isNaN(ci.val)) {
112                 add_3cell_with_filler_ci(tr, 'N/A');
113                 return;
114         }
115
116         let text;
117         if (ci.format === 'percentage') {
118                 text = (100 * ci.val).toFixed(0) + '%';
119         } else {
120                 text = ci.val.toFixed(2);
121         }
122         let element = add_3cell(tr, text);
123         let to_x = (val) => { return ci_width * (val - ci.min) / (ci.max - ci.min); };
124
125         // Container.
126         let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
127         if (ci.inverted === true) {
128                 svg.classList.add('invertedci');
129         } else {
130                 svg.classList.add('ci');
131         }
132         svg.setAttribute('width', ci_width);
133         svg.setAttribute('height', ci_height);
134
135         // The good (green) and red (bad) ranges.
136         let s0 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
137         s0.classList.add('range');
138         s0.classList.add('s0');
139         s0.setAttribute('width', to_x(ci.desired));
140         s0.setAttribute('height', ci_height);
141         s0.setAttribute('x', '0');
142
143         let s1 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
144         s1.classList.add('range');
145         s1.classList.add('s1');
146         s1.setAttribute('width', ci_width - to_x(ci.desired));
147         s1.setAttribute('height', ci_height);
148         s1.setAttribute('x', to_x(ci.desired));
149
150         // Confidence bar.
151         let bar = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
152         bar.classList.add('bar');
153         bar.setAttribute('width', to_x(ci.upper_ci) - to_x(ci.lower_ci));
154         bar.setAttribute('height', ci_height / 3);
155         bar.setAttribute('x', to_x(ci.lower_ci));
156         bar.setAttribute('y', ci_height / 3);
157
158         // Marker line for average.
159         let marker = document.createElementNS('http://www.w3.org/2000/svg', 'line');
160         marker.classList.add('marker');
161         marker.setAttribute('x1', to_x(ci.val));
162         marker.setAttribute('x2', to_x(ci.val));
163         marker.setAttribute('y1', ci_height / 6);
164         marker.setAttribute('y2', ci_height * 5 / 6);
165
166         svg.appendChild(s0);
167         svg.appendChild(s1);
168         svg.appendChild(bar);
169         svg.appendChild(marker);
170
171         element.appendChild(svg);
172 }
173
174 function calc_stats(json, filters) {
175         let players = {};
176         for (const player of json['players']) {
177                 players[player['player_id']] = {
178                         'name': player['name'],
179                         'gender': player['gender'],
180                         'number': player['number'],
181
182                         'goals': 0,
183                         'assists': 0,
184                         'hockey_assists': 0,
185                         'catches': 0,
186                         'touches': 0,
187                         'num_throws': 0,
188                         'throwaways': 0,
189                         'drops': 0,
190                         'was_ds': 0,
191                         'stallouts': 0,
192
193                         'defenses': 0,
194                         'callahans': 0,
195                         'points_played': 0,
196                         'playing_time_ms': 0,
197                         'offensive_playing_time_ms': 0,
198                         'defensive_playing_time_ms': 0,
199                         'field_time_ms': 0,
200
201                         // For efficiency.
202                         'offensive_points_completed': 0,
203                         'offensive_points_won': 0,
204                         'defensive_points_completed': 0,
205                         'defensive_points_won': 0,
206
207                         'offensive_soft_plus': 0,
208                         'offensive_soft_minus': 0,
209                         'defensive_soft_plus': 0,
210                         'defensive_soft_minus': 0,
211
212                         'pulls': 0,
213                         'pull_times': [],
214                         'oob_pulls': 0,
215
216                         // Internal.
217                         'last_point_seen': null,
218                         'on_field_since': null,
219                 };
220         }
221
222         // Globals.
223         players['globals'] = {
224                 'points_played': 0,
225                 'playing_time_ms': 0,
226                 'offensive_playing_time_ms': 0,
227                 'defensive_playing_time_ms': 0,
228                 'field_time_ms': 0,
229
230                 'offensive_points_completed': 0,
231                 'offensive_points_won': 0,
232                 'defensive_points_completed': 0,
233                 'defensive_points_won': 0,
234         };
235         let globals = players['globals'];
236
237         for (const match of json['matches']) {
238                 if (!keep_match(match['match_id'], filters)) {
239                         continue;
240                 }
241
242                 let our_score = 0;
243                 let their_score = 0;
244                 let between_points = true;
245                 let handler = null;
246                 let handler_got_by_interception = false;  // Only relevant if handler !== null.
247                 let prev_handler = null;
248                 let live_since = null;
249                 let offense = null;  // True/false/null (unknown).
250                 let puller = null;
251                 let pull_started = null;
252                 let last_pull_was_ours = null;  // Effectively whether we're playing an O or D point (not affected by turnovers).
253                 let point_num = 0;
254                 let game_started = null;
255                 let last_goal = null;
256                 let current_predominant_gender = null;
257                 let current_num_players_on_field = null;
258
259                 // The last used formations of the given kind, if any; they may be reused
260                 // when the point starts, if nothing else is set.
261                 let last_offensive_formation = null;
262                 let last_defensive_formation = null;
263
264                 // Formations we've set, but haven't really had the chance to use yet
265                 // (e.g., we get a “use zone defense” event while we're still on offense).
266                 let pending_offensive_formation = null;
267                 let pending_defensive_formation = null;
268
269                 // Formations that we have played at least once this point, after all
270                 // heuristics and similar.
271                 let formations_used_this_point = new Set();
272
273                 for (const [q,p] of Object.entries(players)) {
274                         p.on_field_since = null;
275                         p.last_point_seen = null;
276                 }
277                 for (const e of match['events']) {
278                         let t = e['t'];
279                         let type = e['type'];
280                         let p = players[e['player']];
281
282                         // Sub management
283                         let keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
284                         if (type === 'in' && p.on_field_since === null) {
285                                 p.on_field_since = t;
286                                 if (!keep && keep_event(players, formations_used_this_point, last_pull_was_ours, filters)) {
287                                         // A player needed for the filters went onto the field,
288                                         // so pretend people walked on right now (to start their
289                                         // counting time).
290                                         for (const [q,p2] of Object.entries(players)) {
291                                                 if (p2.on_field_since !== null) {
292                                                         p2.on_field_since = t;
293                                                 }
294                                         }
295                                 }
296                         } else if (type === 'out') {
297                                 take_off_field(p, t, live_since, offense, keep);
298                                 if (keep && !keep_event(players, formations_used_this_point, last_pull_was_ours, filters)) {
299                                         // A player needed for the filters went off the field,
300                                         // so we need to attribute time for all the others.
301                                         // Pretend they walked off and then immediately on again.
302                                         //
303                                         // TODO: We also need to take care of this to get the globals right.
304                                         for (const [q,p2] of Object.entries(players)) {
305                                                 if (p2.on_field_since !== null) {
306                                                         take_off_field(p2, t, live_since, offense, keep);
307                                                         p2.on_field_since = t;
308                                                 }
309                                         }
310                                 }
311                         }
312
313                         keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);  // Recompute after in/out.
314
315                         if (match['gender_rule_a']) {
316                                 if (type === 'restart' && !between_points) {
317                                         let predominant_gender = find_predominant_gender(players);
318                                         let num_players_on_field = find_num_players_on_field(players);
319                                         if (predominant_gender !== current_predominant_gender && current_predominant_gender !== null) {
320                                                 console.log(match['description'] + ' ' + format_time(t) + ': Stoppage changed predominant gender from ' + current_predominant_gender + ' to ' + predominant_gender);
321                                         }
322                                         if (num_players_on_field !== current_num_players_on_field && current_num_players_on_field !== null) {
323                                                 console.log(match['description'] + ' ' + format_time(t) + ': Stoppage changed number of players on field from ' + current_num_players_on_field + ' to ' + num_players_on_field);
324                                         }
325                                         current_predominant_gender = predominant_gender;
326                                         current_num_players_on_field = num_players_on_field;
327                                 } else if (type === 'pull' || type === 'their_pull') {
328                                         let predominant_gender = find_predominant_gender(players);
329                                         let num_players_on_field = find_num_players_on_field(players);
330                                         let changed = (predominant_gender !== current_predominant_gender);
331                                         if (point_num !== 0) {
332                                                 let should_change = (point_num % 4 == 1 || point_num % 4 == 3);  // ABBA changes on 1 and 3.
333                                                 if (changed && !should_change) {
334                                                         console.log(match['description'] + ' ' + format_time(t) + ': Gender ratio should have stayed the same, changed to predominance of ' + predominant_gender);
335                                                 } else if (!changed && should_change) {
336                                                         console.log(match['description'] + ' ' + format_time(t) + ': Gender ratio should have changed, remained predominantly ' + predominant_gender);
337                                                 }
338                                                 if (num_players_on_field !== current_num_players_on_field && current_num_players_on_field !== null) {
339                                                         console.log(match['description'] + ' ' + format_time(t) + ': Number of players on field changed from ' + current_num_players_on_field + ' to ' + num_players_on_field);
340                                                 }
341                                         }
342                                         current_predominant_gender = predominant_gender;
343                                         current_num_players_on_field = num_players_on_field;
344                                 }
345                         }
346                         if (match['gender_pull_rule']) {
347                                 if (type === 'pull') {
348                                         if (current_predominant_gender !== null &&
349                                             p.gender !== current_predominant_gender) {
350                                                 console.log(match['description'] + ' ' + format_time(t) + ': ' + p.name + ' pulled, should have been ' + current_predominant_gender);
351                                         }
352                                 }
353                         }
354
355                         // Liveness management
356                         if (type === 'pull' || type === 'their_pull' || type === 'restart') {
357                                 live_since = t;
358                                 between_points = false;
359                         } else if (type === 'catch' && last_pull_was_ours === null) {
360                                 // Someone forgot to add the pull, so we'll need to wing it.
361                                 console.log(match['description'] + ' ' + format_time(t) + ': Missing pull on ' + our_score + '\u2013' + their_score + '; pretending to have one.');
362                                 live_since = t;
363                                 last_pull_was_ours = !offense;
364                                 between_points = false;
365                         } else if (type === 'goal' || type === 'their_goal' || type === 'stoppage') {
366                                 for (const [q,p] of Object.entries(players)) {
367                                         if (p.on_field_since === null) {
368                                                 continue;
369                                         }
370                                         if (type !== 'stoppage' && p.last_point_seen !== point_num) {
371                                                 if (keep) {
372                                                         // In case the player did nothing this point,
373                                                         // not even subbing in.
374                                                         p.last_point_seen = point_num;
375                                                         ++p.points_played;
376                                                 }
377                                         }
378                                         if (keep) attribute_player_time(p, t, live_since, offense);
379
380                                         if (type !== 'stoppage') {
381                                                 if (keep) {
382                                                         if (last_pull_was_ours === true) {  // D point.
383                                                                 ++p.defensive_points_completed;
384                                                                 if (type === 'goal') {
385                                                                         ++p.defensive_points_won;
386                                                                 }
387                                                         } else if (last_pull_was_ours === false) {  // O point.
388                                                                 ++p.offensive_points_completed;
389                                                                 if (type === 'goal') {
390                                                                         ++p.offensive_points_won;
391                                                                 }
392                                                         }
393                                                 }
394                                         }
395                                 }
396
397                                 if (keep) {
398                                         if (type !== 'stoppage') {
399                                                 // Update globals.
400                                                 ++globals.points_played;
401                                                 if (last_pull_was_ours === true) {  // D point.
402                                                         ++globals.defensive_points_completed;
403                                                         if (type === 'goal') {
404                                                                 ++globals.defensive_points_won;
405                                                         }
406                                                 } else if (last_pull_was_ours === false) {  // O point.
407                                                         ++globals.offensive_points_completed;
408                                                         if (type === 'goal') {
409                                                                 ++globals.offensive_points_won;
410                                                         }
411                                                 }
412                                         }
413                                         if (live_since !== null) {
414                                                 globals.playing_time_ms += t - live_since;
415                                                 if (offense === true) {
416                                                         globals.offensive_playing_time_ms += t - live_since;
417                                                 } else if (offense === false) {
418                                                         globals.defensive_playing_time_ms += t - live_since;
419                                                 }
420                                         }
421                                 }
422
423                                 live_since = null;
424                         }
425
426                         // Score management
427                         if (type === 'goal') {
428                                 ++our_score;
429                                 between_points = true;
430                         } else if (type === 'their_goal') {
431                                 ++their_score;
432                                 between_points = true;
433                         }
434
435                         // Point count management
436                         if (p !== undefined && type !== 'out' && p.last_point_seen !== point_num) {
437                                 if (keep) {
438                                         p.last_point_seen = point_num;
439                                         ++p.points_played;
440                                 }
441                         }
442                         if (type === 'goal' || type === 'their_goal') {
443                                 ++point_num;
444                                 last_goal = t;
445                         }
446                         if (type !== 'out' && game_started === null) {
447                                 game_started = t;
448                         }
449
450                         // Pull management
451                         if (type === 'pull') {
452                                 puller = e['player'];
453                                 pull_started = t;
454                                 if (keep) ++p.pulls;
455                         } else if (type === 'in' || type === 'out' || type === 'stoppage' || type === 'restart' || type === 'unknown' || type === 'set_defense' || type === 'set_offense') {
456                                 // No effect on pull.
457                         } else if (type === 'pull_landed' && puller !== null) {
458                                 if (keep) players[puller].pull_times.push(t - pull_started);
459                         } else if (type === 'pull_oob' && puller !== null) {
460                                 if (keep) ++players[puller].oob_pulls;
461                         } else {
462                                 // Not pulling (if there was one, we never recorded its outcome, but still count it).
463                                 puller = pull_started = null;
464                         }
465
466                         // Offense/defense management
467                         let last_offense = offense;
468                         if (type === 'set_defense' || type === 'goal' || type === 'throwaway' || type === 'drop' || type === 'was_d' || type === 'stallout') {
469                                 offense = false;
470                         } else if (type === 'set_offense' || type === 'their_goal' || type === 'their_throwaway' || type === 'defense' || type === 'interception') {
471                                 offense = true;
472                         }
473                         if (last_offense !== offense && live_since !== null) {
474                                 // Switched offense/defense status, so attribute this drive as needed,
475                                 // and update live_since to take that into account.
476                                 if (keep) {
477                                         for (const [q,p] of Object.entries(players)) {
478                                                 if (p.on_field_since === null) {
479                                                         continue;
480                                                 }
481                                                 attribute_player_time(p, t, live_since, last_offense);
482                                         }
483                                         globals.playing_time_ms += t - live_since;
484                                         if (offense === true) {
485                                                 globals.offensive_playing_time_ms += t - live_since;
486                                         } else if (offense === false) {
487                                                 globals.defensive_playing_time_ms += t - live_since;
488                                         }
489                                 }
490                                 live_since = t;
491                         }
492
493                         if (type === 'pull') {
494                                 last_pull_was_ours = true;
495                         } else if (type === 'their_pull') {
496                                 last_pull_was_ours = false;
497                         } else if (type === 'set_offense' && last_pull_was_ours === null) {
498                                 // set_offense could either be “changed to offense for some reason
499                                 // we could not express”, or “we started in the middle of a point,
500                                 // and we are offense”. We assume that if we already saw the pull,
501                                 // it's the former, and if not, it's the latter; thus, the === null
502                                 // test above. (It could also be “we set offense before the pull,
503                                 // so that we get the right button enabled”, in which case it will
504                                 // be overwritten by the next pull/their_pull event anyway.)
505                                 last_pull_was_ours = false;
506                         } else if (type === 'set_defense' && last_pull_was_ours === null) {
507                                 // Similar.
508                                 last_pull_was_ours = true;
509                         } else if (type === 'goal' || type === 'their_goal') {
510                                 last_pull_was_ours = null;
511                         }
512
513                         // Formation management
514                         if (type === 'formation_offense' || type === 'formation_defense') {
515                                 let id = e.formation === null ? 0 : e.formation;
516                                 let for_offense = (type === 'formation_offense');
517                                 if (offense === for_offense) {
518                                         formations_used_this_point.add(id);
519                                 } else if (for_offense) {
520                                         pending_offensive_formation = id;
521                                 } else {
522                                         pending_defensive_formation = id;
523                                 }
524                                 if (for_offense) {
525                                         last_offensive_formation = id;
526                                 } else {
527                                         last_defensive_formation = id;
528                                 }
529                         } else if (last_offense !== offense) {
530                                 if (offense === true && pending_offensive_formation !== null) {
531                                         formations_used_this_point.add(pending_offensive_formation);
532                                         pending_offensive_formation = null;
533                                 } else if (offense === false && pending_defensive_formation !== null) {
534                                         formations_used_this_point.add(pending_defensive_formation);
535                                         pending_defensive_formation = null;
536                                 } else if (offense === true && last_defensive_formation !== null) {
537                                         if (should_reuse_last_formation(match['events'], t)) {
538                                                 formations_used_this_point.add(last_defensive_formation);
539                                         }
540                                 } else if (offense === false && last_offensive_formation !== null) {
541                                         if (should_reuse_last_formation(match['events'], t)) {
542                                                 formations_used_this_point.add(last_offensive_formation);
543                                         }
544                                 }
545                         }
546
547                         if (type !== 'out' && type !== 'in' && p !== undefined && p.on_field_since === null) {
548                                 console.log(match['description'] + ' ' + format_time(t) + ': Event “' + type + '” on subbed-out player ' + p.name);
549                         }
550                         if (type === 'catch' && handler !== null && players[handler].on_field_since === null) {
551                                 // The handler subbed out and was replaced with another handler,
552                                 // so this wasn't a pass.
553                                 handler = null;
554                         }
555
556                         // Event management
557                         if (type === 'goal' && handler === e['player'] && handler_got_by_interception) {
558                                 // Self-pass to goal after an interception; this is not a real pass,
559                                 // just how we represent a Callahan right now -- so don't
560                                 // count the throw, any assists or similar.
561                                 //
562                                 // It's an open question how we should handle a self-pass that is
563                                 // _not_ after an interception, or a self-pass that's not a goal.
564                                 // (It must mean we tipped off someone.) We'll count it as a regular one
565                                 // for the time being, although it will make hockey assists weird.
566                                 if (keep) {
567                                         ++p.goals;
568                                         ++p.callahans;
569                                 }
570                                 handler = prev_handler = null;
571                         } else if (type === 'catch' || type === 'goal') {
572                                 if (handler !== null) {
573                                         if (keep) {
574                                                 ++players[handler].num_throws;
575                                                 ++p.catches;
576                                         }
577                                 }
578
579                                 if (keep) ++p.touches;
580                                 if (type === 'goal') {
581                                         if (keep) {
582                                                 if (prev_handler !== null) {
583                                                         ++players[prev_handler].hockey_assists;
584                                                 }
585                                                 if (handler !== null) {
586                                                         ++players[handler].assists;
587                                                 }
588                                                 ++p.goals;
589                                         }
590                                         handler = prev_handler = null;
591                                 } else {
592                                         // Update hold history.
593                                         prev_handler = handler;
594                                         handler = e['player'];
595                                         handler_got_by_interception = false;
596                                 }
597                         } else if (type === 'throwaway') {
598                                 if (keep) {
599                                         ++p.num_throws;
600                                         ++p.throwaways;
601                                 }
602                                 handler = prev_handler = null;
603                         } else if (type === 'drop') {
604                                 if (keep) ++p.drops;
605                                 handler = prev_handler = null;
606                         } else if (type === 'stallout') {
607                                 if (keep) ++p.stallouts;
608                                 handler = prev_handler = null;
609                         } else if (type === 'was_d') {
610                                 if (keep) ++p.was_ds;
611                                 handler = prev_handler = null;
612                         } else if (type === 'defense') {
613                                 if (keep) ++p.defenses;
614                         } else if (type === 'interception') {
615                                 if (keep) {
616                                         ++p.catches;
617                                         ++p.defenses;
618                                         ++p.touches;
619                                 }
620                                 prev_handler = null;
621                                 handler = e['player'];
622                                 handler_got_by_interception = true;
623                         } else if (type === 'offensive_soft_plus' || type === 'offensive_soft_minus' || type === 'defensive_soft_plus' || type === 'defensive_soft_minus') {
624                                 if (keep) ++p[type];
625                         } else if (type !== 'in' && type !== 'out' && type !== 'pull' &&
626                                    type !== 'their_goal' && type !== 'stoppage' && type !== 'restart' && type !== 'unknown' &&
627                                    type !== 'set_defense' && type !== 'goal' && type !== 'throwaway' &&
628                                    type !== 'drop' && type !== 'was_d' && type !== 'stallout' && type !== 'set_offense' && type !== 'their_goal' &&
629                                    type !== 'pull' && type !== 'pull_landed' && type !== 'pull_oob' && type !== 'their_pull' &&
630                                    type !== 'their_throwaway' && type !== 'defense' && type !== 'interception' &&
631                                    type !== 'formation_offense' && type !== 'formation_defense') {
632                                 console.log(format_time(t) + ": Unknown event “" + e + "”");
633                         }
634
635                         if (type === 'goal' || type === 'their_goal') {
636                                 formations_used_this_point.clear();
637                         }
638                 }
639
640                 // Add field time for all players still left at match end.
641                 const keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
642                 if (keep) {
643                         for (const [q,p] of Object.entries(players)) {
644                                 if (p.on_field_since !== null && last_goal !== null) {
645                                         p.field_time_ms += last_goal - p.on_field_since;
646                                 }
647                         }
648                         if (game_started !== null && last_goal !== null) {
649                                 globals.field_time_ms += last_goal - game_started;
650                         }
651                         if (live_since !== null && last_goal !== null) {
652                                 globals.playing_time_ms += last_goal - live_since;
653                                 if (offense === true) {
654                                         globals.offensive_playing_time_ms += last_goal - live_since;
655                                 } else if (offense === false) {
656                                         globals.defensive_playing_time_ms += last_goal - live_since;
657                                 }
658                         }
659                 }
660         }
661         return players;
662 }
663
664 function process_matches(json, filtersets) {
665         let chosen_category = get_chosen_category();
666         write_main_menu(chosen_category);
667
668         let filterset_values = Object.values(filtersets);
669         if (filterset_values.length === 0) {
670                 filterset_values = [[]];
671         }
672
673         let rowsets = [];
674         for (const filter of filterset_values) {
675                 let players = calc_stats(json, filter);
676                 let rows = [];
677                 if (chosen_category === 'general') {
678                         rows = make_table_general(players);
679                 } else if (chosen_category === 'offense') {
680                         rows = make_table_offense(players);
681                 } else if (chosen_category === 'defense') {
682                         rows = make_table_defense(players);
683                 } else if (chosen_category === 'playing_time') {
684                         rows = make_table_playing_time(players);
685                 } else if (chosen_category === 'per_point') {
686                         rows = make_table_per_point(players);
687                 }
688                 rowsets.push(rows);
689         }
690
691         let merged_rows = [];
692         if (filterset_values.length > 1) {
693                 for (let i = 0; i < rowsets.length; ++i) {
694                         let marker = make_filter_marker(filterset_values[i]);
695
696                         // Make filter header.
697                         let tr = rowsets[i][0];
698                         let th = document.createElement('th');
699                         th.textContent = '';
700                         tr.insertBefore(th, tr.firstChild);
701
702                         for (let j = 1; j < rowsets[i].length; ++j) {
703                                 let tr = rowsets[i][j];
704
705                                 // Remove the name for cleanness.
706                                 if (i != 0) {
707                                         tr.firstChild.nextSibling.textContent = '';
708                                 }
709
710                                 if (i != 0) {
711                                         tr.style.borderTop = '0px';
712                                 }
713                                 if (i != rowsets.length - 1) {
714                                         tr.style.borderBottom = '0px';
715                                 }
716
717                                 // Make filter marker.
718                                 let td = document.createElement('td');
719                                 td.textContent = marker;
720                                 td.classList.add('filtermarker');
721                                 tr.insertBefore(td, tr.firstChild);
722                         }
723                 }
724
725                 for (let i = 0; i < rowsets[0].length; ++i) {
726                         for (let j = 0; j < rowsets.length; ++j) {
727                                 merged_rows.push(rowsets[j][i]);
728                                 if (i === 0) break;  // Don't merge the headings.
729                         }
730                 }
731         } else {
732                 merged_rows = rowsets[0];
733         }
734         document.getElementById('stats').replaceChildren(...merged_rows);
735 }
736
737 function get_chosen_category() {
738         if (window.location.hash === '#offense') {
739                 return 'offense';
740         } else if (window.location.hash === '#defense') {
741                 return 'defense';
742         } else if (window.location.hash === '#playing_time') {
743                 return 'playing_time';
744         } else if (window.location.hash === '#per_point') {
745                 return 'per_point';
746         } else {
747                 return 'general';
748         }
749 }
750
751 function write_main_menu(chosen_category) {
752         let elems = [];
753         const categories = [
754                 ['general', 'General'],
755                 ['offense', 'Offense'],
756                 ['defense', 'Defense'],
757                 ['playing_time', 'Playing time'],
758                 ['per_point', 'Per point']
759         ];
760         for (const [id, title] of categories) {
761                 if (chosen_category === id) {
762                         let span = document.createElement('span');
763                         span.innerText = title;
764                         elems.push(span);
765                 } else {
766                         let a = document.createElement('a');
767                         a.appendChild(document.createTextNode(title));
768                         a.setAttribute('href', '#' + id);
769                         elems.push(a);
770                 }
771         }
772
773         document.getElementById('mainmenu').replaceChildren(...elems);
774 }
775
776 // https://en.wikipedia.org/wiki/1.96#History
777 const z = 1.959964;
778
779 const ci_width = 100;
780 const ci_height = 20;
781
782 function make_binomial_ci(val, num, z) {
783         let avg = val / num;
784
785         // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval
786         let low  = (avg + z*z/(2*num) - z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);   
787         let high = (avg + z*z/(2*num) + z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num); 
788
789         // Fix the signs so that we don't get -0.00.
790         low = Math.max(low, 0.0);
791         return {
792                 'val': avg,
793                 'lower_ci': low,
794                 'upper_ci': high,
795                 'min': 0.0,
796                 'max': 1.0,
797         };
798 }
799
800 // These can only happen once per point, but you get -1 and +1
801 // instead of 0 and +1. After we rewrite to 0 and 1, it's a binomial,
802 // and then we can rewrite back.
803 function make_efficiency_ci(points_won, points_completed, z)
804 {
805         let ci = make_binomial_ci(points_won, points_completed, z);
806         ci.val = 2.0 * ci.val - 1.0;
807         ci.lower_ci = 2.0 * ci.lower_ci - 1.0;
808         ci.upper_ci = 2.0 * ci.upper_ci - 1.0;
809         ci.min = -1.0;
810         ci.max = 1.0;
811         ci.desired = 0.0;  // Desired = positive efficiency.
812         return ci;
813 }
814
815 // Ds, throwaways and drops can happen multiple times per point,
816 // so they are Poisson distributed.
817 //
818 // Modified Wald (recommended by http://www.ine.pt/revstat/pdf/rs120203.pdf
819 // since our rates are definitely below 2 per point).
820 function make_poisson_ci(val, num, z, inverted)
821 {
822         let low  = (val == 0) ? 0.0 : ((val - 0.5) - Math.sqrt(val - 0.5)) / num;
823         let high = (val == 0) ? -Math.log(0.025) / num : ((val + 0.5) + Math.sqrt(val + 0.5)) / num;
824
825         // Fix the signs so that we don't get -0.00.
826         low = Math.max(low, 0.0);
827
828         // The display range of 0 to 0.5 is fairly arbitrary. So is the desired 0.05 per point.
829         let avg = val / num;
830         return {
831                 'val': avg,
832                 'lower_ci': low,
833                 'upper_ci': high,
834                 'min': 0.0,
835                 'max': 0.5,
836                 'desired': 0.05,
837                 'inverted': inverted,
838         };
839 }
840
841 function make_table_general(players) {
842         let rows = [];
843         {
844                 let header = document.createElement('tr');
845                 add_th(header, 'Player');
846                 add_th(header, '+/-');
847                 add_th(header, 'Soft +/-');
848                 add_th(header, 'O efficiency');
849                 add_th(header, 'D efficiency');
850                 add_th(header, 'Points played');
851                 rows.push(header);
852         }
853
854         for (const [q,p] of get_sorted_players(players)) {
855                 if (q === 'globals') continue;
856                 let row = document.createElement('tr');
857                 let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops - p.was_ds - p.stallouts;
858                 let soft_pm = p.offensive_soft_plus + p.defensive_soft_plus - p.offensive_soft_minus - p.defensive_soft_minus;
859                 let o_efficiency = make_efficiency_ci(p.offensive_points_won, p.offensive_points_completed, z);
860                 let d_efficiency = make_efficiency_ci(p.defensive_points_won, p.defensive_points_completed, z);
861                 let name = add_3cell(row, p.name, 'name');  // TODO: number?
862                 add_3cell(row, pm > 0 ? ('+' + pm) : pm);
863                 add_3cell(row, soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
864                 add_3cell_ci(row, o_efficiency);
865                 add_3cell_ci(row, d_efficiency);
866                 add_3cell(row, p.points_played);
867                 row.dataset.player = q;
868                 rows.push(row);
869         }
870
871         // Globals.
872         let globals = players['globals'];
873         let o_efficiency = make_efficiency_ci(globals.offensive_points_won, globals.offensive_points_completed, z);
874         let d_efficiency = make_efficiency_ci(globals.defensive_points_won, globals.defensive_points_completed, z);
875         let row = document.createElement('tr');
876         add_3cell(row, '');
877         add_3cell(row, '');
878         add_3cell(row, '');
879         add_3cell_ci(row, o_efficiency);
880         add_3cell_ci(row, d_efficiency);
881         add_3cell(row, globals.points_played);
882         rows.push(row);
883
884         return rows;
885 }
886
887 function make_table_offense(players) {
888         let rows = [];
889         {
890                 let header = document.createElement('tr');
891                 add_th(header, 'Player');
892                 add_th(header, 'Goals');
893                 add_th(header, 'Assists');
894                 add_th(header, 'Hockey assists');
895                 add_th(header, 'Throws');
896                 add_th(header, 'Throwaways');
897                 add_th(header, '%OK');
898                 add_th(header, 'Catches');
899                 add_th(header, 'Drops');
900                 add_th(header, 'D-ed');
901                 add_th(header, '%OK');
902                 add_th(header, 'Stalls');
903                 add_th(header, 'Soft +/-', 6);
904                 rows.push(header);
905         }
906
907         let goals = 0;
908         let num_throws = 0;
909         let throwaways = 0;
910         let catches = 0;
911         let drops = 0;
912         let was_ds = 0;
913         let stallouts = 0;
914         for (const [q,p] of get_sorted_players(players)) {
915                 if (q === 'globals') continue;
916                 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
917                 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
918
919                 throw_ok.format = 'percentage';
920                 catch_ok.format = 'percentage';
921
922                 // Desire at least 90% percentage. Fairly arbitrary.
923                 throw_ok.desired = 0.9;
924                 catch_ok.desired = 0.9;
925
926                 let row = document.createElement('tr');
927                 add_3cell(row, p.name, 'name');  // TODO: number?
928                 add_3cell(row, p.goals);
929                 add_3cell(row, p.assists);
930                 add_3cell(row, p.hockey_assists);
931                 add_3cell(row, p.num_throws);
932                 add_3cell(row, p.throwaways);
933                 add_3cell_ci(row, throw_ok);
934                 add_3cell(row, p.catches);
935                 add_3cell(row, p.drops);
936                 add_3cell(row, p.was_ds);
937                 add_3cell_ci(row, catch_ok);
938                 add_3cell(row, p.stallouts);
939                 add_3cell(row, '+' + p.offensive_soft_plus);
940                 add_3cell(row, '-' + p.offensive_soft_minus);
941                 row.dataset.player = q;
942                 rows.push(row);
943
944                 goals += p.goals;
945                 num_throws += p.num_throws;
946                 throwaways += p.throwaways;
947                 catches += p.catches;
948                 drops += p.drops;
949                 was_ds += p.was_ds;
950                 stallouts += p.stallouts;
951         }
952
953         // Globals.
954         let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
955         let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
956         throw_ok.format = 'percentage';
957         catch_ok.format = 'percentage';
958         throw_ok.desired = 0.9;
959         catch_ok.desired = 0.9;
960
961         let row = document.createElement('tr');
962         add_3cell(row, '');
963         add_3cell(row, goals);
964         add_3cell(row, '');
965         add_3cell(row, '');
966         add_3cell(row, num_throws);
967         add_3cell(row, throwaways);
968         add_3cell_ci(row, throw_ok);
969         add_3cell(row, catches);
970         add_3cell(row, drops);
971         add_3cell(row, was_ds);
972         add_3cell_ci(row, catch_ok);
973         add_3cell(row, stallouts);
974         add_3cell(row, '');
975         add_3cell(row, '');
976         rows.push(row);
977
978         return rows;
979 }
980
981 function make_table_defense(players) {
982         let rows = [];
983         {
984                 let header = document.createElement('tr');
985                 add_th(header, 'Player');
986                 add_th(header, 'Ds');
987                 add_th(header, 'Pulls');
988                 add_th(header, 'OOB pulls');
989                 add_th(header, 'OOB%');
990                 add_th(header, 'Avg. hang time (IB)');
991                 add_th(header, 'Callahans');
992                 add_th(header, 'Soft +/-', 6);
993                 rows.push(header);
994         }
995
996         let defenses = 0;
997         let pulls = 0;
998         let oob_pulls = 0;
999         let sum_sum_time = 0;
1000         let callahans = 0;
1001
1002         for (const [q,p] of get_sorted_players(players)) {
1003                 if (q === 'globals') continue;
1004                 let sum_time = 0;
1005                 for (const t of p.pull_times) {
1006                         sum_time += t;
1007                 }
1008                 let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
1009                 let oob_pct = 100 * p.oob_pulls / p.pulls;
1010
1011                 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
1012                 ci_oob.format = 'percentage';
1013                 ci_oob.desired = 0.2;  // Arbitrary.
1014                 ci_oob.inverted = true;
1015
1016                 let row = document.createElement('tr');
1017                 add_3cell(row, p.name, 'name');  // TODO: number?
1018                 add_3cell(row, p.defenses);
1019                 add_3cell(row, p.pulls);
1020                 add_3cell(row, p.oob_pulls);
1021                 add_3cell_ci(row, ci_oob);
1022                 if (p.pulls > p.oob_pulls) {
1023                         add_3cell(row, avg_time.toFixed(1) + ' sec');
1024                 } else {
1025                         add_3cell(row, 'N/A');
1026                 }
1027                 add_3cell(row, p.callahans);
1028                 add_3cell(row, '+' + p.defensive_soft_plus);
1029                 add_3cell(row, '-' + p.defensive_soft_minus);
1030                 row.dataset.player = q;
1031                 rows.push(row);
1032
1033                 defenses += p.defenses;
1034                 pulls += p.pulls;
1035                 oob_pulls += p.oob_pulls;
1036                 sum_sum_time += sum_time;
1037                 callahans += p.callahans;
1038         }
1039
1040         // Globals.
1041         let ci_oob = make_binomial_ci(oob_pulls, pulls, z);
1042         ci_oob.format = 'percentage';
1043         ci_oob.desired = 0.2;  // Arbitrary.
1044         ci_oob.inverted = true;
1045
1046         let avg_time = 1e-3 * sum_sum_time / (pulls - oob_pulls);
1047         let oob_pct = 100 * oob_pulls / pulls;
1048
1049         let row = document.createElement('tr');
1050         add_3cell(row, '');
1051         add_3cell(row, defenses);
1052         add_3cell(row, pulls);
1053         add_3cell(row, oob_pulls);
1054         add_3cell_ci(row, ci_oob);
1055         if (pulls > oob_pulls) {
1056                 add_3cell(row, avg_time.toFixed(1) + ' sec');
1057         } else {
1058                 add_3cell(row, 'N/A');
1059         }
1060         add_3cell(row, callahans);
1061         add_3cell(row, '');
1062         add_3cell(row, '');
1063         rows.push(row);
1064
1065         return rows;
1066 }
1067
1068 function make_table_playing_time(players) {
1069         let rows = [];
1070         {
1071                 let header = document.createElement('tr');
1072                 add_th(header, 'Player');
1073                 add_th(header, 'Points played');
1074                 add_th(header, 'Time played');
1075                 add_th(header, 'O time');
1076                 add_th(header, 'D time');
1077                 add_th(header, 'Time on field');
1078                 add_th(header, 'O points');
1079                 add_th(header, 'D points');
1080                 rows.push(header);
1081         }
1082
1083         for (const [q,p] of get_sorted_players(players)) {
1084                 if (q === 'globals') continue;
1085                 let row = document.createElement('tr');
1086                 add_3cell(row, p.name, 'name');  // TODO: number?
1087                 add_3cell(row, p.points_played);
1088                 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
1089                 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
1090                 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
1091                 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
1092                 add_3cell(row, p.offensive_points_completed);
1093                 add_3cell(row, p.defensive_points_completed);
1094                 row.dataset.player = q;
1095                 rows.push(row);
1096         }
1097
1098         // Globals.
1099         let globals = players['globals'];
1100         let row = document.createElement('tr');
1101         add_3cell(row, '');
1102         add_3cell(row, globals.points_played);
1103         add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
1104         add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
1105         add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
1106         add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
1107         add_3cell(row, globals.offensive_points_completed);
1108         add_3cell(row, globals.defensive_points_completed);
1109         rows.push(row);
1110
1111         return rows;
1112 }
1113
1114 function make_table_per_point(players) {
1115         let rows = [];
1116         {
1117                 let header = document.createElement('tr');
1118                 add_th(header, 'Player');
1119                 add_th(header, 'Goals');
1120                 add_th(header, 'Assists');
1121                 add_th(header, 'Hockey assists');
1122                 add_th(header, 'Ds');
1123                 add_th(header, 'Throwaways');
1124                 add_th(header, 'Recv. errors');
1125                 add_th(header, 'Touches');
1126                 rows.push(header);
1127         }
1128
1129         let goals = 0;
1130         let assists = 0;
1131         let hockey_assists = 0;
1132         let defenses = 0;
1133         let throwaways = 0;
1134         let receiver_errors = 0;
1135         let touches = 0;
1136         for (const [q,p] of get_sorted_players(players)) {
1137                 if (q === 'globals') continue;
1138
1139                 // Can only happen once per point, so these are binomials.
1140                 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
1141                 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
1142                 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
1143                 // Arbitrarily desire at least 10% (not everybody can score or assist).
1144                 ci_goals.desired = 0.1;
1145                 ci_assists.desired = 0.1;
1146                 ci_hockey_assists.desired = 0.1;
1147
1148                 let row = document.createElement('tr');
1149                 add_3cell(row, p.name, 'name');  // TODO: number?
1150                 add_3cell_ci(row, ci_goals);
1151                 add_3cell_ci(row, ci_assists);
1152                 add_3cell_ci(row, ci_hockey_assists);
1153                 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
1154                 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
1155                 add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
1156                 if (p.points_played > 0) {
1157                         add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
1158                 } else {
1159                         add_3cell(row, 'N/A');
1160                 }
1161                 row.dataset.player = q;
1162                 rows.push(row);
1163
1164                 goals += p.goals;
1165                 assists += p.assists;
1166                 hockey_assists += p.hockey_assists;
1167                 defenses += p.defenses;
1168                 throwaways += p.throwaways;
1169                 receiver_errors += p.drops + p.was_ds;
1170                 touches += p.touches;
1171         }
1172
1173         // Globals.
1174         let globals = players['globals'];
1175         let row = document.createElement('tr');
1176         add_3cell(row, '');
1177         if (globals.points_played > 0) {
1178                 let ci_goals = make_binomial_ci(goals, globals.points_played, z);
1179                 let ci_assists = make_binomial_ci(assists, globals.points_played, z);
1180                 let ci_hockey_assists = make_binomial_ci(hockey_assists, globals.points_played, z);
1181                 ci_goals.desired = 0.5;
1182                 ci_assists.desired = 0.5;
1183                 ci_hockey_assists.desired = 0.5;
1184
1185                 add_3cell_ci(row, ci_goals);
1186                 add_3cell_ci(row, ci_assists);
1187                 add_3cell_ci(row, ci_hockey_assists);
1188
1189                 add_3cell_ci(row, make_poisson_ci(defenses, globals.points_played, z));
1190                 add_3cell_ci(row, make_poisson_ci(throwaways, globals.points_played, z, true));
1191                 add_3cell_ci(row, make_poisson_ci(receiver_errors, globals.points_played, z, true));
1192
1193                 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
1194         } else {
1195                 add_3cell_with_filler_ci(row, 'N/A');
1196                 add_3cell_with_filler_ci(row, 'N/A');
1197                 add_3cell_with_filler_ci(row, 'N/A');
1198                 add_3cell_with_filler_ci(row, 'N/A');
1199                 add_3cell_with_filler_ci(row, 'N/A');
1200                 add_3cell_with_filler_ci(row, 'N/A');
1201                 add_3cell(row, 'N/A');
1202         }
1203         rows.push(row);
1204
1205         return rows;
1206 }
1207
1208 function open_filter_menu(click_to_add_div) {
1209         document.getElementById('filter-submenu').style.display = 'none';
1210         let filter_div = click_to_add_div.parentElement;
1211         let filter_id = filter_div.dataset.filterId;
1212
1213         let menu = document.getElementById('filter-add-menu');
1214         menu.parentElement.removeChild(menu);
1215         filter_div.appendChild(menu);
1216         menu.style.display = 'block';
1217         menu.replaceChildren();
1218
1219         // Place the menu directly under the “click to add” label;
1220         // we don't anchor it since that label will move around
1221         // and the menu shouldn't.
1222         let rect = click_to_add_div.getBoundingClientRect();
1223         menu.style.left = rect.left + 'px';
1224         menu.style.top = (rect.bottom + 10) + 'px';
1225
1226         let filterset = global_filters[filter_id];
1227         if (filterset === undefined) {
1228                 global_filters[filter_id] = filterset = [];
1229         }
1230
1231         add_menu_item(filter_div, filterset, menu, 0, 'match', 'Match (any)');
1232         add_menu_item(filter_div, filterset, menu, 1, 'player_any', 'Player on field (any)');
1233         add_menu_item(filter_div, filterset, menu, 2, 'player_all', 'Player on field (all)');
1234         add_menu_item(filter_div, filterset, menu, 3, 'formation_offense', 'Offense played (any)');
1235         add_menu_item(filter_div, filterset, menu, 4, 'formation_defense', 'Defense played (any)');
1236         add_menu_item(filter_div, filterset, menu, 5, 'starting_on', 'Starting on');
1237         add_menu_item(filter_div, filterset, menu, 6, 'gender_ratio', 'Gender ratio');
1238 }
1239
1240 function add_menu_item(filter_div, filterset, menu, menu_idx, filter_type, title) {
1241         let item = document.createElement('div');
1242         item.classList.add('option');
1243         item.appendChild(document.createTextNode(title));
1244
1245         let arrow = document.createElement('div');
1246         arrow.classList.add('arrow');
1247         arrow.textContent = '▸';
1248         item.appendChild(arrow);
1249
1250         menu.appendChild(item);
1251
1252         item.addEventListener('click', (e) => { show_submenu(filter_div, filterset, menu_idx, null, filter_type); });
1253 }
1254
1255 function find_all_ratios(json)
1256 {
1257         let ratios = {};
1258         let players = {};
1259         for (const player of json['players']) {
1260                 players[player['player_id']] = {
1261                         'gender': player['gender'],
1262                         'last_point_seen': null,
1263                 };
1264         }
1265         for (const match of json['matches']) {
1266                 for (const [q,p] of Object.entries(players)) {
1267                         p.on_field_since = null;
1268                 }
1269                 for (const e of match['events']) {
1270                         let p = players[e['player']];
1271                         let type = e['type'];
1272                         if (type === 'in') {
1273                                 p.on_field_since = 1;
1274                         } else if (type === 'out') {
1275                                 p.on_field_since = null;
1276                         } else if (type === 'pull' || type == 'their_pull') {  // We assume no cross-gender subs for now.
1277                                 let code = find_gender_ratio_code(players);
1278                                 if (ratios[code] === undefined) {
1279                                         ratios[code] = code;
1280                                         if (code !== '4 F, 3 M' && code !== '4 M, 3 F' && code !== '3 M, 2 F' && code !== '3 F, 2 M') {
1281                                                 console.log('Unexpected gender ratio ' + code + ' first seen at: ' +
1282                                                             match['description'] + ', ' + format_time(e['t']));
1283                                         }
1284                                 }
1285                         }
1286                 }
1287         }
1288         return ratios;
1289 }
1290
1291 function show_submenu(filter_div, filterset, menu_idx, pill, filter_type) {
1292         let submenu = document.getElementById('filter-submenu');
1293
1294         // Move to the same place as the top-level menu.
1295         submenu.parentElement.removeChild(submenu);
1296         document.getElementById('filter-add-menu').parentElement.appendChild(submenu);
1297
1298         let subitems = [];
1299         const filter = find_filter(filterset, filter_type);
1300
1301         let choices = [];
1302         if (filter_type === 'match') {
1303                 for (const match of global_json['matches']) {
1304                         choices.push({
1305                                 'title': match['description'],
1306                                 'id': match['match_id']
1307                         });
1308                 }
1309         } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1310                 for (const player of global_json['players']) {
1311                         choices.push({
1312                                 'title': player['name'],
1313                                 'id': player['player_id']
1314                         });
1315                 }
1316         } else if (filter_type === 'formation_offense') {
1317                 choices.push({
1318                         'title': '(None/unknown)',
1319                         'id': 0,
1320                 });
1321                 for (const formation of global_json['formations']) {
1322                         if (formation['offense']) {
1323                                 choices.push({
1324                                         'title': formation['name'],
1325                                         'id': formation['formation_id']
1326                                 });
1327                         }
1328                 }
1329         } else if (filter_type === 'formation_defense') {
1330                 choices.push({
1331                         'title': '(None/unknown)',
1332                         'id': 0,
1333                 });
1334                 for (const formation of global_json['formations']) {
1335                         if (!formation['offense']) {
1336                                 choices.push({
1337                                         'title': formation['name'],
1338                                         'id': formation['formation_id']
1339                                 });
1340                         }
1341                 }
1342         } else if (filter_type === 'starting_on') {
1343                 choices.push({
1344                         'title': 'Offense',
1345                         'id': false,  // last_pull_was_ours
1346                 });
1347                 choices.push({
1348                         'title': 'Defense',
1349                         'id': true,  // last_pull_was_ours
1350                 });
1351         } else if (filter_type === 'gender_ratio') {
1352                 for (const [title, id] of Object.entries(find_all_ratios(global_json)).sort()) {
1353                         choices.push({
1354                                 'title': title,
1355                                 'id': id,
1356                         });
1357                 }
1358         }
1359
1360         for (const choice of choices) {
1361                 let label = document.createElement('label');
1362
1363                 let subitem = document.createElement('div');
1364                 subitem.classList.add('option');
1365
1366                 let check = document.createElement('input');
1367                 check.setAttribute('type', 'checkbox');
1368                 check.setAttribute('id', 'choice' + choice.id);
1369                 if (filter !== null && filter.elements.has(choice.id)) {
1370                         check.setAttribute('checked', 'checked');
1371                 }
1372                 check.addEventListener('change', (e) => { checkbox_changed(filter_div, filterset, e, filter_type, choice.id); });
1373
1374                 subitem.appendChild(check);
1375                 subitem.appendChild(document.createTextNode(choice.title));
1376
1377                 label.appendChild(subitem);
1378                 subitems.push(label);
1379         }
1380         submenu.replaceChildren(...subitems);
1381         submenu.style.display = 'block';
1382
1383         if (pill !== null) {
1384                 let rect = pill.getBoundingClientRect();
1385                 submenu.style.top = (rect.bottom + 10) + 'px';
1386                 submenu.style.left = rect.left + 'px';
1387         } else {
1388                 // Position just outside the selected menu.
1389                 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1390                 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1391                 submenu.style.left = (rect.right - 1) + 'px';
1392         }
1393 }
1394
1395 // Find the right filter, if it exists.
1396 function find_filter(filterset, filter_type) {
1397         for (let f of filterset) {
1398                 if (f.type === filter_type) {
1399                         return f;
1400                 }
1401         }
1402         return null;
1403 }
1404
1405 // Equivalent to Array.prototype.filter, but in-place.
1406 function inplace_filter(arr, cond) {
1407         let j = 0;
1408         for (let i = 0; i < arr.length; ++i) {
1409                 if (cond(arr[i])) {
1410                         arr[j++] = arr[i];
1411                 }
1412         }
1413         arr.length = j;
1414 }
1415
1416 function add_new_filterset() {
1417         let template = document.querySelector('.filter');  // First one is fine.
1418         let div = template.cloneNode(true);
1419         let add_menu = div.querySelector('#filter-add-menu');
1420         if (add_menu !== null) {
1421                 div.removeChild(add_menu);
1422         }
1423         let submenu = div.querySelector('#filter-submenu');
1424         if (submenu !== null) {
1425                 div.removeChild(submenu);
1426         }
1427         div.querySelector('.filters').replaceChildren();
1428         div.dataset.filterId = next_filterset_id++;
1429         template.parentElement.appendChild(div);
1430 }
1431
1432 function try_gc_filter_menus(cheap) {
1433         let empties = [];
1434         let divs = [];
1435         for (const filter_div of document.querySelectorAll('.filter')) {
1436                 let id = filter_div.dataset.filterId;
1437                 divs.push(filter_div);
1438                 empties.push(global_filters[id] === undefined || global_filters[id].length === 0);
1439         }
1440         let last_div = divs[empties.length - 1];
1441         if (cheap) {
1442                 // See if we have two empty filter lists at the bottom of the list;
1443                 // if so, we can remove one without it looking funny in the UI.
1444                 // If not, we'll have to wait until closing the menu.
1445                 // (The menu is positioned at the second-last one, so we can
1446                 // remove the last one without issue.)
1447                 if (empties.length >= 2 && empties[empties.length - 2] && empties[empties.length - 1]) {
1448                         delete global_filters[last_div.dataset.filterId];
1449                         last_div.parentElement.removeChild(last_div);
1450                 }
1451         } else {
1452                 // This is a different situation from try_cheap_gc(), where we should
1453                 // remove the one _not_ last. We might need to move the menu to the last one,
1454                 // though, so it doesn't get lost.
1455                 for (let i = 0; i < empties.length - 1; ++i) {
1456                         if (!empties[i]) {
1457                                 continue;
1458                         }
1459                         let div = divs[i];
1460                         delete global_filters[div.dataset.filterId];
1461                         let add_menu = div.querySelector('#filter-add-menu');
1462                         if (add_menu !== null) {
1463                                 div.removeChild(add_menu);
1464                                 last_div.appendChild(add_menu);
1465                         }
1466                         let submenu = div.querySelector('#filter-submenu');
1467                         if (submenu !== null) {
1468                                 div.removeChild(submenu);
1469                                 last_div.appendChild(submenu);
1470                         }
1471                         div.parentElement.removeChild(div);
1472                 }
1473         }
1474 }
1475
1476 function checkbox_changed(filter_div, filterset, e, filter_type, id) {
1477         let filter = find_filter(filterset, filter_type);
1478         let pills_div = filter_div.querySelector('.filters');
1479         if (e.target.checked) {
1480                 // See if we must create a new empty filterset (since this went from
1481                 // empty to non-empty).
1482                 if (filterset.length === 0) {
1483                         add_new_filterset();
1484                 }
1485
1486                 // See if we must add a new filter to the list.
1487                 if (filter === null) {
1488                         filter = {
1489                                 'type': filter_type,
1490                                 'elements': new Set([ id ]),
1491                         };
1492                         filter.pill = make_filter_pill(filter_div, filterset, filter);
1493                         filterset.push(filter);
1494                         pills_div.appendChild(filter.pill);
1495                 } else {
1496                         filter.elements.add(id);
1497                         let new_pill = make_filter_pill(filter_div, filterset, filter);
1498                         pills_div.replaceChild(new_pill, filter.pill);
1499                         filter.pill = new_pill;
1500                 }
1501         } else {
1502                 filter.elements.delete(id);
1503                 if (filter.elements.size === 0) {
1504                         pills_div.removeChild(filter.pill);
1505                         inplace_filter(filterset, f => f !== filter);
1506
1507                         if (filterset.length == 0) {
1508                                 try_gc_filter_menus(true);
1509                         }
1510                 } else {
1511                         let new_pill = make_filter_pill(filter_div, filterset, filter);
1512                         pills_div.replaceChild(new_pill, filter.pill);
1513                         filter.pill = new_pill;
1514                 }
1515         }
1516
1517         process_matches(global_json, global_filters);
1518 }
1519
1520 function make_filter_pill(filter_div, filterset, filter) {
1521         let pill = document.createElement('div');
1522         pill.classList.add('filter-pill');
1523         let text;
1524         if (filter.type === 'match') {
1525                 text = 'Match: ';
1526
1527                 let all_names = [];
1528                 for (const match_id of filter.elements) {
1529                         all_names.push(find_match(match_id)['description']);
1530                 }
1531                 let common_prefix = find_common_prefix_of_all(all_names);
1532                 if (common_prefix !== null) {
1533                         text += common_prefix + '(';
1534                 }
1535
1536                 let first = true;
1537                 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1538                 for (const match_id of sorted_match_id) {
1539                         if (!first) {
1540                                 text += ', ';
1541                         }
1542                         let desc = find_match(match_id)['description'];
1543                         if (common_prefix === null) {
1544                                 text += desc;
1545                         } else {
1546                                 text += desc.substr(common_prefix.length);
1547                         }
1548                         first = false;
1549                 }
1550
1551                 if (common_prefix !== null) {
1552                         text += ')';
1553                 }
1554         } else if (filter.type === 'player_any') {
1555                 text = 'Player (any): ';
1556                 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1557                 let first = true;
1558                 for (const player_id of sorted_players) {
1559                         if (!first) {
1560                                 text += ', ';
1561                         }
1562                         text += find_player(player_id)['name'];
1563                         first = false;
1564                 }
1565         } else if (filter.type === 'player_all') {
1566                 text = 'Players: ';
1567                 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1568                 let first = true;
1569                 for (const player_id of sorted_players) {
1570                         if (!first) {
1571                                 text += ' AND ';
1572                         }
1573                         text += find_player(player_id)['name'];
1574                         first = false;
1575                 }
1576         } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1577                 const offense = (filter.type === 'formation_offense');
1578                 if (offense) {
1579                         text = 'Offense: ';
1580                 } else {
1581                         text = 'Defense: ';
1582                 }
1583
1584                 let all_names = [];
1585                 for (const formation_id of filter.elements) {
1586                         all_names.push(find_formation(formation_id)['name']);
1587                 }
1588                 let common_prefix = find_common_prefix_of_all(all_names);
1589                 if (common_prefix !== null) {
1590                         text += common_prefix + '(';
1591                 }
1592
1593                 let first = true;
1594                 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1595                 for (const formation_id of sorted_formation_id) {
1596                         if (!first) {
1597                                 ktext += ', ';
1598                         }
1599                         let desc = find_formation(formation_id)['name'];
1600                         if (common_prefix === null) {
1601                                 text += desc;
1602                         } else {
1603                                 text += desc.substr(common_prefix.length);
1604                         }
1605                         first = false;
1606                 }
1607
1608                 if (common_prefix !== null) {
1609                         text += ')';
1610                 }
1611         } else if (filter.type === 'starting_on') {
1612                 text = 'Starting on: ';
1613
1614                 if (filter.elements.has(false) && filter.elements.has(true)) {
1615                         text += 'Any';
1616                 } else if (filter.elements.has(false)) {
1617                         text += 'Offense';
1618                 } else {
1619                         text += 'Defense';
1620                 }
1621         } else if (filter.type === 'gender_ratio') {
1622                 text = 'Gender: ';
1623
1624                 let first = true;
1625                 for (const name of Array.from(filter.elements).sort()) {
1626                         if (!first) {
1627                                 text += '; ';
1628                         }
1629                         text += name;  // FIXME
1630                         first = false;
1631                 }
1632         }
1633
1634         let text_node = document.createElement('span');
1635         text_node.innerText = text;
1636         text_node.addEventListener('click', (e) => show_submenu(filter_div, filterset, null, pill, filter.type));
1637         pill.appendChild(text_node);
1638
1639         pill.appendChild(document.createTextNode(' '));
1640
1641         let delete_node = document.createElement('span');
1642         delete_node.innerText = '✖';
1643         delete_node.addEventListener('click', (e) => {
1644                 // Delete this filter entirely.
1645                 pill.parentElement.removeChild(pill);
1646                 inplace_filter(filterset, f => f !== filter);
1647                 if (filterset.length == 0) {
1648                         try_gc_filter_menus(false);
1649                 }
1650                 process_matches(global_json, global_filters);
1651
1652                 let add_menu = document.getElementById('filter-add-menu');
1653                 let add_submenu = document.getElementById('filter-submenu');
1654                 add_menu.style.display = 'none';
1655                 add_submenu.style.display = 'none';
1656         });
1657         pill.appendChild(delete_node);
1658         pill.style.cursor = 'pointer';
1659
1660         return pill;
1661 }
1662
1663 function make_filter_marker(filterset) {
1664         let text = '';
1665         for (const filter of filterset) {
1666                 if (text !== '') {
1667                         text += ',';
1668                 }
1669                 if (filter.type === 'match') {
1670                         let all_names = [];
1671                         for (const match of global_json['matches']) {
1672                                 all_names.push(match['description']);
1673                         }
1674                         let common_prefix = find_common_prefix_of_all(all_names);
1675
1676                         let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1677                         for (const match_id of sorted_match_id) {
1678                                 let desc = find_match(match_id)['description'];
1679                                 if (common_prefix === null) {
1680                                         text += desc.substr(0, 3);
1681                                 } else {
1682                                         text += desc.substr(common_prefix.length, 3);
1683                                 }
1684                         }
1685                 } else if (filter.type === 'player_any' || filter.type === 'player_all') {
1686                         let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1687                         for (const player_id of sorted_players) {
1688                                 text += find_player(player_id)['name'].substr(0, 3);
1689                         }
1690                 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1691                         let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1692                         for (const formation_id of sorted_formation_id) {
1693                                 text += find_formation(formation_id)['name'].substr(0, 3);
1694                         }
1695                 } else if (filter.type === 'starting_on') {
1696                         if (filter.elements.has(false) && filter.elements.has(true)) {
1697                                 // Nothing.
1698                         } else if (filter.elements.has(false)) {
1699                                 text += 'O';
1700                         } else {
1701                                 text += 'D';
1702                         }
1703                 } else if (filter.type === 'gender_ratio') {
1704                         let first = true;
1705                         for (const name of Array.from(filter.elements).sort()) {
1706                                 if (!first) {
1707                                         text += '; ';
1708                                 }
1709                                 text += name.replaceAll(' ', '').substr(0, 2);  // 4 F, 3M -> 4 F.
1710                                 first = false;
1711                         }
1712                 }
1713         }
1714         return text;
1715 }
1716
1717 function find_common_prefix(a, b) {
1718         let ret = '';
1719         for (let i = 0; i < Math.min(a.length, b.length); ++i) {
1720                 if (a[i] === b[i]) {
1721                         ret += a[i];
1722                 } else {
1723                         break;
1724                 }
1725         }
1726         return ret;
1727 }
1728
1729 function find_common_prefix_of_all(values) {
1730         if (values.length < 2) {
1731                 return null;
1732         }
1733         let common_prefix = null;
1734         for (const desc of values) {
1735                 if (common_prefix === null) {
1736                         common_prefix = desc;
1737                 } else {
1738                         common_prefix = find_common_prefix(common_prefix, desc);
1739                 }
1740         }
1741         if (common_prefix.length >= 3) {
1742                 return common_prefix;
1743         } else {
1744                 return null;
1745         }
1746 }
1747
1748 function find_match(match_id) {
1749         for (const match of global_json['matches']) {
1750                 if (match['match_id'] === match_id) {
1751                         return match;
1752                 }
1753         }
1754         return null;
1755 }
1756
1757 function find_formation(formation_id) {
1758         for (const formation of global_json['formations']) {
1759                 if (formation['formation_id'] === formation_id) {
1760                         return formation;
1761                 }
1762         }
1763         return null;
1764 }
1765
1766 function find_player(player_id) {
1767         for (const player of global_json['players']) {
1768                 if (player['player_id'] === player_id) {
1769                         return player;
1770                 }
1771         }
1772         return null;
1773 }
1774
1775 function player_pos(player_id) {
1776         let i = 0;
1777         for (const player of global_json['players']) {
1778                 if (player['player_id'] === player_id) {
1779                         return i;
1780                 }
1781                 ++i;
1782         }
1783         return null;
1784 }
1785
1786 function keep_match(match_id, filters) {
1787         for (const filter of filters) {
1788                 if (filter.type === 'match') {
1789                         return filter.elements.has(match_id);
1790                 }
1791         }
1792         return true;
1793 }
1794
1795 // Returns a map of e.g. F => 4, M => 3.
1796 function find_gender_ratio(players) {
1797         let map = {};
1798         for (const [q,p] of Object.entries(players)) {
1799                 if (p.on_field_since === null) {
1800                         continue;
1801                 }
1802                 let gender = p.gender;
1803                 if (gender === '' || gender === undefined || gender === null) {
1804                         gender = '?';
1805                 }
1806                 if (map[gender] === undefined) {
1807                         map[gender] = 1;
1808 q               } else {
1809                         ++map[gender];
1810                 }
1811         }
1812         return map;
1813 }
1814
1815 function find_gender_ratio_code(players) {
1816         let map = find_gender_ratio(players);
1817         let all_genders = Array.from(Object.keys(map)).sort(
1818                 (a,b) => {
1819                         if (map[a] !== map[b]) {
1820                                 return map[b] - map[a];  // Reverse numeric.
1821                         } else if (a < b) {
1822                                 return -1;
1823                         } else if (a > b) {
1824                                 return 1;
1825                         } else {
1826                                 return 0;
1827                         }
1828                 });
1829         let code = '';
1830         for (const g of all_genders) {
1831                 if (code !== '') {
1832                         code += ', ';
1833                 }
1834                 code += map[g];
1835                 code += ' ';
1836                 code += g;
1837         }
1838         return code;
1839 }
1840
1841 // null if none (e.g., if playing 3–3).
1842 function find_predominant_gender(players) {
1843         let max = 0;
1844         let predominant_gender = null;
1845         for (const [gender, num] of Object.entries(find_gender_ratio(players))) {
1846                 if (num > max) {
1847                         max = num;
1848                         predominant_gender = gender;
1849                 } else if (num == max) {
1850                         predominant_gender = null;  // At least two have the same.
1851                 }
1852         }
1853         return predominant_gender;
1854 }
1855
1856 function find_num_players_on_field(players) {
1857         let num = 0;
1858         for (const [q,p] of Object.entries(players)) {
1859                 if (p.on_field_since !== null) {
1860                         ++num;
1861                 }
1862         }
1863         return num;
1864 }
1865
1866 function filter_passes(players, formations_used_this_point, last_pull_was_ours, filter) {
1867         if (filter.type === 'player_any') {
1868                 for (const p of Array.from(filter.elements)) {
1869                         if (players[p].on_field_since !== null) {
1870                                 return true;
1871                         }
1872                 }
1873                 return false;
1874         } else if (filter.type === 'player_all') {
1875                 for (const p of Array.from(filter.elements)) {
1876                         if (players[p].on_field_since === null) {
1877                                 return false;
1878                         }
1879                 }
1880                 return true;
1881         } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1882                 for (const f of Array.from(filter.elements)) {
1883                         if (formations_used_this_point.has(f)) {
1884                                 return true;
1885                         }
1886                 }
1887                 return false;
1888         } else if (filter.type === 'starting_on') {
1889                 return filter.elements.has(last_pull_was_ours);
1890         } else if (filter.type === 'gender_ratio') {
1891                 return filter.elements.has(find_gender_ratio_code(players));
1892         }
1893         return true;
1894 }
1895
1896 function keep_event(players, formations_used_this_point, last_pull_was_ours, filters) {
1897         for (const filter of filters) {
1898                 if (!filter_passes(players, formations_used_this_point, last_pull_was_ours, filter)) {
1899                         return false;
1900                 }
1901         }
1902         return true;
1903 }
1904
1905 // Heuristic: If we go at least ten seconds without the possession changing
1906 // or the operator specifying some other formation, we probably play the
1907 // same formation as the last point.
1908 function should_reuse_last_formation(events, t) {
1909         for (const e of events) {
1910                 if (e.t <= t) {
1911                         continue;
1912                 }
1913                 if (e.t > t + 10000) {
1914                         break;
1915                 }
1916                 const type = e.type;
1917                 if (type === 'their_goal' || type === 'goal' ||
1918                     type === 'set_defense' || type === 'set_offense' ||
1919                     type === 'throwaway' || type === 'their_throwaway' ||
1920                     type === 'drop' || type === 'was_d' || type === 'stallout' || type === 'defense' || type === 'interception' ||
1921                     type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
1922                     type === 'formation_offense' || type === 'formation_defense') {
1923                         return false;
1924                 }
1925         }
1926         return true;
1927 }
1928
1929 function possibly_close_menu(e) {
1930         if (e.target.closest('.filter-click-to-add') === null &&
1931             e.target.closest('#filter-add-menu') === null &&
1932             e.target.closest('#filter-submenu') === null &&
1933             e.target.closest('.filter-pill') === null) {
1934                 let add_menu = document.getElementById('filter-add-menu');
1935                 let add_submenu = document.getElementById('filter-submenu');
1936                 add_menu.style.display = 'none';
1937                 add_submenu.style.display = 'none';
1938                 try_gc_filter_menus(false);
1939         }
1940 }
1941
1942 let global_sort = {};
1943
1944 function sort_by(th) {
1945         let tr = th.parentElement;
1946         let child_idx = 0;
1947         for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
1948                 let element = tr.children[column_idx];
1949                 if (element === th) {
1950                         ++child_idx;  // Pad.
1951                         break;
1952                 }
1953                 if (element.hasAttribute('colspan')) {
1954                         child_idx += parseInt(element.getAttribute('colspan'));
1955                 } else {
1956                         ++child_idx;
1957                 }
1958         }
1959
1960         global_sort = {};
1961         let table = tr.parentElement;
1962         for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) {  // Skip header and globals.
1963                 let row = table.children[row_idx];
1964                 let player = parseInt(row.dataset.player);
1965                 let value = row.children[child_idx].textContent;
1966                 global_sort[player] = value;
1967         }
1968 }
1969
1970 function get_sorted_players(players)
1971 {
1972         let p = Object.entries(players);
1973         if (global_sort.length !== 0) {
1974                 p.sort((a,b) => {
1975                         let ai = parseFloat(global_sort[a[0]]);
1976                         let bi = parseFloat(global_sort[b[0]]);
1977                         if (ai == ai && bi == bi) {
1978                                 return bi - ai;  // Reverse numeric.
1979                         } else if (global_sort[a[0]] < global_sort[b[0]]) {
1980                                 return -1;
1981                         } else if (global_sort[a[0]] > global_sort[b[0]]) {
1982                                 return 1;
1983                         } else {
1984                                 return 0;
1985                         }
1986                 });
1987         }
1988         return p;
1989 }