#!/usr/bin/perl -w
#Developed in 2001 by Philipp Ghring (pg@futureware.at). GPL applies. 

use XML::Sablotron::DOM qw( :constants :functions );
use XML::Sablotron qw( :all );
use CGI qw(:standard :cgi-lib);
use Data::Dumper;

my %in;
CGI::ReadParse(\%in);

my @parameter;
@parameter=%in;

my $user="1"; $user=$1 if ($in{user} =~ m/(\w+)/);
my $auftrag=""; $auftrag=$1 if ($in{auftrag} =~ m/(\d+)/);

print "Content-type: application/msword; filename=\"AS$auftrag.doc\";\n\n";

open IN,"db/$user/auftr/$auftrag";
undef $/;
my $content=<IN>;
close IN;

open IN,"AS022.doc";
my $template=<IN>;
close IN;

my $sit = new XML::Sablotron::Situation();
my $doc = XML::Sablotron::DOM::parseBuffer($sit, $content);

my $myresult= $doc->xql("/AUFTRAG/ITEM_LIST/ITEM/ARTICLE_ID/*");

#foreach my $key (@$myresult)
#{
#  print STDERR Dumper $key->getNodeName();
#  print STDERR Dumper $key->getFirstChild()->getNodeValue();
#}

my $output="";

foreach(my $i=0x30000;$i<=0x32400;$i+=0x200)
{
  my $feldlaenge=unpack("L",substr($template,$i-256,4));

  #print STDERR "Lnge: $feldlaenge\n";

  my $text="";
  $content =~ s/<ITEM>(.*?)<\/ITEM>//s;
  my $item=$1;
  $text.="$1. \n" if($item =~ m/<LINE_ITEM_ID>(\d+)<\/LINE_ITEM_ID>/);
  $text.="$1\n" if($item =~ m/<DESCRIPTION_SHORT>(.*?)<\/DESCRIPTION_SHORT>/);

#      <ARTICLE_ID>
#        <DESCRIPTION_SHORT>Deskjet</DESCRIPTION_SHORT>
#      </ARTICLE_ID>

  #my $text=$node->getNodeName($sit);
  #if ($text eq 'ITEM')
  #{
    $text=substr($text.(" " x $feldlaenge),0,$feldlaenge);
    #print STDERR "Text: '$text'\n";
    substr($template,$i,$feldlaenge)=$text;
  #}
  #$node=$node->getNextSibling($sit);

  $text.="$1\n" if($item =~ m/<DESCRIPTION_LONG>(.*?)<\/DESCRIPTION_LONG>/);
  $output.="$text\n";
}

my $feldlaenge=unpack("L",substr($template,0x2b600-256,4));
$output=substr($output.(" " x $feldlaenge),0,$feldlaenge);
substr($template,0x2b600,length($output))=$output;


print $template;

