import numpy as np
import re

def read_data_to_arrays(filename):
    """
    Reads data from a text file and organizes it into 3D numpy arrays
    for Wind Speed, Wind Direction, and Height.

    Args:
        filename (str): The path to the text file.

    Returns:
        tuple: A tuple containing three 3D numpy arrays (wind_speed, wind_direction, height).
               Returns (None, None, None) if an error occurs during reading.
    """
    wind_speed_data = []
    wind_direction_data = []
    height_data = []
    try:
        with open(filename, 'r') as file:
            content = file.read()
    except FileNotFoundError:
        print(f"Error: File '{filename}' not found.")
        return None, None, None
    # Splitting the content based on the variable names
    sections = re.split(r'Wind_Speed|Wind_Direction|Height', content)[1:]  # Split and ignore the first empty string
    if len(sections) != 3:
        print("Error: Expected three sections (Wind Speed, Wind Direction, Height) in the file.")
        return None, None, None
    for i, section in enumerate(sections):
        # Extracting the data lines, filtering out empty lines
        data_lines = [line.strip() for line in section.strip().split('\n') if line.strip()]
        # Further processing each line into lists of integers
        processed_data = []
        for line in data_lines:
            values = [int(value) for value in line.split()]
            processed_data.append(values)
        # Determine the maximum number of columns
        max_cols = max(len(row) for row in processed_data)
        # Pad each row with zeros to make them the same length
        for row in processed_data:
            while len(row) < max_cols:
                row.append(0)  # Or any other padding value
        # Convert the processed data to a numpy array
        numpy_array = np.array(processed_data)
        if i == 0:
            wind_speed_data = numpy_array
        elif i == 1:
            wind_direction_data = numpy_array
        else:
            height_data = numpy_array
    return wind_speed_data, wind_direction_data, height_data
# Example usage:
filename = 'ECMWFNW_850_spd_000.txt'  # Replace with your file name
wind_speed, wind_direction, height = read_data_to_arrays(filename)

if wind_speed is not None:
    print("Wind Speed Array Shape:", wind_speed.shape)
    print(wind_speed)

if wind_direction is not None:
    print("\nWind Direction Array Shape:", wind_direction.shape)
    print(wind_direction)

if height is not None:
    print("\nHeight Array Shape:", height.shape)
    print(height)
