#!/usr/bin/env python3

import os
import unicodedata

def rename_files(path='.'):
    for root, dirs, files in os.walk(path):
        for filename in files + dirs:
            try:
                if needs_normalization(filename):
                    new_filename = normalize_filename(filename)
                    os.rename(os.path.join(root, filename), os.path.join(root, new_filename))
                    print("Normalised:", filename)
                else:
                    print("Skipped:", filename)
            except Exception as e:
                print("Error:", filename, "due to", str(e))

def needs_normalization(filename):
    for char in filename:
        if ord(char) > 127:
            return True
    return False

def normalize_filename(filename):
    normalized = ""
    for char in filename:
        if ord(char) > 127:
            # Replace Unicode character with closest CP437 equivalent
            cp437_char = unicodedata.normalize('NFKD', char).encode('cp437', 'ignore').decode('cp437')
            normalized += cp437_char
        else:
            normalized += char
    return normalized

rename_files()
