#!/usr/bin/perl -w

# check environment
defined $ENV{'UGROOT'} or die "ugtdev error: 'UGROOT' environment variable not set\n";
$ugmgs=$ENV{'UGROOT'}."/bin/ugmgs";
-e $ugmgs or die "ugtdev error: tool 'ugmgs' not existing\n";

# check input
@ARGV==2 or die "ugtdev usage: ugtdev <s|m|h|D|W|M|Y> <prefix>\n";
$prefix=$ARGV[1];
SWITCH:
{
	if ($ARGV[0] eq 's') { $unit=1; last SWITCH; }
	if ($ARGV[0] eq 'm') { $unit=60; last SWITCH; }
	if ($ARGV[0] eq 'h') { $unit=3600; last SWITCH; }
	if ($ARGV[0] eq 'D') { $unit=86400; last SWITCH; }
	if ($ARGV[0] eq 'W') { $unit=604800; last SWITCH; }
	if ($ARGV[0] eq 'M') { $unit=2592000; last SWITCH; }
	if ($ARGV[0] eq 'Y') { $unit=31536000; last SWITCH; }
}

# subs
sub float
{
    my $real='[+-]?\d+\.?\d*[eE]?[+-]?\d+|[+-]?\d*\.?\d+[eE]?[+-]?\d+|[+-]?\d+';
    my (@list,$f,$s,$in);

    if (@_==1) { @list=grep /$real/,split /($real)/,$_[0]; }
    elsif (@_==2)
    {
        $in=' '.$_[1];
        ($f,$s)=split /$_[0]/,$in,2;
        @list=grep /$real/,split /($real)/,$s;
    }
    else
    {
        $in=' '.$_[2];
        ($f,$s)=split /$_[0]/,$in,2;
        @list=grep /$real/,split /($real)/,$s;
        if ($_[1]>=@list || $_[1]<0) { return undef;}
        for ($s=0; $s<$_[1]; $s++) { shift @list; }
    }
    return wantarray ? @list : $list[0];
}

# run
open(TIME,">time");
open(DT,">time_step");
for($i=0;; $i++)
{
	$data=$prefix.sprintf(".%.6d.ug.data.xdr",$i);
	-e $data or last;
	$r=`$ugmgs $data`;
	($t,$dt)=float 'Identification',$r;
	$t/=$unit; $dt/=$unit;
	print TIME "$i $t\n";
	print DT "$i $dt\n";
}








