#!/bin/bash

# This script is intended to be run within a screen session



# Find the PWD of the window process, from which this script is called
function getSameDir () {

   local WINNB pid 

   # find the current window process pid
   while read pid; do

      [[ $$ == $pid ]] && continue
      WINNB=$(tr '\000' '\n' </proc/${pid}/environ | \
	  sed -n '/^WINDOW=/s///p' 2>/dev/null)

      [[ -z "${WINNB}" ]] && continue
      [[ ${WINDOW} -eq ${WINNB} ]] && break

   done < <(ps --ppid ${PPID} --noheader -o %p | sed 's/^[[:space:]]*//')


   # check if we really found something, or if 
   # we've just reached the end of the loop
   [[ ${WINDOW} -eq ${WINNB} ]] || exit 2

   echo $(readlink /proc/${pid}/cwd)


#     local winnb

#     winnb=$(cat $HOME/.screen/win.$WINDOW.pwd)

#     if [[ -n $winnb ]]; then
# 	echo $winnb
#     else
# 	echo $HOME
#     fi
}



# Open(in the background?) a new window in the same
# dir as the (local) process on the current window
function newWindow () {

   local dir="$(getSameDir)"

   # screen -X eval screen "stuff 'cd \"$DIR\"^M^L'" other
   screen -X eval screen "stuff 'cd \"$dir\" '"
}


      

# if WINDOW is not set, no need to go further,
# we're not in a screen session
[[  -z ${WINDOW} ]] && exit 1



#case "${1}" in
case "nw" in

   nw)
      newWindow
      ;;

esac
