#!/usr/bin/env python

# Copyright 2017 DIANA-HEP
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#     http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import re

from collections import OrderedDict

from arrowed.oam import PrimitiveOAM
from arrowed.oam import ListCountOAM
from arrowed.oam import ListOffsetOAM
from arrowed.oam import RecordOAM
from arrowed.oam import PointerOAM

import uproot

def defineOAM(tree, rename=lambda x: x.name):
    class ListWithName(list):
        def __init__(self, name):
            super(ListWithName, self).__init__()
            self.name = name

    def recurse(branch):
        bycounter = {}
        for subbranch in branch.branches:
            if len(subbranch.leaves) == 1:
                counter = subbranch.leaves[0].counter
                if counter is not None:
                    counter = counter.name

                if counter not in bycounter:
                    bycounter[counter] = ListWithName(subbranch.name)

                if len(subbranch.branches) == 0:
                    bycounter[counter].append(subbranch)
                else:
                    bycounter[counter].append(recurse(subbranch))

        return bycounter
    
    structure = recurse(tree)

    def recurse(counter, group):
        fields = {}
        for obj in group:
            if isinstance(obj, dict):
                for subcounter, subgroup in obj.items():
                    # no more than one level may be counted
                    assert counter is None or subcounter is None
                    if counter is None:
                        counter = subcounter
                    fields[subgroup.name] = recurse(counter, subgroup)

            elif hasattr(obj, "dtype"):
                fields[obj.name] = PrimitiveOAM(obj.name)

        if counter is None:
            return RecordOAM(fields)
        else:
            print "HERE", fields

            return ListCountOAM(counter, RecordOAM(fields))

    return ListCountOAM(None, RecordOAM(dict(recurse(counter, group) for counter, group in structure.items())))

tree = uproot.open("~/storage/data/small-evnt-tree-fullsplit.root")["tree"]

# tree = uproot.open("~/storage/data/nano-TTLHE-2017-09-04-lz4.root")["Events"]

print defineOAM(tree).format()

@@ -641,16 +641,30 @@
 edDict%0A%0A
+import numpy%0A%0A
 from arr
@@ -902,151 +902,8 @@
 e):%0A
-    class ListWithName(list):%0A        def __init__(self, name):%0A            super(ListWithName, self).__init__()%0A            self.name = name%0A%0A
     
@@ -935,22 +935,30 @@
     
-bycounter = %7B%7D
+fields = OrderedDict()
 %0A   
@@ -1029,20 +1029,22 @@
 nch.
-leav
+branch
 es) == 
-1
+0
 :%0A  
@@ -1061,427 +1061,254 @@
     
-counter = subbranch.leaves%5B0%5D.counter%0A                if counter is not None:%0A                    counter = counter.name%0A%0A                if counter not in bycounter:%0A                    bycounter%5Bcounter%5D = ListWithName(subbranch.name)%0A%0A                if len(subbranch.branches) == 0:%0A                    bycounter%5Bcounter%5D.append(subbranch)%0A                else:%0A                    bycounter%5Bcounter%5D.append(recurse
+if getattr(subbranch, %22dtype%22, numpy.dtype(object)) is not numpy.dtype(object):%0A                    if subbranch.name in tree.counter:%0A                        fields%5Bsubbranch.name%5D = ListCountOAM(tree.counter%5Bsubbranch.name%5D.branch, PrimitiveOAM
 (sub
@@ -1317,20 +1317,24 @@
 anch
+.name
 ))%0A
-%0A
         
 retu
@@ -1333,449 +1333,122 @@
     
-return bycounter%0A
+ 
     
-%0A
     
-structure = recurse(tree)%0A%0A    def recurse(counter, group):%0A        fields = %7B%7D%0A        for obj in group:%0A            if isinstance(obj, dict):%0A                for subcounter, subgroup in obj.items():%0A                    # no more than one level may be counted%0A                    assert counter is None or subcounter is None%0A                    if counter is None:%0A                        counter = subcounter%0A    
+   else:%0A                        fields%5Bsubbranch.name%5D = PrimitiveOAM(subbranch.name)%0A            else:%0A
     
@@ -1469,21 +1469,22 @@
 elds%5Bsub
-group
+branch
 .name%5D =
@@ -1496,173 +1496,151 @@
 rse(
-counter, subgroup)%0A%0A            elif hasattr(obj, %22dtype%22):%0A                fields%5Bobj.name%5D = PrimitiveOAM(obj.name)%0A%0A        if counter is None:%0A            return
+subbranch)%0A%0A        if branch is not tree and branch.name in tree.counter:%0A            return ListCountOAM(tree.counter%5Bsubbranch.name%5D.branch,
  Rec
@@ -1653,16 +1653,17 @@
 (fields)
+)
 %0A       
@@ -1685,70 +1685,14 @@
     
-print %22HERE%22, fields%0A%0A            return ListCountOAM(counter,
+return
  Rec
@@ -1705,17 +1705,16 @@
 (fields)
-)
 %0A%0A    re
@@ -1741,89 +1741,26 @@
 ne, 
-RecordOAM(dict(recurse(counter, group) for counter, group in structure.items())))
+recurse(tree))%0A%0A%0A%0A
 %0A%0Atr

correct but unwieldy