#!/usr/bin/env python3

import os
import os.path
import shutil
import subprocess
import sys

#Version  02/17/2003
#Synopsis: retree.csh infile rooted outfile

# Run retree as a command

""" ensure that there are enough command line arguments to parse """
if len(sys.argv) < 4:
    print("Missing parameter");
    print("");
    print("Usage: retree.py  STARTLINE  INFILE  OUTFILE");
    exit();

#Convert arguments to variables
INFILE      = sys.argv[1]
ROOTED      = sys.argv[2]
OUTFILE     = sys.argv[3]

# Remember where we started
STARTDIR = os.getcwd()

# Make a temporary directory to run the program in 
TEMPDIR = 'RETREE.' + os.getpid()
os.mkdir(TEMPDIR)
shutil.copyfile(INFILE, os.path.join(TEMPDIR, 'intree'))
os.chdir(TEMPDIR)

#-------- Run retree, sending terminal output to /dev/null -----------
# high nice level is set just in case we do get an infinite loop
# Remember, retree reads a file called intree, and writes to outtree
os.nice(10)
p = subprocess.Popen(['retree'], stdin=subprocess.PIPE)

#----------------- generate keyboard input to send to program -----

#accept default settings proceed to next menu
p.stdin.write('y\n')

# Tell retree to write tree to outfile
p.stdin.write('w\n')

# Should tree be rooted?
if (ROOTED == 'y'):
   p.stdin.write('r\n')
else:
   p.stdin.write('u\n')

#quit the program
p.stdin.write('q\n')
p.stdin.close()
p.wait()

os.nice(0)
shutil.move('outtree', os.path.join(STARTDIR, OUTFILE))
os.chdir(STARTDIR)
shutil.rmtree(TEMPDIR)







