import epuck2
import struct

def save_mic_array_to_csv(filename="mic_data.csv"):
    # 1. Get raw bytes (1280 bytes)
    mic_buffer = bytearray(1280)
    success = epuck2.get_mic_data(mic_buffer)
    
    if not success:
        print("Failed to acquire mic data.")
        return

    try:
        with open(filename, "w") as f:
            # Write Header
            f.write("Right,Left,Back,Front\n")
            
            # 2. Iterate through 160 sets of samples
            # Each set is 8 bytes (4 mics * 2 bytes)
            for i in range(160):
                start = i * 8
                chunk = mic_buffer[start : start + 8]
                
                # Unpack 4 signed shorts (16-bit) 
                # '<' = Little Endian, 'h' = signed short
                r, l, b, f_mic = struct.unpack('<4h', chunk)
                
                # 3. Write as a row
                f.write("{},{},{},{}\n".format(r, l, b, f_mic))
                
        print("Successfully saved 160 samples per channel to", filename)

    except Exception as e:
        print("Error saving CSV:", e)

# Run the export
save_mic_array_to_csv()
