import os
import re

def main():
    current_dir = os.path.dirname(os.path.realpath(__file__))
    map_files = [f for f in os.listdir(current_dir) if f.endswith('.map')]

    for map_file in map_files:
        print(f"Processing file: {map_file}")
        with open(map_file, 'r', encoding='utf-8') as file:
            lines = file.readlines()

        line_changes = []
        num_lines_changed = 0
        num_values_rounded = 0

        for i, line in enumerate(lines):
            match = re.match(r'^(\s*)"origin"\s*"(.*)"', line)
            if match:
                leading_whitespace = match.group(1)
                numbers_str = match.group(2)
                numbers = numbers_str.strip().split()
                original_numbers = numbers.copy()
                rounded_numbers = []

                for num in numbers:
                    try:
                        num_float = float(num)
                        num_rounded = int(round(num_float))
                        rounded_numbers.append(str(num_rounded))
                        num_values_rounded += 1
                    except ValueError:
                        rounded_numbers.append(num)

                new_numbers_str = ' '.join(rounded_numbers)
                new_line = '{}"origin" "{}"\n'.format(leading_whitespace, new_numbers_str)
                line_changes.append((i, line.strip(), new_line.strip()))
                lines[i] = new_line
                num_lines_changed += 1

                print(f"Line {i+1}:")
                print(f"    Original: {line.strip()}")
                print(f"    Changed : {new_line.strip()}")

        print(f"Total lines changed: {num_lines_changed}")
        print(f"Total values rounded: {num_values_rounded}")

        answer = input("Do you want to save the changes? (yes/no): ")
        if answer.lower() in ['yes', 'y']:
            with open(map_file, 'w', encoding='utf-8') as file:
                file.writelines(lines)
            print(f"Changes saved to {map_file}")
        else:
            print("Changes discarded.")

        input("Press Enter to continue...")

if __name__ == "__main__":
    main()
