
# Make a directory to run in
# This will be a subdir of the current project plus the job id
  set xia2_dir [file join [GetDefaultDirPath] xia2_$job_params(JOB_ID)]
  CreateDir $xia2_dir
  ChangeDirectory $xia2_dir
  AddOutputDir $xia2_dir

# output file will be named [file join $xia2_dir DataFiles \
# $PROJECT_NAME_$XTAL_NAME_free.mtz] - this will be copied to HKLOUT
# at the end...

# Write the input file
  set xinfo xia2_$job_params(JOB_ID).xinfo
  set xin "BEGIN PROJECT $PROJECT_NAME\nBEGIN CRYSTAL $XTAL_NAME\n"

  for {set j 1} {$j <= $N_WAVELENGTHS} {incr j} {
    append xin "BEGIN WAVELENGTH $WAVELENGTH_NAME($j)\n"
    if {"$WAVELENGTH_LAMBDA($j)" != ""} {
      append xin "WAVELENGTH $WAVELENGTH_LAMBDA($j)\n"
    }
    append xin "END WAVELENGTH $WAVELENGTH_NAME($j)\n"
  }

  for {set j 1} {$j <= $N_SWEEPS} {incr j} {
    append xin "BEGIN SWEEP SWEEP$j\n"
    append xin "WAVELENGTH $SWEEP_WAVELENGTH($j)\n"
    append xin "IMAGE $SWEEP_IMAGE($j)\n"
    append xin "DIRECTORY $SWEEP_DIR($j)\n"
    if {"$SWEEP_BEAM_X($j)" != "" && "$SWEEP_BEAM_Y($j)" != ""} {
      append xin "BEAM $SWEEP_BEAM_X($j) $SWEEP_BEAM_Y($j)\n"
    }
    append xin "END SWEEP\n"
  }

  append xin "END PROJECT $PROJECT_NAME\nEND CRYSTAL $XTAL_NAME\n"
  
# Write this content to the named file

  WriteFile $xinfo $xin

# Then launch the job - with command line "xia2 -2d -xinfo $xinfo"

  set cmd "xia2"

  if {$DEBUG} {
    append cmd " -debug"
  }

  if {$THREED} {
    append cmd " -3d"
  } else {
    append cmd " -2d"
  }

  append cmd " -xinfo $xinfo"

  set status [Execute $cmd {} program_status report]

  set XIA2HKLOUT [file join $xia2_dir DataFiles \
    [subst $PROJECT_NAME]_[subst $XTAL_NAME]_free.mtz]

  if {[file exists $XIA2HKLOUT]} {
    file copy $XIA2HKLOUT $HKLOUT
    WriteToLog "Copied final MTZ file to $HKLOUT"
  }

# in here do an ls on the LogFiles directory and record all of these as....
# log files from the job...

  set logfiles [glob -directory [file join $xia2_dir LogFiles] "*.log"]

  foreach file $logfiles { 
    AddOutputFile $file "PROJECT"
  }

