require 'rublib' if IdaRub.remote?
require 'plugins/rublib' if IdaRub.local?

ida, = IdaRub.auto_client

file = IdaFile.new(ida)

# Count instructions
inst = file.map{|f| f.map{|i| i.instruction}}.flatten
total = inst.length
un = inst.uniq.map
count = un.map{|e| inst.select{|f| e == f}.length}

# Create the instruction => count mapping and sort it
instructions = Hash.new
un.size.times { |i| instructions[ un[i] ] = count[i] }
sorted = instructions.sort {|a, b| b[1]<=>a[1]}

# Print the output
idap ida, "Opcode distribution of file: %s\n" % file.name
idap ida, "Total number of opcodes: %i\n\n" % total

sorted.each_with_index {|o, i|
	idap ida, "%04i. %06i %8.2f%%      %s\n" % [i+1, o[1], 100.0 * o[1] / total, o[0]]
}
