#!/usr/bin/perl

# truncate a .t file to a specified number of rounds

use strict;
use warnings;

sub Main ();

Main;

sub Main () {
  my $rounds = shift @::ARGV;
  die "Usage: $0 rounds [file.t...]\n"
    unless (defined $rounds) && $rounds =~ /^\d+$/;
  while (<>) {
    next if /^#/;
    my ($namepair, $scores, $etcs) = split(/\s*;\s*/, $_, 3);
    # pairings
    $namepair =~ /^(\D+\d+\s*)(.*)/ || die "Can't parse: $namepair";
    my $namerating = $1;
    my $pair = $2;
    my (@pair) = split(/\s+/, $pair);
    splice(@pair, $rounds) if @pair > $rounds;
    my (@scores) = split(/\s+/, $scores);
    splice(@scores, $rounds) if @scores > $rounds;
    if ($etcs) {
      my (@etc) = split(/\s*;\s*/, $etcs);
      for my $etc (@etc) {
	my ($type, @args) = split(/\s+/, $etc);
	if ($type =~ /^(?:board|p12)/) {
	  splice(@args, $rounds) if @args > $rounds;
	  }
	$etc = join(' ', $type, @args);
        }
      $etcs = join(' ; ', '', @etc);
      }
    else {
      $etcs = '';
      }
    print "$namerating @pair ; @scores$etcs\n";
    }
  }
