import re

class Assembler:
  def __init__(self, filename):
    self.filename = filename
  
  def dump(self):
    """
    *.bc filename is assembled to generate a *.class file.
    
    Example of input file format:
      00000000 CAFEBABE ; Magic
      00000004 0000 ; Minor version
      00000006 002E ; Major version
      00000008 0239 ; constant_pool_count
      ; constant_pool_start
      ; constant_pool_index = 1
      0000000A 09 ; tag
      0000000B 0010 ; C_Fieldref: class_index
      0000000D 011F ; C_Fieldref: name_and_type_index
      ; constant_pool_index = 2
      0000000F 09 ; tag
      00000010 0010 ; C_Fieldref: class_index
      00000012 0120 ; C_Fieldref: name_and_type_index
      ...
    """
    # Open files
    input = open(self.filename, 'r')
    output = open(self.filename + '.class', 'wb')
    
    # Process all lines in file
    for line in input:
      # If line is not comment then process line
      if not line.startswith(';'):
        # Get hex bytes (discard offset and comment)
        pattern = r'.*? (.*?) ;.*?'
        hex_bytes = re.findall(pattern, line, re.IGNORECASE | re.DOTALL)[0]
        # Process every two bytes and convert them to char to build a string
        assert(len(hex_bytes)%2==0)
        bytes = ''.join([chr(int(hex_bytes[2*i:2*i+2], 16)) for i in range(len(hex_bytes)/2)])
        # Write output file
        output.write(bytes)
      else:
        # If line is comment then do nothing
        pass 
      
    # Close files
    output.close()
    input.close()
  
