#!/bin/bash
# !!! This stripped version doesn't have comments or help !!!
export CUVLIS_CDC=16
export CUVLIS_CDC_PRETTY="ON"
export CUVLIS_CDC_TEST="OFF"
if [[ "z$CUVLIS_CDC_TEST" != "zON" ]]; then
  unset OLDPWDS
fi
OLDPWDS[0]=$PWD
cd () {
  builtin cd "$@"
  local result=$?
  if [[ "z$@" == "z.." || "z$@" == "z" || "${1:0:1}" == "/" ]]; then
    echo "$PWD"
  fi
  if [[ $result -ne 0 || "z$PWD" == "z$OLDPWD" ]]; then
    return $result
  fi
  local numpwds=${#OLDPWDS[*]}
  local i=0
  while (( $i < $numpwds )); do
    if [[ "z${OLDPWDS[i]}" == "z$PWD" ]]; then
      CDCShift $i
      return 0
    fi
    let i=i+1
  done
  if (( $numpwds == $CUVLIS_CDC )); then
    let i=i-1
  fi
  CDCShift $i
  return 0
}
cdn () {
  if [[ $1 -eq 0 ]]; then
    echo CDC: Yikes, I need a number for something in the history
    return 2
  fi
  local numpwds=${#OLDPWDS[*]}
  if (( $numpwds < 2 )); then
    echo CDC: Nothing in the history
    return 3
  elif (( $1 > $numpwds-1 )); then
    echo CDC: $1 not in history, last entry is $(($numpwds-1))
    return 4
  fi
  cd "${OLDPWDS[$1]}"
}
limit=9
if (( $CUVLIS_CDC <= $limit )); then
  let limit=CUVLIS_CDC-1
fi
while (( $limit > 0 )); do
  alias c$limit="cdn $limit"
  let limit=limit-1
done
unset limit
cl () {
  local numpwds=${#OLDPWDS[*]}
  local width=3
  local i=0
  local temp="not much"
  if [[ "z$CUVLIS_CDC_PRETTY" == "zON" ]]; then
    local CBLD="\033[1m"     ;#       bold
    local CDCZ="\033[0;33m"  ;# Z for zero-th entry (pwd)
    local CDCS="\033[0;32m"  ;# S for shortcut
    local CDCO="\033[0;35m"  ;# O for other entries
    local CDCC="\033[0m"     ;# C for clear
  fi
  if (( $numpwds == 2 )); then
    echo CDC is tracking $(($numpwds-1)) directory \($(($CUVLIS_CDC-1)) max\)
  else
    echo CDC is tracking $(($numpwds-1)) directories \($(($CUVLIS_CDC-1)) max\)
  fi
  while (( $i < $numpwds )); do
    if (( $i < 1 )); then
      printf "${CDCZ}%${width}s" "pwd"
    elif (( $i < 10 )); then
      printf "${CDCS}%${width}s" "c$i"
    else
      printf "${CDCO}%${width}s" "$i"
    fi
    temp=${OLDPWDS[i]/#${HOME}/~}
    if [[ "z$1" != "z-l" && ${#temp} -gt 70 ]]; then
      temp=${temp:0:34}${CDCC}...${CBLD}${temp: -33}
    fi
    echo -e ': '${CDCC}${CBLD}$temp${CDCC}
    let i=i+1
  done
}
CDCShift () {
  local i=$1
  local j
  while (( $i > 0 )); do
    let j=i-1
    OLDPWDS[i]=${OLDPWDS[j]}
    let i=j
  done
  OLDPWDS[0]=$PWD
}
