#
#     Copyright (C) 2014 David Waterman
#
#     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$
# ======================================================================
# blend.tcl --
#
# CCP4Interface
#
# =======================================================================

#---------------------------------------------------------------------
proc blend_setup { typedefVar arrayname } {
#---------------------------------------------------------------------
  upvar #0  $typedefVar typedef
  upvar #0 $arrayname array

  global tcl_platform

  # A trick to put Rscript.exe in the path on Windows if it isn't already
  if { ([regexp -nocase windows $tcl_platform(os)]) && ([FindExecutable "Rscript.exe" ] == "") } {
    if { ![catch { exec cmd.exe /c ftype RWorkspace } result] } {
      set path_to_r [file nativename [file dirname [lindex [split $result \"] 1] ] ]
      set ::env(PATH) "$path_to_r;$::env(PATH)"
    }
  }

  # Check that R is installed on this system
  if { ( [FindExecutable "Rscript" ] == "" ) && ( [FindExecutable "Rscript.exe" ] == "" ) } {
         WarningMessage "Dependency Error: BLEND requires R. Please go to http://cran.r-project.org/"
         return 0
  }

  DefineMenu _blend_mode [ list "Analysis" \
                "Synthesis" \
                "Combination" ] \
       [ list ANALYSIS SYNTHESIS COMBINATION ]

  DefineMenu _blend_anomalous_flag [ list "ON" \
                "OFF" ]



  return 1
}

#--------------------------------------------------------------
proc blend_browse { arrayname path_type} {
#--------------------------------------------------------------
# Use the file browser to select a directory of datasets

  upvar #0 $arrayname array

  if { [SelectFile filename -directory] } {

    # Update the parameters in the window
    if { $path_type == "HKL_SOURCE" } {
       set array(HKL_SOURCE) $filename
    }

    if { $path_type == "PREV_RUNDIR" } {
       # The browser can return either a filename or a directory
       # name - make sure we get the leading directory in the
       # former case
       if { [file isdirectory $filename] } {
         set dirname $filename
       } else {
         set dirname [file dirname $filename]
       }
       set array(PREV_RUNDIR) $dirname
    }
  }
  return
}

#--------------------------------------------------------------
proc blend_view { arrayname } {
#--------------------------------------------------------------
# Display the the list of input files in a text viewer

   upvar #0 $arrayname array

   if { [file isfile $array(HKL_SOURCE)] } {
     DisplayTextFile $array(HKL_SOURCE)
   }
}

#--------------------------------------------------------------
proc blend_run { arrayname } {
#--------------------------------------------------------------

  upvar #0 $arrayname array

  # Why is it the Titlecase version and not ALLCAPS?
  if { $array(BLEND_MODE) == "Analysis" } {
    if { $array(HKL_SOURCE) == "none" } {
           WarningMessage "Input Error: You must choose a source of integrated datasets as input!"
          return 0
    }
  }

  if { $array(BLEND_MODE) == "Synthesis" } {
    if { $array(PREV_RUNDIR) == "none" } {
           WarningMessage "Input Error: You must supply the path to a previous run of Blend!"
          return 0
    }
  }

  if { $array(BLEND_MODE) == "Combination" } {
    if { $array(PREV_RUNDIR) == "none" } {
           WarningMessage "Input Error: You must supply the path to a previous run of Blend!"
          return 0
    }
  }
  return 1
}

#---------------------------------------------------------------------
proc CombDatasets { arrayname counter } {
#---------------------------------------------------------------------

  CreateLine line \
    message "Enter the identifying number of a dataset to include" \
    label "Include dataset number" \
    widget INC_DATASETS \
    label "in combination"
}

#---------------------------------------------------------------------
proc CombClusters { arrayname counter } {
#---------------------------------------------------------------------

  CreateLine line \
    message "Enter the identifying number of a cluster to include" \
    label "Include cluster number" \
    widget INC_CLUSTERS \
    label "in combination"
}

#---------------------------------------------------------------------
proc ExclDatasets { arrayname counter } {
#---------------------------------------------------------------------

  CreateLine line \
    message "Enter the identifying number of a dataset to exclude" \
    label "Exclude dataset number" \
    widget EXC_DATASETS \
    label "from combination"
}

#---------------------------------------------------------------------
proc DefRuns { arrayname counter } {
#---------------------------------------------------------------------

  CreateLine line \
    message "Define Runs by Batch ranges" \
    label "Define Run" \
    widget RUNS \
    label "from Batch" \
    widget RUN_BATCH_LO \
    label "to Batch" \
    widget RUN_BATCH_HI \
}

# procedure to draw task window
#---------------------------------------------------------------------
proc blend_task_window { arrayname } {
#---------------------------------------------------------------------

  global configure
  upvar #0 $arrayname array

  if { [CreateTaskWindow $arrayname  \
        "Run BLEND for multiple dataset analysis/combination" "BLEND" \
        [ list "Options" \
        ] ] == 0 } return

  SetProgramHelpFile "blend"

  set array(INITIALISED) 0

#=PROTOCOL==============================================================

  OpenFolder protocol

  CreateTitleLine line TITLE

#=FILES=================================================================

  OpenFolder file

  CreateLine line \
      message "Select the mode for BLEND to run" \
      label "Program Mode:" \
      widget BLEND_MODE

#CreateOutputFileLine line \
#      "Enter output PDB file name (XYZOUT)" \
#       "PDB out" \
#       XYZOUT DIR_XYZOUT

#=Options for analysis mode only========================================

  OpenSubFrame frame \
      -toggle_display BLEND_MODE open [list ANALYSIS]

  CreateLine line \
  message "Dataset source" \
        label "Directory or file list of integrated datasets" \
  widget HKL_SOURCE -oblig \
    -width 50

  set browse [button $line.browse -text "Browse" \
    -command "blend_browse $arrayname HKL_SOURCE"]
  $browse configure -font $configure(FONT_SMALL)

  set view [button $line.view -text "View" \
    -command "blend_view $arrayname"]
  $view configure -font $configure(FONT_SMALL)

  pack $browse $view -after $line.e2 -side left

  CloseSubFrame

#=Options for synthesis mode only========================================

  OpenSubFrame frame \
      -toggle_display BLEND_MODE open [list SYNTHESIS]

  CreateLine line \
  message "Previous run directory" \
        label "Path to an earlier Blend run directory" \
  widget PREV_RUNDIR -oblig \
    -width 50

  set browse [button $line.browse -text "Browse" \
    -command "blend_browse $arrayname PREV_RUNDIR"]
  $browse configure -font $configure(FONT_SMALL)
  pack $browse -after $line.e2 -side left

  CreateLine line \
    label "Enter heights from the dendrogram to define merging groups" \

  CreateLine line \
  message "Enter a height taken from the dendrogram" \
    label "Upper height cutoff" \
    widget DEND_HEIGHT1 \
    label "Lower height cutoff" \
    widget DEND_HEIGHT2 \
    label "(optional)"

  CloseSubFrame

#=Options for combination mode only======================================

  OpenSubFrame frame \
      -toggle_display BLEND_MODE open [list COMBINATION]

  CreateLine line \
  message "Previous run directory" \
        label "Path to an earlier Blend run directory" \
  widget PREV_RUNDIR -oblig \
    -width 50

  set browse [button $line.browse -text "Browse" \
    -command "blend_browse $arrayname PREV_RUNDIR"]
  $browse configure -font $configure(FONT_SMALL)
  pack $browse -after $line.e2 -side left

  CreateLine line \
    message "Enter identifying numbers of datasets you want to combine" \
    label "Specify datasets to include in combination" \
    -italic

  CreateExtendingFrame N_INC_DATASETS CombDatasets \
        "Add an integer to include that dataset in combination" \
        "Add item"\
        [list INC_DATASETS ]

  CreateLine line \
    message "Enter identifying numbers of clusters you want to combine" \
    label "Specify clusters to include in combination" \
    -italic

  CreateExtendingFrame N_INC_CLUSTERS CombClusters \
        "Add an integer to include that cluster in combination" \
        "Add item"\
        [list INC_CLUSTERS ]

  CreateLine line \
    message "Enter identifying numbers of datasets you want to exclude" \
    label "Specify datasets to exclude from combination" \
    -italic

  CreateExtendingFrame N_EXC_DATASETS ExclDatasets \
        "Add an integer to exclude that dataset from combination" \
        "Add item"\
        [list EXC_DATASETS ]

  CloseSubFrame

#=Message to report mode of operation==================================

  OpenSubFrame frame \
      -toggle_display BLEND_MODE open [list ANALYSIS]

  CreateLine line \
    label "Run blend in analysis mode" \
    -italic

  CloseSubFrame

  OpenSubFrame frame \
      -toggle_display BLEND_MODE open [list SYNTHESIS]

  CreateLine line \
    label "Run blend in synthesis mode" \
    -italic

  CloseSubFrame

  OpenSubFrame frame \
      -toggle_display BLEND_MODE open [list COMBINATION]

  CreateLine line \
    label "Run blend in combination mode" \
    -italic

  CloseSubFrame

#=Folder to select special options==================================

  OpenFolder 1 closed

  OpenSubFrame frame \
      -toggle_display BLEND_MODE open [list ANALYSIS]

  CreateLine line \
      message "Set radfrac" \
      widget SET_RADFRAC -width 4 \
      label "Tolerated fraction of damaged average intensity" \
      widget RADFRAC

  CreateLine line \
      message "Set I/sigI" \
      widget SET_ISIGI -width 4 \
      label "I/sigI resolution cut-off" \
      widget ISIGI

  CreateLine line \
      message "Select to use I descriptors" \
      widget USE_IDESC -width 4 \
      label "Use intensity averages rather than cell parameters as descriptors"
      #widget CPARWT

  CreateLine line \
      message "Set Laue group" \
      widget SET_LAUEGROUP -width 4 \
      label "Choose the Laue group " \
      widget LAUEGROUP

  CloseSubFrame

  OpenSubFrame frame \
      -toggle_display BLEND_MODE open [list SYNTHESIS COMBINATION]

  CreateLine line \
    label "Control execution of Pointless" \

  CreateLine line \
      message "Set dataref" \
      widget SET_DATAREF -width 4 \
      label "Input index of a reference dataset in case of alternative indexing" \
      widget DATAREF

  CreateLine line \
      message "Set space group" \
      widget SET_SPACEGROUP -width 4 \
      label "Impose" \
      widget SPACEGROUP \
      label "as final space group"

  CreateLine line \
      message "Set tolerance" \
      widget SET_TOLERANCE -width 4 \
      label "Tolerated unit cell difference (degrees)" \
      widget TOLERANCE

  CreateLine line \
    label "Control execution of Aimless" \

  CreateLine line \
      message "Set resolution" \
      widget SET_RESOLUTION -width 4 \
      label "Set resolution limits. Low:" \
      widget LO_RES  \
      label "Set resolution limits. High:" \
      widget HI_RES  \

  CreateLine line \
      message "Set ANOMALOUS ON/OFF" \
      widget SET_ANOMALOUS -width 4 \
      label "Set value of ANOMALOUS keyword to" \
      widget ANOMALOUS

  CreateLine line \
      message "Set SCALES" \
      widget SET_SCALES -width 4 \
      label "Set value of SCALES keyword to" \
      widget SCALES

  CreateLine line \
      message "Set EXCLUDE BATCH" \
      widget SET_EXC_BATCH -width 4 \
      label "Set value of EXCLUDE BATCH keyword to" \
      widget EXC_BATCH

  CreateLine line \
      message "Set SDCORR" \
      widget SET_SDCORR -width 4 \
      label "Set value of SDCORRECTION keyword to" \
      widget SDCORR

  CreateLine line \
    label "Define Runs by Batch ranges" \
    -italic

  CreateExtendingFrame N_RUNS DefRuns \
        "Enter definitions for Runs" \
        "Add Run"\
        [list RUNS RUN_BATCH_LO RUN_BATCH_HI ]

  CloseSubFrame
}
