import csv
import datetime
import struct

def parse_grouped_efield(input_filename, output_filename):
    with open(input_filename, 'rb') as f:
        data = f.read()

    i = 0
    current_timestamp = None
    current_block = []

    all_blocks = []

    while i + 5 <= len(data):
        entry_id = data[i]
        value_bytes = data[i+1:i+5]
        i += 5

        if entry_id == 0x01:
            # Save the previous block if it exists
            if current_timestamp and current_block:
                all_blocks.append([current_timestamp] + current_block)
                current_block = []

            # Parse timestamp
            value = int.from_bytes(value_bytes, byteorder='little', signed=False)
            current_timestamp = datetime.datetime.utcfromtimestamp(value).strftime('%Y-%m-%d %H:%M:%S')

        elif entry_id in (0x02, 0x1B, 0x1C):
            # Parse E-field values and convert to microvolts
            value = int.from_bytes(value_bytes, byteorder='little', signed=False)
            scaled_value = value / 10000.0
            current_block.append(scaled_value)

    # Save last block
    if current_timestamp and current_block:
        all_blocks.append([current_timestamp] + current_block)

    # Write to CSV
    with open(output_filename, 'w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerow(['Timestamp (UTC)', 'E-Field Samples...'])
        writer.writerows(all_blocks)

    print(f"Saved {len(all_blocks)} timestamped E-field blocks to {output_filename}")

# Usage
parse_grouped_efield("Test.B162", "Grouped_Efield_Output.csv")
