#!/usr/bin/perl
#

$debug = 0;

$temp_file = "./get_starters_stats.tmp";

@txt_files = glob("team_stats/???_????.txt");
foreach $txt_file (@txt_files) {
  if ($debug > 0) {
    printf "next file is ..%s.. \n", $txt_file;
  }

  $output_file = $txt_file;
  $output_file =~ s/.txt/_starters.dat/;
  if ($debug > 0) {
    printf "output file is ..%s.. \n", $output_file;
  }

  open(OUTFILE, ">$output_file") || die("can't openfile $output_file");

  open(INFILE, "$txt_file") || die("can't open file $txt_file");
  $print_flag = 0;
  $count_spacer = 0;
  $good_lines = 0;
  while (<INFILE>) {

    $line = $_;
    chomp($line);
    if ($debug > 0) {
      printf " next lines is ..%s.. \n", $line;
    }

    if ($line =~ /Team Batting/) {
      $print_flag = 1;
      if ($debug > 0) {
        printf "  setting print_flag to 1 \n";
      }
      next;
    }
    if (($line =~ /^\-\-\-/) && ($print_flag == 1)) {
      $count_spacer++;
      if ($debug > 0) {
        printf "  incrementing count_spacer, now %d \n", $count_spacer;
      }

    }

    if (($print_flag == 1) && ($count_spacer < 3)) {

		if (($line =~ /^C /) || ($line =~ /^[123]B/) ||
          ($line =~ /^SS/) || ($line =~ /^[LRC]F/) ||
          ($line =~ /^DH/) || ($line =~ /^Pos/) ) {
         if ($debug > 0) {
           printf "line ..%s.. \n", $line;
           printf "   this had A-Z or 1-9 in first char \n";
         }
         if ($line =~ /^Pos/) {
			  printf OUTFILE "#%s", $line;
         }
         else {
			  printf OUTFILE "%s", $line;
         }
         $print_next = 1;
      }
      elsif ($print_next == 1) {
         printf OUTFILE "%s", $line;
         $print_next = 0;
      }
      if ($line =~ /\-\-\-/) {
        printf OUTFILE "#%s", $line;
        #  $count_spacer++;
      }

      if ($good_lines % 2 == 1) {
        printf OUTFILE "\n"; 
      }
      $good_lines++;

    }


  }
  close(INFILE);
  close(OUTILE);


  # now get rid of completely blank lines
  open(INFILE, "$output_file") || die("can't open file $output_file");
  open(OUTFILE, ">$temp_file") || die("can't openfile $temp_file");
  while(<INFILE>) {
    $line = $_;
    chomp($line);
    @words = split(/\s+/, $line);
    if ($#words > 0) {
      printf OUTFILE "%s\n", $line;
    }
  }
  close(OUTFILE);
  close(INFILE);
  rename($temp_file, $output_file);

}


exit 0;
