#!/usr/bin/perl

# See README for licensing information.

# Copyright 2006 Alexandre Oliva

# This file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.

use strict;
use warnings;

my @choices = ();
my @votes = ();
my @expvotes = ();
my @voteschoices = ();
my $num_choices = 1;
    
$choices[0] = '0';

while (<>) {
  push @votes, $_;
  my @prefs = split /[>\n]/, $_;
  my @voted = ();
  foreach (split /[>\n]/, $_) {
    foreach my $vote (split /=/, $_) {
      die 'choices must be numbers' unless $vote =~ /^(-1|0|[1-9][0-9]*)$/;
      die 'choices must be greater than -1' unless ($vote >= -1);
      die 'choices must not be repeated' if ($voted[$vote+1]);
      $voted[$vote+1] = 1;
      while ($vote >= $num_choices) {
	$choices[$num_choices] = $num_choices;
	++$num_choices;
      }
    }
  }
  push @voteschoices, \@voted;
}

for (@votes) {
  my @voted = @{$voteschoices[$#expvotes + 1]};
  my @prefs = ();
  foreach (split /[>\n]/, $_) {
    my @eqprefs = ();
    foreach my $vote (split /=/, $_) {
      if ($vote == 0) {
	for (my $i = 1; $i < $num_choices; ++$i) {
	  push @eqprefs, $i unless defined $voted[$i+1];
	}
      } else {
	push @eqprefs, $vote;
      }
    }
    push @prefs, join ('=', @eqprefs) if $#eqprefs >= 0;
  }
  if (!defined $voted[0+1]) {
    my @eqprefs = ();
    for (my $i = 1; $i < $num_choices; ++$i) {
      push @eqprefs, $i unless defined $voted[$i+1];
    }
    push @prefs, join ('=', @eqprefs) if $#eqprefs >= 0;
  }
  if (!defined $voted[-1+1]) {
    push @prefs, '-1';
  }
  push @expvotes, join ('>', @prefs);
}

for (@expvotes) {
  print $_ . "\n";
}
