#!/usr/bin/perl
# Time-stamp: <2007-08-31 23:08:17 phm>
BEGIN { $ENV{PATH} = '/bin:/usr/bin:/usr/local/bin' };
use strict;
use POSIX qw(strftime);
use English -no_match_vars;
umask oct('002');
use utf8;
binmode STDIN, ':utf8';
binmode STDOUT, ':utf8';
binmode STDERR, ':utf8';
use Encode qw(_utf8_on);
use IO::File;
use Data::Dumper;

my $fi;

sub usage {
print STDERR <<_EOHELP_
tratext_xget <DATEI>

 Zu übersetzende Zeichenketten in DATEI exportieren 

 Optionen:
  -n :: nur neue Zeichenketten (für die es noch keine Übersetzung gibt)
  -l 14-20 :: nur Zeichenketten aus 14-20 Schriftzeichen
  -D a2e :: Datenbank a2e verwenden
  -t jaen :: Tabelle jaen verwenden
  -v :: geschwätzig
  -d :: Fehlersuche unterstützen

  Im Moment funktioniert das Programm nur unter lokalen Voraussezungen bei a2e.
  s. http://a2e.de/adv/tratext
_EOHELP_
}

use A2E::Opts;
my $opts = A2E::Opts->new('vdht:l:n');

my $VERBOSE = $opts->{v} || $ENV{VERBOSE};
my $DEBUG = $opts->{d} || $ENV{DEBUG};
my $DBNOM = $opts->{D} || 'a2e';
my $TABLE = $opts->{t} || 'jaen';
my $LEN = $opts->{l};
my $NEWONLY = $opts->{n};
my $HELPU = $opts->{h};
my ($LENMIN, $LENMAX) = split '-', $LEN;
$LENMIN ||= 0;
$LENMAX ||= 0;

sub decho {
    return unless $DEBUG;
    printf STDERR @_;
    print STDERR "\n";
};
sub vecho {
    return unless $VERBOSE;
    printf STDERR @_;
    print STDERR "\n";
};

use A2E::db;
my $localhost = !@ARGV;
our $db = new A2E::db $DBNOM, { debug=>$DEBUG, verbose=>$VERBOSE, localhost=>$localhost };

my @conds = ('ok');
push @conds, 'en is null' if $NEWONLY;
my $s_conds = join ' and ', @conds;
my @recs = $db->get_records(qq{select ja, en, dok, file, line from $TABLE where $s_conds order by file, line});

sub write_file {
    my $fh = shift;
    my $ja = '';
    my $en = '';
    my $id = 'd00';
    my $file = '';
    my $dok = '';
    my $dok_or_file = '';
    my $line = 0;
    my @ch_ja = ();
    my $n_ja;
    my $n_ja_sum = 0;
    my $n_rek = 0;
    foreach my $rek (@recs) {
	($ja, $en, $dok, $file, $line) = @$rek;
	@ch_ja = unpack 'U*', $ja;
	$n_ja = scalar @ch_ja;    
	next if $n_ja < $LENMIN;
	next if $LENMAX and $n_ja > $LENMAX;
	$n_rek++;
	$n_ja_sum += $n_ja;
	$dok_or_file = $dok || $file;
	print $fh "\# $dok_or_file $line $n_rek\nja: $ja\nen: $en\n";
    };
    my @msg = ("$n_rek records printed", "$n_ja_sum japanese characters counted");
    print $fh "# $_\n" for @msg;
    print STDERR "$_\n" for @msg;
};

$fi = shift;

if ($HELPU) { usage;exit 0 };

my $fh;
if ($fi) { 
    $fh = new IO::File $fi, 'w' or die "cant write $fi";
    $fh->binmode(':utf8');
    write_file $fh;
    $fh->close if $fi;
} else { 
    do { _utf8_on $_;print STDERR $_, "\n" } for "TEST: $0 läuft.", "Erklärungen bekommst du mit -h.";
    exit 0;
};

# Local Variables:
# coding: utf-8
# url: https://a2e.de/adv/tratext/tratext_xget.pl
# srcfile:/adv/tratext/tratext_xget.pl
# mode: perl
# End:
