+# can be "-" for no escape sequences
+[ "$LINK_COLOR" = "" ] && LINK_COLOR=2
+
+# Start and end link tags
+SL=
+EL=
+if [ "$LINK_COLOR" != "-" ]; then
+ SL="`tput setf $LINK_COLOR``tput setaf $LINK_COLOR`"
+ EL="`tput init`"
+ export LESS="${LESS}-R"
+fi
+
+# 'dialog' or text
+if [ "$USE_DIALOG" = "" ]; then
+ if dialog --help >/dev/null 2>&1; then
+ USE_DIALOG=1
+ else
+ USE_DIALOG=0
+ fi
+fi
+
+# Invert image viewer
+if [ "$INVERT" = 1 ]; then
+ INVERT="--invert"
+else
+ INVERT=
+fi
+
+# $0 [FILE] (dialog)
+# Display a gopher menu for the given resource
+cat_menu() {
+ i=0
+ cat "$1" | grep "^i\|^$PREFIX" | while read ln; do
+ if echo "$ln" | grep "^i" >/dev/null 2>&1; then
+ if [ "$2" != dialog ]; then
+ echo "$ln" | sed "s:^.\([^\t]*\).*$: \1:g"
+ else
+ echo "$ln" | sed 's:":'"''"':g;s:^.\([^\t]*\).*$:" " "\1":g'
+ fi
+ elif echo "$ln" | grep "^$PREFIX" >/dev/null 2>&1; then
+ i=`expr $i + 1`
+ [ $i -le 9 ] && i=0$i
+ field="`echo "$ln" | cut -c1`"
+ case "$field" in
+ 0) typ='TXT';;
+ 1) typ='DIR';; # menu, actually
+ 7) typ='(?)';; # query
+ 8) typ='TEL';; # TELnet (not TELephone)
+ h) typ='WEB';; # HTML
+ I) typ='IMG';;
+ g) typ='GIF';;
+ +) typ='SVR';; # redundant server
+ *) typ='!!!';;
+ esac
+ if [ "$2" != dialog ]; then
+ echo "$ln" | sed "s:^.\\([^\t]*\\).*:$typ $i $SL\\1$EL:g"
+ else
+ echo "$ln" | sed "s:"'"'":'':g;s:^.\\([^\t]*\\).*:"'"'"$typ $i"'"'" "'"\1"'":g"
+ fi
+ fi
+ done
+}
+
+# $0 [FILE] [INDEX] [FIELD]
+# Get a field from the given-by-index link in FILE
+#
+# Fields:
+# 1 = type/name
+# 2 = selector
+# 3 = server
+# 4 = port
+getsel() {
+ cat "$1" | grep "^$PREFIX" | tail -n+"$2" | head -n 1 | cut -f"$3"
+}
+
+# Save page content to 'tmp' file
+tmp="`mktemp -t gofetch.current_page.XXXXXX`"
+finish() {
+ rm -rf "$tmp" "$tmp.jpg" "$tmp.menu" "$tmp.choice"
+}
+trap finish EXIT
+
+echo "$SELECTOR" | nc "$SERVER" "$PORT" > "$tmp"
+if [ $? != 0 ]; then
+ echo Cannot contact gopher server "[$SERVER]" >&2