#!/usr/bin/perl

package Bib::Write;
use strict;
use warnings;
use TeX;

our ( @Months, %Months );

BEGIN {
    use Exporter ();

    our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
    $VERSION = 1.00;                    # version for version checking
    @ISA = qw(Exporter);
    @EXPORT = qw(bib_month
                 bib_key_wcharval bib_key_utf8val bib_key_val bib_key_val_r); 

    @Months = qw( ??? jan feb mar apr may jun jul aug sep oct nov dec );
    for( my $i = 0; $i < 13; $i ++ ) {
        $Months{ $Months[ $i ] } = $i;
    }
}

sub bib_month {
    $_[0] =~ /\d/ ? $Months[ $_[0] ] : $Months{ lc( $_[0] ) };
}

sub bib_key_wcharval {
    my( $key, $val ) = @_;
    $val = TeX::wchar2TeX( $val );
    bib_key_val( $key, $val );
}

sub bib_key_utf8val {
    my( $key, $val ) = @_;
    $val = TeX::utf82TeX( $val );
    bib_key_val( $key, $val );
}

sub bib_key_val {
    my( $key, $val ) = @_;

    "  $key =" . ( ' ' x ( 13 - length( $key ) ) ) . "{" .
        format_to_block( $val, 63, ' ' x 17 ) . "},\n";
}

sub bib_month_val {
    my( $key, $val ) = @_;

    "  $key =" . ( ' ' x ( 13 - length( $key ) ) ) . "$val,\n";
}


sub bib_key_val_r {
    my( $key, $val ) = @_;

    "  $key =" . ( ' ' x ( 13 - length( $key ) ) ) . "$val,\n";
}


sub format_to_block
{
    my ($tx, $len, $pre) = @_;

    $tx or $tx = '???';

    my $acc = '';
    my $l = 0;
    foreach my $i (split '\s', $tx ) {
        if( $l + length( $i ) >=  $len ) {
            $acc .= "\n$pre$i";
            $l = length( $i );
        } else {
            $l and $acc .= ' ';
            $acc .= $i;
            $l += !!$l + length( $i );
        }
    }
    return $acc;
}
