#!/usr/bin/perl
#
# Compute the speed of perfectly struck ball
#    leaving a bat, under greatly simplified
#    conditions:
# 
#        1-D collision only
#        no spin induced
#        assume coefficient restitution has fixed value
#
# Usage: batted_ball_speed.pl   bat_mass_kg
#
# MWR 7/28/2017

use POSIX;
$debug = 0;
$MPH2MPS = (1609.0/3600.0);

# read the mass of the bat from the command line
if ($#ARGV != 0) {
  printf "usage: batted_ball_speed.pl  bat_mass_kg \n";
  exit(1);
}
$mt = $ARGV[0];
if ($debug > 0) {
  printf "# mass of bat  %5.2f kg \n", $mt;
}


# mass of ball (kg)
$mb = 0.143;
# speed of incoming ball (mph)
$vb1_mph = 90.0;
# speed of incoming ball (m/s)
$vb1 = $vb1_mph*$MPH2MPS;
# coefficient of restitution 
$e = 0.4;

# starting point for speed of bat (mph)
$vt1_start_mph = 30.0;
$vt1_start = $vt1_start_mph*$MPH2MPS;
# ending point for speed of bat (mph)
$vt1_end_mph = 110.0;
$vt1_end = $vt1_end_mph*$MPH2MPS;
# stepsize in speed of bat (mph)
$vt1_step_mph = 1.0;
$vt1_step = $vt1_step_mph*$MPH2MPS;


# loop over a range of initial bat speeds,
#   computing final bat and ball speeds for each.
#   Print out one line per initial bat speed
for ($vt1 = $vt1_start; $vt1 <= $vt1_end; $vt1 += $vt1_step) {
  if ($debug > 0) {
    printf " starting look for vt1 = %5.1f m/s = %5.1f mph \n",
         $vt1, $vt1/$MPH2MPS;
  }


  # first, we compute the speed of the bat after the collision
  $top = $mt*$vt1 - $mb*$vb1 - $mb*$vt1*$e - $mb*$vb1*$e;
  $bot = $mt + $mb;
  $vt2 = $top / $bot;

  # next, we compute the speed of the ball after the collision
  $vb2 = $vt2 + $vt1*$e + $vb1*$e;

  if ($debug > 0) {
    printf "  vt2 = %5.1f m/s = %5.1f mph \n",
          $vt2, $vt2/$MPH2MPS;
    printf "      vb2 = %5.1f m/s = %5.1f mph \n",
          $vb2, $vb2/$MPH2MPS;
  }


  # compute the momentum and after collision
  $mom_before = $mt*$vt1 - $mb*$vb1;
  $mom_after = $mt*$vt2 + $mb*$vb2;
  
  # compute the KE before and after collision
  $ke_before = 0.5*$mt*($vt1*$vt1) + 0.5*$mb*($vb1*$vb1);
  $ke_after = 0.5*$mt*($vt2*$vt2) + 0.5*$mb*($vb2*$vb2);
  


  # print one line per initial bat speed
  printf " %5.2f %5.2f  before %6.2f %6.2f  after %6.2f %6.2f ",
        $mt, $mb, 
        $vt1/$MPH2MPS, $vb1/$MPH2MPS,
        $vt2/$MPH2MPS, $vb2/$MPH2MPS;
  printf "  mom %6.1f %6.1f ", $mom_before, $mom_after;
  printf "  KE  %6.1f %6.1f ", $ke_before, $ke_after;
  printf " \n";


}



exit 0;



