file="$1"

RANDOM() {
  # shellcheck disable=SC2312
  # https://shellcheck.net/wiki/SC3028/1f83d59#correct-code
  command -p -- awk -vmax="$(
    command -p -- getconf -- SHRT_MAX
  )" -- 'BEGIN {
  srand()
  printf "%d\n", int(rand() * max)
}'
}

tmpdir=${TMPDIR:-/tmp}/lesspipe."$(RANDOM)"
[ -d "${tmpdir}" ] || mkdir "${tmpdir}"
[ -d "${tmpdir}" ] || exit 1
trap 'rm -rf "$tmpdir";exit 1' INT
trap 'rm -rf "$tmpdir"' EXIT
trap - PIPE

nexttmp() {
  new="${tmpdir}/tmp.$(RANDOM).${file%%:*}"
  echo "${new}"
}

nodash() {
  prog="$1"
  shift
  [ "$1" = - ] && shift
  ${prog} "$@"
}
# shellcheck disable=SC2249
handle_w3m() {
  # if [[ "$1" == *\?* ]]; then
  case "$1" in
    *\?*)
      t=$(nexttmp)
      ln -s "$1" "${t}"
      set "${t}" "$1"
      ;;
  esac
  nodash "w3m -dump -T text/html" "$1"
}
