#!/usr/bin/perl

my($string,$stringnew,$txt,$zpgm,$zkey,%hash);
my($zfn);
local($zii);
$hash{aaa}='www';
$hash{bbb}='xxx';
$hash{ccc}='zzz';

$zii=0;
#$string='<%zzz%>original text <%=aaa%> value</%zzz%>
#          some filler stuff <%xxx%>2nd orig <%=bbb%> txt  
#         </%xxx%> and later
#         <%zzz%>2nd original text <%=ccc%> value</%zzz%>';
$zfn='member_update.html';


undef $/;
open(FN,"<$zfn") || die("Unable to open '$zfn'");
$string=<FN>;
close(FN);
$/="\n";

# print "\norig string='$string\n";
$hash{u_loc}='city1#11111:city2#2222222:city3#333333333:city4#44444444';
foreach $zpgm ($string =~ /<%.*?%>/g)
{ 
  $zpgm=substr($zpgm,2,length($zpgm)-4);
  next if(substr($zpgm,0,1) eq '=');

  $string =~ s|<%$zpgm%>(.*?)</%$zpgm%>|&$zpgm($1,%hash);|sge;
  print "zpgm='$zpgm' used\n";
# print "string='$string'\n";

}
$zfn='member_update.html2';
open (FN,">$zfn") || die("could not open $zfn for write");
print FN $string;
close (FN);
exit;

sub www
{ my($xtemp,%xhash)=@_;
  print "\nwww xtemp='$xtemp'\n";
  return(&zzz($xtemp,%xhash));
}

sub xxx
{ my($xtemp,%xhash)=@_;
  print "\nxxx xtemp='$xtemp'\n";
  return(&zzz($xtemp,%xhash));
}

sub zzz
{ my($xtemp,%xhash)=@_;
  my($zkey,$zval);
  $zii++;
  print "zzz $zii xtemp='$xtemp'\n";
  foreach $zkey($xtemp =~ /<%=.*?%>/g)
  { $zkey=substr($zkey,3,length($zkey)-5);
    $zval=$xhash{$zkey};
    $xtemp =~ s/<%=$zkey%>/$zval/g;
  }
  return($xtemp);
}

#####################################################################
# process city/phone locations
# template lines from parse_template routine.
#####################################################################
sub city_loc_phone
{ my($xtemplate,%xhash)=@_;                     # input args
  my($zrec,$zkey,$zresult,%zhash);              # internal variables

  $xhash{ii}=0;
  $zresult='';                                  # reset output
  $zu_loc=$xhash{u_loc}.':#';
  while ($zu_loc ne '')
  { $xhash{ii}++;

    ($zcityphone,$zu_loc)=split(/:/,$zu_loc,2);
    ($xhash{uu_city},$xhash{uu_phone})=split(/#/,$zcityphone,2);
    $zresult.=$xtemplate;                       # concat template to result
    foreach $zkey($zresult =~ /<%=.*?%>/g)      # <%=key%> in template
    {
      $zkey=substr($zkey,3,length($zkey)-5);    # get actual key
print "xhash{$zkey}='$xhash{$zkey}'\n";
      $zresult =~ s/<%=$zkey%>/$xhash{$zkey}/g; # replace with value
    }
  }                                             # next subset db entry
  return($zresult);                             # return result
}


    foreach $zkey ($zrec =~ /<%=.*?%>/g)
    { $zkey=substr($zkey,3,length($zkey)-5);
      $zval=$xmrg{$zkey};
      if($zval eq '')
      { $zrec =~ s/"<%=$zkey%>"/"$zval"/g;
        $zrec =~ s/<%=$zkey%>/$zval2/g;
      }
      else
      { if($zrec =~ /"<%=$zkey%>"/
         ||$zrec =~ /><%=$zkey%></)
        { $zval =~ s/<br>/\n/ig;
        }
        $zrec =~ s/<%=$zkey%>/$zval/g;
      }
    }

