#!/usr/bin/perl
#: add commas to numbers on STDIN or from named files.
#======================================================================
# sburke@cpan.org Time-stamp: "2009-11-21 22:22:57 AKST sburke@cpan.org"

use strict; use warnings;
use constant TESTING => 0;
my $number_catcher =
  qr<
        ( [ \t]*   )
        ( \d{5,} )
    >x
;

while(<>) {
  TESTING and print "Got: $_";
      s<$number_catcher><commulate($`,$1,$2)>megx;
  TESTING ? print "  => $_\n" : print $_;
}


if(TESTING) {
  print "Running self-tests...\n";
  
  foreach my $test (
  
    [  "552523"    =>  "552,523"     ],
    [ "(552523)"   => "(552,523)"    ],
  
    [ "Q#(552523)" => "Q#(552,523)"  ],
  
    [ "abc 123456" => "abc 123,456"  ],
  
    ["!!2,523!!"   => "!!2,523!!"  ],
    ["2,523"       => "2,523"  ],
    ["!22,523!!"   => "!22,523!!"  ],
    ["!!22,523!!"  => "!!22,523!!"  ],
  
    ["789,552523"  => "789, 552,523"  ],
  
    [ "abc123456"  => "abc 123,456"  ],
    [ "abc123456!" => "abc 123,456!" ],
    [ "abc123456x" => "abc 123,456x" ],
  
    [  "552523"    =>  "552,523"     ],
  
  ) {
    my($in, $should_out) = @$test;
    my $out = $in;
    $out =~
      s<$number_catcher><commulate($`,$1,$2)>megx;
  
    if( $out eq $should_out ) {
      print qq[.ok.  "$in" => "$out"\n\n];
    } else {
      print qq[FAIL  "$in" => "$out", but should have been "$should_out"\n\n];
    }
  
  }
}

exit;

#======================================================================

sub commulate {
  my($well_before, $space, $i) = @_;

  TESTING and printf "  Got (%s)-[%s spaces]-(%s)\n",
    $_[0], length($_[1]), $_[2];

  while( $i =~ s/(\d)(\d\d\d)(\,|$)/$1,$2$3/g ) {
    TESTING > 2 and print "      new figure $i\n";
  }

  if(length $space) {

    my $c_count =  $i =~ tr/,//;
    if($space =~ m/\t/ ) {
      # Tabs are hard, let's just give up on them.
    } else {
      $space = ' ' x (length($space) - $c_count);
    }
  }

  $space = ' ' if
    not length $space
    and $well_before =~ m<[\w,]\z>;

  return $space . $i;
}

#======================================================================
__END__
