#!/user/bin/perl
#
#  readSbs  Extract information from sbs file.
#
#  Arguments:  <filespec>  File specification (RegExp style),
#
#  Command options
#      -v             Verbose
#      -h             Generate html output
#      -h<directory>  Select directory for html files
#      -p<filepath>   Generate player-data file
#      -m<filepath>   Generate match data file
#      -a<filepath>   Generate player averages file
#      -w<filepath>   Generate fall-of-wicket data file
#      -r             Recursive search from root directory
#      -d<rootdir>    Root directory for input file search
#
   $verbose = 0;
   $recursive = 0;
   $rootdir = './';
   while ($ARGV[0] =~ /^-/) {
      $_ = shift;
      if (/^-v/) {
         $verbose = 1;
      } elsif (/^-h(.*)/) {
         $printhtml = 1;
         $htmldir = $1;
      } elsif (/^-p(.*)/) {
         $printpdata = 1;
         $pdatafile = $1;
      } elsif (/^-m(.*)/) {
         $printmdata = 1;
         $mdatafile = $1;
      } elsif (/^-a(.*)/) {
         $printadata = 1;
         $adatafile = $1;
      } elsif (/^-w(.*)/) {
         $printwdata = 1;
         $wdatafile = $1;
      } elsif (/^-r/) {
         $recursive = 1;
      } elsif (/^-d(.*)/) {
         $rootdir = $1;
      }
   }


   &readSbs;
#   &fileLoop($rootdir);

sub fileLoop {
#
#   Run through directories and data files
   local($rootdir) = @_;
   local(*ROOTDIR);
   local($currentFile);

#  Find all files in this directory which match the spec.
   if ($verbose) {print "Data directory = $rootdir\n";}
   opendir(ROOTDIR,$rootdir) || die "fileLoop: Unable to open directory $rootdir\n";
      while ($file=readdir(ROOTDIR)) {
         if ($recursive && -d $rootdir.$file && $file !~ /\.+/) {
            &SearchDir($rootdir.$file."\\",$fileSpec,$recursive);
         }
         elsif ($file=~/$fileSpec.*/) {
               print $rootdir.$file."\n";
      }
   }   

   closedir(ROOTDIR);

}

sub readSbs {
   ($dpath,$dummy,$ffilter) = ($ARGV[0] =~ m=((.*/)*)(.*)=);

   if ($dpath=~/^\s*$/) {
      $dpath = './';
   }
#
#  Convert to DOS-style path (with \s)
   $dpath =~ s=/=\\=g;

#  Deal with file selection starting with a wildcard
   if ($ffilter=~/^\*.*/) {
      $ffilter = ".".$ffilter;
   }

#
#  Find files matching the supplied pattern
   opendir(DATADIR,$dpath) || die "readSbs: Could not open directory $dpath \n";

   while ($datafile=readdir(DATADIR)) {
      if ($datafile=~/$ffilter.*/) {
         if ($verbose) {print $dpath.$datafile."\n";}
         open(DATAFILE,$dpath.$datafile) || die "Could not open file $dpath.$file\n";
         &readDataFile_03;
         close(DATAFILE);

         if ($verbose) {&dumpSbsData;}   # For debugging
         if ($printhtml) {
            &scoreSheetAnalysis;
#           Create html output file
            ($filename,$type) = $datafile=~/(\w.*)\.(\w.*)$/;
            $htmlfile = $htmldir.$filename.".htm";
            if ($verbose) {print "html output to $htmlfile\n";}
            &makehtml($htmlfile);
         }

         if ($printpdata) {
#           Write player data to output file
            if ($verbose) {print "player data to $pdatafile\n";}
            &makepdata($pdatafile);
         }

         if ($printmdata) {
#           Write match data to output file
            if ($verbose) {print "match data to $mdatafile\n";}
            &makemdata($mdatafile);
         }

         if ($printadata) {
#           Write player average data to output file
            if ($verbose) {print "match data to $mdatafile\n";}
            &accumulateAverages();
         }

         if ($printwdata) {
#           Write fall-of-wicket data to output file
            if ($verbose) {print "Fall-of-wicket data to $wdatafile\n";}
            &makewdata($wdatafile);
         }

#
#  Tidy up data structure for next file
         undef %sbsdata;
      }
   }   
   close(DATADIR);

#
#  Output data for this batch of files.

   if ($printadata) {
      if ($verbose) {&printAverages();}
      &printAverages($adatafile);
   }
}

sub readDataFile_03 {
#
#   Read files in "sbs"  (Score Book Summary) format
#   (cf match_example_03.sbs)
#   +section
#      sub1:data !comment
#      sub2:data ! comment
#   +section2
#      sub1:stuff
#... etc

#
   while (<DATAFILE>) {
#  Strip comments before parsing data line
      chop;
      ($line,$cmark,$comment) = $_=~/^([^!#]*)([!#]?)(.*)$/;
#     print "$_->$line ? $cmark ? $comment\n";
      if ($line=~/^\+(.*)/) {
         $section = $1;
         $#{$sbsdata{$section}}++;
         $sectionCount = $#{$sbsdata{$section}};
         if ($verbose) {print "Found start of section header data: $section $sectionCount\n";}
      } elsif ($line=~/\s*(\w+):(.*)$/) {
         if ($verbose) {print "Datatype $1 - $2\n";}
         push @{$sbsdata{$section}[$sectionCount]{$1}}, $2;
      }
   }
}

sub dumpSbsData {
#
#   Print SBS data structure for debugging purposes
#
   foreach $key (keys %sbsdata) {
      print "$key $#{$sbsdata{$key}}\n";
      for ($ii=0; $ii<=$#{$sbsdata{$key}}; $ii++) {
         foreach $subkey (keys  %{$sbsdata{$key}[$ii]} ) {
            print "   $ii $subkey $#{$sbsdata{$key}[$ii]{$subkey}}\n";
            for ($jj=0; $jj<=$#{$sbsdata{$key}[$ii]{$subkey}}; $jj++) {
               print "      $jj $sbsdata{$key}[$ii]{$subkey}[$jj] \n";
            }
         }
      }
   }
}

#
#--------- Subroutines to create html file -----------------------------
#
sub scoreSheetAnalysis {
#
#  Extract scoresheet data from sbs record, and format for html output.
#
#
#  Scoresheet header data.
#
#  Undefine previous version of data structures to avoid hangovers from previous files.
   undef %matchhdr;
   undef @innData;
   undef @innPlayers;

   if ($verbose) {
      print "scoreSheetAnalysis\n";
      print "Date -> $sbsdata{'match'}[0]{'date'}[0]\n";
      print "Home team -> $sbsdata{'match'}[0]{'hometeam'}[0]\n";
      print "Away team -> $sbsdata{'match'}[0]{'awayteam'}[0]\n";
      print "Venue -> $sbsdata{'match'}[0]{'venue'}[0]\n";
      print "Result -> $sbsdata{'match'}[0]{'result'}[0]\n";
      print "Margin -> $sbsdata{'match'}[0]{'margin'}[0]\n";
   }

   %wonlost = ('w','Won','W','Won','l','Lost','L','Lost','d','Match drawn','D','Match drawn');
   %wintype = ('w','wickets','W','wickets','r','runs','R','runs');
   $matchhdr{'date'} = $sbsdata{'match'}[0]{'date'}[0];
   $matchhdr{'venue'} = $sbsdata{'match'}[0]{'venue'}[0];

#  Get name of opponents (could be home or away).
   $oppo = $sbsdata{'match'}[0]{'hometeam'}[0];
   if ($oppo=~/^RBCC/ || $oppo=~/.*[Rr]ed.*[Bb]at/) {
      $oppo = $sbsdata{'match'}[0]{'awayteam'}[0];
   }
   $matchhdr{'opponents'} = $oppo;

#  Determine match result (could be abbreviated or written in full).
   ($res) = $sbsdata{'match'}[0]{'result'}[0]=~/\s*(\w.*)/;
   if ($res=~/^[WwLlDd]$/) {
     $mar = $sbsdata{'match'}[0]{'margin'}[0];
     if ($mar=~/\s*(\d*)([wrWR])/) {
        $res = "$wonlost{$res} by $1 $wintype{$2}";
     } else {
        $res = $wonlost{$res};
     }
     if ($verbose) {print "result, margin = $res, $wonlost{$res}, $mar\n";}
   }
   $matchhdr{'result'} = $res;
   $matchhdr{'ninnings'} = 1 + $#{$sbsdata{'innings'}};
   $nnotes = 0;
   foreach $note (@{$sbsdata{'match'}[0]{'comment'}}) {
      $matchhdr{'notes'}[$nnotes++] = $note;
   }

#  Determine correct ordering of innings.
   for ($ii=0; $ii<$matchhdr{'ninnings'}; $ii++) {$innSeq[$ii]=$ii;}
   @innSeq = sort {$sbsdata{'innings'}[$a]{'number'}[0] <=> $sbsdata{'innings'}[$b]{'number'}[0]} @innSeq;
   if ($verbose) {
      print "Innings sequence is @innSeq ($matchhdr{'ninnings'})\n";
      foreach $inn (@innSeq) {
         print "   $inn $sbsdata{'innings'}[$inn]{'number'}[0] $sbsdata{'innings'}[$inn]{'team'}[0] $sbsdata{'innings'}[$inn]{'runs'}[0]\n";
      }
   }

#  Arrange innings data for scoresheet printing.
   foreach $inn (@innSeq) {
      $team = $sbsdata{'innings'}[$inn]{'team'}[0];
      $innNumber = $sbsdata{'innings'}[$inn]{'number'}[0];
      $innData[$innNumber]{'runs'} = $sbsdata{'innings'}[$inn]{'runs'}[0];
      $innData[$innNumber]{'wickets'} = $sbsdata{'innings'}[$inn]{'wickets'}[0];
      $innData[$innNumber]{'extras'}{'nb'} = $sbsdata{'innings'}[$inn]{'nb'}[0];
      $innData[$innNumber]{'extras'}{'w'} = $sbsdata{'innings'}[$inn]{'w'}[0];
      $innData[$innNumber]{'extras'}{'b'} = $sbsdata{'innings'}[$inn]{'b'}[0];
      $innData[$innNumber]{'extras'}{'lb'} = $sbsdata{'innings'}[$inn]{'lb'}[0];
      $innData[$innNumber]{'extras'}{'total'} = $sbsdata{'innings'}[$inn]{'ex'}[0];
      $nnotes = 0;
      foreach $note (@{$sbsdata{'innings'}[$inn]{'comment'}}) {
         $innData[$innNumber]{'notes'}[$nnotes++] = $note;
      }
      
#     Determine batting and bowling teams.
      for ($it=0; $it<=$#{$sbsdata{'team'}}; $it++) {
         if ($sbsdata{'team'}[$it]{'name'}[0] eq $team) {
            $status = 'batting';
            $itbat = $it;
         } else {
            $status = 'bowling';
            $itbowl = $it;
         }
         if ($status eq 'batting') {
            $iseg = 1;
         } else {
            $iseg = 2;
         }
         if ($innNumber > 2) {$iseg += 2;}
         if ($verbose) {print "Innings: $inn $innNumber $team $status $iseg\n";}

         $nplayers = $#{$sbsdata{'team'}[$it]{'pl'}};
         $innData[$innNumber]{$status}{'team'} = $sbsdata{'team'}[$it]{'name'}[0];
         $innData[$innNumber]{$status}{'nplayers'} = $nplayers;
         for ($ip=0; $ip<=$nplayers; $ip++) {
            @segments = split /;/, $sbsdata{'team'}[$it]{'pl'}[$ip];
            $playerName = $segments[0];
            @figures = split /,/, $segments[$iseg];
            $innPlayers[$innNumber]{$status}[$ip]{'name'} = $segments[0];
            $innPlayers[$innNumber]{$status}[$ip]{'seq'} = $figures[0];
            for ($ii=1; $ii<=$#figures; $ii++) {
               $innPlayers[$innNumber]{$status}[$ip]{'figures'}[$ii] = $figures[$ii];
            }

            if ($verbose) {
               print "$ip $sbsdata{'team'}[$it]{'pl'}[$ip]\n";
               if ($status eq 'batting') {
                  print "$status $iseg $innPlayers[$innNumber]{$status}[$ip]{'name'} $innPlayers[$innNumber]{$status}[$ip]{'seq'} runs=$innPlayers[$innNumber]{$status}[$ip]{'figures'}[1] $innPlayers[$innNumber]{$status}[$ip]{'figures'}[2]\n";
               } else {
                  print "$status $iseg $innPlayers[$innNumber]{$status}[$ip]{'name'} 
                         $innPlayers[$innNumber]{$status}[$ip]{'seq'} overs=$innPlayers[$innNumber]{$status}[$ip]{'figures'}[1] $innPlayers[$innNumber]{$status}[$ip]{'figures'}[2]\n";
               }
            }
         }
         if ($verbose) {
            if ($status eq 'batting') {
               print "Total $innData[$innNumber]{'runs'} for $innData[$innNumber]{'wickets'}\n";
               print "Extras $innData[$innNumber]{'extras'}{'nb'} $innData[$innNumber]{'extras'}{'w'} $innData[$innNumber]{'extras'}{'b'} $innData[$innNumber]{'extras'}{'lb'} $innData[$innNumber]{'extras'}{'total'}\n";
            }
         }

#        Create sorted index to players.
         for ($ii=0; $ii<=$innData[$innNumber]{$status}{'nplayers'}; $ii++) {$index[$ii]=$ii};
#         @sortindex = sort {$xx=$innPlayers[$innNumber]{$status}[$a]{'seq'};$yy=$innPlayers[$innNumber]{$status}[$b]{'seq'};$xx<=>$yy;} @index;
         @{$innData[$innNumber]{$status}{'index'}} = sort bysequence @index;
         undef @index;

         if ($verbose) {
            print "*** Status is $status\n";
            print "Inns, team, nplayers = $innNumber $innData[$innNumber]{$status}{'team'} $innData[$innNumber]{$status}{'nplayers'}\n";
            print "@{$innData[$innNumber]{$status}{'index'}} \n";
            print "Players in $status order ...\n";
            for ($ii=0; $ii<$#{$innData[$innNumber]{$status}{'index'}}; $ii++) {
               $ip = ${$innData[$innNumber]{$status}{'index'}}[$ii];
###            foreach $ip (@{$innData[$innNumber]{$status}{'index'}}) {
               print "... $ii $ip $innPlayers[$innNumber]{$status}[$ip]{'name'} $innPlayers[$innNumber]{$status}[$ip]{'figures'}[1]\n";
            }
         }

         if ($verbose) {
            print "$it $sbsdata{'team'}[$it]{'name'}[0] $team batting ? $batting $innNumber $segment\n";
         }

         if ($status eq 'batting') {
#        Extract fall-of-wicket data
            @fowdata = split /,/, $sbsdata{'innings'}[$inn]{'fw'}[0];
            if ($verbose) {
               print "$inn Fall of wicket data: @fowdata\n";
            }
            foreach $fow (@fowdata) {
               ($wkt,$score,$dummy,$bat) = $fow=~/([\?\d]+)\-([\?\d]+)(\/*)([\?\d]*)/;
               if ($verbose) {print "    $wkt, $score, $bat \n";}
               $innData[$innNumber]{$status}{'fows'}[$wkt] = $score;
               $innData[$innNumber]{$status}{'fowb'}[$wkt] = $bat;
            }
         }
      }
   }
     

}

sub bysequence {
#
#   Sorting routine used by scoreSheetAnalysis
#
#   Sort by sequence position, with undefined elements at the end of the list.
#

#   if (defined($innPlayers[$innNumber]{$status}[$b]{'seq'})) {
#      if (defined($innPlayers[$innNumber]{$status}[$a]{'seq'})) {
#         $innPlayers[$innNumber]{$status}[$a]{'seq'} <=> $innPlayers[$innNumber]{$status}[$b]{'seq'};
#      } else {
#         1;
#      }
#   } else {
#      -1;
#   }

# Compare with null string instead of using "defined".
   if ($innPlayers[$innNumber]{$status}[$b]{'seq'}!='') {
      if ($innPlayers[$innNumber]{$status}[$a]{'seq'}!='') {
         $innPlayers[$innNumber]{$status}[$a]{'seq'} <=> $innPlayers[$innNumber]{$status}[$b]{'seq'};
      } else {
         1;
      }
   } else {
      -1;
   }
}

sub makehtml {
   my($htmlfile) = $_[0];
   if ($htmlfile) {
      open(HTMLFILE,">$htmlfile")  || die "Unable to open html file $htmlfile\n";
      my $oldfh = select(HTMLFILE);
   }

   $title = "Autogenerated scorecard - prototype version 0.01";
   $title = "RedBat CC v $matchhdr{'opponents'}, $matchhdr{'date'}";
   &writeHeader($title);

   &writeBody;

   &writeFooter;

   if ($htmlfile) {
      close(HTMLFILE);
      select($oldfh);
   }

}

sub writeHeader {
#
#  Standard boilerplate file header.  Note use of qq| contruction
#  instead of ", to avoid confusion with quotes in html code.
#
   my $title = shift(@_);
   print qq|
<html>

<head>
<meta http-equiv="Content-Language" content="en-gb">
<meta name="GENERATOR" content="Microsoft FrontPage 5.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>$title</title>
<meta name="Microsoft Border" content="tl, default">
<style><!-- Default style sheet in case external file is not available -->
H1 {font-size: 24pt; color: red; font-family: "Tahoma, sans-serif"}
H2 {color: navy; font-size: 14pt; font-family: "Tahoma, sans-serif"; font-style: italic}
H3 {color: #008000; font-size: 12pt; font-family: "Tahoma, sans-serif"}
H4 {color: maroon; font-size: 12pt; font-family: "Tahoma, sans-serif"}
P {color: black; font-size: 12pt; font-family: "Tahoma, sans-serif"}
TABLE {font-family: "Tahoma, sans-serif"}
.permtext {color: red;  font-family: "Tahoma, sans-serif"}
.varitext {color: #555555; font-family: "Tahoma, sans-serif"}
</style>
<link rel="stylesheet" type="text/css" href="scorecard.css">
</head>

<body><!--msnavigation-->
<table border="0" cellpadding="0" cellspacing="0" width="100%"><tr><td>
<div align="center"><center>

<table border="2" bordercolor="#000000" cellpadding="6" bgcolor="#000000" cellspacing="4" width="100%">
  <tr>
    <td bgcolor="#FFFFFF" width="6%">&nbsp;</td>
    <td bgcolor="#FFFFFF" width="6">&nbsp;</td>
    <td bgcolor="#FFFFFF">&nbsp;<p>&nbsp;</td>
    <td bgcolor="#FF0000" width="6">&nbsp;</td>
    <td bgcolor="#FFFFFF">&nbsp;</td>
  </tr>
  <tr>
    <td bgcolor="#FFFF00" width="5%">&nbsp;</td>
    <td width="5%" bgcolor="#FFFFFF">&nbsp;</td>
    <td bgcolor="#FFFFFF" valign="baseline" align="center" width="60%"><big><font  color="#FF0000">RED BAT CRICKET COLLECTIVE</font></big><p>&nbsp;</td>
    <td width="5%" bgcolor="#FFFFFF">&nbsp;</td>
    <td bgcolor="#0000FF" width="20%">&nbsp;</td>
  </tr>
</table>
</center></div>

</td></tr><!--msnavigation--></table><!--msnavigation--><table dir="ltr" border="0" cellpadding="0" cellspacing="0" width="100%"><tr><td valign="top" width="1%">

<p><a href="default.htm">Home</a><br>
<a href="constitution.htm">The Constitution</a><br>
<a href="history.htm">History</a><br>
<a href="fixtures.htm">Fixtures</a><br>
<a href="history.htm#AGM-EGM">AGMs/EGMs</a><br>
<a href="averages.htm">Averages</a><br>
<a href="records.htm">Records</a><br>
<a href="features.htm">Features</a><br>
<a href="gallery.htm">Picture&nbsp;Gallery</a>&nbsp;&nbsp; <a href="links.htm">Links</a></p>

</td>
|

}

sub writeBody {
#
#  Create body of html scoresheet file.  Note use of qq| contruction
#  instead of ", to simplify use of quotes in html code.
#

#  Set up colour variables.
   $tableBGColour = '"#FFFFCC"';            # Table background - pale yellow/buff
   $tableBorderColour = '"#008000"';        # Table border - green
   $tablePermColour = '"#FF0000"';          # Table permanent text - red
   $tableVariColour = '"#555555"';          # Table variable text - black

   $nPlayers  =11;

   print qq|
<td valign="top" width="24"></td><!--msnavigation--><td valign="top">

<table border="1" cellpadding="2" cellspacing="0" style="border-collapse: collapse" bordercolor=$tableBorderColour
       width="100%" id="AutoNumber1" bgcolor=$tableBGColour>
  <tr>
    <td width="100%" colspan="20" align="center">
    <br><font class="permtext">RED BAT CRICKET COLLECTIVE
    <br>Versus<br></ofnt>
    <font class="varitext">$matchhdr{'opponents'}
    <br>&nbsp;</font></td>
  </tr>
  <tr>
    <td width="100%" colspan="20" align="left">
    <font class="permtext">Date: </font>
    <font class="varitext">$matchhdr{'date'}</font>
    <font class="permtext">&nbsp; </font></td>
  </tr>
  <tr>
    <td width="100%" colspan="20" align="left">
    <font class="permtext">Venue: </font><font  class="varitext">$matchhdr{'venue'}</font>
    </td>
  </tr>
  <tr>
    <td width="100%" colspan="20" align="left">
    <font class="permtext">Result: </font>
    <font class="varitext">$matchhdr{'result'}</font></td>
  </tr>
|;
   foreach $note (@{$matchhdr{'notes'}}) {
      print qq|
  <tr>
    <td width="100%" colspan="20" align="left">
    <font class="permtext">Note: </font>
    <font class="varitext">$note</font>
    <font class="permtext">&nbsp; </font></td>
  </tr>
|;
   }

#  Loop over innings
   for ($inn=1; $inn<=$matchhdr{'ninnings'}; $inn++) {
      print qq|
  <tr>
    <td width="66%" colspan="15"><font class="permtext">Innings of: </font>
       <font class="varitext">$innData[$inn]{'batting'}{'team'}</font></td>
    <td width="17%"><font class="permtext">Bowling</font></td>
    <td width="5%"><font class="permtext">O</font></td>
    <td width="4%"><font class="permtext">M</font></td>
    <td width="4%"><font class="permtext">R</font></td>
    <td width="4%"><font class="permtext">W</font></td>
  </tr>
|;
#     Loop over player lines

      $nBat  = $innData[$inn]{'batting'}{'nplayers'}+1;
      $nBowl = $innData[$inn]{'bowling'}{'nplayers'}+1;
      $nPlayers = 11;
      if ($nBat  > $nPlayers) { $nPlayers = $nBat;}
      if ($nBowl > $nPlayers) { $nPlayers = $nBowl;}
      @lineData=($ii,'W G Grace','bowled','Nichol',399,'D.Lloyd',15,0,68,3);
      for ($ii=0; $ii<$nPlayers; $ii++) {
         $lineData[0] = $ii+1;
# Batting team
         if ($ii < $nBat) {
            $ip = ${$innData[$inn]{'batting'}{'index'}}[$ii];

            $lineData[1] = $innPlayers[$inn]{'batting'}[$ip]{'name'};

            $howOut = $innPlayers[$inn]{'batting'}[$ip]{'figures'}[2];
            if ($howOut=~/^no.*/i) {
               $howOut = "Not Out";
            } elsif ($howOut=~/^ru.*/i) {
              $howOut = "run out";
            } elsif ($howOut=~/.*hurt.*/i) {
              $howOut = "retired hurt";
            } elsif ($howOut=~/^h.*/i) {
              $howOut = "hit wicket";
            } elsif ($howOut=~/.*\&.*/) {
               $howOut = "c & b";
            } elsif ($howOut=~/^c.*/i) {
               $howOut = "ct";
               $assistId = $innPlayers[$inn]{'batting'}[$ip]{'figures'}[4];
               if ($assistId=~/\d{1,2}/) {
                  $assistId = barename($innPlayers[$inn]{'bowling'}[$assistId-1]{'name'});
               }
               $howOut = $howOut." ".$assistId;
               } elsif ($howOut=~/^s.*/i) {
               $howOut = "st";
               $assistId = $innPlayers[$inn]{'batting'}[$ip]{'figures'}[4];
               if ($assistId=~/\d{1,2}/) {
                  $assistId = barename($innPlayers[$inn]{'bowling'}[$assistId-1]{'name'});
               }
               $howOut = $howOut." ".$assistId;
            }
            $lineData[2] = $howOut;

            $lineData[4] = $innPlayers[$inn]{'batting'}[$ip]{'figures'}[1];

            $bowlerId = $innPlayers[$inn]{'batting'}[$ip]{'figures'}[3];
            if ($bowlerId=~/\d{1,2}/) {
               $bowlerId = barename($innPlayers[$inn]{'bowling'}[$bowlerId-1]{'name'});
            }
            $lineData[3] = $bowlerId;
         } else {
            $lineData[1] = '';
            $lineData[2] = '';
            $lineData[3] = '';
            $lineData[4] = '';
         }

#Bowling team
         if ($ii < $nBowl) {
            $lineData[5] = '';
            $lineData[6] = '';
            $lineData[7] = '';
            $lineData[8] = '';
            $lineData[9] = '';
            $ip = ${$innData[$inn]{'bowling'}{'index'}}[$ii];
            $overs = $innPlayers[$inn]{'bowling'}[$ip]{'figures'}[1];
            if ($overs>0) {
               $lineData[5] = barename($innPlayers[$inn]{'bowling'}[$ip]{'name'});
               $lineData[6] = $overs;
               $lineData[7] = $innPlayers[$inn]{'bowling'}[$ip]{'figures'}[2];
               $lineData[8] = $innPlayers[$inn]{'bowling'}[$ip]{'figures'}[3];
               $lineData[9] = $innPlayers[$inn]{'bowling'}[$ip]{'figures'}[4];
            }
         }

         &writePlayerLine(@lineData);
      }

# Total, extras, etc
      &writeTotals;

# Fall of wickets
      &writeFoW;


      print qq|
      <tr>
        <td width="100%" colspan="20">&nbsp;</td>
      </tr>
      |;
   }

  print qq|
  <tr>
    <td width="100%" colspan="20">&nbsp;</td>
  </tr>
</table>

<p>&nbsp;</p>

<!--msnavigation--></td></tr><!--msnavigation--></table></body>

|;
}

sub writePlayerLine {
     print qq| 
     <tr>
       <td width="28%" valign="top" colspan="3">
          <font class="permtext">$_[0].&nbsp;&nbsp; </font>
          <font class="varitext">$_[1]</font>
       </td>
       <td width="16%" valign="top" colspan="4"><font class="varitext">$_[2]</font></td>
       <td width="17%" valign="top" colspan="5"><font class="varitext">$_[3]</font></td>
       <td width="5%" align="right" valign="top" colspan="3"><font class="varitext">$_[4] &nbsp;</font></td>
       <td width="17%" align="left" valign="top"><font class="varitext">$_[5]</font></td>
       <td width="5%" align="left" valign="top"><font class="varitext">$_[6]</font></td>
       <td width="4%" align="left" valign="top"><font class="varitext">$_[7]</font></td>
       <td width="4%" align="left" valign="top"><font class="varitext">$_[8]</font></td>
       <td width="4%" align="left" valign="top"><font class="varitext">$_[9]</font></td>
     </tr>|;
}

sub writeTotals {
#
#   Write innings total, extras, & notes

     $xnb  = $innData[$inn]{'extras'}{'nb'};
     $xw   = $innData[$inn]{'extras'}{'w'};
     $xb   = $innData[$inn]{'extras'}{'b'};
     $xlb  = $innData[$inn]{'extras'}{'lb'};
     $xtot = $innData[$inn]{'extras'}{'total'};
     print qq| 
     <tr>
       <td width="44%" colspan="7" rowspan="2" valign="top">
         <font class="varitext">* Denotes captain</font><br>
         <font class="varitext">+ Denotes wicketkeeper</font>
       </td>
       <td width="17%" valign="top" align="left" colspan="5"><font class="permtext">(nb,w/b,lb) Extras</font></td>
       <td width="5%" align="right" valign="top" colspan="3"><font class="varitext">($xnb,$xw/$xb,$xlb) $xtot</font></td>

     </tr>
     <tr>
       <td width="17%" valign="top" align="left"  colspan="5"><font class="permtext">Total</font></td>
       <td width="5%" align="right" valign="top" colspan="3"><font class="varitext">$innData[$inn]{'runs'} for $innData[$inn]{'wickets'}</font></td>

       <td width="34%" colspan="5" rowspan="5" align="left" valign="top" height="79">
       <font class="permtext">Notes:</font>
|;
       foreach $note (@{$innData[$inn]{'notes'}}) {
       print qq|
       <font class="varitext"><br>$note</font></td>
|;     }
     print qq|
     </tr>
|;
}
sub writeFoW {
#
#   Write fall-of-wickets information
#

    $hwid = "44%";
#   Header line
    $ncwkts = 10;
    if ($ncwkts<$innData[$inn]{'wickets'}) {$ncwkts = $innData[$inn]{'wickets'}};
    $nchdr = 15 - $ncwkts;
    print qq|
    <tr>
      <td width="$hwid" colspan="$nchdr"><font class="permtext">Wicket</font></td>
|;
    for ($iw=1; $iw<=$ncwkts; $iw++) {
       print qq|
      <td colspan="1" width="5%"><font class="permtext">$iw</font></td>
|;
    }
    print qq|
    </tr>

|;

# Score line
    print qq|
    <tr>
      <td width="$hwid" colspan="$nchdr"><font class="permtext">Score</font></td>
|;
    for ($iw=1; $iw<=$ncwkts; $iw++) {
       print qq|
      <td colspan="1" width="5%"><font class="varitext">$innData[$inn]{'batting'}{'fows'}[$iw]</font></td>
|;
    }
    print qq|
    </tr>
|;

# Batsman line
    print qq|
    <tr>
      <td width="$hwid" colspan="$nchdr"><font class="permtext">Bat</font></td>
|;
    for ($iw=1; $iw<=$ncwkts; $iw++) {
       print qq|
      <td colspan="1" width="5%"><font class="varitext">$innData[$inn]{'batting'}{'fowb'}[$iw]</font></td>
|;
    }
    print qq|
    </tr>
|;
}


sub writeFooter {
#
#  Standard boilerplate file footer.  Note use of qq| contruction
#  instead of ", to avoid confusion with quotes in html code.
#
   @ltime = localtime(time);
   $yy = $ltime[5]+1900;
   $mm = $ltime[4]+1;
   $date = "$ltime[3]\.$mm\.$yy";
   $time = "$ltime[2]\.$ltime[1]";
   print qq|
   <em>Scoresheet generated from data file $datafile at $time on $date.</em>
</html>
|;
}

sub barename {
   my($playername) = $_[0];
   ($prefix,$name,$suffix) = $playername=~/(^[\W]*)([\w\.\']+)([\W]*$)/;
   return $name;
}
#
#--------- Subroutines to create player data file ----------------------
#
sub makepdata {

   my($pdatafile) = $_[0];
   if ($verbose) {
      print "makepdata: file is $pdatafile\n";
   }

#
#  Open data file.  If it does not exist, create it with a set of column headings
   if (! -e $pdatafile) {
      open PFILE, ">".$pdatafile or die "Cannot open new player file $pdatafile\n";
      print PFILE "Player,matchid,capt,wk,batpos,batted,notout,runs,howout,bowlpos,balls,mdns,runs,wkt,ct,std\n";
   } else {
      open PFILE, ">>".$pdatafile or die "Cannot open existing player file $pdatafile\n";
   }
# Extract player data from data structure
   for ($it=0; $it<2; $it++) {
      $team[$it] = $sbsdata{'team'}[$it]{'name'}[0];
      $nplayers = $#{$sbsdata{'team'}[$it]{'pl'}};
      if ($verbose) {
         print "    Team, nplayers = $it  $team[$it] $nplayers \n";
      }
#     Limit output to RBCC
      if ($team[$it] eq 'RBCC') {
         for ($ip=0; $ip<=$nplayers; $ip++) {
            if ($verbose) {print "$ip -> $sbsdata{'team'}[$it]{'pl'}[$ip]\n";}
            @playerdata = split /;/, $sbsdata{'team'}[$it]{'pl'}[$ip];
            @playername = &stripname($playerdata[0]);
            @batdata  = split /,/, $playerdata[1];
            if ($batdata[2] ne '') {
               $batted = 1;
            } else {
               $batted = 0;
            }
            if ($batdata[2] eq "not") {
               $notout = 1;
            } else {
               $notout = 0;
            }

            @bowldata = split /,/, $playerdata[2];
            $bowldata[1] = &otob($bowldata[1]);
            if ($verbose) {print "Name $playername[0], capt $playername[1], wk $playername[2] _ @batdata _ @bowldata\n";}
            print PFILE "$playername[0],$sbsdata{'match'}[0]{'matchid'}[0],$playername[1],$playername[2],$batdata[0],$batted,$notout,$batdata[1],$batdata[2],$bowldata[0],$bowldata[1],$bowldata[2],$bowldata[3],$bowldata[4],$bowldata[5],$bowldata[6]\n";
         }
      }
   }
   close PFILE;
}

sub stripname {
   my($playername) = $_[0];
   ($prefix,$name,$suffix) = $playername=~/(^[\W]*)([\w\.\']+)([\W]*$)/;
   $flags = $prefix.$suffix;
   if ($verbose) {print "$playername -> $name / $flags \n";}
   $return[0] = $name;
   if ($flags=~/.*\*.*/) {
      $return[1] = 1;
   } else {
      $return[1] = 0;
   }
   if ($flags=~/.*\+.*/) {
      $return[2] = 1;
   } else {
      $return[2] = 0;
   }
   if ($verbose) {print "Name, capt, wk = @return\n";}

   return @return;
}

sub otob {
#
#   Convert overs.balls into balls
#
   my($ob) = $_[0];
   ($overs,$xballs) = $ob=~/(\d*)\.*(\d*)/;
   $balls = 6*$overs + $xballs;
   if ($verbose) {print "otob: $ob $overs $xballs $balls\n";}
   return $balls;
}



#
#--------- Subroutines to create match data file -----------------------
#
sub makemdata {
#
#   Create match data file from sbsdata record.
#

   $selTeam = "RBCC";

   my($mdatafile) = $_[0];
   if ($verbose) {
      print "makemdata: file is $mdatafile\n";
   }

#
#   Extract data
#
   for ($inn=0; $inn<2; $inn++) {
      if ($sbsdata{'innings'}[$inn]{'team'}[0] eq $selTeam) {
         if ($verbose) {print "$inn $sbsdata{'innings'}[$inn]{'team'}[0] $selTeam\n";}
         $innsel = $inn;
      } else {
         $innopp = $inn;
         if ($verbose) {print "$inn $sbsdata{'innings'}[$inn]{'team'}[0] opponents\n";}
      }
   }
   $matchid   = $sbsdata{'match'}[0]{'matchid'}[0];
   $date      = $sbsdata{'match'}[0]{'date'}[0];
   $opponents = $sbsdata{'innings'}[$innopp]{'team'}[0];
   $venue     = $sbsdata{'match'}[0]{'venue'}[0];
   $bat12     = $innsel + 1;
   $result    = $sbsdata{'match'}[0]{'result'}[0];
   ($margin,$mtype) = $sbsdata{'match'}[0]{'margin'}[0]=~/(\d+)(\D+)/;
   $runsel    = $sbsdata{'innings'}[$innsel]{'runs'}[0];
   $wicsel    = $sbsdata{'innings'}[$innsel]{'wickets'}[0];
   $runopp    = $sbsdata{'innings'}[$innopp]{'runs'}[0];
   $wicopp    = $sbsdata{'innings'}[$innopp]{'wickets'}[0];

#
#  Analysis fall-of-wicket data
#
   &analyseFallData($innsel);

#
#  Open data file.  If it does not exist, create it with a set of column headings
   if (! -e $mdatafile) {
      open MFILE, ">".$mdatafile or die "Cannot open new match file $mdatafile\n";
      print MFILE "MatchID	Date	opponents	venue	bat12	result	margin	mtype	rscored	wlost	rconc	wtaken\n";
   } else {
      open MFILE, ">>".$mdatafile or die "Cannot open existing match file $mdatafile\n";
   }

   if ($verbose) {
      print "makemdata: $innsel $runsel $wicsel $innopp $runopp $wicopp\n";
   }
#
#  Print data to output file, tab-separated for easy importation to other programs
#
   print MFILE "$matchid	$date	$opponents	$venue	$bat12	$result	$margin	$mtype	";
   print MFILE "$runsel	$wicsel	$runopp	$wicopp";
   print MFILE "\n";

   close MFILE;

}

sub analyseFallData {
   my($currentInns) = $_[0];
   @FoWs = split /,/, $sbsdata{'innings'}[$currentInns]{'fw'}[0];
   $innsTotal = $sbsdata{'innings'}[$currentInns]{'runs'}[0];

#
#  Ensure no hangover from previous match
   undef @stand;
   undef @scores;

#
#  Each partnership has a new batsman and a batsman surviving from the previous wicket.

   foreach $FoW (@FoWs) {
      ($wkt,$score,$bat) = $FoW=~/(\d*)\-(\d*)\/(\d*)/;
      $scores[$wkt] = $score;
      $bats[$wkt] = $bat; 
   }

   for ($iwkt=1; $iwkt<=$#scores; $iwkt++) {
      if ($iwkt==1) {
         $stand[$iwkt] = $scores[$iwkt];
         $surv[$iwkt]   = 1;
      } else {
         $stand[$iwkt] = $scores[$iwkt] - $scores[$iwkt-1];
         if ($bats[$iwkt-1] == $surv[$iwkt-1]) {
            $surv[$iwkt] = $iwkt;
         } else {
            $surv[$iwkt] = $surv[$iwkt-1];
         }
      }
   }
   if ($innsTotal > $scores[$iwkt-1]) {
#     (-ve here to signal unbroken stand)
      $stand[$iwkt] = -($innsTotal - $scores[$iwkt-1]);
      if ($bats[$iwkt-1] == $surv[$iwkt-1]) {
         $surv[$iwkt] = $iwkt;
      } else {
         $surv[$iwkt] = $surv[$iwkt-1];
      }
   }


   if ($verbose) {
      print "FoW: $sbsdata{'innings'}[$currentInns]{'fw'}[0]\n";
      foreach $FoW (@FoWs) {
         ($wkt,$score,$bat) = $FoW=~/(\d*)\-(\d*)\/(\d*)/;
         print "> $FoW [$wkt,$score,$bat] ";
      }
      print "\n";
      print "$#stand $#scores wickets\n";
      for ($iwkt=1; $iwkt<$#stand; $iwkt++) {
         $newb = $iwkt+1;
         $compact = $stand[$iwkt]+0.01*$newb + 0.0001*$surv[$iwkt];
         print " Wicket $iwkt - $stand[$iwkt] - bats $newb & $surv[$iwkt] - $compact\n";
      }
   }
}

#
#--------- Subroutines to create player averages file ------------------
#
sub accumulateAverages {

# Extract player data from data structure, and create averages structure

   for ($it=0; $it<2; $it++) {
      $team[$it] = $sbsdata{'team'}[$it]{'name'}[0];
      $nplayers = $#{$sbsdata{'team'}[$it]{'pl'}};
      if ($verbose) {
         print "    Team, nplayers = $it  $team[$it] $nplayers \n";
      }
#     Loop over RBCC players.
      if ($team[$it] eq 'RBCC') {
         for ($ip=0; $ip<=$nplayers; $ip++) {
            if ($verbose) {print "$ip -> $sbsdata{'team'}[$it]{'pl'}[$ip]\n";}
            @playerdata = split /;/, $sbsdata{'team'}[$it]{'pl'}[$ip];
            @playername = &stripname($playerdata[0]);
            $pp = &normalisedName($playername[0]);  #Abbreviation for current player
            if ($pp=~/[\w\.\'\-\s]+/) {
               if ($verbose) {
                  print "Accumulating averages for player $pp\n";
               }
               $averages{$pp}{'nplayed'} += 1;
               if ($averages{$pp}{'nplayed'} == 1) {
#                 Initialise data structure for this player
                  &initAvge($pp);
               }

#           Loop over innings if more than 1
               for($inns=0; $inns<$#{$sbsdata{'innings'}}; $inns++) {
                  @batdata  = split /,/, $playerdata[2*$inns+1];
                  if ($batdata[2] ne '') {
                     $batted = 1;
                  } else {
                     $batted = 0;
                  }
                  if ($batdata[2] eq "not") {
                     $notout = 1;
                  } else {
                     $notout = 0;
                  }

                  @bowldata = split /,/, $playerdata[2*$inns+2];
                  $bowldata[1] = &otob($bowldata[1]);
                  if ($verbose) {print "Name $playername[0], capt $playername[1], wk $playername[2] _ @batdata _ @bowldata\n";}

#                 Accumulate sums - prefix na => batting, no => bowling, nf => fielding
                  $averages{$pp}{'nabatted'} += $batted;
                  $averages{$pp}{'nanotout'} += $notout;
                  $averages{$pp}{'naruns'} += $batdata[1];
                  if ($batdata[1] >=25) {
                     $averages{$pp}{'na25'} += 1;
                     if ($batdata[1] >=50) {
                        $averages{$pp}{'na50'} += 1;
                        if ($batdata[1] >=100) {
                           $averages{$pp}{'na100'} += 1;
                        }
                     }
                  }

                  $averages{$pp}{'noballs'} += $bowldata[1];
                  $averages{$pp}{'nomdns'} += $bowldata[2];
                  $averages{$pp}{'noruns'} += $bowldata[3];
                  $averages{$pp}{'nowkts'} += $bowldata[4];
                  if ($bowldata[4] >= 3) {
                     $averages{$pp}{'no3for'} += 1;
                     if ($bowldata[4] >= 5) {
                        $averages{$pp}{'no5for'} += 1;
                     }
                  }
                  $averages{$pp}{'nfct'} += $bowldata[5];
                  $averages{$pp}{'nfst'} += $bowldata[6];
                  $nout= $averages{$pp}{'nabatted'}-$averages{$pp}{'nanotout'};
                  if ($nout>0) {
                     $averages{$pp}{'aavge'} = sprintf "%4.2f", $averages{$pp}{'naruns'}/$nout;
                  }
                  $nwkts = $averages{$pp}{'nowkts'};
                  if ($nwkts > 0) {
                     $averages{$pp}{'oavge'} = sprintf "%4.2f", $averages{$pp}{'noruns'}/$nwkts;
                  }


#                 Keep track of best batting & bowling
                  if ($batted) {
                     if ($batdata[1] > $bestbat{$pp}[1] || $batdata[1] == $bestbat{$pp}[1] && $notout >= $bestbat[2]) {
                        @{$bestbat{$pp}} = ($sbsdata{'match'}[0]{'matchid'}[0],$batdata[1],$notout);
                        @{$averages{$pp}{'abest'}} = @{$bestbat{$pp}};
                     }
                  }
                  if ($bowldata[1] > 0) {
                     if ($bowldata[4] > $bestbowl{$pp}[1] || $bowldata[4] == $bestbowl{$pp}[1] && $bowldata[3] <= $bestbowl{$pp}[2]) {
                        @{$bestbowl{$pp}} = ($sbsdata{'match'}[0]{'matchid'}[0],$bowldata[4],$bowldata[3]);
                        @{$averages{$pp}{'obest'}} = @{$bestbowl{$pp}};
                     }
                  }
                  if ($verbose) {
                     print "$pp -> ";
                     foreach $key (keys %{$averages{$pp}}) {
                        print " $key $averages{$pp}{$key}";
                     }
                     print "\n";
                  }
               }   #End loop over innings
            }
         }   #End loop over players
      }
   }   #End loop over teams
}

sub initAvge {
#
#   Initialise averages structure for given player
#
   my($pp) = $_[0];

#  Batting variables
   $averages{$pp}{'nabatted'} = 0;
   $averages{$pp}{'nanotout'} = 0;
   $averages{$pp}{'naruns'}   = 0;
   $averages{$pp}{'na25'}     = 0;
   $averages{$pp}{'na50'}     = 0;
   $averages{$pp}{'na100'}    = 0;
   $averages{$pp}{'aavge'}    = '-';
   @{$averages{$pp}{'abest'}} = ('-') x 3;

#  Bowling variables
   $averages{$pp}{'noballs'}  = 0;
   $averages{$pp}{'nomdns'}   = 0;
   $averages{$pp}{'noruns'}   = 0;
   $averages{$pp}{'nowkts'}   = 0;
   $averages{$pp}{'no3for'}   = 0;
   $averages{$pp}{'no5for'}   = 0;
   $averages{$pp}{'oavge'}    = '-';
   @{$averages{$pp}{'obest'}} = ('-') x 3;

#  Fielding variables
   $averages{$pp}{'nfct'}     = 0;
   $averages{$pp}{'nfst'}     = 0;

}

sub backup_accumulateAverages {

# Extract player data from data structure, and create averages structure

   for ($it=0; $it<2; $it++) {
      $team[$it] = $sbsdata{'team'}[$it]{'name'}[0];
      $nplayers = $#{$sbsdata{'team'}[$it]{'pl'}};
      if ($verbose) {
         print "    Team, nplayers = $it  $team[$it] $nplayers \n";
      }
#     Loop over RBCC players.
      if ($team[$it] eq 'RBCC') {
         for ($ip=0; $ip<=$nplayers; $ip++) {
            if ($verbose) {print "$ip -> $sbsdata{'team'}[$it]{'pl'}[$ip]\n";}
            @playerdata = split /;/, $sbsdata{'team'}[$it]{'pl'}[$ip];
            @playername = &stripname($playerdata[0]);
            $pp = $playername[0];  #Abbreviation for current player
            @batdata  = split /,/, $playerdata[1];
            if ($batdata[2] ne '') {
               $batted = 1;
            } else {
               $batted = 0;
            }
            if ($batdata[2] eq "not") {
               $notout = 1;
            } else {
               $notout = 0;
            }

            @bowldata = split /,/, $playerdata[2];
            $bowldata[1] = &otob($bowldata[1]);
            if ($verbose) {print "Name $playername[0], capt $playername[1], wk $playername[2] _ @batdata _ @bowldata\n";}

#           Accumulate sums - prefix na => batting, no => bowling, nf => fielding
            $averages{$pp}{'nplayed'} += 1;
            $averages{$pp}{'nabatted'} += $batted;
            $averages{$pp}{'nanotout'} += $notout;
            $averages{$pp}{'naruns'} += $batdata[1];
            if ($batdata[1] >=25) {
               $averages{$pp}{'na25'} += 1;
               if ($batdata[1] >=50) {
                  $averages{$pp}{'na50'} += 1;
                  if ($batdata[1] >=100) {
                     $averages{$pp}{'na100'} += 1;
                  }
               }
            }

            $averages{$pp}{'noballs'} += $bowldata[1];
            $averages{$pp}{'nomdns'} += $bowldata[2];
            $averages{$pp}{'noruns'} += $bowldata[3];
            $averages{$pp}{'nowkts'} += $bowldata[4];
            if ($bowldata[4] >= 3) {
               $averages{$pp}{'no3for'} += 1;
               if ($bowldata[4] >= 5) {
                  $averages{$pp}{'no5for'} += 1;
               }
            }
            $averages{$pp}{'nfct'} += $bowldata[5];
            $averages{$pp}{'nfst'} += $bowldata[6];
            $nout= $averages{$pp}{'nabatted'}-$averages{$pp}{'nanotout'};
            if ($nout>0) {
               $averages{$pp}{'aavge'} = sprintf "X%4.2d", $averages{$pp}{'naruns'}/$nout;
            } else {
               $averages{$pp}{'aavge'} = '-';
            }
            $nwkts = $averages{$pp}{'nowkts'};
            if ($nwkts > 0) {
               $averages{$pp}{'oavge'} = sprintf "X%4.2d", $averages{$pp}{'noruns'}/$nwkts;
            } else {
               $averages{$pp}{'oavge'} = '-';
            }


#           Keep track of best batting & bowling
            if ($batdata[1] > $bestbat{$pp}[1] || $batdata[1] == $bestbat{$pp}[1] && $notout >= $bestbat[2]) {
               @{$bestbat{$pp}} = ($sbsdata{'match'}[0]{'matchid'}[0],$batdata[1],$notout);
               @{$averages{$pp}{'abest'}} = @{$bestbat{$pp}};
            }
            if ($bowldata[4] > $bestbowl{$pp}[1] || $bowldata[4] == $bestbowl{$pp}[1] && $bowldata[3] <= $bestbowl{$pp}[2]) {
               @{$bestbowl{$pp}} = ($sbsdata{'match'}[0]{'matchid'}[0],$bowldata[4],$bowldata[3]);
               @{$averages{$pp}{'obest'}} = @{$bestbowl{$pp}};
            }
            if ($verbose) {
               print "$pp -> ";
               foreach $key (keys %{$averages{$pp}}) {
                  print " $key $averages{$pp}{$key}";
               }
               print "\n";
            }
         }
      }
   }
}

sub printAverages {

#  Print averages to file specified as argument

   my($xmlfile) = shift(@_);
   $opened = 0;
   my $ofile = SELECT;
   if ($xmlfile) {
      open(XMLFILE,">$xmlfile") || die "Unable to open xml file $xmlfile for output\n";
      $opened = 1;
      my $ofile = select(XMLFILE);
   }

# Standard xml header
   print qq|<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<RBCCaverages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|;

# Averages file header section
   print qq|
      <header>
         <title>
            RBCC averages
         </title>
      </header>
|;
#  Loop over players
   foreach $pp (keys %averages) {
      print qq|
      <player>
         <pid>
            <name>$pp</name>
            <played>$averages{$pp}{'nplayed'}</played>
         </pid>
         <batting>
            <innings>$averages{$pp}{'nabatted'}</innings>
            <notout>$averages{$pp}{'nanotout'}</notout>
            <runs>$averages{$pp}{'naruns'}</runs>
            <n25>$averages{$pp}{'na25'}</n25>
            <n50>$averages{$pp}{'na50'}</n50>
            <n100>$averages{$pp}{'na100'}</n100>
            <average>$averages{$pp}{'aavge'}</average>
            <hsruns>$averages{$pp}{'abest'}[1]</hsruns>
            <hsno>$averages{$pp}{'abest'}[2]</hsno>
            <hsid>$averages{$pp}{'abest'}[0]</hsid>
         </batting>
         <bowling>
            <balls>$averages{$pp}{'noballs'}</balls>
            <mdns>$averages{$pp}{'nomdns'}</mdns>
            <runs>$averages{$pp}{'noruns'}</runs>
            <wickets>$averages{$pp}{'nowkts'}</wickets>
            <n3for>$averages{$pp}{'no3for'}</n3for>
            <n5for>$averages{$pp}{'no5for'}</n5for>
            <average>$averages{$pp}{'oavge'}</average>
            <bbwkts>$averages{$pp}{'obest'}[1]</bbwkts>
            <bbruns>$averages{$pp}{'obest'}[2]</bbruns>
            <bbid>$averages{$pp}{'obest'}[0]</bbid>
         </bowling>
         <fielding>
            <caught>$averages{$pp}{'nfct'}</caught>
            <stumped>$averages{$pp}{'nfst'}</stumped>
         </fielding>
      </player>
|;
   }

#
#  Close RBCCaverages tag
   print qq|
</RBCCaverages>
|;


#  Reset previous default filehandle for output.
   select $ofile;
   if ($opened) {close(XMLFILE)};
}

sub nonull {
#
#   Convert null value to default
#
   my($value) = $_[0];
   my($default) = $_[1];

   if ($value eq '') {
      $value = $default;
   }
   return $value;
}

sub normalisedName {
#
#   Convert name to surname,initial format (J.Smith->Smith,J)
#
   my($name) = $_[0];
   if ($name eq '') {
      $name = '?';
   }
   if (($inits,$surname)=$name=~/([\w\.]*)[\s\.]([\w\'\-]*)/) {
      $name = $surname.','.$inits;
   }
   if ($verbose) {
      print "normaliseName: $_[0] -> $name\n";
   }

   return $name;
}

#
#--------- Subroutines to create fall-of-wickets data file -------------
#
sub makewdata {

   my($wdatafile) = $_[0];
   if ($verbose) {
      print "makewdata: file is $wdatafile\n";
   }

#
#  Open data file.  If it does not exist, create it with a set of column headings
   if (! -e $wdatafile) {
      open WFILE, ">".$wdatafile or die "Cannot open new FoW file $pdatafile\n";
      print WFILE "Wicket,score,stand,*,innings,matchid,date,players\n";
   } else {
      open WFILE, ">>".$wdatafile or die "Cannot open existing FoW file $wdatafile\n";
   }

   $selTeam = "RBCC";
   my(@stand) = (0);
   my(@scores) = @stand;

#
#  Find team list for RBCC
   $teamlist = -1;
   for ($it=0; $it<=$#{$sbsdata{'team'}}; $it++) {
      if ($sbsdata{'team'}[$it]{'name'}[0] eq $selTeam) {
         $teamlist = $it;
      }
   }

#
#  Loop over innings and select RBCC data only.
   for ($inn=0; $inn<=$#{$sbsdata{'innings'}}; $inn++) {
      if ($verbose) {print "$inn $sbsdata{'innings'}[$inn]{'team'}[0] $selTeam\n";}
      if ($sbsdata{'innings'}[$inn]{'team'}[0] eq $selTeam) {
         $matchid   = $sbsdata{'match'}[0]{'matchid'}[0];
         $date      = $sbsdata{'match'}[0]{'date'}[0];
         @FoWs = split /,/, $sbsdata{'innings'}[$inn]{'fw'}[0];
         $innsTotal = $sbsdata{'innings'}[$inn]{'runs'}[0];

#
#  Each partnership has a new batsman and a batsman surviving from the previous wicket.
         foreach $FoW (@FoWs) {
            ($wkt,$score,$bat) = $FoW=~/(\d*)\-(\d*)\/(\d*)/;
            $scores[$wkt] = $score;
            $bats[$wkt] = $bat; 
         }
         if ($innsTotal > $scores[$#scores]) {
            $scores[$#scores+1] = $innsTotal;
         }

         $unbroken = 0;
         for ($iwkt=1; $iwkt<=$#scores; $iwkt++) {
            if ($iwkt==1) {
               $stand[$iwkt] = $scores[$iwkt];
               $surv[$iwkt]   = 1;
            } elsif ($iwkt<$#scores) {
               $stand[$iwkt] = $scores[$iwkt] - $scores[$iwkt-1];
               if ($bats[$iwkt-1] == $surv[$iwkt-1]) {
                  $surv[$iwkt] = $iwkt;
               } else {
                  $surv[$iwkt] = $surv[$iwkt-1];
               }
            } elsif ($innsTotal > $scores[$iwkt-1]) {
#              Unbroken last stand
               $unbroken = 1;
               $stand[$iwkt] = $innsTotal - $scores[$iwkt-1];
               if ($bats[$iwkt-1] == $surv[$iwkt-1]) {
                  $surv[$iwkt] = $iwkt;
               } else {
                  $surv[$iwkt] = $surv[$iwkt-1];
               }
            }
            @partners = ($iwkt+1,$surv[$iwkt]);
            $ip = 0;
            if ($teamlist >= 0) {
               foreach $partner (@partners) {
                  @segments = split /;/, $sbsdata{'team'}[$teamlist]{'pl'}[$partner-1];
                  $pnames[$ip++] = $segments[0];
               }
            }
            if ($verbose) {
               print "$iwkt, $scores[$iwkt], $stand[$iwkt], $unbroken, $inn, $matchid, $date, @partners @pnames\n";
            }
            $innings = $inn + 1;
            print WFILE "$iwkt, $scores[$iwkt], $stand[$iwkt], $unbroken, $innings, $matchid, $date, $pnames[0]/$pnames[1]\n";

         }

      }
   }

   close WFILE;
}

#--------- Obsolete subroutines ----------------------------------------


