#!/bin/sh
# customization parameters
#ttyprefix=/dev/tty ;# what to add to ttycolumn's word to obtain valid device
ttyprefix=/dev/; #for linux systems with /dev/pts
cmdcolumn=5 ;# where to find command in ps output
ttycolumn=2 ;# where to find tty name in ps output
psargs=aww; 
# displays usage information
usage () {
 echo "xtitle [ -t tty|-c command] [-i|-w|-f] title" >&2
 echo " -t specifies tty associated with xterm to change" >&2
 echo " -c specifies command running in this xterm" >&2
 echo " -i notifies, that only icon name should be changed" >&2
 echo " -w that window name only (default - both)">&2
 echo " -f changes font instead of title" >&2
 echo " -r raises/deiconifies window instead of changing title" >&2
}
# tries to get tty name from command name
get_tty_from_command () {
  local t
  echo \"$cmdcolumn\" \"$ttycolumn\"
  t=`ps $psargs|awk "\\$$cmdcolumn~/$1/ {print \"$ttyprefix\" \\$$ttycolumn;exit}"`
  if [ -z "$t" ]
     then
       echo "None of your processes matches pattern \"$1\"" >&2
       exit 1
     fi
  check_tty $t
}
# checks if supplied tty name is valid device name
check_tty () {
  if [ ! -c $1 ] 
     then
       echo "$i is not valid tty name" >&2
       exit 1
     fi
  if [ ! -w $1 ]
     then
       echo "$i is not writable for you" >&2
       exit 1
     fi
  tty=$1
}
# by default change our own xterm title
tty=`tty`
# by default change both window name and icon name
mode=0
set -- `getopt "iwrfc:t:h" $*`
if [ $? != 0 ]
then
 usage
 echo Invalid options. Usage: >&2
 exit 1
fi
for i
do
       case $i
       in 
	  -i) mode=1;shift;;
          -w) mode=2;shift;;
          -f) mode=50;shift ;;
	  -t) check_tty $2;shift;shift;;
          -c) get_tty_from_command $2;shift;shift;;
          -h) echo "$0: changes a title of xterm window" 
              usage 
              exit 0 
             ;;
		-r) raise_mode=1; shift;;
          --) shift; break;;
       esac
       
done
echo "tty=$tty"
if [ -n "$raise_mode" ]; then
	echo -ne "\\033[1t\\033[5t" >$tty
fi	
echo -e "\\033]$mode;$*\a\c" >$tty 

