#!/usr/bin/perl -w
# NAME: lib_xml.pl
# AIM: Gathering together useful 'xml' parsing functions
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )

# added 20120625
# added 07/12/2008 from fgscanvc.pl in Dell02:D:\fg\26
sub xml_array_to_lines {
    my ($rlm, @lns) = @_;
    my $intag = 0;
    my $text = '';
    my @nlines = ();
    my ($fln, $ln, $ch, $pch, $nch, $len, $i, $i2, $tag, $xml, $dnx);
    my ($lnnm, $lnb, $nlnm);
	my ($ppch, $rem, $incomm);
    $pch = '';
    $nch = '';
    $tag = '';
    $xml = '';
	$ppch = '';
    $dnx = 0;
    $lnnm = 0;
    $nlnm = 0;
    $lnb = 0;
	$incomm = 0;
	$text = '';
    foreach $fln (@lns) {
        chomp $fln;
        $ln = trim_all($fln);
        $len = length($ln);
        $lnnm++;    # count another xml line
        for ($i = 0; $i < $len; $i++) {
            $i2 = $i + 1;
            $ch = substr($ln,$i,1);
            $nch = (($i2 < $len) ? substr($ln,$i2,1) : ' ');
            if ($intag) {
                # on close of tag
                $tag .= $ch;
                if ($ch eq '>') {
                    # end of XML tag
					if (( ! $incomm) || ( $incomm && ($pch eq '-') && ($ppch eq '-') )) {
						$nlnm++;
						push(@nlines,$tag);
						### prt( "push(\@xlnmap, [ $nlnm, $lnb, $lnnm ]); # each NEW line has BEGIN and END\n" );
						$$rlm{$nlnm} = "$lnb-$lnnm";    # each NEW line has BEGIN and END
						$tag = '';
						$intag = 0;
						$xml = '';
						$incomm = 0;
					}
                }
            } else {
                if ($ch eq '<') {
					if (length($text)) {
						$nlnm++;
						push(@nlines,$text);
						### prt( "push(\@xlnmap, [ $nlnm, $lnb, $lnnm ]); # each NEW line has BEGIN and END\n" );
						$$rlm{$nlnm} = "$lnb-$lnnm";    # each NEW line has BEGIN and END
						$text = '';
					}
					if ($nch eq '!') {
						# potential start of comment <!-- until -->
						$rem = $len - $i;
						if (($rem > 4) && (substr($ln,$i,4) eq '<!--')) {
							$incomm = 1;
						}
					}
                    $tag = $ch; # start a tag line
                    $intag = 1; # signal in a tag
                    $xml = '';
                    $dnx = 0;
                    $lnb = $lnnm;    # set the BEGIN xml line
                } else {
					$text .= $ch;
				}
            }
			$ppch = $pch;
            $pch = $ch;
        }
        # done a line - this is like a SPACE
        if ($intag && length($tag)) {
            $tag .= ' ' if !($tag =~ /\s$/);
        }
    }
    if (length($tag)) {
        prtw("WARNING: xml re-lining error! Left pending tag [$tag]\n");
    }
    return @nlines;
}


1;
# eof - lib_xml.pl
