package STASH;
use Tie::Hash;
@ISA=qw(Tie::Hash);
sub TIEHASH { 
    my ($name, $dbfilename, $tag) = @_;
    my $self={}; bless $self; 
    $self->{"filename"} = $dbfilename;
    $self->{"tag"} = $tag.":" if defined $tag;
    $self->{"tag"} = "" if !defined $tag;
    return $self;
}
sub FETCH {
    my $self = shift;
    my $key = shift;
    local $/ = undef;
    local (*DB);
    my $out;
    my $dbname = "$self->{filename}.filedb";
    open(DB, "<$dbname/$self->{tag}$key") || return undef;
    $out=<DB>;
    close(DB);
    return $out;
}
sub EXISTS {
    my $self = shift;
    my $key = shift;
    my $dbname = "$self->{filename}.filedb";
    return stat("$dbname/$self->{tag}$key");
}
sub STORE {
    my $self = shift;
    my ($key, $value) = @_;
    local (*DB);
    local $/ = undef; # unneeded on store?
    my $dbname = "$self->{filename}.filedb";
    mkdir($dbname, 0777) if (! -d $dbname);
    open(DB, ">$dbname/$self->{tag}$key") || return $!;
    print DB $value;
    close(DB);
    return undef;
}
sub FIRSTKEY {
    my $self = shift;
    local (*DB);
    my $dbrawname = $self->{"filename"};
    my $dbname ="$self->{filename}.filedb";
    my $tag = $self->{"tag"};
    opendir(DB, $dbname);
    # both check *and* delete the tag automatically
    @out = grep($_ ne "." && $_ ne ".." && s/^$tag//, readdir(DB));
    closedir(DB);
    $self->{"out"} = \@out;
    return shift @{$self->{"out"}};
}
sub NEXTKEY {
    my $self = shift;
    my $lastkey = shift;
    return shift @{$self->{"out"}};
}

1;
