#!/usr/bin/env perl
#
# TODO
# add a -h height cli argument
# add a .bmirc file to contain default height
#
# NOTE
# From https://www.nhlbi.nih.gov/health/educational/lose_wt/BMI/bmicalc.htm
#
# The BMI range boundaries are
# < 18.5 underweight
# 18.5-24.9 healthy
# 25.0-29.9 overweight
# >= 30 obese
#
# change history
# 13/04/24 initial

use strict;
use warnings;
use feature ':5.10';
use Data::Dumper;
use Getopt::Long;
use feature qw(say);
use POSIX();

# version
my $version=0;
my $subversion=1;

my %opts;

sub usage {
    my $txt = <<"USAGE";
Synopsis.

bmi [-c] [-v] [-t] <weight in kg>

Options.

-c: convert weight to imperial only
-t: prepend current time
-v: print version and exit

Examples.

bmi 85.4
bmi -c 85.4
bmi -t 85.4
bmi -v

USAGE
    say "Unknown option: @_" if ( @_ );
    say $txt;
    exit 0;
}

my $argc = @ARGV+0;

usage() if (!GetOptions(
        # options
        't'                   => \$opts{t},
        'v'                   => \$opts{v},
        'c'                   => \$opts{c},
) or $argc == 0);

die "bmi: version $version.$subversion\n" if $opts{v};

if ($opts{t}) {
  my ($sec, $min, $hour) = localtime();
  printf "%02d%02d ", $hour, $min;
}

# height value in metres
my $height=1.762;

my $kg=$ARGV[0];
my $stone = $kg / 6.35029318;
my $stn = int $stone;
my $frac = $stone - $stn;
my $pds = $frac * 14;
my $pdsrounded = POSIX::round($pds);
my $lbs = ($stn * 14) + $pdsrounded;

print "bmi: ${kg}kg ${lbs}lbs ${stn}:${pdsrounded}st";

# print conversion only if -c was specified
if ($opts{c}) {
   say "";
   exit 0;
}

# ------------------------------------------
# calculate bmi

my $bmi = $kg / ($height**2);
print " bmi ", sprintf("%.1f", $bmi), " ";

if ($bmi >= 30) {
    print 'obese';
} elsif ($bmi >= 25) {
    print 'overweight';
} elsif ($bmi >= 18.5) {
    print "normal weight";
  } else {
    print "underweight";
}

# within the 'overweight' range, print a bar chart to show the position between
# the upper and lower limits, in increments of 0.5

print " ";
if ($bmi >= 25 && $bmi < 30) {
  my $i = 25.0;
  #say "bmi $bmi";

  while ($i <= $bmi) {
    print '#';
    $i += 0.5;
  }

  while ($i < 30.0) {
    print '.';
    $i += 0.5;
  }
}

say '';

