#!/bin/sh

# Setup:  source this file in when making a new shell.
#  Have base defined.
#  In .bachrc
#
#  #mac
#  export base="Users/zero/base"
#  source $base/p1/comsci/sh/chel.sh 
#
#  #fedora9
#  export base="/home/zero/base"
#  source $base/p1/comsci/sh/chel.sh

export player="mplayer -loop 0 -fs";
export CVSROOT="/home/zero/newrepos";
export LD_LIBRARY_PATH="/home/zero/base/p1/misc/qwt/lib";


declare PATH=$PATH:/lib/:$base/p1/comsci/sh:$base/p1/comsci/pl:/usr/local/Trolltech/Qt-4.2.2/lib:/usr/local/Trolltech/Qt-4.2.2/bin:/usr/local/include/:/usr/include/:/usr/local/apache2/bin:/usr/X11/bin:/usr/local/mysql/bin:/usr/lib/:/usr/local/bin:/usr/lib:/opt/local/bin:/opt/local/sbin

export QTDIR=/usr/local/Trolltech/Qt-4.2.2
#export QWT=/home/zero/q2/qwt
#export LD_LIBRARY_PATH=$QWT/lib




# Clean the source of object files and the executable main.
function cleansource
{
#  pushd ${base}
  local i
  for i in `find . -name \*.o`; do
    rm ${i}
  done;
  for i in `find . -name main`; do
    rm ${i}
  done;
#  popd
}

# list possible corrupted vim files(have .swp extension)
function swpls 
{ 
  find . -name ".*.swp";
}

# Move corrupted files to /tmp/ directory. 
function swpmv { mv -i .*swp /tmp/; }

# Start a gvim session and load with Session.vim .
function gvims
{
  gvim -S Session.vim &
}

# Recursively find all swap files and delete.
function swpdel
{
  local swpdel_i
  for swpdel_i in `find . -name "*.swp"`; do
    mv $swpdel_i /tmp
  done;
}


 

function dimg
{
  local i
  for i in $1*.jpg;
  do
    mozilla $i;
  done
}

function dmpg
{
  local i
  for i in $1*.mpg
  do
    mplayer -fs $i
  done
}

function dwmv
{
  local i
  for i in $1*.wmv
  do
    mplayer -fs -speed .4 $i
  done
}

function dotpng
{
  dot -Tpng $1.dot -o $1.png
}

# List function declarations.
function declaref
{
  declare | grep "()";
}

function grepn
{
  grep -n $1 *;
}


# Back up a file, tar and gzip it. 
function backf
{
  if [ $# = 0 ]
  then
    echo "Back up a file. e.g. a directory.";
    echo "The backup appends a time stamp after the name.";
    echo "e.g. backf a1  resulted in the new file  a1_20040118.tar.gz  .";
                                                                                
    return;
  fi;
                                                                                
  declare datestamp=`date +%Y%m%d`;
  #echo $datestamp;
 
  declare archive=$1_${datestamp}.tar;
 
  #echo $archive;
 
  tar -cf ${archive} $1;
  gzip -f ${archive}
}


# List subdirectories relative to the current location.
function lsdr
{
# Full path listed.
#  frecursivesilent pwd;
                                                                                
# Remove the front path by pattern matching.
  local temp;
  local i
  for i in `frecursivesilent pwd`; do
    temp=${i#$PWD};
    #Remove front / .
    echo ${temp#/*};
  done;
}


#function school
#{
#  pushd ${base}/p1/school/;
#}

# Move to geometry directory.
function geometry
{
  pushd ${base}/p1/math/geometry;
}

# Move to math directory.
function math
{
  local loc=${base}/p1/math;

  if [ $# = 1 ]; then
    loc=$loc/$1;
  fi;

  pushd $loc;
}


# Move to number theory directory.
function number
{
   pushd ${base}/p1/math/number
}

# Move to downloads directory.
function downloads
{
  pushd ${base}/../downloads;
}

# Move to comsci directory.
#function comsci
#{
#  local loc=${base}/p1/comsci;
   
#  if [ $# = 1 ]; then
#    loc=$loc/$1;
#  fi;

#  pushd $loc;
#}

function tasks
{
  pushd ${base}/p1/tasks;
}

# Move to calculus directory.
function calculus
{
  pushd ${base}/p1/math/calculus;
}

#function taff
#{
#  pushd ${base}/taff
#}

# Move to calculus of variations.
function variations
{
  pushd ${base}/p1/math/calculus/variations;
}

# Move to Open-GL
function opgl
{
  pushd ${base}/p1/misc/opgl;
}

# Move to stl directory.
function stl
{
   pushd ${base}/p1/misc/stl
}

# Move to directory or its subdirectory
# 3: optional subdirectory
# 2: optional subdirectory
# 1: directory (assumed to exist)
# Example:  pushd ${base}/p1/misc/ java3d
function pushdsub
{
  local loc=$1;

  if [ $# = 2 ]; then
    loc=$loc/$2;
  fi;

  if [ $# = 3 ]; then
    loc=$loc/$2/$3;
  fi;

  pushd $loc;
}

# Move to misc directory.
function misc
{
  pushdsub ${base}/p1/misc $1 $2
}


# Move to the base directory.
function bas
{
  pushdsub ${base} $1 $2
}

# Move to software directory.
function software 
{
   pushd ${base}/software;
}


function comsci
{
  pushdsub ${base}/p1/comsci $1 $2;
}

function vu
{
  pushdsub ${base}/ce/VU $1 $2;
}


# Move to proj directory.
# Move to a directory relative to proj by suplying the directory relative to proj .
#function proj
#{
#  local loc=${base}/p1/misc/proj;
   
#  if [ $# = 1 ]; then
#    loc=$loc/$1;
#  fi;

#  pushd $loc;
#}

# Refresh user definitions.
function chelinit
{
    pushd ${base}/p1/comsci/sh;
    source chel.sh;
    popd;
}

# Edit user definitions. 
function cheledit
{
    pushd ${base}/p1/comsci/sh;
    vi chel.sh;
    source chel.sh;
    popd;
}

# List directories in the current directory.
function lsd
{
  local i
  for i in `ls`; do
    if [ -d $i ]; then
      echo $i;
    fi;
  done;
}

# Apply a function to directory tree recursively.
function frecursive
{
  $1;

  local i
  for i in `ls -d`; do
    if [ -d $i ]; then
      pushd $i;
      frecursive $1;
      popd;
    fi;
  done;
}

function frecursivesilent
{
  $1;

 # Redirect pushd and popd messages.
 for i in `ls`; do
   if [ -d $i ]; then
     pushd $i > /tmp/temp.dat;
     frecursivesilent $1;
     popd > /tmp/temp.dat;
   fi;
 done;
}

# List subdirectories relative to the current location.
function lsdr
{
# Full path listed.
#  frecursivesilent pwd;

# Remove the front path by pattern matching.
  local temp;
  local i
  for i in `frecursivesilent pwd`; do
    temp=${i#$PWD};
    #Remove front / .
    echo ${temp#/*};
  done;
}

# Edit my work diary.
function work
{
  bas ce;
  vi work.txt;
  popd;
}

function mvfiles
{
  local i
  for i in `ls $1*`; do mv $i $2${i#$1}; done;
}

function basecopytotmp
{
  pushd ~;

  rm -R -f /tmp/base;
  cp -R base /tmp;
  cd /tmp/base;

  rm -Rf /tmp/base/res/
  rm -R /tmp/base/p1/misc/ntl*
  rm -f /tmp/base/p1/misc/cppcode.tar.gz;
  rm -R /tmp/base/p1/misc/proj/html

  local i
  for i in `find . -name \*.class`; do rm -f ${i}; done;
  for i in `find . -name \*.o`; do rm -f ${i}; done;
  for i in `find . -name \*.bak`; do rm -f ${i}; done;
  for i in `find . -name \*.html~`; do rm -f ${i}; done;
  for i in `find . -name .xvpics`; do rm -R -f ${i}; done;
  for i in `find . -name main`; do rm -f ${i}; done;
  for i in `find . -name ~\*`; do rm -f ${i}; done;
  for i in `find . -name \*.gch`; do rm -f ${i}; done;
  for i in `find . -name \*~`; do rm -f ${i}; done;
  for i in `find . -name \*.out`; do rm -f ${i}; done;

  popd
}

# Write the file to a string.
declare filetostringval
function filetostring()
{
  local filetostringi
  filetostringval="";
  for filetostringi in `cat $1`; do
    filetostringval=$filetostringval" "$filetostringi;
  done;
}
  
#Remove carriage returns and replace with space.
function filetostringprint()
{
  local i
  filetostringval="";
  for i in `cat $1`; do
    filetostringval=$filetostringval" "$i;
  done;
  echo $filetostringval;
}


function filesortbytime()
{
  echo "ls -al -t " > /tmp/t1.txt;
  find . -mtime -$1 -type f >> /tmp/t1.txt;
  filetostringprint /tmp/t1.txt > /tmp/t2.txt;
  bash /tmp/t2.txt;
} 

function filesortbytime2()
{
  find . -mtime -$1 -type f | xargs ls -al -t
}



# Move to the current projects directory.
function current
{
  cd /home/zero/base/p1/comsci/qt/code/polarplot
  #cd /home/zero/base/p1/misc/proj/tetrahedron
}



#current;


#  Brief:  Make multiple directories
#
#  Example:  
#          $mkdirm f5/f8/f12  
#          Makes directories f5/f8/f12 relative to the current directory.
function mkdirm
{
  if [ $# != 1 ]; then return; fi

  local a=${1%%/*}
  local b=${1#*/}

# Warning on Pattern matching.  Directories of relative paths
#   and absolute paths are treaded differently.

# In the event that the client supplies an absolute path,
# it is tested for and made into a relative path problem.
# When an absolute path is given $a is striped of everything.
# The quotes inside the test [ -z "$a" ] is a unix way of converting $a to a empty string
# This then means that the test will evaluate and turn true when given an absolute address.
  if [ -z "$a" ]; then 
    echo absolute path
    pushd /
   
    #It just so happens that if $a is left with nothing $b has everything except
    # the forward slash at the start.  This is one of the few times I am lucky.
    mkdirm ${b}

    popd
    return
  fi
  
#echo a=${a}
#echo b=${b}

  # Does the directory already exist?
  # If not make it.  If it is already another file leave it.
  if [ ! -d ${a} ]; then 
    if [ ! -e ${a} ]; 
      then mkdir ${a};
    else
      echo error: ${a} is not a directory
      return
    fi
  fi

  # If the pattern matchings are equal no further decending is possible.
  if [ ${a} = ${b} ]; then return; fi

  # Recursively call this function to make or move through the directories.
  if [ -d ${a} ]; then
    pushd ${a}
    mkdirm ${b}
    popd
  fi
}


#  Brief:  Copys the directory structure of the file to the destination
#
#  Example:
#          $cpm f2 rpn/include/rpn.h 
#          Assume directory ./f2 exists and is empty,
#          and assume file /rpn/include/rpn.h exists,
#          then the new file and directories created are
#          ./f2/rpn/include/rpn.h
#
#  Note:  cpm has the reverse order of arguments to cp.  
function cpm
{
  # Strip the ./ off.  so ./print/include/print.h becomes print/include/print.h
  local src=${2#./*}
  local dest=${1}
echo dest=${dest}
echo src=${src}

  # a and b are the directory and the file.
  # e.g.  rpn/include/rpn.h   has a=rpn/include  and  b=rpn.h
  local a=${src%/*}
  local b=${src##*/}
#echo a=${a}
#echo b=${b}
  
  if [ $# != 2 ]; then return; fi 

  if [ ! -e "$src" ]; then echo error: ${src} does not exist; return; fi;

  if [ ! -d "$dest" ]; then echo error: ${dest} is not a directory; return; fi

  # If the copy is normal ie no extension then use the normal cp command
  if [ "$a" = "$b" ]; then cp -R ${dest}; return; fi

  local targ=${dest}/${a}

#echo targ=${targ}

  mkdirm ${targ}
  cp -R ${src} ${targ}
}


function qwtexamples
{
  pushd /home/zero/downloads/qwt-20050831/examples
}

function qtexamples
{
  pushd /home/zero/downloads/qt-x11-opensource-src-4.1.0/examples
}

#Recursively changes all time stamps.
function timestampsmash
{
  local i
  for i in `ls -d *`
  do
    if [ -d ${i} ]
    then
      pushd ${i}
      touch *
      popd
    fi
  done
}

#Moving the hard drive to other computers with different clocks
#  caused the timestamps to be in the future. This resets future times
#  to now.
function clockskewed
{
  #local temp=/tmp/temp.txt
  local temp=/tmp/tempfile`date +%s``date +%N`.txt
  echo crap > $temp
  #touch $temp
  #cat $temp
  #ls --full-time $temp
  #ls --full-time /tmp/temp.txt
  local i
  for i in `find . -newer $temp`
  do
    touch $i
    #echo $i
  done
  #find . -newer $temp 
  rm $temp
}

# 1: list name
# 2: value added to list
function stringlistadd
{
  local stringlistaddtemp="$1=\"\$$1 $2\""
  eval "$stringlistaddtemp"
}

# 1: list name
# 2: value added to list
function stringlistpush
{
  local stringlistpushtemp="$1=\"\$$1 $2\""
  eval "$stringlistpushtemp"
}


# 1: list name
# 2: name of return variable
function stringlistlast
{
  # Use long local variable names because using indirect references.
  local stringlistlastlast=""
  local stringlistlasti
  local stringlistlastarg
  #for i in $lst; do last=$i; done

  stringlistlastarg="for stringlistlasti in \$$1; do stringlistlastlast=\$stringlistlasti; done"
  eval "$stringlistlastarg"
  stringlistlastarg="$2=$stringlistlastlast"
  eval "$stringlistlastarg"
}


# 1: list name
# 2: target
function stringlistremove
{
  local stringlistremovearg
  local stringlistremovei
  local stringlistremovenewlist
  stringlistremovearg="for stringlistremovei in \$$1; do if [ \"\$stringlistremovei\" != \"$2\" ]; then stringlistremovenewlist=\"\$stringlistremovenewlist \$stringlistremovei\"; fi done;"
  #echo "arg=$arg"

  eval "$stringlistremovearg"
  stringlistremovearg="$1=\"$stringlistremovenewlist\""
  eval "$stringlistremovearg"
}


# 1: list name
# 2: target
# 3: result as a string "" or "1"
#  Example
#  local l1="cat dog fish turtle"
#  local result
#  stringlistfind l1 cat result
#  echo "result=$result"
#  if [ "$result" == "1" ]; then
#    echo "found";
#  fi
function stringlistfind
{
  local stringlistfindarg
  local stringlistfindi
  local stringlistfindres=""
  stringlistfindarg="for stringlistfindi in \$$1; do if [ \"\$stringlistfindi\" == \"\$2\" ]; then stringlistfindres=\"1\"; fi done;"
  eval "$stringlistfindarg"

  stringlistfindarg="$3=$stringlistfindres"
  eval "$stringlistfindarg"
}

#<TODO>
#${t1% *} removes the first first.


# 1: list name
# 2: return variable name
function stringlistpop
{
  stringlistlast $1 $2
  local stringlistpopval
  local stringlistpoparg="stringlistpopval=\$$2"
#echo "arg=$arg"
  eval "$stringlistpoparg"
#echo "val=$val"
  stringlistremove $1 $stringlistpopval
}


# 1: The list to be made unique.
function stringlistunique
{
  local stringlistuniquel2=""
  local stringlistuniquei
  local stringlistuniqueres
  local stringlistuniquearg
  stringlistuniquearg="for stringlistuniquei in \$$1; do stringlistfind stringlistuniquel2 \$stringlistuniquei stringlistuniqueres; if [ \"\$stringlistuniqueres\" == \"\" ]; then stringlistpush stringlistuniquel2 \$stringlistuniquei; fi done"
  eval "$stringlistuniquearg"
  stringlistuniquearg="$1=\$stringlistuniquel2"
  eval "$stringlistuniquearg"
}


# 1: The first list being subtracted from, label A.
# 2: The target list, label B.
# A-B -> A
function stringlistsubtract
{
  local stringlistsubtractk
  local stringlistsubtractarg
  stringlistsubtractarg="for stringlistsubtractk in \$$2; do stringlistremove $1 \$stringlistsubtractk; done"
  eval "$stringlistsubtractarg"
}

# Trim leading and trailing spaces from a variable.
# 1: variable name.
function stringtrim
{
  local stringtrimarg="$1=\`echo \$$1 | sed -e 's/^ *//' -e 's/ *$//'\`"
  eval "$stringtrimarg"
}

# 1: string
# 2: target
# 3: variable name with result "1" or "" for true or false respectivley. 
# Example with metacharacter, search string i for string with /
# stringcontainsstring i "\/" res
function stringcontainsstring
{
  local stringcontainsstringstr;
  local stringcontainsstringarg="stringcontainsstringstr=\$$1"
  eval "$stringcontainsstringarg"

  local stringcontainsstringe3
  local stringcontainsstringresult="1"
  stringcontainsstringarg="stringcontainsstringe3=\`echo \$stringcontainsstringstr | sed -n '/$2/p'\`"
  eval "$stringcontainsstringarg"
  if [ "$stringcontainsstringe3" == "" ]; then stringcontainsstringresult=""; fi

  stringcontainsstringarg="$3=$stringcontainsstringresult"
  eval "$stringcontainsstringarg"
}

# 1: file
# 2: name of string to write to.
function filetostring2()
{
  local filetostring2i
  filetostring2val="";
  for filetostring2i in `cat $1`; do
    filetostring2val=$filetostring2val" "$filetostring2i;
  done;
  local filetostring2arg
  filetostring2arg="$2=\$filetostring2val"
  eval "$filetostring2arg"
}


# Command line processing. 
# Assign the variables and call with the command line.
# Example
# In the bash file t01.sh 
#   commandlinetoken=print
#   commandinecommand="echo cat passed in"
#   commandline $@
# Call the function
#   bash t01.sh print  
export commandlinetoken
export commandlinecommand
function commandline
{
  local commandlinek=1
  local commandlinekmax=$#
  while (( commandlinek <= commandlinekmax ))
  do
    if [ "$1" == "$commandlinetoken" ]; then 
      eval "$commandlinecommand"
      return
    fi
    (( commandlinek++ ))
    shift
  done
}  


export projdirectory=${base}/p1/misc/proj;
source ${projdirectory}/ide/ide.sh

source ${base}/p1/comsci/OpenSSL/d01/shellcrypt.sh

function ce 
{
  local loc=${base}/ce;

  if [ $# = 1 ]; then
    loc=$loc/$1;
  fi;

  pushd $loc;
}

function myxterm
{
  xterm -bg black -bd black -fg green &
}


# Convert a string to an array.
# Assign the string to global variable $stringtoarraystring.
# Call strringtoarray function.
# Get the array from $stringtoarrayarray variable. 
# e.g.
#  stringtoarraystring="a ba c"
#  stringtoarray 
#  echo "${stringtoarrayarray[2]}"
export stringtoarraystring
export stringtoarrayarray
function stringtoarray
{

  unset stringtoarrayarray

  local xi
  local ki=0
  for xi in $stringtoarraystring
  do
    echo "$xi"
    stringtoarrayarray[$ki]=$xi
    (( ki++ ))
  done 
}

#/bin/sh

#  e.g. diskusage G, diskusage M, diskusage K, diskusage B
# 1:  <G,M,K,B>
function diskusage
{
  du -h > /tmp/disk.txt
  awk '$1~/'$1'/ {print $0}' /tmp/disk.txt
}

# Look at the to n processes at that instant in time.
# e.g.  $ pslook 5
function macpslook
{
  ps Au | grep -v "%CPU" | sort -r -k 3 | head -n $1 | awk '{print $3, $11}';
}


function opensslE
{
  openssl rsautl -encrypt -in $1 -pubin -inkey ~/.openssl/key-pub.txt -out $1.enc
}

function opensslD
{
  openssl rsautl -decrypt -inkey ~/.openssl/key.txt -in $1.enc -out $1
}

function lsdot
{
  ls -d .[a-z,A-Z]*
}

# gvim on Mac had issues accepting command line arguments.
# Recommended to use bash
# For example $ gvimmac -S Session.vim &
function gvimmac
{
  /Applications/Vim.app/Contents/MacOS/Vim -g $*;
}

# gvim on Mac - support loading and saving a session.
# To load a session, go to a directory with Session.vim
# $ gvimmacs &
# To save the session from gvim :mksession! Session.vim
function gvimmacs
{
  /Applications/Vim.app/Contents/MacOS/Vim -g -S Session.vim $*;
  #/Applications/Vim.app/Contents/MacOS/Vim -g -S Session.vim $*;
}

function myip
{
  /sbin/ifconfig | grep inet
}

# Mount my sshfs
function sshfsmac
{
  mount_sshfs zero@10.1.1.7 ~/p3;
}

# Unmount file system by sshfsmac
function sshfsmac~
{
  umount ~/p3
}

# Mount my sshfs in Linux
function sshfslinux
{
  # e.g. zero@10.1.1.7
  local user=$1
  sshfs ${user}: ~/p3
}
# Unmount file system by sshfslinux
function sshfslinux~
{
  fusermount -u ~/p3
}

function sshfsmac2
{
  mount_sshfs zero@10.1.1.7:/media/INFINITY ~/p4;
}

# Phone
function sshfsmac3
{
  # user@
  mount_sshfs root@192.168.1.121 ~/p5;
}
  
# 1: latex file name without .tex extension
# e.g. file a001.tex called with $ latexpdf a001
function latexpdf
{
  latex $1
  dvips -o $1.ps $1.dvi
  ps2pdf $1.ps 
}


source ${base}/p1/comsci/OpenSSL/d01/shellcrypt.sh;
source ${base}/script/validatehtml.sh;

function g++mac 
{
  g++ $1 -framework GLUT -framework OpenGL
}

function findname
{
  find . -name "*$1*";
}

function checkhtml
{
  tidy -errors -q -f /tmp/error_file.txt  $1; cat /tmp/error_file.txt
}

# Get the first few lines from validate
function validate2
{
  clear; validate $1 | head
}




