simplify this code so that it is easier on the eyes. Remove all the try/catch/error handling stuff #!/usr/bin/python3

import time
import traceback
from picamera2 import Picamera2
import numpy as np
import scipy.io
import datetime

# --- Configuration ---
CAMERA_INDEX = 0
ACTUAL_SENSOR_RESOLUTION = (1456, 1088) # For IMX296
REQUESTED_BIT_DEPTH = 10 

# Using 'R10' as the requested format string, which resulted in an 'R16' actual format.
# This 'R16' format contains the 10-bit sensor data MSB-aligned in uint16 words.
desired_raw_stream_config = {
    "format": 'R10', 
    "size": ACTUAL_SENSOR_RESOLUTION
}
# --- ---

picam2 = None
raw_image_array = None

try:
    print(f"Initializing Picamera2 for camera index {CAMERA_INDEX}...")
    picam2 = Picamera2(camera_num=CAMERA_INDEX)

    print("\nAttempting to configure with create_preview_configuration (main with dummy, raw format 'R10')...")
    preview_config = picam2.create_preview_configuration(
        main={"size": (640, 480), "format": "XRGB8888"}, 
        raw=desired_raw_stream_config
    )
    
    print(f"\nConfiguring camera with: {preview_config}")
    picam2.configure(preview_config)
    
    print("\nActual configuration applied by libcamera:")
    cam_config = picam2.camera_configuration()
    
    actual_main_format = cam_config.get('main', {}).get('format', 'N/A')
    actual_main_size = cam_config.get('main', {}).get('size', 'N/A')
    print(f"--> Actual Main stream: Format '{actual_main_format}', Size {actual_main_size}")

    if 'raw' not in cam_config or cam_config.get('raw') is None:
        raise RuntimeError("Raw stream was not configured.")

    actual_raw_format_str = cam_config.get('raw', {}).get('format', 'Unknown')
    actual_raw_size = cam_config.get('raw', {}).get('size', 'Unknown')
    actual_raw_stride_bytes = cam_config.get('raw', {}).get('stride', 'Unknown')
    
    if not all([isinstance(actual_raw_format_str, str) and actual_raw_format_str != 'Unknown',
                isinstance(actual_raw_size, tuple) and len(actual_raw_size) == 2,
                isinstance(actual_raw_stride_bytes, int)]):
        detailed_raw_config = cam_config.get('raw', 'Not available')
        raise RuntimeError(f"Critical raw stream information missing or invalid. Full raw config: {detailed_raw_config}")

    print(f"--> Actual Raw stream: Format '{actual_raw_format_str}', Size {actual_raw_size}, Stride {actual_raw_stride_bytes} bytes")

    if actual_raw_format_str.upper() == 'R16':
        print(f"INFO: Actual raw format is 'R16'. This will contain 10-bit data MSB-aligned in uint16 words.")
    else:
        print(f"Warning: Expected actual raw format 'R16' (from 'R10' request), but got '{actual_raw_format_str}'.")


    img_height = actual_raw_size[1]
    img_width = actual_raw_size[0] 

    print("\nStarting camera...")
    picam2.start() 
    time.sleep(2) 

    if REQUESTED_BIT_DEPTH == 10:
        target_image_dtype = np.uint16
        target_itemsize = 2 
    else: 
        # This case should ideally not be hit with current config
        print(f"Warning: REQUESTED_BIT_DEPTH is {REQUESTED_BIT_DEPTH}, not 10. Adjusting target_image_dtype.")
        target_image_dtype = np.uint8
        target_itemsize = 1
    print(f"INFO: Target image dtype for processing: {target_image_dtype} (itemsize: {target_itemsize} bytes)")
    
    print(f"\nAttempting capture_buffers for stream 'raw'...")
    buffers_obj = picam2.capture_buffers(["raw"]) 
    metadata_after_capture = picam2.capture_metadata() 

    print(f"DEBUG: Type of 'buffers_obj' from capture_buffers: {type(buffers_obj)}")

    dma_buf_or_array = None
    if isinstance(buffers_obj, (list, tuple)):
        if not buffers_obj: raise RuntimeError("capture_buffers returned an empty sequence.")
        candidate = buffers_obj[0]
        if isinstance(candidate, (list, tuple)): 
            if not candidate: raise RuntimeError("capture_buffers returned a nested empty sequence.")
            dma_buf_or_array = candidate[0]
        else: dma_buf_or_array = candidate
    else: dma_buf_or_array = buffers_obj

    if dma_buf_or_array is None: raise RuntimeError("Could not extract buffer/array object.")
    print(f"DEBUG: Extracted 'dma_buf_or_array' is of type: {type(dma_buf_or_array)}")

    try:
        current_img_height = img_height 

        if isinstance(dma_buf_or_array, np.ndarray):
            print(f"INFO: 'dma_buf_or_array' is already a NumPy array. Shape: {dma_buf_or_array.shape}, Dtype: {dma_buf_or_array.dtype}.")
            
            if dma_buf_or_array.dtype == np.uint8 and target_image_dtype == np.uint16 and actual_raw_format_str.upper() == 'R16':
                print(f"INFO: Buffer is uint8, actual format is R16. Reinterpreting as uint16.")
                elements_per_line_from_stride = actual_raw_stride_bytes // target_itemsize 
                expected_uint16_elements_total = current_img_height * elements_per_line_from_stride
                actual_uint16_elements_from_buffer = dma_buf_or_array.size // target_itemsize

                if actual_uint16_elements_from_buffer < expected_uint16_elements_total:
                    effective_height = actual_uint16_elements_from_buffer // elements_per_line_from_stride
                    if effective_height == 0: 
                        raise ValueError(f"uint8 NumPy array (size {dma_buf_or_array.size} bytes) too small to form one line "
                                         f"of {elements_per_line_from_stride} uint16 elements (stride {actual_raw_stride_bytes} bytes).")
                    print(f"Warning: Buffer smaller than expected for uint16. Using effective height: {effective_height} instead of {current_img_height}")
                    current_img_height = effective_height
                    expected_uint16_elements_total = current_img_height * elements_per_line_from_stride
                
                num_bytes_for_view = expected_uint16_elements_total * target_itemsize
                temp_target_dtype_array_1d = dma_buf_or_array[:num_bytes_for_view].view(dtype=target_image_dtype)
                
                reshaped_buffer_target_dtype = temp_target_dtype_array_1d.reshape((current_img_height, elements_per_line_from_stride))
                raw_image_array = reshaped_buffer_target_dtype[:, :img_width].copy()
                print(f"INFO: Successfully reinterpreted uint8 buffer as {target_image_dtype} and reshaped.")
            elif dma_buf_or_array.dtype == target_image_dtype: # Buffer already correct dtype
                 print(f"INFO: Buffer dtype already matches target_image_dtype ({target_image_dtype}).")
                 buffer_itemsize_match = dma_buf_or_array.dtype.itemsize
                 elements_per_line_from_stride = actual_raw_stride_bytes // buffer_itemsize_match
                 if len(dma_buf_or_array.shape) == 1:
                    expected_elements_in_buffer = current_img_height * elements_per_line_from_stride
                    if dma_buf_or_array.size < expected_elements_in_buffer:
                        effective_height = dma_buf_or_array.size // elements_per_line_from_stride
                        if effective_height == 0: raise ValueError("Buffer too small.")
                        current_img_height = effective_height
                        expected_elements_in_buffer = current_img_height * elements_per_line_from_stride
                    temp_buffer_1d = dma_buf_or_array[:expected_elements_in_buffer]
                    reshaped_buffer = temp_buffer_1d.reshape((current_img_height, elements_per_line_from_stride))
                    raw_image_array = reshaped_buffer[:, :img_width].copy()
                 elif len(dma_buf_or_array.shape) == 2 and dma_buf_or_array.shape[0] == current_img_height and dma_buf_or_array.shape[1] == img_width:
                    raw_image_array = dma_buf_or_array.copy() 
                 elif len(dma_buf_or_array.shape) == 2 and dma_buf_or_array.shape[0] == current_img_height and dma_buf_or_array.shape[1] == elements_per_line_from_stride: # Stride included
                    raw_image_array = dma_buf_or_array[:, :img_width].copy()
                 else: 
                    raise ValueError(f"Pre-existing NumPy array (type {dma_buf_or_array.dtype}) has unexpected shape: {dma_buf_or_array.shape}.")
            else: 
                # This path should not be taken if R16 is configured and buffer is uint8
                raise TypeError(f"Unhandled buffer condition: dtype {dma_buf_or_array.dtype}, target {target_image_dtype}, actual format {actual_raw_format_str}")

        elif hasattr(dma_buf_or_array, 'mmap'): 
            # This path should also work correctly if target_image_dtype is np.uint16
            print(f"INFO: 'dma_buf_or_array' (type: {type(dma_buf_or_array)}) has .mmap(). Processing with target_image_dtype={target_image_dtype}.")
            with dma_buf_or_array.mmap() as m: 
                print(f"DEBUG: mmap successful. Memoryview length: {len(m)} bytes.")
                elements_per_line_from_stride = actual_raw_stride_bytes // target_itemsize 
                
                num_full_lines_in_buffer = len(m) // actual_raw_stride_bytes
                if num_full_lines_in_buffer < current_img_height:
                    if num_full_lines_in_buffer == 0: raise ValueError(f"Buffer too small ({len(m)} bytes) for one strided line ({actual_raw_stride_bytes} bytes, itemsize {target_itemsize}).")
                    print(f"Warning: Mapped memory provides {num_full_lines_in_buffer} lines, expected {current_img_height}. Adjusting height.")
                    current_img_height = num_full_lines_in_buffer

                num_elements_to_read_total = current_img_height * elements_per_line_from_stride
                readable_bytes = (len(m) // target_itemsize) * target_itemsize 
                temp_array_1d = np.frombuffer(m[:readable_bytes], dtype=target_image_dtype) 
                
                if temp_array_1d.size < num_elements_to_read_total: 
                    current_img_height = temp_array_1d.size // elements_per_line_from_stride
                    if current_img_height == 0: raise ValueError(f"Cannot form one line from read buffer (elements: {temp_array_1d.size}, els/line: {elements_per_line_from_stride}).")
                    print(f"Warning: Further adjusting height to {current_img_height} based on actual elements read.")
                    num_elements_to_read_total = current_img_height * elements_per_line_from_stride

                temp_array_1d_for_reshape = temp_array_1d[:num_elements_to_read_total]
                raw_image_reshaped = temp_array_1d_for_reshape.reshape((current_img_height, elements_per_line_from_stride))
                raw_image_array = raw_image_reshaped[:, :img_width].copy()
        else:
            raise TypeError(f"'dma_buf_or_array' is of unexpected type {type(dma_buf_or_array)}.")

        print(f"\n*** Successfully obtained/processed raw buffer into NumPy array! ***")
        print(f"NumPy array shape: {raw_image_array.shape}, dtype: {raw_image_array.dtype}")
        if raw_image_array.size > 0:
            min_val, max_val, mean_val = np.min(raw_image_array), np.max(raw_image_array), np.mean(raw_image_array)
            print(f"Min value: {min_val}, Max value: {max_val}, Mean: {mean_val:.2f}")
            if raw_image_array.dtype == np.uint16 and max_val > 255 : 
                 print(f"INFO: Max value > 255 (actual max: {max_val}). Data is uint16. For 10-bit data, values are likely MSB-aligned (0-1023 shifted left by 6 bits -> 0-65472).")
            elif raw_image_array.dtype == np.uint16 and max_val <= 255:
                 print(f"INFO: Data is uint16, but max value <= 255. Could be low light or already scaled to 8-bit effective range.")
            elif raw_image_array.dtype == np.uint8:
                 print("INFO: Data is uint8. Max value <= 255. Appears to be 8-bit data (this should not happen if R16 was processed correctly).")

    except Exception as proc_e:
        print(f"\n--- ERROR PROCESSING BUFFER ---")
        print(f"Failed to process buffer (initial type: {type(dma_buf_or_array)}): {proc_e}")
        traceback.print_exc()
    finally:
        if 'buffers_obj' in locals(): del buffers_obj
        print("DEBUG: References to buffer objects potentially cleared.")
        
    if raw_image_array is not None and raw_image_array.size > 0 :
        print(f"\nRaw buffer successfully converted/accessed as NumPy array.")
        try:
            timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S_%f") 
            filename = f"raw_image_data_{timestamp}.mat"
            
            mat_data = {
                'raw_image_matrix': raw_image_array, 
                'actual_resolution_width': raw_image_array.shape[1],
                'actual_resolution_height': raw_image_array.shape[0],
                'configured_raw_format_string': desired_raw_stream_config["format"], 
                'actual_raw_format_string': actual_raw_format_str,    
                'actual_raw_stride_bytes': actual_raw_stride_bytes,
                'requested_bit_depth': REQUESTED_BIT_DEPTH,
                'numpy_dtype_saved': str(raw_image_array.dtype),
                'note_on_pixel_values': 'For 10-bit R16 data, values are MSB-aligned in uint16. Original 0-1023 sensor values become 0-65472 (value * 64).',
                'metadata_ExposureTime': metadata_after_capture.get("ExposureTime", "N/A"),
                'metadata_AnalogueGain': metadata_after_capture.get("AnalogueGain", "N/A"),
                'metadata_SensorTimestamp': metadata_after_capture.get("SensorTimestamp", "N/A")
            }
            scipy.io.savemat(filename, mat_data)
            print(f"Successfully saved raw image data to '{filename}'")
            print("\nTo load in MATLAB:")
            print(f"  data = load('{filename}');")
            print(f"  imageMatrix = data.raw_image_matrix; % This is uint16")
            print(f"  fprintf('Image size: %d x %d, Dtype: %s\\n', size(imageMatrix,1), size(imageMatrix,2), class(imageMatrix));");
            print(f"  disp(['Min value in matrix: ', num2str(min(imageMatrix(:)))]);");
            print(f"  disp(['Max value in matrix: ', num2str(max(imageMatrix(:)))]);");
            print(f"  % To get original 10-bit scale (0-1023):");
            print(f"  % imageMatrix_10bit_scale = bitshift(imageMatrix, -6);");
            print(f"  % Or: imageMatrix_10bit_scale = floor(double(imageMatrix) / 64);");
            print(f"  figure; imshow(imageMatrix, []); title('Raw Image Data (as stored, MSB-aligned 10-bit in uint16)'); colorbar;");
            if raw_image_array.dtype == np.uint16:
                 print(f"  % Max value in this uint16 image (likely 10-bit MSB-aligned): {np.max(raw_image_array)}")

        except Exception as save_e:
            print(f"\n--- ERROR SAVING .MAT FILE ---")
            print(f"Failed to save .mat file: {save_e}")
            traceback.print_exc()
    else:
        print("\nFailed to create NumPy array from buffer, or array is empty.")

except Exception as e:
    print(f"\n--- SCRIPT LEVEL ERROR ---")
    print(f"An error occurred: {e}")
    traceback.print_exc()

finally:
    if picam2 is not None:
        if hasattr(picam2, 'started') and picam2.started:
            print("\nStopping camera (in main finally block)...")
            picam2.stop()
        print("Closing camera (in main finally block)...")
        picam2.close()
    print("\nScript finished.")