(defvar yoruba-texifications
  '((?. . "\\d ")
    (?á . "{\\'a}") (?à . "{\\`a}")
    (?Á . "{\\'A}") (?À . "{\\`A}")
    (?é . "{\\'e}") (?è . "{\\`e}")
    (?É . "{\\'E}") (?È . "{\\`E}")
    (?í . "{\\'\\i}") (?ì . "{\\`\\i}")
    (?Í . "{\\'\\I}") (?Ì . "{\\`\\I}")
    (?ó . "{\\'o}") (?ò . "{\\`o}")
    (?Ó . "{\\'O}") (?Ò . "{\\`O}")
    (?ú . "{\\'u}") (?ù . "{\\`u}")
    (?Ú . "{\\'U}") (?Ù . "{\\`U}")
    (?ń . "{\\'n}") (?ǹ . "{\\`n}")
    (?Ń . "{\\'N}") (?Ǹ . "{\\`N}")
    (?{ . "$\\lbrace$") (?} . "$\\rbrace$") (?& . "\\&")))

(defvar hungarian-texifications
  '((?á . "{\\'a}") (?é . "{\\'e}") (?í . "{\\'\\i}")
    (?Á . "{\\'A}") (?É . "{\\'E}") (?Í . "{\\'\\I}")
    (?ó . "{\\'o}") (?ö . "{\\\"o}") (?ő . "{\\H o}")
    (?Ó . "{\\'O}") (?Ö . "{\\\"O}") (?Ő . "{\\H o}")
    (?ú . "{\\'u}") (?ü . "{\\\"u}") (?ű . "{\\H u}")
    (?Ú . "{\\'U}") (?Ü . "{\\\"U}") (?Ű . "{\\H u}")
    (?{ . "$\\lbrace$") (?} . "$\\rbrace$") (?& . "\\&")))

(defun texify (str dictionary)
  (reduce #'concat
          (mapcar (lambda (c)
                    (or (cdr (assoc c dictionary))
                        (string c)))
                  str)))

(defun szotar-next-line ()
  "Takes the next line and prints its TeX representation."
  (if (re-search-forward "^\\(.*\\) = \\(.*\\)$" (point-max) t)
      (let* ((yoruba (match-string 1))
             (definition (match-string 2)))
        (princ (concat (texify yoruba yoruba-texifications) "\n"
                       "\\hfill\n"
                       (texify definition hungarian-texifications)
                       "\\vskip 2pt\\hrule\\vskip 2pt\n"))
        t)
      nil))

(defun szotar-texify ()
  "Generates a plain TeX file from the current buffer.
The buffer is assumed to be in UTF-8 encoding."
  (interactive)
  (with-output-to-temp-buffer (concat (buffer-name (current-buffer)) ".tex")
    (princ (concat "\\magnification=\\magstep2\n"
                   "\\parindent=0pt\n"))
    (save-excursion
      (goto-char (point-min))
      (while (szotar-next-line)))
    (princ "\\bye")))

(defun yoruba-png (str)
  (let ((tmp-base (make-temp-name (concat temporary-file-directory "yoruba-")))
        (original-dir default-directory))
    (with-temp-buffer
      (insert "\\nopagenumbers\n"
              (texify str yoruba-texifications) "\n"
              "\\bye\n")
      (write-region (point-min) (point-max) (concat tmp-base ".tex")))
    (cd temporary-file-directory)
    (shell-command-to-string (concat "tex --halt-on-error " tmp-base ".tex"))
    (shell-command-to-string (concat "dvipng -D 200 -T tight -q* -o "
                                     tmp-base ".png " tmp-base ".dvi"))
    (cd original-dir)
    (concat tmp-base ".png")))

; (shell-command (concat "display " (yoruba-png ".e j.ò.ó")))
; (insert-image (create-image (yoruba-png ".e j.ò.ó")))