#! /usr/bin/python3

import os

# Jean-Christophe Beumier - GPLv3 - 2022.11.30
# https://www.gnu.org/licenses/gpl-3.0.en.html

print("""This application takes an Atari text-file
and produces UTF-8 coded HTML-page and simple text
Upper bullet / black degree (0xF9) converted to black disc

Ce programme transforme des fichiers de texte issus
d'Atari ST/TT/Falcon en une page HTML et un texte codés en UTF-8
La puce haute (octet 0xF9) devient un disque noir

Atari text file only!""")

fichier =input("Texte à convertir: ")
with open(fichier, "rb") as fd :
  octets =fd.read()

atari ="ÇüéâäàåçêëèïîìäÅÉæÆôöòûùÿöÜ¢£¥ßƒáíóúñÑªº¿⌐¬½¼¡«»ãõØøœŒÀÃÕ¨´†¶©®™ĳĲ"
atari +="אבגדהוזחטיכלמנסעפצקךשתןרםףץ"
atari +="∞∧§αβΓπΣσμτΦθΩδ∮ϕ∈Π≡±≥≤⌠⌡÷≈°●•√ⁿ²³¯"

acc =""
octets +=b" "  # convertit en objet bytes
for i in range(len(octets) -1) :
  rg =octets[i]
  if 31 < rg < 128 :
    acc +=chr(rg)
  elif rg > 127 :
    acc +=atari[rg -128]
  else :
    if rg ==13 and octets[i+1] !=10  : # McClassic and Amiga end-of-line
      acc +="<br>\n"
    if rg ==10 :
      acc +="<br>\n" # Unix and Windows end-of-line, since 13+10 wasn't taken
    if rg ==9 :
      acc +="\t"

utf =acc.replace("<br>", "") # utf-8 plain text
with open(fichier +".utf", "w") as fd :
  fd.write(utf)

acc =acc.replace("●", "<sup>●</sup>") # high bullet

html ="""<!doctype html>
<html lang="fr"><head>
<meta charset="utf-8">
<title>«%s» : lecture UTF-8</title>
<meta name="author" content="www.jchr.be">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head><body>
<h3>Le fichier-texte "Atari"<kbd> %s </kbd>traduit en page HTML codée en UTF-8</h3>
<kbd>
%s
</kbd>
</body></html>""" %(fichier, fichier, acc)


with open(fichier +".html", "w") as fd :
  fd.write(html)

