#!/usr/bin/env python
# slicesforsample - assess whether number of line for sample ali is enough
#
# $Id: slicesforsample,v 937343107256 2023/02/19 22:44:16 mast $
#

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


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

#
# 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)


if len(sys.argv) != 6:
   prnstr(prefix + 'Need 5 params: current lines, Y offset, ali Y size, '+\
          'raw Y size, and tilt com file name')
   sys.exit(1)

try:
   curLines = int(sys.argv[1])
   yOffset = int(sys.argv[2])
   fullY = int(sys.argv[3])
   ysize = int(sys.argv[4])
   tiltCom = sys.argv[5]
except ValueError:
   prnstr(prefix + 'Error converting one of the parameters to integer')
   sys.exit(1)

tiltLines = readTextFile(tiltCom, returnOnErr = True)
if isinstance(tiltLines, str):
   prnstr('0')
   sys.exit(0)

xtilt = optionValue(tiltLines, 'XAXISTILT', FLOAT_VALUE, numVal = 1)
thickness = optionValue(tiltLines, 'THICKNESS', INT_VALUE, numVal = 1)
if xtilt == None or thickness == None:
   prnstr('0')
   sys.exit(0)

# The slices needed have two components: first the number of slices required for the
# reconstruction, based on sin * thickness, then the change in the center offset in the
# aligned stack needed to reconstruct tilted slices at that offset, based on offset/cos
# minus the aligned stack offset.  This is doubled to make the sample extend that far
# out but still be centered on the original offset
radt = math.fabs(math.radians(xtilt))
newLines = 2 * (int(round(math.sin(radt) * thickness + \
                          2 * yOffset * (1. / math.cos(radt) - 1.)) + 4) // 2)
maxLines = 2 * (fullY // 2 - yOffset - 8)
newLines = min(newLines, maxLines)
if newLines > curLines:
   outLine = str(newLines)

   # Copy the computation of blend Y limits from copytomocoms.  Yes the resulting
   # possibly out of range values do work with a montage being rotated by 90 degrees
   offarr = (0, yOffset, -yOffset)
   halfsampali = newLines // 2
   for ind in range(3):
      offind = offarr[ind]
      ymin = ysize // 2 + offind - halfsampali
      ymax = ysize // 2 + offind + halfsampali
      outLine += fmtstr(' {} {}', ymin, ymax)
   
   prnstr(outLine)
else:
   prnstr('0')

sys.exit(0)
          

