#!/usr/local/bin/perl -w
# Dan Boger
# first we calculate the correct shares from the data
# then we see if we have to fudge it.  
# If we do, fudge the first share.

use strict;
use List::Util qw/sum/;

while (<DATA>) {
  my @params = split ' ';
  print "\n@params ->\n  ";
  print join ", ", &fudge_numbers(@params);
}

sub fudge_numbers {
  my ($prec, @data) = @_;
  my @share;
  
  # find out total, in order to find %
  my $sum = sum @data;

  # caculate the shares
  while (defined(my $num = shift @data)) {
    push @share, sprintf("%0.${prec}f", $num / $sum * 100);
  }

  # fudge the first share to make the total add up to 100
  my $loc = 0;
  my $fudge = 1/10**$prec * (sum(@share)>100 ? -1 : 1);
  until (sum(@share) == 100) {
    $share[$loc++] += $fudge;
  }

  return @share;
}

__DATA__
1 100 100 100
0 100 100 100
2 100 100 100
2 7   7   7
1 30  30  10
1 50
2 20 0 10
