#
#     Copyright (C) 1999-2004  Liz Potterton, Peter Briggs
#
#     This code is distributed under the terms and conditions of the
#     CCP4 Program Suite Licence Agreement as a CCP4 Library.
#     A copy of the CCP4 licence can be obtained by writing to the
#     CCP4 Secretary, Daresbury Laboratory, Warrington WA4 4AD, UK.
#
#CCP4i_cvs_Id $Id$
#=========================================================================
#
# refmac.script
#
#=========================================================================

# Source pdb_utils for harvest handling & move to project directory 
# if we are going to dump harvest file to current directory 
  source [SearchPath TOP utils pdb_utils.tcl ] 
  if { [StringSame $HARVEST_MODE  CURRENTDIR ] } { ChangeDirectory [GetDefaultDirPath] } 

# Source the utils/maps_utils.tcl script for map drawing

  if { $IF_MAPOUT } {
    source [SearchPath TOP utils map_utils.tcl] }


#---------------------------------------------------------------------
# Prosmart script
#---------------------------------------------------------------------

  if { $IFPROSMART && ![regexp INPUT $PROSMART_MODE ] } {

# set output directory
    set prosmart_output_dir [ FileJoin [GetDefaultDirPath] $job_params(JOB_ID)_prosmart ]
    AddOutputDir $prosmart_output_dir
    set cmd "[BinPath prosmart] -p1 \"$XYZIN\" -o \"$prosmart_output_dir\""

    if { $IFEXTREST_USEMAIN } {
       append cmd " -main"
    } else {
       append cmd " -side"
    }
    if { $USE_PROSMART_KEYFILE } {
       append cmd " -f $PROSMART_KEYFILE"
    }
    
    if [regexp DNARNA $PROSMART_MODE ] {
       append cmd " -dna_rna"
    }

    if { [regexp EXTERNAL $PROSMART_MODE ] || [regexp DNARNA $PROSMART_MODE ] } {
       # using prosmart for external restraints to reference structure
       append cmd " -p2 \"$EXT_XYZIN\""
       set restraint_file [ FileJoin $prosmart_output_dir Output_Files \
                            Restraints [FileRootName $XYZIN].txt ]
       WriteToLog "\n *** Starting Prosmart to determine restraints to external structure *** \n  Using command: $cmd \n  Writing results to directory $prosmart_output_dir \n"
    } elseif [regexp HBOND $PROSMART_MODE ] {
            # using prosmart for h-bond restraints
            append cmd " -h"
            if { !$PROSMART_HBOND } {
                if { $PROSMART_HBONDHELIX3 } {
                    append cmd " -3_10"
                }
                if { $PROSMART_HBONDHELIX4 } {
                    append cmd " -alpha"
                }
                if { $PROSMART_HBONDHELIX5 } {
                    append cmd " -pi"
                }
                if { $PROSMART_HBONDSHEET } {
                    append cmd " -h_sheet"
                }
            }
            
            if { !$PROSMART_HBOND && $PROSMART_HBONDSHEET && !$PROSMART_HBONDHELIX3 && !$PROSMART_HBONDHELIX4 && !$PROSMART_HBONDHELIX5 } {
                set restraint_file [ FileJoin $prosmart_output_dir Output_Files \
                                Restraints LIB_[FileRootName $XYZIN].txt ]
            } else {
                set restraint_file [ FileJoin $prosmart_output_dir Output_Files \
                                Restraints [FileRootName $XYZIN].txt ]
            }
            WriteToLog "\n *** Starting Prosmart to determine h-bond restraints *** \n  Using command: $cmd \n  Writing results to directory $prosmart_output_dir \n"
    } else {
       # using prosmart for secondary structure restraints
       if { $PROSMART_HELIX } {
         append cmd " -helix"
       }
       if { $PROSMART_STRAND } {
         append cmd " -strand"
       }
       set restraint_file [ FileJoin $prosmart_output_dir Output_Files \
                            Restraints LIB_[FileRootName $XYZIN].txt ]
       WriteToLog "\n *** Starting Prosmart to determine secondary structure restraints *** \n  Using command: $cmd \n  Writing results to directory $prosmart_output_dir \n"
    }

    set status [Execute $cmd "" program_status report ]

    if { ![file exists $restraint_file] } {
      WriteToLog "Restraint file not generated by Prosmart - check Prosmart logfile"
      TerminateScript 0 -report "Prosmart failed to generate a file of restraints"
    }

    WriteToLog "\n *** Prosmart finished *** \n  Copying file of restraints $restraint_file to $RESTRAINTFILE \n"
    CopyFile $restraint_file $RESTRAINTFILE
  }

#---------------------------------------------------------------------
# Libg script
#---------------------------------------------------------------------

  if { $IF_LIBG } {

    # set output directory
    set libg_output_dir [ FileJoin [GetDefaultDirPath] $job_params(JOB_ID)_libg ]
    set cmd "[BinPath libg] -o \"$LIBG_RESTRAINTFILE\" -p \"$XYZIN\"" 

    if { $USE_LIBG_DICTFILE } {
       append cmd " -d $LIBG_DICTFILE"
    }

    if [regexp MANULY $LIBG_MODE ] {
       # using libg in user's defined mode
       append cmd " -u \"$USE_LIBG_KEYFILE\""
    }

    #CreateComScript libg libg_script
    set status [Execute $cmd "" program_status report ]
  }

#---------------------------------------------------------------------
# Refmac script
#---------------------------------------------------------------------

  if [regexp REVIEW $REFINE_TYPE] {
    foreach param [list MAKE_CHECK MAKE_PEPTIDE MAKE_CISPEPTIDE \
	MAKE_SSBRIDGE MAKE_SYMMETRY MAKE_CHAIN MAKE_NEWLIGAND MAKE_CONNECTIVITY \
	MAKE_LINK MAKE_SUGAR ] {
      eval set $param \$REVIEW_$param
    }
    set MAKE_REVIEW 1
  } else {
    set MAKE_REVIEW 0
    # If not in REVIEW mode then set up a job-specific name
    # for LIBOUT
    set LIBOUT "[SetOutputFileRoot]_lib.cif"
  }

  if { [regexp TLS $REFINE_TYPE ] } {
    set IFTLS 1
    set REFINE_TYPE REST
  } else {
    set IFTLS 0
  }

  if [regexp ANIS $B_REFINEMENT_MODE] {
    set REFINE_ANISO 1
  } else { 
    set REFINE_ANISO 0
  }

  CreateComScript refmac5 refmac_script

#################################################################################
#------------------------------------------------------------------------------
# Run cycles of refmac (coot etc )
#------------------------------------------------------------------------------
#################################################################################

  set CURRENT_PDB $XYZIN
  set CURRENT_MTZ $HKLIN
  set CURRENT_TLS $TLSIN

  if {$EXTERNAL_NCYCLES < 1} { set EXTERNAL_NCYCLES 1 }

  for { set loop 1 } { $loop <= $EXTERNAL_NCYCLES } { incr loop } {

  # Set the output PDB, MTZ and TLS file variables (15/10/09: removed the old option of
  # outputting a temporary file in each loop. This is no longer neccessary. RMK)
  set NEW_PDB $XYZOUT
  set NEW_MTZ $HKLOUT 
  set NEW_TLS $TLSOUT 

  DeleteFile $NEW_PDB
  DeleteFile $NEW_MTZ
  DeleteFile $NEW_TLS

#------------------------------------------------------------------------------
# run refmac
#------------------------------------------------------------------------------

  set cmd "[BinPath refmac5] XYZIN \"$CURRENT_PDB\" XYZOUT \"$NEW_PDB\""
  if { ![StringSame $REFINE_TYPE REVIEW IDEA ] } { 
    append cmd " HKLIN \"$CURRENT_MTZ\" HKLOUT \"$NEW_MTZ\"" }
  if { $MAKE_LIBRARY != "" && [file exists $MAKE_LIBRARY] } {
    append cmd " LIBIN \"$MAKE_LIBRARY\"" 
  }
  if $IFTLS { append cmd " TLSIN \"$CURRENT_TLS\" TLSOUT \"$NEW_TLS\"" }
  if $IFFIXTLS { append cmd " TLSIN \"$CURRENT_TLS\"" }
  if { $loop == 1 && $LIBOUT != "" } { 
# Handle possibility that refmac finds new monomer and exits after creating
# library file
# Is there already a file LIBOUT - find when it was created
    set libout_date 0
    if { [file exists $LIBOUT] } {
      file stat $LIBOUT file_stat
      set libout_date $file_stat(ctime)
    }
    append cmd " LIBOUT \"$LIBOUT\"" 
    set status [Execute $cmd $refmac_script program_status report -noexit]
    if { $status <= 0 || [regexp REVIEW $REFINE_TYPE] } {
       if { $LIBOUT != "" && [file exists $LIBOUT] } {
         file stat $LIBOUT file_stat
         if { $file_stat(ctime) > $libout_date } { 
			AddOutputFile $LIBOUT $DIR_LIBOUT }
       }
       TerminateScript $status -report $report
    }
  } else {
    set status [Execute $cmd $refmac_script program_status report]
  }


#------------------------------------------------------------------------------
# If requested, run findwaters utility from Coot
#------------------------------------------------------------------------------
  if $RUN_COOT_FW {

    set findwaters [BinPath findwaters]
    if { [regexp -nocase windows $::tcl_platform(os)] } { set findwaters  [BinPath findwaters-real.exe] }

    set COOT_PDB_W [GetTmpFileName -ext coot_pdb_$loop ]
    set COOT_PDB1 [GetTmpFileName -ext coot_pdb_$loop ]
    set COOT_PDB2 [GetTmpFileName -ext coot_pdb_$loop ]
    DeleteFile $COOT_PDB_W
    DeleteFile $COOT_PDB1
    DeleteFile $COOT_PDB2

    set cmd "$findwaters --pdbin \"$NEW_PDB\" --hklin \"$NEW_MTZ\" --f $DELFWT --phi $PHDELWT --pdbout \"$COOT_PDB_W\" --sigma $COOT_SIGMA_ADD"
    WriteToLog " *** Starting COOT:findwaters to find new waters *** \n Using command: $cmd"
    set status [Execute $cmd "" program_status report]

    MergePdbFiles $COOT_PDB1 [list $NEW_PDB $COOT_PDB_W]

    set cmd "$findwaters --pdbin \"$COOT_PDB1\" --hklin \"$NEW_MTZ\" --f $FWT --phi $PHWT --pdbout \"$COOT_PDB2\" --chop --sigma $COOT_SIGMA_REMOVE"
    WriteToLog " *** Starting COOT:findwaters to remove poor waters *** \n Using command: $cmd"
    set status [Execute $cmd "" program_status report]

    DeleteFile $COOT_PDB_W
    DeleteFile $COOT_PDB1

    WriteToLog " *** Ending COOT:findwaters ***  "
  }

#-----------------------------------------------------------------------------
# Update files
#-----------------------------------------------------------------------------

  if { $RUN_COOT_FW } {
    set CURRENT_PDB $COOT_PDB2
  } else {
    set CURRENT_PDB $NEW_PDB
  }

  if $IFTLS { set CURRENT_TLS $NEW_TLS }

# end of external loop
  }  

#############################################################################
# termination
#############################################################################

  HandleHarvestFile $HARVEST_MODE $HARVEST_PNAME $HARVEST_DNAME refmac 

# If running Coot then add one final REFMAC cycle

  if { $RUN_COOT_FW } {

  WriteToLog "NEW_PDB: $NEW_PDB"
  set cmd "[BinPath refmac5] XYZIN \"$CURRENT_PDB\" XYZOUT \"$NEW_PDB\" HKLIN \"$CURRENT_MTZ\" HKLOUT \"$NEW_MTZ\""
  if { $MAKE_LIBRARY != "" && [file exists $MAKE_LIBRARY] } {
    append cmd " LIBIN \"$MAKE_LIBRARY\"" }

  if $IFTLS {
    append cmd " TLSIN \"$CURRENT_TLS\" TLSOUT \"$NEW_TLS\"" 
  }
  if $IFFIXTLS { append cmd " TLSIN \"$CURRENT_TLS\"" }

    set status [Execute $cmd $refmac_script program_status report ]
    set CURRENT_PDB $NEW_PDB
    if $IFTLS { set CURRENT_TLS $NEW_TLS }

  }

  WriteToLog "Writing final coordinates (XYZOUT) to $XYZOUT"
  WriteToLog "Writing final phases (HKLOUT) to $HKLOUT"
  if $IFTLS { 
    WriteToLog "Writing final TLS (TLSOUT) to $TLSOUT"
  }


#--------------------------------------------------------------------
# generate maps
#--------------------------------------------------------------------

  if { $IF_MAPOUT  } {

    source  [SearchPath TOP scripts refmac_maps.script ]

  }