#!/usr/bin/env python

import sys

# initialize stock hash table for collecting details
stock_table = {}

# hash for storing last timestamp of stock
stock_ts = {}

# hash for storing total volume of stock
stock_qty = {}

# hash for storing array of tuples of price and qty per stock
stock_px = {}

# initialize variables to capture details from each line
ts, sym, qty, px, line_no = 0, "", 0, 0, 0


# not used here we do not want to mess up output.csv 
def validate_input(ts, sym, qty):
    if len(sym) != 3:
        print("Invalid symbol {} at ts {}".format(sym, ts))
    if (int(qty) <= 0):
        print("Invalid quantity {} for symbol {} at ts {}". format(qty, sym, ts))


#Calculate timestamp gap and store the new one. 
def get_max_ts_gap(sym: str, ts: int) -> int:
    prev_ts, prev_gap, ts_gap = 0, 0, 0

    if sym in stock_ts:
        prev_ts, prev_gap = stock_ts[sym]
        ts_gap = int(ts) - int(prev_ts)
        if prev_gap > ts_gap:  # if old gap is bigger, take it as latest
            ts_gap = prev_gap
    else: # first iteration for this stock
        ts_gap = 0
    if prev_gap > ts_gap:
        ts_gap = prev_gap
    else:
        stock_ts[sym] = [ts, ts_gap]
    return ts_gap


def prepare_total_cost_per_stock(sym, qty, px):
    if sym in stock_px:
        stock_px[sym] += int(qty) * int(px)
    else:
        stock_px[sym] = int(qty) * int(px)

#Calculate and populate total volume of each traded stock
def populate_total_volume(sym, qty):
    if sym in stock_qty:
        stock_qty[sym] += int(qty)
    else:
        stock_qty[sym] = int(qty)

#populate stock table	

def populate_stock_table(sym, qty, px, ts_gap):

    if sym in stock_table:
        stock_table[sym] = [ts_gap, int(
            stock_table[sym][1]) + int(qty), max(int(stock_table[sym][2]), int(px))]
    else:
        stock_table[sym] = [0, qty, px]

#Read standard input data and process

def process_stdin():
    try:
       for line in sys.stdin:
          (ts, sym, qty, px) = line.split(',')
      #    validate_input(ts, sym, qty)
          populate_total_volume(sym, qty)
          prepare_total_cost_per_stock(sym, qty, px)
          populate_stock_table(sym, qty, px, get_max_ts_gap(sym, ts))
    except:
      #print("An exception has occured, Give more information in next iteration of coding")
      pass
    finally:
      #print("Handle something here in future")
      pass

if __name__ == "__main__":
    process_stdin()
    for (key, value) in sorted(stock_table.items()):
        stock_table[key].append(stock_px[key]//stock_qty[key])
        stock_table[key][-1], stock_table[key][-2] = stock_table[key][-2], stock_table[key][-1]
        print(key, stock_table[key])
