#Copyright Massachusetts Institute of technology, 1998.
#Written by Eric Prud'hommeaux for the World Wide Web Consortium

use strict;
require Exporter;
require AutoLoader;

use W3C::Database::DBStreamHandle;

$W3C::Database::FlatfileInterface::REVISION = '$Id: FlatfileInterface.pm,v 1.12 2000/12/07 22:24:43 eric Exp $ ';

package W3C::Database::FlatfileInterface;
use vars qw($VERSION $DSLI @ISA @EXPORT @EXPORT_OK @TODO);
@ISA = qw(Exporter AutoLoader);
@EXPORT = qw();
@EXPORT_OK = qw();
$VERSION = 0.97;
$DSLI = 'adpO';
@TODO = ();

package W3C::Database::StdHandle;
@W3C::Database::StdHandle::ISA = ('W3C::Database::DelimStreamHandle');
sub new {
    my $proto = shift;
    my $class = ref($proto) || $proto;
    my $self  = $class->SUPER::new(@_);
    bless ($self, $class);
    $self->{DB} = ($self->{ACCESS} == $W3C::DBStreamHandle::READ_ONLY) ? *STDIN : *STDOUT;
    $self->{LINE_TERM} = $self->{STRICT} ? $self->{DELIM}."\n" : "\n";
    return $self;
}

sub put {
    my ($self, @values) = @_;
    my ($handle, $lineTerm) = ($self->{DB}, $self->{LINE_TERM});
    print $handle $self->encode(@values), $lineTerm;
}

sub forEach {
    my ($self) = @_;
    my $handle = $self->{DB};
    # todo: if ($self->{'strict'} && $line );
    my ($entry, $delim) = ('', $self->{DELIM});
    #print 'strict: "'.$self->{STRICT}.'"  delim: "'.$delim."\"\n";
    while (my $line = readline($handle)) {
	if ($self->{STRICT} && !($line =~ s/\Q$delim\E\n$/\n/s)) {
	    $entry .= $line;
	    next;
	}
	#print "'$line'\n";
	chop $line;
	my (@values) = $self->decode($entry.$line);
	$self->{SINK}->put(@values);
	$entry = '';
    }
}

package W3C::Database::TextHandle;
@W3C::Database::TextHandle::ISA = ('W3C::Database::StdHandle');
sub new {
    my $proto = shift;
    my $class = ref($proto) || $proto;
    my ($flatfileName) = shift;
    my $self = $class->SUPER::new(@_);
    bless ($self, $class);
    local (*HANDLE);
    $self->{DB} = *HANDLE;
    my $opt = ($self->{ACCESS} == $W3C::DBStreamHandle::WRITE_ONLY ? '>' : '<');
    open(HANDLE, "$opt$flatfileName") || return $!;
    return $self;
}

package W3C::Database::FlatfileInterface;

1;

__END__

=head1 NAME

W3C::Database::FlatfileInterface - DBStreamHandle to talk to flat database files

=head1 SYNOPSIS

see ddb.pl

=head1 DESCRIPTION

This module is part of the W3C::Database CPAN module.

=head1 AUTHOR

Eric Prud\'hommeaux <eric@w3.org>

=head1 SEE ALSO

perl(1).

=cut
