#!/bin/bash
# count-lib.sh  -  shared counting helper for pipeline shell scripts.
#
# Why: `grep -c` prints "0" AND exits 1 when nothing matches, so the common
# idiom `$(grep -c pattern file || echo 0)` emits TWO lines ("0" plus the
# fallback "0"). That breaks arithmetic (`$((x + 0\n0))` is a syntax error)
# and numeric comparisons (`[ "0\n0" -le 1 ]` silently evaluates false).
#
# count_matches guarantees single-line numeric output in every case:
#   - match count when grep succeeds
#   - "0" when nothing matches or grep itself errors (missing file, ...)
#
# Usage (same arguments as grep -c, file or stdin):
#   n=$(count_matches -E 'pattern' "$file")
#   n=$(printf '%s\n' "$blob" | count_matches .)
#
# Source from a sibling script:
#   . "$(cd "$(dirname "$0")" && pwd)/count-lib.sh"

count_matches() {
  local n
  n=$(grep -c "$@" 2>/dev/null) || true
  case "$n" in
    '' | *[!0-9]*) n=0 ;;
  esac
  printf '%s\n' "$n"
}
