#!/bin/sh
# Count non-blank lines in .rad files, skipping tests.

if [ "$#" -eq 0 ]; then
  set -- .
fi

tmpList=$(mktemp)
tmpFiles=$(mktemp)
trap 'rm -f "$tmpList" "$tmpFiles"' EXIT HUP INT TERM

for input in "$@"; do
  if [ -d "$input" ]; then
    find "$input" -type f -name "*.rad" -not -path "*/tests/*" -not -name "tests.rad" >> "$tmpList"
  elif [ -f "$input" ]; then
    case "$input" in
      */tests/*|*/tests.rad|tests.rad)
        ;;
      *.rad)
        printf '%s\n' "$input" >> "$tmpList"
        ;;
      *)
        echo "Error: File '$input' is not a .rad file" >&2
        exit 1
        ;;
    esac
  else
    echo "Error: Path '$input' does not exist" >&2
    exit 1
  fi
done

echo "Counting non-blank lines in .rad files for inputs: $*"
echo "------------------------------------------------------"

total=0
sort -u "$tmpList" > "$tmpFiles"

while IFS= read -r file; do
  if [ -f "$file" ]; then
    count=$(grep -v '^[[:space:]]*$' "$file" | wc -l)
    total=$((total + count))
    printf "%6d  %s\n" "$count" "$file"
  fi
done < "$tmpFiles"

echo "------------------------------------------------------"
printf "%6d  TOTAL\n" "$total"
