#!/bin/csh
# Find baseball stats
# First argument is a player list file (First Last format), second is a year

if ( XX$1 == XX || XX$2 == XX ) then
  echo use getbaseball PlayerFile Year
  exit
endif

set mainURL = "http://www.mlb.com/NASApp/mlb/mlb/stats_historical/mlb_player_locator_results.jsp"
set altURL = "http://www.mlb.com/NASApp/mlb/mlb/stats_historical/mlb_individual_stats_player.jsp"
set tmp = tmpDeleteThis
set players = `cat $1`
set final = $#players
set index = 1

while ( $index < $final )
  set first = $players[$index]
  @ index++
  set last = $players[$index]
  @ index++

  lynx -source "$mainURL?playerLocator=$last" > $tmp

  # Use scanhtml to return the first line with "No information" or "NA" if no match (unlisted player)
  if ( `cat $tmp | scanhtml "No information" 0` != "NA" ) then
    echo No info on $first $last

  # Use scanhtml to return the first line with "Hitting Stats" or "NA" if no match
  else if ( `cat $tmp | scanhtml "Hitting Stats" 0` != "NA" ) then
    # A unique match was found if there is a "Hitting Stats" section.
    # Need to find first ">year<" after "Hitting Stats" because pitchers have Hitting Stats second.
    # Use scanhtml2 to find 1st through 5th lines after the match from n-th character
    #   up to just before the "<".
    set team = `cat $tmp | scanhtml2 "Hitting Stats" \>$2\< 1 -67 \<`
    if ( "$team" == "NA" ) then
      echo $first $last did not play in $2
    else
      set games = `cat $tmp | scanhtml2 "Hitting Stats" \>$2\< 2 -50 \<`
      set atbat = `cat $tmp | scanhtml2 "Hitting Stats" \>$2\< 3 -50 \<`
      set runs = `cat $tmp | scanhtml2 "Hitting Stats" \>$2\< 4 -50 \<`
      set hits = `cat $tmp | scanhtml2 "Hitting Stats" \>$2\< 5 -50 \<`
      echo $first $last G=$games B=$atbat R=$runs H=$hits $team
    endif

  # Last possibility is multiple players with this last name.
  else
    # Need to find player ID number that matches first and last names.
    # Use scanhtml to find the player ID from character 127 to just before the quote mark
    # on the line with the full name.
    set ID = `cat $tmp | scanhtml "$first $last" 0 -127 \"`
    if ( "$ID" == "NA" ) then
      echo No info on $first $last
    else
      # Slightly different URL is needed with ID rather than last name.
      lynx -source "$altURL?playerID=$ID" > $tmp
      # Now it is the same as for a unique match.

      # But did the player hit this year?
      set team = `cat $tmp | scanhtml2 "Hitting Stats" \>$2\< 1 -67 \<`
      if ( "$team" == "NA" ) then
        echo $first $last did not play in $2
      else
        set games = `cat $tmp | scanhtml2 "Hitting Stats" \>$2\< 2 -50 \<`
        set atbat = `cat $tmp | scanhtml2 "Hitting Stats" \>$2\< 3 -50 \<`
        set runs = `cat $tmp | scanhtml2 "Hitting Stats" \>$2\< 4 -50 \<`
        set hits = `cat $tmp | scanhtml2 "Hitting Stats" \>$2\< 5 -50 \<`
        echo $first $last G=$games B=$atbat R=$runs H=$hits $team
      endif
    endif
  endif
end
