#!/bin/sh

CXTERM_AD=/usr/X11R6/lib/X11/cxterm.dic/CXterm.ad
XFONTDIR=/usr/X11R6/lib/X11/fonts/chinese

# ENCODE_FONTS:		automaticially search for a font from the list
GB_FONTS="hanzigb16st cclib16st beijing16"
BIG5_FONTS="hku16et taipei16 taipei15"

if [ "$BINDIR" != "" ]; then
    CXTERM="$BINDIR/cxterm"
else
    CXTERM=cxterm
fi

check_use_font ()
{
    for f in "$@" ; do
	# the awk'ing is needed if $f exists in more than one font dir - DEO
	TRYFONT=`xlsfonts $f 2>/dev/null | /usr/bin/awk '{print $1 ; exit}'`
	if [ "$TRYFONT" = "$f" ]; then
	    echo $f
	    return 0
	fi
    done
    xset fp+ "$XFONTDIR"
    for f in "$@" ; do
	TRYFONT=`xlsfonts $f 2>/dev/null | /usr/bin/awk '{print $1 ; exit}'`
	if [ "$TRYFONT" = "$f" ]; then
	    echo $f
	    return 0
	fi
    done
    return 1
}

NAME=cxterm
case "$1" in
  -gb* | -GB* )		NAME=cxterm;  shift 1 ;;
  -big5 | -Big5 | -BIG5 | -b5 | -B5 )	NAME=cxtermb5;  shift 1 ;;
  -jis | -JIS )		NAME=cxtermjis;  shift 1 ;;
  -ks* | -KS* )		NAME=cxtermks;  shift 1 ;;
esac

CF=""
FH=0
for i in "$@" ; do 
    if [ "$i" = "-fh" ]; then
	FH=1;  continue;
    fi
    if [ "$FH" -eq 1 ]; then
	CF=`check_use_font $i`
	if [ "$CF" = "" ]; then
	    echo "Specified font doesn't exist in the X Window system."
	    exit 1
	fi
	break
    fi
    FH=0
done

if [ "$CF" = "" ]; then
    if [ "$NAME" = "cxterm" ]; then
	CF=`check_use_font $GB_FONTS`
	if [ "$CF" = "" ]; then
	    echo "Cannot identify a chinese font in the X Window system."
	    exit 1
	fi
	FH_OPT="-fh $CF"
    elif [ "$NAME" = "cxtermb5" ]; then
	CF=`check_use_font $BIG5_FONTS`
	if [ "$CF" = "" ]; then
	    echo "Cannot identify a chinese font in the X Window system."
	    exit 1
	fi
	FH_OPT="-fh $CF"
    fi
fi

XENVIRONMENT=$CXTERM_AD
export XENVIRONMENT
exec $CXTERM -name $NAME $FH_OPT $*
