#!/usr/bin/perl
#
#   gnuplot で X ウィンドーにグラフを描き、プリントアウトするかどうかを尋ねる
#
#  ＜ 使用法 ＞
#
#   % gx fname1 fname2 ......
#
#   fname1 は gnuplot 用のコマンドファイル。
#   コマンドファイル名の拡張子が .gnp のときは拡張子を省略可
#
#  ＜ 注意事項 ＞
#
#   コマンドファイルは x11 への描画後 pause -1 し、
#   その後 psfile , epsfile を作成することを前提としている
#
#   コマンドファイルの雛型は refx.gnp を参照すること
#
#  ＜ 履歴 ＞
#
#   ver 1.0   1997.9.19   初版
#       1.1        12.25  拡張子を省略可能
#                         ps ファイル名をコマンドファイル中から抽出
#       1.2   1999.1.26   複数のファイルに対応
#       2.0        12.30  コマンドファイルのフォーマットを変更
#       2.1   2000.1.22   整理
#

$argc = @ARGV;

for($i=0;$i<$argc;$i++){

	# コマンドファイル名を確定

	$fname = @ARGV[$i];
	if ( ! -e $fname ) {
		$fname = $fname . ".gnp";   # ファイルが無い場合は .gnp を補う
		if ( ! -e $fname ){
			print stderr "Cannot open file.\n";
			exit 1;
		}
	}

	# ps ファイルと eps ファイルのファイル名を取り出す

	print "command file : $fname\n";
	open(FP,"< $fname");
	while(<FP>){
		if ( m/set\s+terminal\s+postscript/ ){
			if ( m/eps/ ) {
				$mode = 'eps';
			} else {
				$mode = 'ps';
			}
		}
		if ( m/set\s+output\s+[\"\'](.*)[\"\']/ ){
			if ( $mode eq 'ps' ) {
				$ps_fname = $1;
			} elsif ( $mode eq 'eps' ){
				$eps_fname = $1;
			} else {
				print stderr "command file is not correct.\n";
				exit 1;
			}
		}
	}
	close(FP);

	if ( $ps_fname eq "" || $eps_fname eq "" ){
		print stderr "command file is not correct.\n";
		exit 1;
	}

	# gnuplot を起動

	if ( system("gnuplot -geometry +0+0 -bg gray $fname") != 0 ){
		print "Error on gnuplot.  Exit.\n";
		exit(1);
	}

	# プリントアウトするかどうかの処理
	
	print "Print out ?  (y/n/f)  y:yes  n:no  f:file  ";
	$a = <STDIN>;
	if ( $a =~ m/y/i ) {
		if ( system("lpr $ps_fname") != 0 ){
			print "Error on lpr.\n";
		}
		system("rm -f $ps_fname");
		system("rm -f $eps_fname");
	} elsif ( $a =~ m/f/i ) {

	} elsif ( $a =~ m/n/i ) {
		system("rm -f $ps_fname");
		system("rm -f $eps_fname");
	}
}

