#!/usr/local/bin/perl -w

#
# dbfilesplit
# Copyright (C) 2000 by John Heidemann <johnh@isi.edu>
# $Id: dbfilesplit,v 1.3 2000/08/30 00:41:04 johnh Exp $
#
# This program is distributed under terms of the GNU general
# public license, version 2.  See the file COPYING
# in $dblibdir for details.
#
sub usage {
    print <<END;
usage: $0 [-p prefix] [-s suffix]

Splits the input into multiple files
'filename.0',, 'filename.1', ..., using lines starting
with "#h" or "#l" as a marker-separator.
By default files are called stdin.0.jdb, stdin.1.jdb, etc.

Options:

-p prefix	the prefix on files (default "stdin.")
-s suffix	the suffix on files (default ".jdb"

If you specify your own prefix and suffix, you need to include dots (if
you want them).

Sample input:
#h sid cid
1 10
2 11
1 12
2 12
#h cid cname
10 pascal
11 numanal
12 os

Command:
cat DATA/filesplit.jdb | dbfilesplit -p classinfo.

Sample output:
(nothing to stdout)

File classinfo.0.jdb:
#h sid cid
1 10
2 11
1 12
2 12

File classinfo.1.jdb:
#h cid cname
10 pascal
11 numanal
12 os

This program is based on code contributed from Pavlin Radoslavov.

END
# '
    exit 1;
}

BEGIN {
    $dbbindir = "/usr/local/bin";
    $dblibdir = "/usr/local/lib/jdb";
    push(@INC, $dblibdir);
}
require "$dblibdir/dblib.pl";
use DbGetopt;

my(@orig_argv) = @ARGV;
my($prog) = &progname;
my($debug);
my($prefix, $suffix) = qw(stdin. .jdb);

my($dbopts) = new DbGetopt("dp:s:?", \@ARGV);
my($ch);
while ($dbopts->getopt) {
    $ch = $dbopts->opt;
    if ($ch eq 'd') {
	$debug++;
    } elsif ($ch eq 'p') {
	$prefix = $dbopts->optarg;
    } elsif ($ch eq 's') {
	$suffix = $dbopts->optarg;
    } else {
	&usage;
    };
};
# &usage if ($#ARGV < -1);

my($count) = -1;

while (<STDIN>) {
    if (/^$headertag_regexp/) {
	&process_header($_);
	&close_file;
	&open_file;
	&write_header();
    } else {
	die "$0: lines before first tag\n" if ($count < 0);
	print $_;
    };
};
&close_file;

exit 0;


sub open_file {
    $count++;
    open(STDOUT, ">$prefix$count$suffix") || die "$0: cannot write $prefix$count$suffix\n";
}

sub close_file {
    return if ($count < 0);
    # die "$0: close_file before open_file\n" if ($count < 0);
    print "#  | $prog ", join(" ", @orig_argv), "\n";
    close STDOUT;
}


# warning suppression
my($dummy) = $dbbindir;
$dummy = $headertag_regexp;
