#! /usr/bin/perl
# prtag2tag.pl: print lines from input_file from /TAG1/ thru /TAG2/ (or EOF)
# (C) Copyright 2007-2008, Randy Dunlap
#
# ver. 002 changes:
# - add prcount and exit (2) if it is 0;
# - add -i (ignore case) option;
# - add usage info for '-' == STDIN (Perl does this);
#
# NB: can use . for spaces in either arg (regex) so that the arg(s)
# will be seen as one string;

$VER = "002";

use Getopt::Std;

getopts("i");

sub usage() {
	print "usage: prtag2tag [-i] begin_tag end_tag file(s) [ver. $VER]\n";
	print "  -i : ignore case\n";
	print "  file(s) can be '-' for STDIN\n";
	exit (1);
}

my $printing = 0;
my $begin_tag = shift (@ARGV) || usage();
my $end_tag = shift (@ARGV) || usage();
my $prcount = 0;

if ($begin_tag eq "" || $end_tag eq "") {
	usage();
}

##print "begin /$begin_tag/, end /$end_tag/\n";
##print "files: @ARGV\n";

foreach my $file (@ARGV) {

	open (FILE, $file) || die "Cannot open file: $file\n";

	LINE: while ($line = <FILE>) {
		chomp $line;

		if ($opt_i) {
			if ($line =~ /$begin_tag/i) {
				$printing = 1;
			}
		}
		elsif ($line =~ /$begin_tag/) {
			$printing = 1;
		}

		if ($printing) {
			print "$line\n";
			$prcount++;
		}

		if ($opt_i) {
			if ($line =~ /$end_tag/i) {
				$printing = 0;
			}
		}
		elsif ($line =~ /$end_tag/) {
			$printing = 0;
		}
	}

	close (FILE);
}

if ($prcount == 0) {
	printf(STDERR "no matching lines\n");
	exit (2);
}
