#!/usr/bin/perl
#
# zeffsum - Zentrale Zeit Erfassung (.csv file summarizer)
#
# Thomas Linden <tom@daemon.de>
#
# Copyright (c) 2002 Thomas Linden.


use strict;

my $VERSION = "1.1.0";

my %zeff;

if (@ARGV) {
  #
  # first step, read all files in and store its contents in %zeff
  foreach my $zeffile (@ARGV) {
    open DB , "<$zeffile" or die "Could not open $zeffile: $!\n";
    while (<DB>) {
      next if /^\s*#/; # ignore comments
      my($date,$cost,$hours) = split /;/;
      chomp $hours;
      my $time = &human2sec($hours);
      if (exists $zeff{$date}->{$cost}) {
	# add time
	$zeff{$date}->{$cost} += $time;
      }
      else {
	$zeff{$date}->{$cost} = $time;
      }
    }
    close DB;
  }

  #
  # next step, print all contents out
  print qq(#
# SUMMARY Time data file for zeff(ix)
# Do not edit manually.
#
# Format: DD.MM.YYYY;Cost Center;hh:mm:ss
#
# Last edited by $0 $VERSION
#
);

  foreach my $date (sort keys %zeff) {
    foreach my $cost (sort keys %{$zeff{$date}}) {
      print $date . ";" . $cost . ";" . &sec2sec($zeff{$date}->{$cost}) . "\n";
    }
  }

  #
  # end
}
else {
  print "zeffsum zeff.MMYYYY.csv [ ... ]   > output.csv\n"
       ."Summarize a couple of zeff csv files into one single csv file.\n"
       ."zeffsum version $VERSION. COPYRIGHT (c) 2002 Thomas Linden.\n";
  exit -1;
}




sub human2sec {
  #
  # convert hh:mm:ss => %010d seconds since 1.1.1970
  #
  my $human = shift;
  my($hh, $mm, $ss) = split /:/, $human;
  return sprintf "%010d", ($hh * 3600) + ($mm * 60) + $ss;
}


sub sec2sec {
  #
  # convert given seconds into
  # human readable hour value (YY:MM:SS)
  #
  my $seconds = shift;

  my $hours = int($seconds / 3600);

  my $min   = int(($seconds - ($hours * 3600)) / 60);

  my $secs  = $seconds - ($hours * 3600) - ($min * 60);

  return sprintf "%02d:%02d:%02d", $hours, $min, $secs;
}
