#
# Copyright (c) 2004-2007 - Consultas, PKG.fr
#
# This file is part of A2P.
#
# A2P is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# A2P is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with A2P; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#
# $Id: Flux.pm 3 2007-10-18 16:20:19Z root $
#
# Class to implement print object
#

package AFPDS::Flux;

use strict ;
use Encode 'from_to' ;
use A2P::Globals ;
use A2P::Syslog;
use AFPDS::MODCA ;
use A2P::Common qw( validate );
use A2P::Com    qw( GetCom comINF );

BEGIN {
    our $VERSION = sprintf "%s", q$Rev: 1023 $ =~ /([0-9.]+)\s+/ ;
}
our $VERSION ;

sub new {
    &Debug("new AFPDS::Flux v$VERSION");
    my $class = shift ;
    my $self = {
        AFPDSFILE       =>  shift   ,   PAGEFORMATs =>  {}        ,
        LogoLines       =>    []    ,   COPYGROUPs  =>  {}        ,
        PAGES           =>    0     ,   FORMDEF     =>  ""        ,
        LANDSCAPE       =>    0     ,   PAGEDEF     =>  ""        ,
        LastChannel     =>    1     ,   OUTFILE     =>  "none"    ,
        CHANNELNUMBER   =>    1     ,   CHANNEL     =>  'A'       ,
        MaxRepeat       =>    1     ,   LOGOS       =>  []        ,
        LINE            =>    0     ,   LINES       =>  []        ,
        PrintLineTab    =>    []    ,   PrintLine   =>  {}        ,
        PCLCOND         =>    0     ,   INSERT_LOGO =>  0         ,
        StartNewPage    =>    0     ,   ROTSEGMENT  =>  0         ,
        CurrentPAGEFORMAT =>  ""    ,   THREAD      =>  shift     ,
        BADCHANNELALERT =>    0     ,   JOB         =>  shift     ,
        ERROR           =>    []    ,   LOGOs       =>  {}        ,
        OPENEDCHANNEL   =>    0     ,   COPYGROUP   =>  ""        ,
        OPENEDPFORMAT   =>    0     ,   LOGO_INDEX  =>  0         ,
        HAS_LOGO        =>    0     ,   PAGEFORMAT  =>  ""        ,
        RESOURCE        =>    {}    , SELECTED_RESOURCE => ""     ,
        DefaultTRC      =>    "\\FONtTrcA",
        LastDefaultTRC  =>    "\\FONtTrcA",
        texpackages     =>    [ 'afp2print' ]
    };

    return bless $self , $class ;
}

sub Return {
    # Used to call Return member to be able to provide info to JobManager
    my $self = shift ;
    my $this = $self->{THREAD} ;
    $this->Return( $self->{JOB} => &GetCom( comINF, Conversion => @_ ));
}

sub getlineindex {
    my $self = shift ;
    return $self->{LINE} ;
}

sub afpline {
    my $self    = shift ;
    my $cctrl   = shift ;
    my $buffer  = shift ;

    my ( $comment , $lsp ) = ( "none" , 0 );

    # If no PageFormat still has been requested, we must load the first one
    # as default before output any line
    unless ($self->{PAGEFORMAT}) {
        $self->{COPYGROUP}   = "%\n% No COPYGROUP defined"
            unless ($self->{COPYGROUP});
        $self->{PAGEFORMAT}  = "\\pageformatA{%" ;
        # This is simulating printing on channel 1, so $cctrl = 1 is implicite
        $cctrl = '1' ;
    }

    if ( $cctrl eq " " ) {
        $comment = "Space one line then print (single spacing)";
        $lsp = 1 ;

    } elsif ( $cctrl eq "0" ) {
        $comment = "Space 2 lines then print (double spacing)";
        $lsp = 2 ;

    } elsif ( $cctrl eq "-" ) {
        $comment = "Space 3 lines then print (triple spacing)";
        $lsp = 3 ;

    } elsif ( $cctrl eq "+" ) {
        $comment = "Suppress spacing, then print (overstrike previous line)";
        $lsp = 0 ;
        if ($self->LastLineMatch(qr/^\\PrintLineChannel/,2)
        and $self->{LINE} == $self->{MaxRepeat} and $self->{MaxRepeat} > 0) {
            $comment .= ", selecting new channel" ;
            my @insertlines = pop( @{$self->{LINES}} );
            unshift @insertlines , pop( @{$self->{LINES}} );
            $self->nextChannel();
            $self->addline( @insertlines );
        }

    } elsif ( $cctrl =~ /^[1-9ABC]$/i ) {
        if ($self->nextChannel($cctrl)) {
            $comment = "Print data to Channel #" . $self->{CHANNELNUMBER} ;

        } else {
            # Work around for bad channel selection
            $comment = "Space one line then print (single spacing)";
            $lsp = 1 ;
        }

    } else {# Not an ANSI Carriage Control Character,
            # see table 1. p7 of Advanced Function Presentation:
            #     Programming Guide and Line Data Reference
        &Error(sprintf("Got '$cctrl' (%Xh) not supported control char",$cctrl));
        return undef;
    }
    &Debug("cctrl=[$cctrl], $comment");

    # Compute Line Max repetition and switch to next channel if needed
    $self->{LINE} += $lsp ;

    # Start new channel when required
    $self->nextChannel()
        if (( $self->{LINE} > $self->{MaxRepeat} and $self->{MaxRepeat} > 0 )
        or $self->{StartNewPage} );

    # Insert Line spacing if necessary
    if ($lsp > 0) {

        # Update previous line spacing if exists
        if ( $self->LastLineMatch( qr/\\LineSpacing\{\d+\}%$/ ) ) {
            # We prefer update last Linespacing
            my $index   = $#{$self->{LINES}} ;
            ${$self->{LINES}}[$index] =~ /\{(\d+)\}%$/ ;
            $lsp += $1 ;
            ${$self->{LINES}}[$index] =~ s/\{\d+\}%$/\{$lsp\}%/ ;

        } else {
            $self->newline( "\\LineSpacing{$lsp}%" );
        }
    }

    # Is fieldAA is defined ? If no, just print the line as is
    if (defined($self->{PrintLine}->{'fieldAAstart'})) {
        my $buflen = length( $buffer );
        my @fields = grep( /^field..start$/ , keys(%{$self->{PrintLine}}) ) ;
        map s/start$//, @fields ; # Just keep indexes which are in upper case
        for my $field ( @fields ) {

            my ( $start , $len ) = ( $field . "start" , $field . "length" );

            # Check field definition from auto-generated library, needed to
            # detect bad converted Perl library
            if (!( defined($self->{PrintLine}->{$start})
            and defined($self->{PrintLine}->{$len}))) {
                &Error("Found incomplete field for field $field");
                next ;
            }

            my $readlen   = $self->{PrintLine}->{$len} ;
            my $readstart = $self->{PrintLine}->{$start} - 1 ;

            # Check there is enough text in buffer to extract field value
            if ( $readstart >= $buflen ) {
                #&Debug("text for field $field starts out of buffer, skip it" );
                next ;
            }

            # Check available text length from buffer for that field
            if ( $readstart + $readlen > $buflen ) {
                &Debug("Available text for field " . $field .
                    " is not as long as expected ($readlen chars)");
                $readlen = $buflen - ( $self->{PrintLine}->{$start} - 1 ) ;
                &Debug("Will read only $readlen chars from buffer");
            }

            # Extract text from buffer and validate it
            my $text = substr( $buffer , $readstart , $readlen ) ;
            &validate( \$text ) ;

            # Don't print this text if there's only white spaces
            if ( $text =~ /\S/ ) {
                &Debug("Print new $field: length=$readlen, text='$text')");
                $self->newline( "\\" . $field . "{$text}%" ) ;
            }
        }
    } else {

        &validate( \$buffer );
        # Print a non formatted line if not empty
        $self->newline("\\PrintLine{" . $buffer . "}%") if (length($buffer));
    }

    # Remember which channel is defined next time
    $self->{LastChannel} = $self->{CHANNELNUMBER};
}

sub nextChannel {
    my $self    = shift ;
    my $channel = shift ;
    my $startnewpage = 0 ;

    if (defined($channel)) {
        $self->{CHANNELNUMBER} = eval("0x$channel"); # Hex evaluation is correct

        # Start a new page on that channel if asking the same channel as
        # previous (default to 1), so this activate also the first page
        # (LastChannel default to 1) or if new channel is lower than previous
        $startnewpage ++
            if ( $self->{LastChannel} >= $self->{CHANNELNUMBER}
            or $self->{StartNewPage} );

    } else {
        &Debug("No channel selection defined");
        # Use next channel on the pagedef (or next FCB in old logic)
        $self->{CHANNELNUMBER} ++ ;

        # Start a new page on channel 1 if no more channel in PAGEDEF available
        if ( $self->{StartNewPage}
        or ! defined(${$self->{PrintLineTab}}[$self->{CHANNELNUMBER}]) ) {
            $startnewpage ++ ;
            $self->{CHANNELNUMBER} = 1 ;
        }
    }

    $channel = $self->{CHANNELNUMBER} ;
    &Debug("Selecting channel #" . $channel );

    # Check channel has been defined in library unless it's the first channel
    # (default)
    if ( $channel > 1 ) {
        unless (defined(${$self->{PrintLineTab}}[$channel])
            and ${$self->{PrintLineTab}}[$channel])
        {
            # If channel is defined, {PrintLine} must a hash, otherwise don't
            # select TeX not defined channel
            $self->addline("% Bad channel #$channel selection here");
            $self->Return("Bad channel #$channel selection found");
            &Warn("Bad channel #$channel on P1" . $self->{PAGEDEF});
            # Only warn with max informations one time
            &Warn("Tried to select bad printline channel with pageformat " .
                $self->{CurrentPAGEFORMAT} . "during processing on " .
                $self->{OUTFILE})
                    unless ($self->{BADCHANNELALERT} ++);
            return 0 ;
        }
    }

    # Start new page if required
    $self->startnewpage() if $startnewpage ;

    # Del the previous line if not needed and fix channel block
    if ($self->LastLineMatch( qr/^\\PrintLineChannel/ )) {
        $self->deloneline();

    } elsif ($self->{OPENEDCHANNEL}) {
        # Close previous channel
        $self->closeblock();

        # Select default font if it has changed
        $self->{TRCFONT} = $self->{DefaultTRC}
            unless (defined($self->{TRCFONT}) or
                $self->{LastDefaultTRC} eq $self->{DefaultTRC});
    }

    # Skip font selection when it has not changed
    undef ($self->{TRCFONT})
        if (defined($self->{TRCFONT})
        and $self->{TRCFONT} eq $self->{LastDefaultTRC});

    # Open this channel TeX block
    $self->openblock() unless ($self->LastLineMatch( qr/{%$/ ));
    $self->{LastDefaultTRC} = $self->{DefaultTRC} ;

    # Authorize TeX to load corresponding channel definitions
    $self->newline( "\\PrintLineChannel" . chr( 64 + $channel ) . "%" );

    # Initialize new known channel
    $self->{PrintLine} = ${$self->{PrintLineTab}}[$channel];

    # Reset line repetition control
    $self->{MaxRepeat} = $self->{PrintLine}->{'REPEAT'} ;
    $self->{LINE} = 1 ;
}

sub addline {
    my $self = shift ;
    push @{$self->{LINES}} , @_ if @_;
}

sub openblock {
    # It's better to select font before opening the block
    defined($_[0]->{TRCFONT}) ? $_[0]->newline( "{%" ) : $_[0]->addline( "{%" );
    $_[0]->{OPENEDCHANNEL} = 1 ;
}

sub closeblock {
    $_[0]->addline( "}%" );
    $_[0]->{OPENEDCHANNEL} = 0 ;
}

sub newline {
    my $self = shift ;
    my $line = shift ;

    # Insert TRC font selection if defined
    if (defined($self->{TRCFONT})) {
        # Del the previous line if also and only a font selection
        $self->deloneline() if ($self->LastLineMatch( qr/^\\FONtTrc\w+%$/ ));

        # Insert TRC font selection
        if ( $line !~ /^\\/ ) {
            $self->addline( $self->{TRCFONT} . "%" );

        } else {
            $line = $self->{TRCFONT} . $line ;
        }

        # undefine it to not select font next call
        undef $self->{TRCFONT} ;
    }

    $self->addline( $line );
}

sub newlogo {
    my $self = shift ;
    my $logo = shift ;

    # Current document has logos
    $self->{HAS_LOGO} ++ ;

    push @{$self->{LogoLines}} , $logo ;
}

sub tex_logo_tag { "%%INSERT LOGO HERE" }

sub addsegpath {
    my $self = shift ;
    my ( $path, $name ) = @_ ;

    # Add path only if logo is still not in our list
    push @{$self->{LOGOS}}, $path . $name . '.def'
        unless (exists($self->{LOGOs}->{$name}));
}

sub insertLogos {
    my $self = shift ;
    my $logo = $self->{LOGO_INDEX} ;

    &Debug("Inserting " . @{$self->{LogoLines}} . " lines for logos");

    if ( ! @{$self->{LogoLines}} or $self->{INSERT_LOGO} > 0 ) {
        # Insert current logos
        if ( $self->{INSERT_LOGO} and $logo ) {
            local $" = "\n" ;

            if ( $self->{LINES}->[$logo] eq tex_logo_tag ) {
                &Debug("Inserting logos at previous position tag");
                $self->{LINES}->[$logo] = @{$self->{LogoLines}} ?
                    "@{$self->{LogoLines}}" : "% No logo inserted" ;

                # Fix logo insertion index
                $self->addline( tex_logo_tag );

                # Keep logo index
                $self->{LOGO_INDEX} = $#{$self->{LINES}} ;

            } else {
                # TODO Check if this case happens some time
                &Warn("Not expected logo insertion detected (case #1)");

                # Append logo lines to last inserted logo
                $self->{LINES}->[$logo] .= "\n@{$self->{LogoLines}}" ;
            }

        } elsif ($self->{HAS_LOGO} or ($self->{LINE} and $self->{PAGES})) {

            &Debug("Inserting logos position tag");
            # Fix logo insertion index
            $self->addline( tex_logo_tag );

            $self->{INSERT_LOGO} ++ ;

            # Keep logo index
            $self->{LOGO_INDEX} = $#{$self->{LINES}} ;

        } else {
            &Debug("Nothing to insert");
        }

    } else {
        if (@_ and $_[0] =~ /^LASTINSERT$/) {
            # Called from the end: it's a very bad case
            # TODO Check if this case happens some time
            &Warn("Not expected logo insertion detected (case #2)");

            # Append logo lines to last inserted logo
            local $" = "\n" ;
            $self->{LINES}->[$logo] .= "\n@{$self->{LogoLines}}" ;

        } else {
            &Debug("Inserting logos at current position");
            # Normal case, just add logo lines to lines buffer
            $self->addline( @{$self->{LogoLines}} );

            # Keep logo index
            $self->{LOGO_INDEX} = $#{$self->{LINES}} ;
        }
    }

    $self->{LogoLines} = [] ;
    # Reset flag rotsegment to default
    $self->{ROTSEGMENT} = 0 ;
}

sub selectDefaultTRC {
    # Set current default TRC
    $_[0]->addline( $_[0]->{DefaultTRC} ."%" );
}

sub selectTRCfont {
    # This function analyses the second binary value from linedata
    # It is given as ascii code of a char
    my $self = shift ;
    my $TRC  = shift ;
    my $font = "" ;

    &Debug("TRC font selection byte is $TRC " . sprintf("(0x%X)",$TRC));
    # Ignore left most bits if higher or equal to 0xF0
    $TRC &= 0x0F if ($TRC >= 0xF0);

    &Debug("Font still selected") , return if ( $self->{CurrentTRC} == $TRC );
    $self->{CurrentTRC} = $TRC ;

    # We should not need more TRC fonts, and this skip considering 0x40
    # often found and invalid value
    if ( $TRC < 20 ) { # Must be adapted as needed
    #if ( $TRC < 128 ) {
        #if ( $TRC > 25 ) {
        #    $font = chr( 65 + $TRC / 26 );
        #    $TRC %= 26 ;
        #}
        $font .= chr( 65 + $TRC );
        $self->{TRCFONT} = "\\FONtTrc$font" ;
        &Debug("Selecting Trc{$font} font");
    } else {
        &Debug("Forcing default TrcA font selection as TRC byte is '$TRC'");
        $self->{TRCFONT} = "\\FONtTrcA" ;
    }

    # Redefine default TRC when selecting TRC at the base document
    $self->{DefaultTRC} = $self->{TRCFONT} ;
}

sub startnewpage {
    my $self = shift ;
    $self->{LINE} = 1 ;

    # Remove any unuseful line spacing
    while ( $self->LastLineMatch( qr/LineSpacing/ ) ) {
        $self->deloneline();
    }

    # Close current Page and open new one
    if ($self->{OPENEDCHANNEL}) {
        # Close previous channel if one opened
        $self->closeblock();
    }

    # Check if we are closing the first page reaching the linemax limit
    # (COPYGROUP still not set to close a TeX block)
    if ( $self->{COPYGROUP} !~ /^}%/ and $self->{PAGES} > 0 ) {
        $self->addline( "}%\n" );

    } else {
        $self->addline( $self->{COPYGROUP} );
    }
    $self->addline( $self->{PAGEFORMAT} );
    $self->insertLogos();
    $self->{PAGES} ++ ;

    # Select last used font for this pageformat
    $self->selectDefaultTRC();

    &UPSTAT('GETJOBPAGE');

    &Debug("Composing page number $self->{PAGES}");
    $self->{LastChannel}  = 1 ;
    $self->{StartNewPage} = 0 ;

    # To close last pageformat as at least one is inserted
    $self->{OPENEDPFORMAT}= 1 ;
}

sub updateFlux {
    my $self = shift ;
    my $hashref = shift ;
    map {
        if ( ref($hashref->{$_}) =~ /^HASH/ ) {
            my $key = $_ ;
            map {
                $self->{$key}->{$_} = $hashref->{$key}->{$_}
            } keys(%{$hashref->{$key}}) ;

        } else {
            $self->{$_} = $hashref->{$_}
        }
    } keys(%{$hashref}) ;
}

sub updateEnv {
    my $self = shift ;
    my $hashref = shift ;
    map { $self->{JOBENV}->{$_} = $hashref->{$_} } keys(%{$hashref}) ;
}

sub toclean {
    my $self = shift ;
    my $toclean = $self->{JOBENV}->{TOCLEAN} ;
    $toclean .= ';' if $toclean ;
    $toclean .= shift ;
    $self->{JOBENV}->{TOCLEAN} = $toclean ;
}

sub has_pageformat {
    my $self = shift ;
    return ( defined($self->{PAGEFORMAT}) and $self->{PAGEFORMAT} ) ? 1 : 0 ;
}

sub orientations {
    my $self = shift ;
    return ( $self->{LANDSCAPE}, $self->{ROTSEGMENT} ) ;
}

sub issplitted {
    my $self = shift ;
    return exists($self->{JOBENV}->{SPLIT_TAG}) ;
}

sub getEnv {
    my $self = shift ;

    my $JobEnv = $self->{JOBENV} ;

    # Only return the requested argument value if exists
    return $JobEnv->{$_[0]} || 0 if ( @_ and defined($_[0]) );

    # Update COPIES as it's not including first print
    $JobEnv->{COPIES} = scalar($JobEnv->{COPIES}) + 1 ;

    return join('',
        map {
            qq|<env key='$_'>| . $JobEnv->{$_} . qq|</env>|
        } keys(%{$JobEnv}) );
}

my $yes = qr/^yes$/i ;
sub getstat {
    my $self = shift ;

    my $kind = 'P' ; # By default, it's a print
    my $env = $self->{JOBENV} ;

    if ( defined($env->{ISPRINT}) and ! $env->{ISPRINT} ) {
        if ( defined($env->{DO_ARCH}) and $env->{DO_ARCH} =~ $yes ) {
            $kind = 'A' ;
        }
        if ( defined($env->{DO_ESERVICE}) and $env->{DO_ESERVICE} =~ $yes ) {
            $kind = ( $kind eq 'A' )? 'E' : 'S' ;
        }
    }

    return ( $env->{JOBNAME}, $env->{DESTID}, $env->{PAGEDEF}, $env->{FORMDEF},
        $env->{DOCNAME}, join('+',keys(%{$self->{PAGEFORMATs}})),
        join('+',keys(%{$self->{COPYGROUPs}})),
        join('+',keys(%{$self->{LOGOs}})),
        $self->{PAGES} * $env->{COPIES}, $kind, $LOCKID );
}

sub deloneline {
    my $self = shift ;
    return defined( pop( @{$self->{LINES}} ) ) ;
}

sub LastLineMatch {
    my $self    = shift ;
    my $pattern = shift ;
    my $index   = $#{$self->{LINES}} ;
    $index -= $_[0] if ($_[0]);
    return 0 if ( $index < 0 ); # $#{} gives -1 when array is empty or undefined
    return ${$self->{LINES}}[$index] =~ $pattern ;
}

sub getoutbase {
    my $self = shift ;
    return $self->{OUTFILE} || '' ;
}

sub setoutfile {
    my $self    = shift ;
    my $outfile = shift ;
    &Debug("Updating OUTFILE='$self->{OUTFILE}' with '$outfile'");
    $self->{OUTFILE} = $outfile ;
}

sub setTRCforTeX {
    my $self    = shift ;
    my $texcode = shift ;
    return if (!defined($texcode));
    return if (length($texcode) == 0);
    $self->{TRCTeXCode} = "\n" . $texcode . "\n" ;
    &Debug("TRCTeXCode initialized");
}

sub setpagedef {
    my $self    = shift ;
    my $pagedef = shift ;
    &Debug("Updating PAGEDEF='$self->{PAGEDEF}' with '$pagedef'");
    $self->{PAGEDEF} = $pagedef ;
}

sub pagedef {
    my $self = shift ;
    return $self->{PAGEDEF} || "" ;
}

sub setformdef {
    my $self    = shift ;
    my $formdef = shift ;
    &Debug("Updating FORMDEF='$self->{FORMDEF}' with '$formdef'");
    $self->{FORMDEF} = $formdef ;
}

sub setpclcond {
    my $self = shift ;
    my $cond = shift ;
    $cond = 0 if (!defined($cond));
    &Debug("Updating PCLCOND='$self->{PCLCOND}' with '$cond'");
    $self->{PCLCOND} = $cond ;
}

sub gentex {
    my $self = shift ;
    my $file = shift ;
    my $line ;
    my $index = 0 ;
    my $pclspecial = "" ;

    # Add automatically EOL to each print command
    local $\ = "\n" ;

    # Set a localtime mark up
    $self->{TeXGenTime} = localtime() ;

    # Flush LogoLines if empty new page still exists
    $self->insertLogos('LASTINSERT') if ( $#{$self->{LogoLines}} >= 0 );

    # PageDef and FormDef should right at that time
    push @{$self->{texpackages}} , "p1" . lc( $self->{PAGEDEF} ) ;
    push @{$self->{texpackages}} , "f1" . lc( $self->{FORMDEF} ) ;

    # Check if PCL5 will be generated to define some TeX special command
    # 1. \pclportrait and \pcllandscape must be set to insert usefull PCL5
    #    commands
    # 2. Bin/tray support, define the right \special commands to include
    #    print specific settings
    if ($self->{PCLCOND} and ! $USE_PCLCMD ) {
        my $pcl5cmdpath = "/apps/afp2print/printlib/texlib" ;
        # PCL5 commands files path can be overided using PCL5CMDPATH ENV
        $pcl5cmdpath = $ENV{PCL5CMDPATH} if (defined( $ENV{PCL5CMDPATH} ));
        $pcl5cmdpath =~ s/\/+$// ;
        $pclspecial =
            "\\def\\SelectBinTrayA{\\special{" . $self->{OUTFILE} .
                ".trayone}}\n" .
            "\\def\\SelectBinTrayB{\\special{" . $self->{OUTFILE} .
                ".traytwo}}\n\n" .
            "\\def\\pclportrait{\\special{" .
                $pcl5cmdpath . "/afp2print_portrait.pcl5}}\n" .
            "\\def\\pcllandscape{\\special{" .
                $pcl5cmdpath . "/afp2print_landscape.pcl5}}\n\n" ;
    }

    # Check LOGO files are existing
    my $segment_libraries = "" ;
    foreach my $logo ( @{$self->{LOGOS}} ) {
        my $thisone = "\\input{$logo}\n" ;
        if ( -e $logo ) {
            $logo =~ s/\.def$// ;
            # Define image base if one exists as .def need it
            # TODO Add this to test "or -e $logo . '.tif'" when
            # TIFF will be supported for PCL
            if ( -e $logo . '.png' ) {
                $thisone = "\\def\\segbase{$logo}\n" . $thisone ;
                &Debug("TeX code added to enable PNG image loading");
            }
            $segment_libraries .= $thisone ;

        } else {
            $logo =~ $1 if ( $logo =~ m|([^/]+)$| );
            &Warn("Won't load $logo segment as not found in library");
        }
    }

    # TeX debugging to be used in validation only
    my $TeXDEBUG = "" ;
    if ( $ADDTEX_DEBUG ) {
        $TeXDEBUG .= "\\def\\DEBUG{$ADDTEX_DEBUG}\n" .
            "\\def\\DEBUGPAGEDEF{$TEX_PAGEDEF_DEBUG}\n" .
            "\\def\\DEBUGOVERLAY{$TEX_OVERLAY_DEBUG}\n" .
            "\\def\\DEBUGSEGMENT{$TEX_SEGMENT_DEBUG}\n" .
            "\\def\\SHOWSEGMENT{$TEX_SHOW_SEGMENT}\n" ;
    }

    # TeX info
    my $DocInfo = "" ;
    if ( $ADDTEX_DOCINFO ) {
        $DocInfo .= "/Title   (" . $self->{JOBENV}->{JOBNAME} . ")\n"
            if ($self->{JOBENV}->{JOBNAME});
        $DocInfo .= "/Author  (" . $self->{JOBENV}->{USERNAME} . ")\n"
            if ($self->{JOBENV}->{USERNAME});
        $DocInfo .= "/Creator (A2P v" . A2P_RPM_VERSION . ")\n"
            if (A2P_RPM_VERSION);
        $DocInfo = "\n\\ifpdf\n\\pdfinfo{" . $DocInfo . "}\\fi\n" if $DocInfo ;
    }

    # Insert in first position default definitions package to load for archivage
    if (defined($self->{JOBENV}->{ISPRINT}) and ! $self->{JOBENV}->{ISPRINT}) {
        unshift @{$self->{texpackages}}, 'afp2print_archi_pre_def' ;
    }

    if ( print( $file
        "\\documentclass{minimal}\n",
        $self->{PCLCOND} ? "\\def\\pcloutput{1}\n" : "" ,
        map( "\\usepackage{" . $_ . "}\n" , @{$self->{texpackages}} ) ,
        $segment_libraries,
        "\\listfiles\n" ,
        "%% \n%% AFPDS File: " . $self ->{AFPDSFILE} ,
        "\n%% FormDef   : "    . $self ->{FORMDEF} ,
        "\n%% PageDef   : "    . $self ->{PAGEDEF} ,
        "\n%% TexGenTime: "    . $self ->{TeXGenTime} ,
        "\n%% \n" ,
        "\\ResetLength\n" ,$TeXDEBUG , $DocInfo ,
        $self->{TRCTeXCode} , $pclspecial ,
        "\\begin{document}\\FONtTrcA% Default font") )
    {
        &Debug("Output TeX header done") ;
    } else {
        return &Error("Can't output TeX header") ;
    }

    # Output all lines stripping and compressing some unuseful patterns
    if ( join('',map { print $file $_ } @{$self->{LINES}}) !~ /^0+$/ ) {
        &Debug("Output TeX Content done") ;
    } else {
        return &Error("Can't output TeX Content") ;
    }

    # ErAl008w fix support when only close last Pageformat is one opened
    if ( $self->{OPENEDPFORMAT} ) {
        print( $file "}%" ) if ($self->{OPENEDCHANNEL});
        print( $file "}%" );
    }

    # And add TeX end block to the output
    if ( print( $file "\\end{document}" )) {
        &Debug("Output TeX Footer done") ;
    } else {
        return &Error("Can't output TeX Footer") ;
    }
    return 1 ;
}

sub got5Achar {
    my $self = shift ;

    # Create MODCA object
    my $afpobject = new AFPDS::MODCA( $self, @_ );

    # Check object
    my @err = $afpobject->check ;

    # Create object on no check error
    @err = $afpobject->create unless ( @err and defined($err[0]) and $err[0] );

    # Report error as ABTERM if present or return 0
    return ( @err and defined($err[0]) and $err[0] ) ? $self->ABTERM(@err) : 0 ;
}

sub setjobindex {
    my $self = shift ;
    # Index is starting at 0
    $self->{JOBINDEX} = ( shift || 1 ) - 1 ;
}

sub set_resource {
    my $self = shift ;
    my $object = shift ;

    # Resource must be a MO:DCA object
    return $self->{SELECTED_RESOURCE} = ""
        unless ( ref($object) =~ /^AFPDS::MODCA/ );

    # Keep a uniq TeX/LaTeX name if still not set
    my $texname = exists($self->{RESOURCE}->{$object->name}) ?
        $self->{RESOURCE}->{$object->name}->[1] : '' ;

    # Keep a resource number as expected for PCL macro ID
    my $number = exists($self->{RESOURCE_NUMBER}) ?
        $self->{RESOURCE_NUMBER} + 1 : 0 ;

    unless ( $texname ) {
        my $texbase = "JOB" . ( $self->{JOBINDEX} || 0 ) . $object->name ;
        $texbase =~ y/0-9/a-j/ ;
        $texname = $texbase ;

        my %existing = map { $self->{RESOURCE}->{$_}->[1] => 1 }
            keys(%{$self->{RESOURCE}}) ;

        my $index = 0 ;
        while (++$index) {
            my $tag = sprintf("%02d",$index);
            $tag =~ y/0-9/a-j/ ;
            $texname = $texbase . $tag ;
            last unless (exists($existing{$texname}));
        }
    }

    # Keep buffer reference
    $self->{RESOURCE}->{$object->name} = [ $object, $texname, $number ] ;

    # Select it as current resource
    $self->{SELECTED_RESOURCE} = $object->name ;

    # Update resource number for next resource
    $self->{RESOURCE_NUMBER} = $number ;
}

sub get_resource {
    my $self = shift ;
    my $name = shift || $self->{SELECTED_RESOURCE} ;

    return 0 unless ($name and exists($self->{RESOURCE}->{$name}));

    # Resource must be a MO:DCA object
    my $object = $self->{RESOURCE}->{$name}->[0] ;
    return ref($object) =~ /^AFPDS::MODCA/ ? $object : 0 ;
}

sub resource_texname {
    my $self = shift ;
    my $name = shift || $self->{SELECTED_RESOURCE} ;

    return 0 unless ($name and exists($self->{RESOURCE}->{$name}));

    return "InlineResource" . $self->{RESOURCE}->{$name}->[1] ;
}

sub resource_number {
    my $self = shift ;
    my $name = shift || $self->{SELECTED_RESOURCE} ;
    my $reso = shift || 240 ;

    return undef unless ($name and exists($self->{RESOURCE}->{$name}));

    my $number = $self->{RESOURCE}->{$name}->[2] ;
    # if a scalar, ref is false
    if (ref($number)) {
        if (exists($number->{$reso})) {
            $number = $number->{$reso} ;

        } else {
            # Set a new number
            $number->{$reso} = $self->{RESOURCE_NUMBER} ;
            $number = $self->{RESOURCE_NUMBER} ++ ;
        }
    } else {
        # Just initialize the number list by resolution
        $self->{RESOURCE}->{$name}->[2] = { $reso => $number } ;
    }
    return $number ;
}

sub ABTERM {
    my $self = shift ;
    @{$self->{ERROR}} = @_ ;
    &Error($self->{ERROR}->[1]);
    return - $self->{ERROR}->[0] ;
}

sub geterror {
    return @{$_[0]->{ERROR}} ;
}

sub DESTROY {
    my $self = shift;
    my @err  = @{$self->{ERROR}};

    # Free arrays memory
    map { $self->{$_} = () if (ref($self->{$_}) eq 'ARRAY' ) } keys(%{$self});

    if (@err) {
        &UPSTAT('GETFLUXERROR');
        &UPSTAT('GETFLUXERROR-' . $err[0] );
        &Debug("Conversion object for $self->{JOB} destroyed with error #" .
            $err[0]);

    } else {
        &UPSTAT('GETGOODAFPDS');
        &Debug("Conversion object for $self->{JOB} destroyed");
    }
}

&Debug("Module " . __PACKAGE__ . " v$VERSION loaded");

1;
