import re
import struct


def extract_ir(input_file, output_file):
    """
    Given an integration header input file and an output file open in binary
    mode, extracts the kernel IR binary from the header into the output file.
    Returns the type of IR found ('spir32', 'spir64', 'spirv32', 'spirv64') or
    '' if unknown.
    """
    start_re = re.compile(
        'unsigned char [A-Za-z-0-9_]*_bin_spirv?(64|32)\[\] = {')
    spir32_re = re.compile('spir32')
    spir64_re = re.compile('spir64')
    spirv32_re = re.compile('spirv32')
    spirv64_re = re.compile('spirv64')
    end_line = '};\n'

    reached_start = False
    bin_type = ''

    # Read the file line by line until we reach the start of the binary blob
    for line in input_file:
        if reached_start:
            if line == end_line:
                break
            else:
                line = line.replace(',', '')
                hex_list_as_string = line.split()

                for byte in hex_list_as_string:
                    output_file.write(struct.pack('B', int(byte[2:], 16)))

        if not reached_start and start_re.match(line):
            reached_start = True
            if spir32_re.search(line):
                bin_type = 'spir32'
            elif spir64_re.search(line):
                bin_type = 'spir64'
            elif spirv32_re.search(line):
                bin_type = 'spirv32'
            elif spirv64_re.search(line):
                bin_type = 'spirv64'

    for line in input_file:
        # Make sure the header has been fully read
        pass

    return bin_type