#!/usr/bin/perl -w

use locale;                     # make Perl locale aware
use POSIX qw(locale_h strtod);  # Imports setlocale(), LC_ constants, strtod.
use Text::CSV;                  # CSV parsing module

(@ARGV == 1) or die "Usage: cvtcsv.pl <filename>\n"; 
$fname = $ARGV[0];

setlocale (LC_NUMERIC, "fr_BE.utf8")
  or die "Unable to set 'fr_BE.utf8' locale\n";

$csv = Text::CSV->new ({binary => 1, allow_whitespace => 1})
         or die "Cannot use CSV: ".Text::CSV->error_diag ();
# Use ';' rather than ',' for separating fields when radix is comma
$csv->sep_char (';');

open $FH, "<:encoding(utf8)", "$fname" or die "Error opening $fname: $!";

while (<$FH>)
{
  $okay = $csv->parse ($_);
  if (! $okay) {warn "Unable to parse line $.\n"; next;}
  @fields = $csv->fields ();

  @cvt_row = ();
  foreach my $field (@fields)
  {
    $val = strtod ($field);
    $val = $field if ($val == 0);  # simple check to pass non-numbers through
    push (@cvt_row, $val); 
  }

  push (@rows, [@cvt_row]);
}
unless ($csv->eof) { $csv->error_diag(); }
close $FH;

setlocale (LC_NUMERIC, "C") or die "Unable to set 'C' locale\n";
# Use ',' as field separator when radix is '.'
$csv->sep_char (',');
$csv->eol ("\n");

open $FH, ">:encoding(utf8)", "$fname.cvt"
  or die "Error opening $fname.cvt: $!";

$csv->print ($FH, $_) foreach @rows;
close $FH;

