"""
name: Merge continue records (XLS)
category: office
filetype: Office.Workbook8
author: malcat
icon: wxART_FILE_ADD

This script merge contiguous CONTINUE records and consecutive similar records. This is useful to recover subfiles (like pictures) from the Workbook, since otherwise they would be interrupted by several CONTINUE record headers which would mess with analysis's file detection algorithm.
 
Note that this will make the Workbook *invalid* since there is no way to nicely patch the records: a record size is a uint16 and multiple CONTINUE record can be > 65K
"""
import argparse

res = bytearray()
for book in analysis.struct:
    prev = None
    for record in book:
        if record.Opcode.enum == "CONTINUE" or prev is not None and prev == record.Opcode.value:
            # skip Opcode header
            res.extend(analysis.file.read(record.offset + 4, record.size - 4))
        else:
            res.extend(analysis.file.read(record.offset, record.size))
        prev = record.Opcode.value
if len(res) == analysis.file.size:
    print("No CONTINUE records where found")
else:
    gui.open_after(bytes(res), "expanded")
