#!/usr/bin/env ksh
# Pops the top directory
# shellcheck disable=SC2154  # .sh._push_stack[@] is referenced but not assigned
# shellcheck disable=SC2211  # .sh.var assignments are not "glob used as a command name"

function popd {
    typeset dir
    # shellcheck disable=SC2154
    if ((.sh._push_top >= .sh._push_max))
    then  print popd: Nothing to pop.
        return 1
    fi
    case $1 in
    "")
        dir="${.sh._push_stack[.sh._push_top]}"
        case $dir in
        \~*) dir="$HOME${dir#\~}"
        esac
        cd "$dir" || return 1
        ;;
    +[1-9]|+[1-9][0-9])
        integer i=$((.sh._push_top - $1))
        if ((i >= .sh._push_max))
        then
            print pushd: Directory stack not that deep.
            return 1
        fi
        while ((i > .sh._push_top))
        do
            .sh._push_stack[i]="${.sh._push_stack[i-1]}"
            (( i = i - 1 ))
        done
        ;;
    *)  print pushd: Bad directory.
        return 1
    esac
    unset '.sh._push_stack[.sh._push_top]'
    (( .sh._push_top = .sh._push_top + 1 ))
    dirs
}
