#!/bin/sh

find_target(){
  myexe="$1"
  dir=`dirname $myexe`

  target=`ls -l $myexe | awk '{loc=match($0,"->");target=substr($0,loc+3);print target}'`
  target_strip_slash=`echo $target | sed -e 's=^/=='`

  if [ x"$target_strip_slash" = x"$target" ]; then
  target="$dir/$target"
  fi
  
  if [ -h "$target" ]; then
    echo `find_target "$target" "$dir"`
  else
    echo $target  
  fi
}

if [ -h "$0" ]; then
  target=`find_target "$0"`
else
  target="$0"
fi

mydir=`dirname $target`

mydir_strip_dot=`echo $mydir | sed -e 's/^\.//'`
mydir_strip_dotdot=`echo $mydir | sed -e 's/^\.\.//'`

MGROOT="$mydir/.."

if [ x"$mydir" = x"." ]; then
  MGROOT="$PWD/.."
fi

if [ x"$mydir" != x"$mydir_strip_dot" ]; then
  MGROOT="$PWD/$mydir/.."
fi

if [ x"$mydir" != x"$mydir_strip_dotdot" ]; then
  MGROOT="$PWD/$mydir/.."
fi

if [ "${MGROOT#/}" = "${MGROOT}" ]; then
  #echo "This is a relative path, so let us make it absolute."
  MGROOT="`pwd`/$MGROOT"
fi

echo $MGROOT

PATH="$MGROOT/pythondist/bin/":$PATH "$MGROOT/pythondist/lib/python2.7/site-packages/ccp4mg/bin/ccp4mg" $*
