#!/usr/bin/env ruby
 
FILENAME = 'gigatek_dc6150_complete.bin'
 
file = File.open(FILENAME, 'rb');
 
records = []
 
RECORD_SEPARATOR = [
  %w[55 aa 55 aa 55 aa 55 aa],
  %w[55 aa 55 aa 55 aa 55 aa],
  %w[55 aa 55 aa 55 aa 55 aa],
  %w[55 aa 55 aa 55 aa 55 aa],
  %w[55 aa 55 aa ff ff 00 00]
]
 
buffer = []
BUFFER_LINES = RECORD_SEPARATOR.length
 
record_count = 0
# limit = 200
limit = -1
position = 0
 
records = [[]]
 
until file.eof? || (limit -= 1) == 0
  line = file.read(8)
  line = line.unpack("H*")[0].scan(/../)
  position += 8
 
 
  records[-1] << line
  # puts "#{line.map{|b| "0x#{b}"}.join(' ')}\n"
  # puts "#{line.join(' ')}\n"
  puts "Position: #{position}" if position % (1024 * 1000) == 0
 
  if buffer.length >= BUFFER_LINES
    buffer.pop
  end
 
  buffer << line
 
  if buffer == RECORD_SEPARATOR
    record_count += 1
    puts "Found record #{record_count}"
 
    records << [] if record_count > 1
  end
end
file.close
 
puts "Record Count: #{record_count}"
puts "Payload Count: #{records.length}"
 
puts "Average Record size: #{(records.map{|r| r.length}.inject(:+))/records.length}"
puts "Average net Record size: #{(records.map{|r| (r-RECORD_SEPARATOR).length}.inject(:+))/records.length}"
 
puts "\n\n"
first_lines = records.map{|r| (r-RECORD_SEPARATOR).first}
puts "#{first_lines.uniq.length} unique first lines."
# require 'byebug'; byebug;
# puts first_lines.each_with_index.map{|a, idx| [a.join(' '), (records[idx]-RECORD_SEPARATOR).length].join(' - ')}.join("\n")
puts 'done.'