(in-package "KPML")

;;; File: lexicons.lisp

(defun ERASE-LEXICON ()
  (setq words nil)
  (clrhash words-of-a-feature)
  (clrhash lexicon) t)

;;;----------------------------------------------------------------------
;;; Following makes a file of newly acquired lexical items...
;;; 1.1 Note the the parameter is changed to be a language
;;; root directory rather than a file as it was prior to 1.1.

(defun MAKE-NEW-LEXICAL-ITEMS-FILE (lg-root-directory)
  (write-lexical-items 
   lg-root-directory *new-lexical-items*)
  (setf *new-lexical-items* nil))


;;; ----------------------------------------------------------------------
;;; Utilities...

(defun subtract-lexicons (lex1 lex2 lex3)
  "Removes from lex1 any words which are in lex2 and writes result to lex3"
  (let (
	(lexicon-pathname-1 (merge-pathnames (pathname (string lex1))
					     (user-homedir-pathname)))
	(lexicon-pathname-2 (merge-pathnames (pathname (string lex2))
					     (user-homedir-pathname)))
	(lexicon-pathname-3 (merge-pathnames (pathname (string lex3))
					     (user-homedir-pathname)))
	(lexicon1 nil)(lexicon2 nil))
    
    (let ((old-lexicon lexicon))
      (unwind-protect
	(block nil
	  (setq lexicon (make-hash-table))
	  (load lexicon-pathname-1)
	  (setq lexicon1 lexicon)
	  (setq lexicon (make-hash-table))
	  (load lexicon-pathname-2)
	  (setq lexicon2 lexicon))
	(setq lexicon old-lexicon)))

    (maphash #'(lambda (key val)
		 (when (gethash key lexicon1)
		   (format t "~%Removing ~a" key))
		 (remhash key lexicon1))
	     lexicon2)
    (with-open-file (lexicon-stream lexicon-pathname-3
				    :direction :output
				    :if-exists :new-version)
      (let ((*standard-output* lexicon-stream))
	(maphash #'(lambda (key val)
		     (declare (ignore key))
		     (print-lexeme val))  ;; 2.0
		 lexicon1)))))

(defun check-lexicons (lex1 lex2 )
  "prints to terminal-io list of words that are spelled the same in lex1 and lex2"
  (let (
	(lexicon-pathname-1 (merge-pathnames (pathname (string lex1))
					     (user-homedir-pathname)))
	(lexicon-pathname-2 (merge-pathnames (pathname (string lex2))
					     (user-homedir-pathname)))
	
	(lexicon1 nil)(lexicon2 nil)
	( spell1 (make-hash-table :test #'equal))
	( spell2 (make-hash-table :test #'equal)))

    (let ((old-lexicon lexicon))
      (unwind-protect
	  (block nil
	    (setq lexicon (make-hash-table))
	    (load lexicon-pathname-1)
	    (setq lexicon1 lexicon)
	    (setq lexicon (make-hash-table))
	    (load lexicon-pathname-2)
	    (setq lexicon2 lexicon))
	(setq lexicon old-lexicon)))

    (maphash
      #'(lambda (key val)
	  (push key (gethash (lexical-item-spelling val) spell1)))
      lexicon1)
    (maphash
      #'(lambda (key val)
	  (push key (gethash (lexical-item-spelling val) spell2)))
      lexicon2)
    (maphash
      #'(lambda (key val)
	  (let ((item (gethash key spell2)))
	    (when item
	      (format t "~%spelling: ~a  lex1:  ~a lex2: ~a" key val item))))
	  spell1)))


