#!/usr/bin/perl
#
# gtcontex - gtcont wrapper for `right adjusted title'
#
# Copyright (C) by TOYODA Eizi, 1999.  All rights reserved.

$xname = "gtcont";
$title = undef;
$rtitle = undef;
$str = "";
$titlemax = 28;
@XARGV = ();

foreach $arg (@ARGV) {
	if ($arg =~ /^gtcont=(.*)/) {
		$xname = $1;
	} elsif ($arg =~ /^-/) {
		push @XARGV, $arg;
	} elsif ($arg =~ /^title[=:](.*)/i) {
		$title = $1;
	} elsif ($arg =~ /^titlemax[=:](.*)/i) {
		$titlemax = $1;
	} elsif ($arg =~ /^rtitle[=:](.*)/i) {
		$rtitle = $1;
	} elsif ($arg =~ /^str[=:](.+)/i) {
		$str = $1;
		push @XARGV, $arg;
	} elsif ($arg =~ /[=:]/) {
		push @XARGV, $arg;
	} else {
		$filename = $arg;
		push @XARGV, $arg;
	}
}

$filename = "gtool.out" if not defined $filename;

if (defined $rtitle and not defined $title) {
	print "[gtshow -head $filename tend=$str tstr=$str]\n";
	open(PIPE, "gtshow -head $filename tend=$str tstr=$str |");
	while ($line = <PIPE>) {
		if ($line =~ /^ TITLE/) {
			$line =~ s/^ TITLE *: *//;
			$line =~ s/\s*$//;
			$title = $line;
		}
		if ($line =~ /^ DSET/) {
			$line =~ s/^ DSET *: *//;
			$line =~ s/\s*$//;
			$dset = $line;
		}
	}
	close(PIPE);
}

$rtitle = $dset if $rtitle eq '.DSET.';

if (defined $title) {
	$title =~ s/'(.*)'/\1/g;
	$title =~ s/"(.*)"/\1/g;
	$leftlen = length($title);
	$rightlen = length($rtitle);
	if ($leftlen + 1 + $rightlen > $titlemax) {
		$leftlen = $titlemax - 1 - $rightlen;
		$title = substr($title, 0, $leftlen);
	}
	$midlen = $titlemax - $leftlen - $rightlen;
	$xtitle = $title . (' ' x $midlen) . $rtitle;
	$c = '\'';
	$c = '"' if ($xtitle =~ /'/);
	push @XARGV, "TITLE=$c$xtitle$c";
}

$gtcont = undef;
foreach $dir (split(/:/, $ENV{'PATH'})) {
	$gtcont = "$dir/$xname" if -x "$dir/$xname";
}

die "$xname: command not found\n" if not defined $gtcont;

print "[", join('|', $gtcont, @XARGV), "]\n";
exec $gtcont, @XARGV;
