_pipesz_module()
{
	local WORD OPTS OPTARG OPTEND SOPT LOPT TARG
	local SOPTS=(g s f n i o e c q v h V)
	local LOPTS=(get set file fd stdin stdout stderr check quiet verbose help version)
	local AOPTS=(0 1 1 1 0 0 0 0 0 0 0 0) # takes argument
	local TOPTS=(1 0 1 1 1 1 1 0 0 0 0 0) # specifies target
	local XOPTS=(0 0 0 0 0 0 0 0 0 0 1 1) # exits immediately
	local MOPTS=(0 0 1 1 0 0 0 0 0 0 0 0) # repeatable
	local NOPTS=(0 0 0 0 0 0 0 0 0 0 0 0) # number of repeats
	local IDXG=0 IDXS=1                   # index of --get and --set

	for ((i=1; i<COMP_CWORD; i++)); do
		WORD=${COMP_WORDS[i]}

		if [[ ${NOPTS[$IDXG]} -eq 0 ]]; then
			case $WORD in
				--)
					_command_offset $((i+1))
					return 0;;
				[^-]*)
					_command_offset $i
					return 0;;
			esac
		fi

		for ((j=0; j<${#NOPTS[@]}; j++)); do
			SOPT=${SOPTS[$j]}
			LOPT=${LOPTS[$j]}

			case $WORD in
				--$LOPT) OPTEND=l;;
				--*) continue;;
				-*$SOPT) OPTEND=s;;
				-*$SOPT*) OPTEND=n;;
				*) continue;;
			esac

			if [[ ${XOPTS[$j]} -ne 0 ]]; then
				COMPREPLY=()
				return 0
			fi

			((NOPTS[j]++))

			[[ ${TOPTS[$j]} -ne 0 ]] && TARG=y
			[[ $OPTEND != n ]] && ((i+=AOPTS[j]))
			[[ $OPTEND == l ]] && break
		done
	done

	case $3 in
		--fd) OPTARG=n;;
		--file) OPTARG=f;;
		--size) OPTARG=s;;
		--*) ;;
		-*n) OPTARG=n;;
		-*f) OPTARG=f;;
		-*s) OPTARG=s;;
	esac

	case $OPTARG in
		f)
			compopt -o filenames
			COMPREPLY=( $(compgen -f -- "$2") )
			return 0;;
		n)
			COMPREPLY=( $(compgen -W "0 1 2" -- "$2") )
			return 0;;
		s)
			WORD=$2
			if [[ ! $WORD =~ ^[0-9]+[a-zA-Z]*$ ]]; then
				COMPREPLY=()
				return 0
			fi

			while [[ $WORD =~ [a-zA-Z]$ ]]; do WORD=${WORD:0:-1}; done

			compopt -o nosort
			COMPREPLY=( $(compgen -W "$WORD $WORD{K,M,G}{B,iB}" -- "$2") )
			return 0;;
	esac

	for ((j=0; j<${#NOPTS[@]}; j++)); do
		[[ $j -eq $IDXG && ${NOPTS[$IDXS]} -ne 0 ]] && continue
		[[ $j -eq $IDXS && ${NOPTS[$IDXG]} -ne 0 ]] && continue
		[[ $COMP_CWORD -ne 1 && ${XOPTS[$j]} -ne 0 ]] && continue
		[[ ${NOPTS[$j]} -gt 0 && ${MOPTS[$j]} -eq 0 ]] && continue

		[[ $2 != --* && $2 == -* ]] && OPTS+=" -${SOPTS[$j]}"
		OPTS+=" --${LOPTS[$j]}"
	done

	if [[ ! $TARG || ${NOPTS[$IDXG]} -ne 0 ]]; then
		COMPREPLY=( $(compgen -W "$OPTS" -- "$2") )
	else
		compopt -o filenames
		COMPREPLY=( $(compgen -c -W "$OPTS --" -- "$2") )
	fi
}

complete -F _pipesz_module pipesz
