import shutil, os

ORIJ = r'D:\__sistem__\Masaustu\FikoYT.Yeni.Cag\_yama_tmp\orijinal'


def yedekle(path):
    os.makedirs(ORIJ, exist_ok=True)
    hedef = os.path.join(ORIJ, os.path.basename(path))
    if not os.path.exists(hedef):
        shutil.copy2(path, hedef)


def oku(path):
    with open(path, 'rb') as f:
        b = f.read()
    crlf = b'\r\n' in b
    t = b.decode('utf-8')
    return t.replace('\r\n', '\n'), crlf


def yaz(path, t, crlf):
    if crlf:
        t = t.replace('\n', '\r\n')
    with open(path, 'wb') as f:
        f.write(t.encode('utf-8'))


def bir_kez(t, eski):
    n = t.count(eski)
    if n != 1:
        raise SystemExit('ESLESME HATASI (%d kez): %r' % (n, eski[:70]))


def degistir(t, eski, yeni):
    bir_kez(t, eski)
    return t.replace(eski, yeni)


def aralik_degistir(t, bas, bitis, yeni):
    """bas isaretinin satir basindan, bitis isaretinin satir basina kadar degistirir."""
    bir_kez(t, bas)
    bir_kez(t, bitis)
    i = t.index(bas)
    i = t.rfind('\n', 0, i) + 1
    j = t.index(bitis)
    j = t.rfind('\n', 0, j) + 1
    if j <= i:
        raise SystemExit('SIRA HATASI: %r' % bas[:50])
    return t[:i] + yeni + t[j:]
