#!/bin/sh
#
# barchart - makes bar chart from input files or standard input if no files given
#
# ---
# source: https://github.com/TurkeyMcMac/barchart

char=#
[ -r /dev/tty ] && cols=$(stty </dev/tty size 2>/dev/null | awk '{ print $2 }')
[ -n "${cols}" ] || cols=80

while [ "$#" -gt 0 ]; do
  opt="$1"
  case "${opt}" in
    -c)
      shift
      char="$1"
      ;;
    -c*)
      char="${1##-c}"
      ;;
    -w)
      shift
      cols="$1"
      ;;
    -w*)
      cols="${1##-w}"
      ;;
    -h)
      cat <<EOT
Usage: barchart [-w cols] [-c char] [-h] [--] file...
Makes a bar chart from input files, or standard input if no files are given.
Options:
  -w cols  Force bar chart width to the given columns. Without this, the program
           tries to use the controlling terminal width.
  -c char  Make bars out of the given character.
  -h       Print this help.
Each input line is a non-negative integer followed by an optional label.
EOT
      exit 0
      ;;
    --)
      shift
      break
      ;;
    -?*)
      echo >&2 "${0##*/}: Invalid option: ${opt}"
      exit 1
      ;;
    *)
      break
      ;;
  esac
  [ "$#" -gt 0 ] || {
    echo >&2 "${0##*/}: Option ${opt} requires an argument"
    exit 1
  }
  shift
done

exec awk -v char="${char}" -v cols="${cols}" '
{ count = +$1;
  $1 = "";
  label = substr($0, 2);
  sum += count;
  if (count > max) max = count;
  l = length(""count);
  if (l > countlen) countlen = l;
  l = length(label);
  if (l > labellen) labellen = l;
  counts[+n] = count;
  labels[+n] = label;
  ++n }
END {  width = cols - countlen - 1 - labellen - 1;
  for (i = 0; i < +n; ++i) {
    printf "%"countlen"d %-"labellen"s ", counts[i], labels[i];
    if (max > width) counts[i] = counts[i] / max * width;
    while (counts[i]-- > 0) printf "%s", char;
    printf "\n";
  } }' "$@"
