# -*- coding: utf-8 -*-

import os

def make_output_name(input_name):
    base, ext = os.path.splitext(input_name)
    return "%s_cv%s" %(base,ext)

def convert_file(input_file):
    output_file = make_output_name(input_file)

    with open(input_file, "r", encoding="utf-8", newline="") as fin:
        lines = fin.readlines()

    # Header prüfen
    if not lines or (lines[0].strip() != "X;Y;Gültig" and lines[0].strip() != "X;Y;valid"):
        print("Übersprungen (falscher Header): %s" % (input_file))
        return

    x0 = None
    y0 = None

    with open(output_file, "w", encoding="utf-8", newline="\n") as fout:
        # Erste zwei Kopfzeilen überspringen
        for line in lines[2:]:
            line = line.strip()
            if not line:
                continue

            parts = line.split(";")
            if len(parts) != 3:
                continue

            x_str, y_str, valid_str = parts

            if valid_str.strip() != "1":
                continue

            x = float(x_str)
            y = float(y_str)

            # Erster gültiger Punkt → Nullpunkt (nicht schreiben)
            if x0 is None:
                x0 = x
                y0 = y
                continue

            # Relative Werte, beide * 1000
            x_rel = (x - x0) * 1000.0
            y_rel = (y - y0) * 1000.0

            fout.write("%12.8f   %12.8f\n" %(x_rel,y_rel))

    print("Fertig: %s" %(output_file))

def main():
    files = [
        f for f in os.listdir(".")
        if f.lower().endswith(".asc") and "_cv" not in f
    ]

    if not files:
        print("Keine passenden .asc-Dateien gefunden.")
        return

    for file in files:
        convert_file(file)

if __name__ == "__main__":
    main()
