use warnings;
use strict;

use Getopt::Long;

my $inputfile = '';
my $outputfile = 'a.out';

GetOptions ("i|input|inputfile=s"   => \$inputfile,       # string
            "o|output|outputfile=s" => \$outputfile );    # string

unless ($inputfile) {
  die("Missing option -i");
}

open(my $inFile, "<", $inputfile) || die "Can't open $inputfile: $!";
open(my $outFile, ">", "$outputfile.csv") || die "Can't open $outputfile: $!";

my %funHash = ();
my %funHashTrace = ();
my $trace;

while (<$inFile>) {
  if (/0::@\d+:(\S+)\s/) {
    $funHash{$1} += 1;
    $funHashTrace{$1} += 1;
  } elsif ($trace && /^TraceId\s(\d+)/) {
    open(my $traceOutFile, ">", "$outputfile-$trace.csv") || die "Can't open $outputfile-$trace.csv: $!";
    while (my ($key, $value) = each %funHashTrace) {
      print $traceOutFile "$key;$value\n";
    }
    $trace = $1;
    %funHashTrace = ();
  } elsif (/^TraceId\s(\d+)/) {
    $trace = $1;
    %funHashTrace = ();
  }
}

open(my $traceOutFile, ">", "$outputfile-$trace.csv") || die "Can't open $outputfile-$trace.csv: $!";
while (my ($key, $value) = each %funHashTrace) {
  print $traceOutFile "$key;$value\n";
}

while (my ($key, $value) = each %funHash) {
  print $outFile "$key;$value\n";
}
