#!/usr/bin/perl -w

# Copyright by Doug Coulter, 3/22/2011
# GPL V2 license -- please improve and email improvements to
# info@coultersmithing.com
# gun guys should do GPL better -- we already help each other

# This math is based on some insights by Richard Lee, as expressed in his book
# Modern Reloading, second edition, where he describes how pressure and velocity
# vs powder can be predicted (exponential decay, different exponents).
# As he points out (and I've duplicated) there is a pressure that's best for a given
# hardness bullet -- just enough to upset the bullet metal *a little*.  This helps
# you find that load that will shoot your cast bullets the best.


# it would be nice to have the cursor display at bottom show both or either plot values,
# rather than just where the cursor happens to be

# you need to have gnuplot in your path, and the GnuplotIF perl module to get pretty pictures

use strict;
use Graphics::GnuplotIF qw(GnuplotIF);

 ################################
 
 # numbers should be close for varget/.223/ 63 gr jacketed bullet
 # we still need to learn them for cast bullets
 
my $velocity = 3199;
my $pressure = 55365;
my $grains = 26.4;
my $pfactor = 0.9206;
my $vfactor = .9626;
my $temp;

#################################

my @x;	# for gnuplot
my @y;
my @y2; # a very adventurous joke

# a way to pause so things don't disapear off the screen
  sub hitret
  {
  my $dummy = shift;
  print ("\n$dummy Hit return to continue ->");
  $dummy = <>; 
  }

# main, get data from user

print ("This program can be edited for different defaults.  This is Varget, .223, and 63 gr bullet.\n");

#fancy regexes from Perl Cookbook to just take numbers.

print ("Starting pressure? ($pressure)    >");
chomp ($temp = <STDIN>);
if ($temp =~/^-?(?:\d+(?:\.\d*)?|\.\d+)$/) {$pressure = $temp;}

print ("Starting grains? ($grains)    >");
chomp ($temp = <STDIN>);
if ($temp =~/^-?(?:\d+(?:\.\d*)?|\.\d+)$/) {$grains = $temp;}

print ("pressure reduction pfactor? ($pfactor)    >");
chomp ($temp = <STDIN>);
if ($temp =~/^-?(?:\d+(?:\.\d*)?|\.\d+)$/) {$pfactor = $temp;}

print ("velocity reduction vfactor? ($vfactor)    >");
chomp ($temp = <STDIN>);
if ($temp =~/^-?(?:\d+(?:\.\d*)?|\.\d+)$/) {$vfactor = $temp;}


# compute arrays and print values on the terminal
print ("\nGrains\tPressure\tVelocity\n");
while ($grains > 0)
{
 printf ("%05.2f\t%08.2f\t%.2f\n",$grains,$pressure,$velocity);
 push (@x,$grains);
 push (@y,$pressure);
 push (@y2,$velocity * 10.0);
 $grains -= 1;
 $pressure *= $pfactor;
 $velocity *= $vfactor;
}


# plot this crap

my  $plot = Graphics::GnuplotIF->new(title => "Pressure, Velocity vs Grains", style => "linespoints", xlabel => 'Grains of powder');
$plot->gnuplot_set_plot_titles("Pressure, psi","Velocity, fps * 10");          # set legend
$plot->gnuplot_cmd( "set grid" );                   # send a gnuplot command
$plot->gnuplot_plot_many( \@x, \@y, , \@x, \@y2);
hitret ("bye now!");


