class TableNode(Node):
    def __init__(self, cellvar, sequence, cols, cellnodes):
        self.cellvar = cellvar
        self.sequence = sequence
        self.cols = cols
        self.cellnodes = cellnodes
        
    def __iter__(self):
        for node in self.cellnodes:
            yield node
        
    def get_nodes_by_type(self, nodetype):
        nodes = []
        if isinstance(self, nodetype):
            nodes.append(self)
        nodes.extend(self.cellnodes.get_nodes_by_type(nodetype))
        return nodes
    
    def render(self, context):
        nodelist = NodeList()
        if context.has_key('parenttable'):
            parenttable = context['parenttable']
        else:
            parenttable = {}
        context.push()
        try:
            values = self.sequence.resolve(context, True)
        except VariableDoesNotExist:
            values = []
        if values is None:
            values = []
        if not hasattr(values, '__len__'):
            values = list(values)
        len_values = len(values)
      
        innernodelist = NodeList()
        for i, item in enumerate(values):
            loopctx = {
                # shortcuts for current loop iteration number
                'counter0': i,
                'counter': i+1,
                'rowcounter0': i / self.cols,
                'rowcounter': (i/self.cols) + 1,
                'even': (i % 2 == 0),
                # boolean values designating first and last items
                'firstrow': (i < self.cols),
                'lastrow': (i > len_values - self.cols),
                'firstcell': (i == 0),
                'lastcell': (i == len_values - 1),
                'parenttable': parenttable,
            }
            context[self.cellvar] = item
            loopctx["startrow"] = False
            loopctx["endrow"] = False            
            if i % self.cols == 0:
                nodelist.append(innernodelist.render(context))
                innernodelist = NodeList()
                loopctx["startrow"] = True
            elif (i + 1) % self.cols == 0:
                loopctx["endrow"] = True

            context['table'] = loopctx            
            for node in self.cellnodes:
                innernodelist.append(node.render(context))
        if innernodelist != None and len(innernodelist) > 0:
            nodelist.append(innernodelist.render(context))
        print "Done rendering table"
        context.pop()
        return nodelist.render(context)

def do_table(parser,token):
    bits = token.contents.split()
    cellvar = bits[1]
    sequence = parser.compile_filter(bits[2])
    cols = int(bits[3])
    cellnodes = parser.parse(('endtable',))
    parser.delete_first_token()
    return TableNode(cellvar, sequence, cols, cellnodes)

register.tag("table", do_table)

##Sample usage:
    	<table>
    	{% table pic gallery_pics 5 %}
    	   {% if table.firstcell %}<tbody>{% endif %}
    	   {% if table.startrow %}<tr>{% endif %}
    	   <td>{{pic.filename}}</td>
    	   {% if table.endrow %}</tr>{% endif %}
    	   {% if table.lastcell %}</tbody>{% endif %}
    	{% endtable %}
    	</table>