# CWzer by Gabriele Battaglia IZ4APU
# Data concepimento 25/5/2022
import sys

# Costants
SUBS = "CWzer_subs.txt"

# variables
changes={}
firstline="# CWzer from IZ4APU, Gabriele Battaglia\n# Format for substitutions is: old=new\n# The symbol '#' is a comment and the line will be ignored.\n# The special character 'X' changes from *old* to *nothing*. E.G.:\n# _=X will remove all the occurrences of _ from the file\n# The special character 'X' must be uppercase.\n"

print("\tCWzer 1.1, may 27th, 2022 by Gabe, IZ4APU.\n\tThis small utility takes a text file and prepare it to be converted\n\tin morse with other apps like Ebook2CW by DJ5CW.")

try:
	f = open(SUBS, "rt", encoding="utf-8")
	rig = f.readlines()
	f.close()
	for r in rig:
		if len(r) > 2 and not r.startswith("#") and r.count("=") > 0:
			if r.startswith("=="):
				a = "="; b=r[r.rfind('=')+1:]
			else:
				a,b=r.split("=",maxsplit=1)
			b=b.replace("\n","")
			a,b = a[:12],b[:12]
			if b == "X": b = ""
			if a not in changes.keys(): changes[a]=b
	print(f"Read {len(changes)} substitutions from file: {SUBS}")
	del rig
except:
	print(f"File {SUBS} not found.\nI'll create a new one, please edit your substitutions on it then relaunch the app.")
	f=open(SUBS, "wt",encoding="utf-8")
	f.write(firstline)
	f.close()
	sys.exit()

fn = input("The document has to be encoded in UTF-8\nfilename.ext to prepare? > ")
try:
	f=open(fn, "rt",encoding="utf-8")
	rig = f.readlines()
	f.close()
	print(f"File: {fn} found, with {len(rig)} lines of text.")
except:
	print(f"Sorry, file: {fn} not found.\nRelaunch the App and try with another filename.")
	sys.exit()

print("Applying substitutions...")
changes_counter = changes.copy()
for k in changes.keys():
	changes_counter[k] = 0
totx = 0; rigp = []
for r in rig:
	p=r
	p=p.replace('\n','')
	for k in changes.keys():
		x = p.count(k)
		if x > 0:
			changes_counter[k] += x
			p=p.replace(k, changes[k])
			totx += x
	rigp.append(p)
fn=fn.replace(".","_CWzed.")
f=open(fn, "wt",encoding="utf-8")
for r in rigp:
	f.write(r+"\n")
f.close()
print("Substitutions report:")
for k,v in changes.items():
	print(f"{k:^12}->{v:^12}={changes_counter[k]:^12}={changes_counter[k]/totx:^12.2%}")

print(f"Prepared file has been saved as: {fn}\n\t73 de IZ4APU.")