#!/usr/bin/python
#
# Copyright (C) 2005  Alexandre Boeglin <alex@boeglin.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import sys

f = open(sys.argv[1])
line_list = f.readlines()

packet_min = None
packet_max = None
displayed_len = 8

direction_dict = {'3' : 'in ', '2' : 'out'}

processing = 0

for line in line_list :
  if line.startswith('[') :
    if not processing and 'URB' in line : # begin processing
      processing = 1

      data = 0
    elif processing == 1: # end processing
      if ((packet_min is None) or (number >= packet_min)) and ((packet_max is None) or (number <= packet_max)) :
        if data != 0 :
          tmp = ('%X' % data).zfill(data_len << 1)
          tmp_list = []
          tmp_len = min (data_len, displayed_len)
          for i in range(0, 2 * tmp_len, 2) :
            tmp_list.append('%c%c' % (tmp[i], tmp[i + 1]))
          data_print = ' '.join(tmp_list)

          if data_len > displayed_len :
            data_print += ' ... (too many bytes)'
        else :
          data_print = ''
        print 'seq : %4d | type : %s | ep : 0x%02X | dir : %3s | len = %5d %s' % (
            number,
            'BULK' in p_type and 'BULK' or p_type,
            ep,
            direction_dict.get(str(direction), 'X%d' % direction),
            data_len,
            data_print != '' and '| data : %s' % data_print or '')
      processing = 0

  if processing :
    param = line.split()[0]
    if param.startswith('[') :
      number = int(line.split()[4])
      pkt = '>>>' in line and 2 or 3
    elif param == '--' :
      p_type = line.split()[1][:-1]
      if not 'BULK' in p_type :
        processing = 0
    elif param == '*******' :
      if 'non printable URB' in line :
        processing = 0
    elif param == 'PipeHandle' :
      if len(line.split()) == 5 :
        ep = int(line.split()[4][:-1], 16)
    elif param == 'TransferFlags' :
      direction = int(line.split()[2], 16)
      if direction != pkt :
        processing = 0
    elif param == 'TransferBufferLength' :
      data_len = int(line.split()[2], 16)
    elif param.startswith('0') :
      weight = int(param[:-1], 16)
      data += int(''.join(line.split()[1:]), 16) << (weight << 3)

