#!/usr/bin/python

import sys
import re
import itertools as it
import collections

def parse_varstr(token):
    token = token.strip("[]")
    tokens = token.split(",")
    tokens = [t.strip(' "') for t in tokens]
    return tokens

def parse_header(header):
    header_vars = header.split("\t")
    columns_b = {}
    columns_s = {}
    row = -1
    for elem, count in it.izip(header_vars, it.count()):
        match = re.match("(?:\((.*?)\))?(.*)", elem)
        op_name, var_name = match.groups()
        if var_name == "$s:ROW":
            row = count
        elif var_name.startswith("$b:bCOLUMN_"):
            rel = var_name.split("$b:bCOLUMN_")[1]
            columns_b[rel] = count
        elif var_name.startswith("$s:sCOLUMN_"):
            rel = var_name.split("$s:sCOLUMN_")[1]
            columns_s[rel] = count

    if row == -1:
        sys.stderr.write("header error: no $s:ROW variable\n")
        sys.stderr.flush()
        return None

    rels = []
    for s_var, s_idx in columns_s.items():
        if s_var in columns_b:
            b_idx = columns_b.pop(s_var)
            rels.append((s_var, b_idx, s_idx))
        else:
            sys.stderr.write("warning: skipping variable $s:sCOLUMN_%s because $b_bCOLUMN_%s is not present in header\n" % (s_var, s_var))
            sys.stderr.flush()

    for b_var in columns_b:
        sys.stderr.write("warning: skipping variable $b:bCOLUMN_%s because $s_sCOLUMN_%s is not present in header\n" % (b_var, b_var))
        sys.stderr.flush()

    return row, rels

def flush_data(data):
    for k, v in data.iteritems():
        sys.stdout.write("%s;%s;%s;%d\n" % (k[0], k[1], k[2], v))
        sys.stdout.flush()
    data.clear()

header = sys.stdin.readline().strip()
header_parse = parse_header(header)
if header_parse is None:
    sys.exit(-1)
row_idx, rels = header_parse

data = collections.defaultdict(int)
for line in sys.stdin:
    line = line.strip()
    toks = line.split("\t")
    for name, bool_idx, str_idx in rels:
        matched = True if toks[bool_idx] == "True" else False
        if matched:
            disambs_col = parse_varstr(toks[str_idx])
            for dis_col in disambs_col:
                for dis_row in parse_varstr(toks[row_idx]):
                    data[(dis_row, name, dis_col)] += 1
                    if len(data) > 10:
                        flush_data(data)
flush_data(data)
