import os

def transform_lat_lon(file_path, new_lat, new_lon, output_folder="output"):
    """
    Transforms latitude and longitude in log files and stores them in the output folder.

    Parameters:
    - file_path (str): Path to the input log file.
    - new_lat (float): New latitude value.
    - new_lon (float): New longitude value.
    - output_folder (str): Folder where the modified files are saved.
    """

    os.makedirs(output_folder, exist_ok=True)
    
    base_name = os.path.basename(file_path)
    name, ext = os.path.splitext(base_name)
    output_file = os.path.join(output_folder, f"{name}_GPS{ext}")

    # Remove existing file
    if os.path.exists(output_file):
        os.remove(output_file)

    with open(file_path, "r") as file:
        lines = file.readlines()

    modified_lines = []
    for line in lines:
        parts = line.strip().split(",")

        if line.startswith("AHR2") and len(parts) > 7:
            lat_index, lon_index = 6, 7  
        elif line.startswith("POS") and len(parts) > 3:
            lat_index, lon_index = 2, 3  
        elif line.startswith("GPS") and len(parts) > 9:
            lat_index, lon_index = 8, 9
        elif line.startswith("ORGN") and len(parts) > 3:
            lat_index, lon_index = 2, 3
        elif line.startswith("TERR") and len(parts) > 4:
            lat_index, lon_index = 3, 4
        elif line.startswith("EAHR") and len(parts) > 3:
            lat_index, lon_index = 2, 3
        else:
            modified_lines.append(line.strip())
            continue  

        old_lat = str(parts[lat_index]).strip()
        old_lon = str(parts[lon_index]).strip()

        try:
            if float(old_lat) == 0.0 or float(old_lon) == 0.0:
                modified_lines.append(line.strip())
                continue
        except ValueError:
            modified_lines.append(line.strip())
            continue

        old_lat_decimal = old_lat[5:] if len(old_lat) > 5 else ""
        old_lon_decimal = old_lon[5:] if len(old_lon) > 5 else ""

        transformed_lat = f"{str(new_lat)[:5]}{old_lat_decimal}"
        transformed_lon = f"{str(new_lon)[:5]}{old_lon_decimal}"

        parts[lat_index] = transformed_lat
        parts[lon_index] = transformed_lon

        modified_lines.append(",".join(parts))

    with open(output_file, "w") as file:
        file.write("\n".join(modified_lines))

    print(f"Transformed file saved: {os.path.basename(output_file)}")

