#!/bin/perl -w
# $Id: cnvmsgfile,v 2.1 1998/12/19 14:23:41 hasegawa Exp $
# copyright (c)1997-1998 Yoshinori Hasegawa <hasegawa@madoka.org>

@TABLE = (1, 60, 3600, 86400, 2678400, 31536000);
$MAXTRY = 20;

&main(@ARGV);

sub main {
  local(@args) = @_;
  local(@data, $line, $old, $n, $date, $time, $rest);
  if (@args < 1) {
    &usage();
    exit(1);
  }
  foreach $file (@args) {
    if (!open(FILE, $file)) {
      print "$file not found\n";
      next;
    }
    @data = ();
    while (defined($line = <FILE>)) {
      $line =~ tr/\r\n//d;
      push(@data, $line);
    }
    close(FILE);
    $count = 0;
    foreach $line (@data) {
      next if $line =~ /^\s*\#/;
      ($date, $time, $rest) = split(/\s+/, $line, 3);
      if ($date =~ /^\d+\/\d+\/\d+$/ && $time =~ /^\d+\:\d+\:\d+$/) {
        $count++;
      }
    }
    if ($count == 0) {
      print "$file already converted\n";
      next;
    }
    $old = $file . '.old';
    if (-e $old) {
      $n = 0;
      while (-e $old . $n) {
        $n++;
      }
      $old .= $n;
    }
    rename($file, $old);
    if (open(FILE, ">$file")) {
      foreach $line (@data) {
        ($date, $time, $rest) = split(/\s+/, $line, 3);
        if ($date =~ /^\d+\/\d+\/\d+$/ && $time =~ /^\d+\:\d+\:\d+$/) {
          print FILE '', &timelocal($date, $time), ' ', $rest, "\n";
        } else {
          print FILE $line, "\n";
        }
      }
      close(FILE);
    }
  }
}

sub usage {
  print 'usage: perl cnvmsgfile <file>', "\n";
}

sub timelocal {
  local($date, $time) = @_;
  local(@time, $now, $ndate, $ntime, @time, $try);
  $now = time();
  $try = 0;
  $ndate = '';
  $ntime = '';
  while (($date ne $ndate || $time ne $ntime) && $try < $MAXTRY) {
    $now = &convert($date, $time, $now);
    @time = localtime($now);
    $time[5] += 1900;
    $time[4] += 1;
    $ndate = sprintf("%04d/%02d/%02d", $time[5], $time[4], $time[3]);
    $ntime = sprintf("%02d:%02d:%02d", $time[2], $time[1], $time[0]);
    $try++;
  }
  print "$date $time -> $ndate $ntime\n";
  return $now;
}

sub convert {
  local($date, $time, $now) = @_;
  local(@ntime, @time, $last, $i);
  @ntime = localtime($now);
  $ntime[4] += 1;
  $ntime[5] += 1900;
  @time = ();
  push(@time, reverse(split(/\:/, $time)));
  push(@time, reverse(split(/\//, $date)));
  $last = $now;
  for ($i = 0; $i < 6; $i++) {
    $last -= ($ntime[$i] - $time[$i]) * $TABLE[$i];
  }
  return $last;
}
