# Eta Library 
import os

def read_ascii_line_by_line(filename):
    """
    Reads an ASCII file line by line and prints each line.
    Useful for simple text files or when processing each line individually.
    """
    print(f"\n--- Reading '{filename}' line by line ---")
    if not os.path.exists(filename):
        print(f"Error: File '{filename}' not found.")
        return

    try:
        with open(filename, 'r') as f:
            for line_num, line in enumerate(f):
                print(f"Line {line_num + 1}: {line.strip()}") # .strip() removes leading/trailing whitespace and newline
    except Exception as e:
        print(f"An error occurred while reading line by line: {e}")

def read_specific_grid_info(filename):
    """
    Reads specific grid information (west, east, north, south, res)
    and two subsequent integer values from an ASCII file.
    """
    print(f"\n--- Reading specific grid information from '{filename}' ---")
    if not os.path.exists(filename):
        print(f"Error: File '{filename}' not found.")
        return None

    grid_info = {}
    expected_keys = ['west', 'east', 'north', 'south', 'res']
    
    try:
        with open(filename, 'r') as f:
            # Read key-value pairs
            for key in expected_keys:
                line = f.readline().strip()
                if not line:
                    print(f"Error: Unexpected end of file while reading '{key}'.")
                    return None
                
                # Split by '=' and take the second part, then strip whitespace
                try:
                    value_str = line.split('=')[1].strip()
                    grid_info[key] = float(value_str)
                except (IndexError, ValueError) as e:
                    print(f"Error parsing line for '{key}': '{line}' - {e}")
                    return None
            
            # Read the next two integer values
            line1 = f.readline().strip()
            line2 = f.readline().strip()

            if not line1 or not line2:
                print("Error: Unexpected end of file while reading integer values.")
                return None
            
            try:
                grid_info['nlons'] = int(line1)
                grid_info['nlats'] = int(line2)
            except ValueError as e:
                print(f"Error parsing integer values: '{line1}', '{line2}' - {e}")
                return None
        
        print("\nParsed Grid Information:")
        for key, value in grid_info.items():
            print(f"  {key}: {value}")
        
        return grid_info

    except Exception as e:
        print(f"An unexpected error occurred: {e}")
        return None


#if __name__ == "__main__":
#
#    # --- Demonstrate reading the specific grid information file ---
#    grid_info_file = "grid_info.txt"
#    parsed_grid_data = read_specific_grid_info(grid_info_file)
#    # os.remove(grid_info_file) # Uncomment to clean up

