#!/bin/zsh -f

# Get the directory for the new tab or terminal window
    
    if [[ $# == 0 ]]; then
          ThisDirectory=$PWD
    elif [[ $# == 1 && -d "$1" ]]; then
          ThisDirectory="$@"
    else
          print "usage: ntrm [directory]"
          return 1
    fi


if [[  $TERM_PROGRAM == Apple_Terminal ]]; then

    #If we are running Apple's Terminal.app, open a new window in the
    #specified directory, if given, or else in $PWD.
    
    open -a Terminal
    osascript <<-EOF 
       tell app "Terminal" 
          do script "cd \"$ThisDirectory\" "
       end tell
EOF
    return 0
    
    

elif [[ $TERM_PROGRAM == iTerm.app ]];then

    #If we are running iTerm.app, open a new TAB in the
    #specified directory, if given, or else in $PWD.
    
    osascript <<-eof
       tell application "iTerm"
        make new terminal
        tell the last terminal
            activate current session
            launch session "Default Session"
            tell the last session
                write text "cd \"$ThisDirectory\""
            end tell
        end tell
       end tell
eof
    return 0

else
    
    # assume we want xterm

    xterm &
    return 0

fi