#!/usr/bin/python
# create an umbrella for 3 subtrees

from MDSplus import *

import sys
import subprocess
import os

if len(sys.argv) != 2:
	sys.exit("usage make-acq196-supertree NNN")

NNN=sys.argv[1]

SUPERT = 'acq196_'+ NNN
SUBTREE = 'a'+ NNN + '_'

def makeTags(stree, field, ch1, nch):
    tree = Tree(stree, -1, "edit")
    for ch in range(ch1, ch1+nch):
        tag = 'CH%02d' % ch
        leaf = '%s.CH%02d' % (field, ch - ch1 + 1)
        print "%s:%s -> \\%s" % (stree, leaf, tag)
        try:
            tree.getNode(leaf).addTag(tag)
        except Exception as detail:
            print "exception:", detail

def makeNewShotScript(trees):
	NEWSHOT = "%s/bin/%s_newshot" % (os.getenv('HOME'), trees[0])
	f = open(NEWSHOT, "w")
	cmd = ''	
	for t in trees:
		cmd += t+' '
	f.write("#!/bin/bash\n")
	f.write("for tree in " + cmd + "\n")
	f.write("do\n")
	f.write("	newshot $tree\n")
	f.write("	echo Tree:$tree shot:$(getshot $tree)\n")
	f.write("done\n")
	f.close()
	subprocess.call(['chmod', 'a+rx', NEWSHOT])

def createShot(trees):
	for t in trees:
		subprocess.call(['setshot', t, '0'])

def makeTree(supert, subtree):
	trees = list()
	trees.append(supert)

	print "NEW %s" % (supert)
	tt = Tree(supert, -1, 'NEW')

	for st in [1,2,3]:
		stree = '%s%d' % (subtree, st)
		trees.append(stree)
		blk = st -1
		field = 'AI%02d%02d' % (blk*32+1, blk*32+32)
		
		subprocess.call(['make_acqtree', stree, '%s,32' % (field)])
		print "addNode %s" % (stree.upper())
		tt.addNode('.%s' % (stree.upper()), 'SUBTREE')
		makeTags(stree, field, blk*32+1, 32)

	tt.write()
	createShot(trees)
	makeNewShotScript(trees)

SUPERT_KEY = '%s_path' % SUPERT
SUPERT_PATH = os.getenv(SUPERT_KEY)
if not SUPERT_PATH:
	print "path not defined %s" % SUPERT_KEY
	exit(1)

subprocess.call(['mkdir', '-p', SUPERT_PATH])
os.chdir(SUPERT_PATH)
makeTree(SUPERT, SUBTREE)
