## Modus:
#  -1 Voreinstellung, aber keine Direktausgabe
#  0  Voreinstellung
#  1  stdout
#  2  less
#  3  Datei
#  4  /dev/null (genauer gesagt, "wc")
#  5  String
#  6..sonstige Drucker
#  Modus

## Globals: Db::...
# pr_modus   Modus wie oben (positiv); wenn negativ: permanent
# pr_fh      Filehandle

use utf8;
use warnings; no warnings "redefine";
use strict;
use Dbase::Globals qw(flatten get_descr);
use Dbase::Help qw(DoFn);
use Fehler qw(problem);
use Loader qw(line_in line_printer);  # Letztzerer wegen $Db::OutHandle
use IO::File;
use IO::Pipe;
use IO::Handle;
use IO::String;
use POSIX qw(dup);
use Umlaut qw(textmodus);

sub lister($;@) {
	my $modus = shift;
	my(@data) = @_;
	my $fh;
	$modus ||= 1;

	if($modus <= 0 and $Db::pr_fh and $Db::pr_fh != $Db::OutHandle) {
		$fh = IO::Handle->new_from_fd(dup(fileno($Db::pr_fh)),"w");
	}
	$modus = 2 if $modus == -1 and $Db::pr_fh == $Db::OutHandle;

	my $cmd = DoFn("select befehl from ausgabe where ausgabe = $modus");
	if(defined $cmd) {
		print STDERR "Umleitung an ".get_descr("ausgabe",$modus)."..."
			if $modus > 2; # nicht wenn "less"
		$|=1;
		$fh = new IO::Pipe;
		$fh->writer($cmd);
		$|=0;

		textmodus($fh);
	} elsif($modus == 1) {
		$fh = $Db::OutHandle || \*STDOUT;
	} elsif($modus == 2) {
		$fh = new IO::Pipe;
		local $ENV{LESS} = '-RS' . ( defined $ENV{LESS} && " $ENV{LESS}" );
		$fh->writer( defined $ENV{PAGER} ? $ENV{PAGER} : 'less' );

		textmodus($fh);
	} elsif($modus == 3) {
		my $fn = line_in "Dateiname: ";
		return undef if not defined $fn or $fn eq "";

		$fh = new IO::File $fn,O_RDWR|O_CREAT|O_APPEND,0644;

		textmodus($fh);
	} elsif($modus == 4) {
		$|=1; print STDERR "| wc..:";
		#$fh = new IO::File "/dev/null","w";
		$fh = new IO::Pipe;
		$fh->writer("wc");
		$|=0;
	} elsif($modus == 5) {
		$Db::output = "";
		$fh = new IO::String($Db::output)
	}
	unless($fh) {
		problem "Ausgabe:$modus",$!;
		return undef;
	}

	unless(@data) {
		no warnings 'once';
		$Db::pr_fh = $fh;
		$Db::pr_fh_modus = $modus;
		return $fh;
	}
	flatten {
		goto out unless print $fh $_[0];
	} @data;
out:
	$fh->close if $fh and $fh != $Db::OutHandle;
	1;
}
1;
