#! /bin/sh

# Conversion of an absolute path to a relative path.

# Copyright (c) 2008 by Marc Feeley, All Rights Reserved.

TARGET_PATH=`echo "$1" | sed -e 's#\\\\#/#g' -e 's#//*#/#g' -e 's#/$##' -e 's#\([/]\{0,1\}\)\(.*\)#\2/#' -e 's#^/$##'`
ORIG_DIR=`echo "$2" | sed -e 's#\\\\#/#g' -e 's#//*#/#g' -e 's#/$##' -e 's#\([/]\{0,1\}\)\(.*\)#\2/#' -e 's#^/$##'`
ENABLE_MV="$3"

while test "$TARGET_PATH" != "" -a "$ORIG_DIR" != ""; do
  TP_CAR=`echo "$TARGET_PATH" | sed -e 's#\([^/]*[/]\)\(.*\)#\1#'`
  TP_CDR=`echo "$TARGET_PATH" | sed -e 's#\([^/]*[/]\)\(.*\)#\2#'`
  OD_CAR=`echo "$ORIG_DIR" | sed -e 's#\([^/]*[/]\)\(.*\)#\1#'`
  OD_CDR=`echo "$ORIG_DIR" | sed -e 's#\([^/]*[/]\)\(.*\)#\2#'`
  if test "$TP_CAR" = "$OD_CAR"; then
    TARGET_PATH="$TP_CDR"
    ORIG_DIR="$OD_CDR"
  else
    break
  fi
done

REL_PATH=`echo "$ORIG_DIR" | sed -e 's#[^/]*[/]#../#g'`"$TARGET_PATH"

if test "$ENABLE_MV" = "yes"; then
  echo "$REL_PATH" | sed -e 's#^#/#' -e 's#^\(.*/\)\([^/][^/]*\)/\([^/][^/]*\)/$#\1current/\3/#' -e 's#^/##'
else
  echo "$REL_PATH"
fi
