#!/usr/bin/env python
# sampletilt - to run tilt for a sample tomogram
#
# $Id: sampletilt,v cf4d3fed2248 2024/04/24 21:44:26 mast $
#

progname = 'sampletilt'
prefix = 'ERROR: ' + progname + ' - '


#### MAIN PROGRAM  ####
#
# load System Libraries
import os, sys

#
# Setup runtime environment
if os.getenv('IMOD_DIR') != None:
   IMOD_DIR = os.environ['IMOD_DIR']
   if sys.platform == 'cygwin' and sys.version_info[0] > 2:
      IMOD_DIR = IMOD_DIR.replace('\\', '/')
      if IMOD_DIR[1] == ':' and IMOD_DIR[2] == '/':
         IMOD_DIR = '/cygdrive/' + IMOD_DIR[0].lower() + IMOD_DIR[2:]
   sys.path.insert(0, os.path.join(IMOD_DIR, 'pylib'))
   from imodpy import *
   addIMODbinIgnoreSIGHUP()
else:
   sys.stdout.write(prefix + " IMOD_DIR is not defined!\n")
   sys.exit(1)

#
# load IMOD Libraries
from pysed import *

numArgs = len(sys.argv) - 1
if numArgs // 2 != 3 and (numArgs + 1) // 2 != 5:
   prnstr(prefix + 'Need 6, 7, 9, or 10 params: slice start & end, ystart, set name, ' +\
          'rec name, com file name, [aliFile] | [orig and new # of lines, # ' +\
          'of slices [aliFile]]')
   sys.exit(1)

slstart = sys.argv[1]
slend = sys.argv[2]
ystart = sys.argv[3]
setname = sys.argv[4]
recname = sys.argv[5]
tiltname = sys.argv[6]
aliName = ''
if numArgs == 7 or numArgs == 10:
   aliName = sys.argv[numArgs]

if numArgs == 9 or numArgs == 10:

   # The 3 new parameters allow us to supercede the starting and ending slice numbers
   # at the beginning, which are still there in case old sampletilt is run 
   try:
      origLines = int(sys.argv[7])
      numLines = int(sys.argv[8])
      numSlices = int(sys.argv[9])
      ystart = int(ystart) - (numLines - origLines) // 2
      slstart = numLines // 2 - numSlices // 2
      slend = slstart + numSlices - 1
   except ValueError:
      prnstr(prefix + 'Error converting number of input lines or output slices to ' + \
             'integer')
      sys.exit(1)

sedcom = ['/^[$#]/d',
          fmtstr("/^SUBSETSTART.*/s//SUBSETSTART 0 {}/", ystart),
          fmtstr("/^OutputFile/s/[ 	]{}.*/ {}/", setname, recname),
          '/^SLICE/d',
          '/^WIDTH/d',
          '/^AdjustOrigin/d',
          fmtstr('/^THICKNESS/a/SLICE {} {} 1/', slstart, slend)]
if aliName:
   sedcom.append(fmtstr("/^InputProjections/s/[ 	].*/ {}/", aliName))

tiltLines = readTextFile(tiltname)
for ind in range(len(tiltLines)):
   tiltLines[ind] = tiltLines[ind].lstrip()
tiltcom = pysed(sedcom, tiltLines, None, True)

try:
   runcmd('tilt -StandardInput', tiltcom, 'stdout')
   if aliName:
      cleanupFiles([aliName])
except ImodpyError:
   if aliName:
      cleanupFiles([aliName])
   exitFromImodError(progname)

sys.exit(0)
