#!/bin/zsh -f

#################################################################################
#                                                                               #
#   getpdb -- function to download a pdb file and display it in the default     #
#             pdb display program (chosen with GetInfo command for filetype)    #
#                                                                               #
#################################################################################


if [[ $# > 1 || $1 == --help || $1 == -h || $1 == -help ]];then
    print "Usage:  getpdb [PDBCODE] "
    print "example:  getpdb 2goz "
    return 2
fi

# If one command line argument is given, assume it is the PDB code.
# A reality check could be added here.

if [[ -n $1 ]];then
    PDBCODE=$1
fi

# Use GUI querry to obtain PDB code if none is give on command line.

if [[ -z $1 ]]; then

  function GetPDBcode {
    osascript << eof-1
        tell app "Finder"
            activate
            set prompt to "Enter PDB code (eg: 1MME): "
            set dialogResult to display dialog prompt default answer ""
        end tell

eof-1
}


PDBCODE=$(GetPDBcode | cut -d: -f2 | cut -d, -f1)
 
fi

# Find a directory in which to download the pdb file. Store the previous
# selection in ~/.getpdbrc and use that as the default.  If ~/.getpdbrc 
# doesn't exist, then querry the user for what directory to use.

  #if [[ -f  ~/.getpdbrc ]];then
  #    OLD_PDBDIRECTORY=$(command cat ~/.getpdbrc | head -n 1 )
  #fi

  if [[ -z $OLD_PDBDIRECTORY ]];then
      OLD_PDBDIRECTORY="$PWD"
  fi

  function GetPDBdir {
    osascript << eof-1
        tell app "Finder"
            activate
            set prompt to "Download PDB into this directory: "
            set dialogResult to display dialog prompt default answer "$OLD_PDBDIRECTORY"
        end tell

eof-1
}

PDBDIRECTORY=$(GetPDBdir | cut -d: -f2 | cut -d, -f1)



# Download into /tmp, rename the pdb file to the standard, and
# then move it to the pre-selected pdb directory, and open it into
# the default pdb viewer.
    
cd /tmp

command wget "http://bip.weizmann.ac.il/oca-bin/save-pdb?id=$PDBCODE"

if [[ -s /tmp/save-pdb?id=$PDBCODE ]];then

    if [[ -z $PDBDIRECTORY ]];then
        PDBDIRECTORY='~/pdb'
    fi
    
    if [[ -n $PDBDIRECTORY && ! -d $PDBDIRECTORY ]];then
        mkdir -p "$PDBDIRECTORY"
    fi
    
    cd "$PDBDIRECTORY"; pwd

    echo "$PDBDIRECTORY" >| ~/.getpdbrc

    mv /tmp/save-pdb?id=$PDBCODE  $PDBCODE.pdb

    print "Saving file as $PDBCODE.pdb in directory $PDBDIRECTORY"

    open $PDBCODE.pdb

else

    print "File download failed. Check validity of PDB assession code."
    print ""
    command rm save-pdb?id=$PDBCODE
    return 1
    
fi

