package xm::sub;

use strict;

sub xx # also defined as xm::o::xx
{
    return defined $_[0] ? $_[0] : "" ;
}

sub off 
{
    my $in = shift;
    $in =~ s{\&}  {\&}gs;
    $in =~ s{\<}  {\&lt;}gs;
    $in =~ s{\>}  {\&gt;}gs;
    $in =~ s{\"}  {\&quot;}gs;
    return $in;
}

sub on 
{
    my $in = shift;
    $in =~ s{\&quot;} {\"}gs;
    $in =~ s{\&gt;}   {\>}gs;
    $in =~ s{\&lt;}   {\<}gs;
    $in =~ s{\&amp;}  {\&}gs;
    return $in;
}

sub off3 
{
    my $in = shift;
    $in =~ s{\&}  {\&amp;}gs;
    $in =~ s{\<}  {\&lt;}gs;
    $in =~ s{\>}  {\&gt;}gs;
    return $in;
}

sub on3
{
    my $in = shift;
    $in =~ s{\&gt;}   {\>}gs;
    $in =~ s{\&lt;}   {\<}gs;
    $in =~ s{\&amp;}  {\&}gs;
    return $in;
}

sub un_quote
{
    my $in = shift;
    $in =~ s{^ \&quot\;   } {}gsx;
    $in =~ s{  \&quot\; $ } {}gsx;
    return $in;
}

sub C
{
    my $in = shift;
    if ($in =~ /^\"(.*)\"$/)
    {
	$in = $1;
	$in =~ s{\\(.)} {
	    $1 eq "n" ? "\n" :
		$1 eq "t" ? "\t" :
		    $1 }gse;
    }elsif ($in =~ /^\&quot;(.*)\&quot;$/)
    {
	$in = $1;
	$in =~ s{\\(.)} {
	    $1 eq "n" ? "\n" :
		$1 eq "t" ? "\t" :
		    $1 }gse;
    }elsif ($in =~ /^\'(.*)\'$/)
    {
	$in = $1;
	$in =~ s{\\(.)} {
	    $1 eq "n" ? "\n" :
		$1 eq "t" ? "\t" :
		    $1 }gse;
    }
    
    return $in;
}

sub split # (LEADER,TEXT) -> \@splitted that asserts (TEXT == join("",@$splitted))
{
  my ($N,$T) = @_;
  $T = $_ if not defined $T;
  
  my $A = [ ];
  
  my $save = "";
  my $f = sub 
  { 
      if (1 == index($_[1],"/") )
      { push(@$A, $save.$_[0].$_[1]); $save = ""; }
      else
      { $save = $_[1]; push(@$A, $_[0]) if length $_[0]; }
  };
  
  $T =~ s{ ^(</?$N(?:\s[^<>]*)?>) } 
      	 { &$f("",$1) }sex;
  $T =~ s{ ((?:.(?!</?$N[\s>]))*.) (</?$N(?:\s[^<>]*)?>); "" } 
      	 { &$f($1,$2); "" }gsex;
        
  push @$A, $save.$T
}

1;