# Makefile for the Norwegian dictionary for Ispell v. 2.0
# Copyright (C) 2000, Rune Kleveland, 2005-2006 the spell-norwegian
# maintainers
#
# Maintainer: The spell-norwegian maintainer group
# Email : i18n-no@lister.ping.uio.no
# License : GNU General Public License v2 or later

VERSION         = 2.0.11
PACKAGE         = spell-norwegian

prefix          = /usr
libdir          = $(prefix)/lib
sharedir        = $(prefix)/share
bindir          = $(prefix)/bin
docdir          = $(sharedir)/doc/$(PACKAGE)
wordsdir        = $(sharedir)/dict
ispelldir       = $(libdir)/ispell
myspelldir      = $(sharedir)/myspell/dicts
aspelldir       = $(libdir)/aspell
aspellsharedir  = $(sharedir)/aspell

# Make sure we work with a known locale setting.
export LC_ALL=C

SHELL = /bin/sh
MAKE = make
INSTALL      = install -m 755
INSTALL_DATA = install -m 644

PATHADDER	=	../..
BUILDHASH	=	buildhash
ASPELL          =       aspell
ISPELL          =       ispell
ISPELLAFF2MYSPELL =     ispellaff2myspell
AWK		=	awk
SED		=	ssed
PERL            =       perl

# List of characters used in the thesaurus files
theschars = abcdefghijklmnopqrstuvwxyzæøåABCDEFGHIJKLMNOPQRSTUVWXYZÆØÅ-()\#

ECHO            =       echo

export PATH:=$(PATHADDER):$(PATH)

DOC = \
	COPYING \
	NEWS \
	README \
	README.myspell \
	thesaurus-README.txt

# Files to include in tarball
EXTRA_DIST = \
	$(DOC) \
	ispell-3.1.20.no.patch \
	ispell-3.2.06.no.patch \
	aspell-nb.info.in \
	aspell-nn.info.in \
	aspell-proc.pl \
	aspell-phonet.dat \
	bokmaal \
	forkort-nb.txt \
	forkort-nn.txt \
	inorsk-compwordsmaybe \
	inorsk-hyphenmaybe \
	Makefile \
	Makefile.new \
	nohyphbc.tex \
	nohyphb.tex \
	nb.aff.in \
	nn.aff.in \
	norsk.cfg \
	norsk.words \
	missing.nb \
	rejected-words.nb \
	missing.nn \
	words_clean.nynorsk \
	thesaurus-nb.txt \
	thesaurus-nn.txt \
	nb_NO.myheader \
	nn_NO.myheader \
	iaff2myaff.pl


# Directories to include in tarball
SUBDIRS = \
	missing \
	scripts \
	patterns \
	ooo-hyph

srcdir      := .
distdir     := $(PACKAGE)-$(VERSION)
top_distdir := $(distdir)
DISTFILES    = $(EXTRA_DIST)
TAR          = tar
GZIP_ENV     = --best

# The following variables make it easy to adapt this Makefile to
# numerous languages.
#
LANGUAGE	=	norsk

#
#	Set this to "-vx" in the make command line if you need to
#	debug the complex shell commands.
#
SHELLDEBUG = +vx

# Some technical variables for managing hyphen points and the header

# CATNOHEADER=$(SED) -e '/^\#/ D' -e 's/[	]*\#.*//' ${LANGUAGE}.words
# This command gets the whole file except the comments
CATNOHEADER=grep -v '^\#' ${LANGUAGE}.words
ALPHASUBST=tr '=' 'î'
ALPHASUBSTSED=s/=/î/g
STREKSUBST=tr 'î' '='
STREKSUBSTSED=s/î/=/g
STREKREM=tr -d 'îÎ'
STREKREMSED=s/[îÎ]//g

# What characters and flags do we use for Norwegian?

# Not including dash (-) in LCH and UCH, as - has special meaning in
# regex and need to be listed first and only one.  Adding it to CH
# instead.

LCH=\"a-zæøåéêèóôòçëüäöî
UCH=A-ZÆØÅÉÊÈÓÔÒÇËÜÄÖÎ
CH=-${LCH}${UCH}
PRE=a-s
SUFFNORM=][t-zA-Z^
SUFFCOMP=\\\\\\\`_
SUFF=${SUFFNORM}${SUFFCOMP}
#SUFF=][t-zA-Z\\\\\\\`^_


# The awk scripts below tells which words from in each category that
# should be in the dictionary.  The line

# /^[${LCH}=]{4}\[${SUFF}]/   {if ($$2>4) {print $$1,$$2}}

# says that words with length 4 containing only lowercase letters with
# frequency greater then 5 should be included.  Edit the scripts as
# you like, but please don't make syntactic errors.  Awk forgives
# nothing.  Remember that it is more likely that a mistyping turns out
# to be a legal word if the word is short.  `re' is legal!

# The CHOOSEFLAG script sets the limit for flag inclusion.  Example:
# adgangs-tegn is a common word, but the form adgangstegnenes scores 0
# on frequency.  It will be excluded by the script below if you don't
# change it.

# The CHOOSEROOT script selects the root words to be included after
# the uncommonly used flags have been deleted.  The key used is the
# frequency category of of the union of all words this root and its
# flags generates.

# The reason for the two pass system is that the space required by a
# root word is much bigger than what is required by just a flag.

# You are of course free to change the selection system.

# The B file contains all kinds of words.


CATHEGORIES=B A N M K D O C

# Configuration for the words file.

# The words file is a plain text file containing words in alphabetical
# order.  It is used by ispell via the look/grep programs to display
# words starting with a specific string or matching a specific
# pattern.  It is also useful if one want to make a dictionary for
# some stupid spell-checker in a word processor.

# Lets make this simple.

WORDSFILTER='{if ($$2>=0) {print $$1}}'

# Configuration for building ispell dictionaries.

# The frequency category works best for B, A and N categories.

# Very young people and people which don't speak Norwegian natively
# will probably be much more happy with a smaller dictionary than the
# complete one.  A smaller dictionary should also be considered if the
# machine is low on memory.  Below is a quite advanced system for
# building such dictionaries.

# It is possible to remove all words that is accepted by ispell in
# controlled compoundwords mode with frequency indicator less than
# COMPOUNDLIMIT.  Thus if `naturvern' and `direktorat' are words which
# is marked as allowed in compounds, it might not be nessesary to
# include `naturverndirektorat' in the dictionary.

# However, if one misspells `naturverndirektorat', ispell will not be
# able to make a suggestion for this word.  And one must use the
# controlled compoundwords mode to accept this word, and that is not
# as secure as the -B mode.

# In sum; It is nice if ispell can make a suggestion words like
# `angrefrisperiode', but it consumes space and memory.

COMPOUNDLIMIT=0

# There is a system for selecting words to include in the Ispell
# dictionary.  Unfortunately it is rather complex and not too easy to
# use, but this was what I came up with, so you must use it or invent
# your own.  The good thing is that one can select both flags and
# roots, depending on how the root word looks line and the frequency
# og all forms coming from the flag or the root.

# Somewhere in the long pipe making the input file for buildhash, the
# data looks like
#
# gutte=drøm/ 17
# gutte=drøm/A 18
# gutte=drøm/E 14
# gutte=drøm/G 7
#
# thus the frequenzy indicator for each flag is availiable.  Awk is
# used to pick the flags we want, and the variable holding the program
# is CHOOSEFLAG[CATHEGORY]. Don't throw away the root, since that
# messes things up badly.
#
# Later in the pipe the data looks like
#
# gutte=drøm/17A18E14G7 19
#
# The second field (19) is the frequenzy indicator for all words
# coming from the root gutt.  So here we can throw away a root with
# all its derivied forms if we like.

DEFAULTROOTFILTER='{print $$1,$$2}' # This selects all words in a file

# Don't include all rare words allowed in compounds.

define DEFAULTFLAGFILTER
'!/[${SUFFCOMP}]/      {print $$1,$$2} \
/\/[${SUFFCOMP}]/      {if ($$2>6) {print $$1,$$2}}'
endef

# Select all words by default.  Then override with more elaborate
# rules if desired.

CHOOSEFLAGA=${DEFAULTFLAGFILTER} # `newspaper' words, but very useful.
CHOOSEFLAGB=${DEFAULTFLAGFILTER} # Normal words
CHOOSEFLAGC=${DEFAULTFLAGFILTER} # Sammendragning
CHOOSEFLAGD=${DEFAULTFLAGFILTER} # Words from Dagbladet
CHOOSEFLAGK=${DEFAULTFLAGFILTER} # Conservative writing
CHOOSEFLAGM=${DEFAULTFLAGFILTER} # Words from mathematics
CHOOSEFLAGN=${DEFAULTFLAGFILTER} # Words from NOU
CHOOSEFLAGO=${DEFAULTFLAGFILTER} # Words from technical oil business
CHOOSEFLAGS=${DEFAULTFLAGFILTER} # Samnorsk, radical forms

CHOOSEROOTA=${DEFAULTROOTFILTER} # `newspaper' words, but very useful.
CHOOSEROOTB=${DEFAULTROOTFILTER} # Normal words
CHOOSEROOTC=${DEFAULTROOTFILTER} # Sammendragning
CHOOSEROOTD=${DEFAULTROOTFILTER} # Words from Dagbladet
CHOOSEROOTK=${DEFAULTROOTFILTER} # Conservative writing
CHOOSEROOTM=${DEFAULTROOTFILTER} # Words from mathematics
CHOOSEROOTN=${DEFAULTROOTFILTER} # Words from NOU
CHOOSEROOTO=${DEFAULTROOTFILTER} # Words from technical oil business
CHOOSEROOTS=${DEFAULTROOTFILTER} # Samnorsk, radical forms

# Here is an example of an awk script that excludes some short
# uncommon words, and some long very uncommon words.  It is most
# likely that you want to exclude short uncommon words, since those
# are most likely to be typed by mistake.  Exclude long words to save
# memory.  Also see the COMPOUNDLIMIT variable above if you want to
# make a resource-friendly dictionary.

# define CHOOSEFLAGB
# '/\/[ ${PRE}]/                                  {print $$1,$$2}  \
# /^[${LCH}=]{1,2}\/[${SUFF}]/        {if ($$2>6) {print $$1,$$2}} \
# /^[${LCH}=]{3}\/[${SUFF}]/          {if ($$2>5) {print $$1,$$2}} \
# /^[${LCH}=]{4}\/[${SUFF}]/          {if ($$2>3) {print $$1,$$2}} \
# /^[${LCH}=]{5,7}\/[${SUFF}]/        {if ($$2>1) {print $$1,$$2}} \
# /^[${LCH}=]{8,}\/[${SUFF}]/         {if ($$2>=0) {print $$1,$$2}} \
# /^[${UCH}][${CH}=]{1,2}\/[${SUFF}]/ {if ($$2>4) {print $$1,$$2}} \
# /^[${UCH}][${CH}=]{3}\/[${SUFF}]/   {if ($$2>3) {print $$1,$$2}} \
# /^[${UCH}][${CH}=]{4}\/[${SUFF}]/   {if ($$2>2) {print $$1,$$2}} \
# /^[${UCH}][${CH}=]{5,7}\/[${SUFF}]/ {if ($$2>1) {print $$1,$$2}} \
# /^[${UCH}][${CH}=]{8,}\/[${SUFF}]/  {if ($$2>=0) {print $$1,$$2}}'
# endef

# define CHOOSEROOTB
# '/^[${LCH}=]{1,2}\//       {if ($$2>8) {print $$1,$$2}} \
# /^[${LCH}=]{3}\//          {if ($$2>6) {print $$1,$$2}} \
# /^[${LCH}=]{4}\//          {if ($$2>5) {print $$1,$$2}} \
# /^[${LCH}=]{5,7}\//        {if ($$2>2) {print $$1,$$2}} \
# /^[${LCH}=]{8,}\//         {if ($$2>1) {print $$1,$$2}} \
# /^[${UCH}][${CH}=]{1,2}\// {if ($$2>8) {print $$1,$$2}} \
# /^[${UCH}][${CH}=]{3}\//   {if ($$2>6) {print $$1,$$2}} \
# /^[${UCH}][${CH}=]{4}\//   {if ($$2>3) {print $$1,$$2}} \
# /^[${UCH}][${CH}=]{5,7}\// {if ($$2>2) {print $$1,$$2}} \
# /^[${UCH}][${CH}=]{8,}\//  {if ($$2>1) {print $$1,$$2}}'
# endef

# Try to make it easier to change the OOo2 build variables
# and to make them consistent
TH_NB1 = th_nb_NO
TH_NN1 = th_nn_NO
TH_NB2 = th_nb_NO_v2
TH_NN2 = th_nn_NO_v2
TH_NB1_DICT = 'THES nb NO' $(TH_NB1)
TH_NN1_DICT = 'THES nn NO' $(TH_NN1)
TH_NB2_DICT = 'THES nb NO' $(TH_NB2)
TH_NN2_DICT = 'THES nn NO' $(TH_NN2)



#all: words ispell myspell aspell
all: words ispell
ispell: nb.hash nn.hash nb.aff nn.aff
words: words.nb words.nn

install: install-ispell install-words install-aspell install-myspell install-scripts install-doc

install-doc: $(DOC)
	$(INSTALL) -d $(DESTDIR)$(docdir)
	for d in $(DOC) ; do \
		$(INSTALL_DATA) $$d $(DESTDIR)$(docdir)/$$d ; \
	done

install-ispell: install-ispell-nb install-ispell-nn
install-ispell-nb: nb.hash nb.aff
	$(INSTALL) -d $(DESTDIR)$(ispelldir)
	$(INSTALL_DATA) nb.hash $(DESTDIR)$(ispelldir)/nb.hash
	$(INSTALL_DATA) nb.aff $(DESTDIR)$(ispelldir)/nb.aff
	if true ; then \
	    ln -sf $(ispelldir)/nb.hash $(DESTDIR)$(ispelldir)/bokmaal.hash ; \
	    ln -sf $(ispelldir)/nb.aff $(DESTDIR)$(ispelldir)/bokmaal.aff ; \
	fi
	if true ; then \
	    ln -sf $(ispelldir)/nb.hash $(DESTDIR)$(ispelldir)/norsk.hash ; \
	    ln -sf $(ispelldir)/nb.aff $(DESTDIR)$(ispelldir)/norsk.aff ; \
	fi

install-ispell-nn: nn.hash nn.aff
	$(INSTALL) -d $(DESTDIR)$(ispelldir)
	$(INSTALL_DATA) nn.hash $(DESTDIR)$(ispelldir)/nn.hash
	$(INSTALL_DATA) nn.aff $(DESTDIR)$(ispelldir)/nn.aff
	if true ; then \
	    ln -sf $(ispelldir)/nn.hash $(DESTDIR)$(ispelldir)/nynorsk.hash ; \
	    ln -sf $(ispelldir)/nn.aff $(DESTDIR)$(ispelldir)/nynorsk.aff ; \
	fi

install-words: install-words-nb install-words-nn
install-words-nb: words.nb
	$(INSTALL) -d $(DESTDIR)$(wordsdir)
	$(INSTALL_DATA) words.nb $(DESTDIR)$(wordsdir)/bokmaal
	ln -sf bokmaal $(DESTDIR)$(wordsdir)/bokmål
install-words-nn: words.nn
	$(INSTALL) -d $(DESTDIR)$(wordsdir)
	$(INSTALL_DATA) words.nn $(DESTDIR)$(wordsdir)/nynorsk

install-scripts:  inorsk-compwordsmaybe inorsk-hyphenmaybe
	$(INSTALL) -d $(DESTDIR)$(bindir)
	$(INSTALL) inorsk-compwordsmaybe inorsk-hyphenmaybe $(DESTDIR)$(bindir)

# subst er en intern kommando i make 
# $(subst .hash,.aff,$@ ) betyr  å endre suffikset .hash til .aff for innholdet i variabelen $@
# 
# Det som er under kan skrives om til dette for bokmålsdelene, tilsvarende for nynorskdelen
# nb.hash: nb.mch nb.aff
#	 rm -f $@
#	 buildhash nb.mch nb.aff $@
#
# Det som her egentlig foregår er:
# buildhash nb.mch nb.aff nb.hash
# syntaksen er:
#  buildhash dict-file aff-file hash-file
# dict-file og aff-file må en ha i fra før for å lage hash-file
# dict-file er en liste over ord
# aff-file er en liste over affikser

nb.hash nn.hash: %.hash: %.mch %.aff
	rm -f $@
	${BUILDHASH} $< $(subst .hash,.aff,$@) $@

# nb.aff.in er en suffikstabell
# nb.aff er en redigert versjon av nb.aff.in
# sed komandoen nedenfor fjerner alle forekomster av "stringchar *î *Î" og $(STREKREMSED)
# STREKREMSED=s/[îÎ]//g

nb.aff nn.aff: %.aff: %.aff.in
	$(SED) -e 's/stringchar *î *Î//' -e '$(STREKREMSED)' $< > $@.new && \
	  mv $@.new $@

# Denne oppretter nb.aff.munch ut fra nb.aff.in, tilsvarende for nynorsk
# Forenklet versjon for bokmål:
# nb.aff.munch: nb.aff.in
# idet regulære uttrykket:
# Linje 1: Første linje gjør per i dag ingenting
# Dette gjør linje 2:
# Den erstatter ZYZYZY med en -
#<     Z Y Z Y Z Y    >       -ZYZYZY,ZYZYZY       #- flerezyzyzy > fler-
#---
#>     Z Y Z Y Z Y    >       -ZYZYZY,-       #- flerezyzyzy > fler-
# Linje 3: I linjer som starter med "flag" og har følgende mønster:
# ^flag  *~..\?: så fjernes ~. feks: 
#  < flag ~\\:
#---
# > flag \\:
# Linje 4: Denne erstatter  "compoundwords controlled z"  med  "compoundwords off"
# De 4 nederste linjene er rett og slett å legge linjer på slutten av fila.
nb.aff.munch nn.aff.munch: %.aff.munch: %.aff.in
	( \
	  $(SED) -e 's/\(.*> *[-,${UCH}]*\)    \( *#~.*$$\)/\1XXXX\2 *HACK*/' \
	    -e 's/-ZYZYZY,-\( *#-.*$$\)/-ZYZYZY,ZYZYZY\1/' \
	    -e 's/\(^flag  *\)~\(..\?:\)/\1\2/'  \
	    -e 's/^\(compoundwords\) controlled z/\1 off/' $< ; \
	  $(ECHO) ; \
	  $(ECHO) ; \
	  $(ECHO) 'flag z: # Brukes for å bevare z-flagg gjennom munchlist' ;\
	  $(ECHO) '    .              >       YYYY            # *HACK*' \
	) > $@.new && mv $@.new $@

# strukturen på buildhash-kommandoen som oppretter nb.munch.hash er:
# buildhash [-s] dict-file affix-file hash-file
# -s oppsjonen her betyr bare silent
nb.munch.hash nn.munch.hash: %.munch.hash: %.aff.munch
	echo 'QQQQQQQQ' > FAKEDICT
	${BUILDHASH} -s FAKEDICT $< $@
	rm -f FAKEDICT FAKEDICT.cnt FAKEDICT.stat

# 
# $(SED) -e '/^prefixes.*/,//d' 
# fjerner fra og med linja som begynner med prefix og ut fila
# De to første ECHO-kommandoene legger inn 2 nye linjer i nb.aff.null som på siste echo-linje blir overskrevet
# Disse to første ECHO-kommandoene har derfor ingen hensikt
nb.aff.null nn.aff.null: %.aff.null: %.aff.in
	$(SED) -e '/^prefixes.*/,//d' $< > $@.new
	$(ECHO) 'suffixes' >> $@
	$(ECHO) 'flag *z:' >> $@
	$(ECHO) 'Y Y Y Y Y   >   YYYYYY' >> $@.new
	mv $@.new $@

# The following ugly code munches a part of the base file, keeping the
# indications of the frequency of the words.  It also removes some
# redundant flags that munchlist does not find.  That part could be
# improved.

# munched.% kalles opp der en erstatter tegnet % med et av tegnene i lista $CATHEGORIES
# dette gjøres for å kunne dele opp store ordlistefiler i mindre filer
munched.%: ${LANGUAGE}.words nb.aff.munch nb.munch.hash
# The first pipe produces a list of all words in the % category, with
# each root word followed by one line for each flag containing the
# root word and the flag.  The prefix flags are treated as part of the
# root word, except that there is one line containing just the root
# word (the last bug I catched...) The hyphen character is ignored
# when the list is sorted.  Some redundant flags are also removed.
# Isn't it amazing how much you can do with sed?

# If we try to munch the whole B dictionary in one run, ispell will
# probably dump core.  This happens when one gets `hash overflows'.
# Check the log, and change the splitting (^[${UCH}]) if nessesary.
# Nasty bug, and very silent.

# grep -e '$(subst munched.,,$@)$$' finner frem til de som ender på rett kategorimarkør ( eks. B )
# eks. munched.B fører til at følgende uttrykk:'$(subst munched.,,$@)$$'
# betyr B$
# $(SED) -e 's/ .*//' -e '$(ALPHASUBSTSED)' -e 's/ \*//' gjør 3 ting
# 1) Fjerner alt som starter med mellomrom (metainformasjon)
# 2) Erstatter = tegn med i med topphatt på (dette er ordskillemarkør)
# 3) Fjern alle instanser av " *" ( nynorskmarkører)
# grep '^[${UCH}]' finner alle ord som inneholder store bokstaver
# grep -v '^[${UCH}]' er det motsatte av det ovenfor, altså ord som inneholder utelukkende små bokstaver.
# munchlist komprimerer en liste med ord ved å slå sammen flere av endelsene til en oppføring med ny metainformasjon
	${CATNOHEADER} \
	  | grep -e '$(subst munched.,,$@)$$' \
	  | $(SED) -e 's/ .*//' -e '$(ALPHASUBSTSED)' -e 's/ \*//' \
	  | grep '^[${UCH}]' \
	  | munchlist -v -l nb.aff.munch \
	  > munch1.tmp
	${CATNOHEADER} \
	  | grep -e '$(subst munched.,,$@)$$' \
	  | $(SED) -e 's/ .*//' -e '$(ALPHASUBSTSED)' -e 's/ \*//' \
	  | grep -v '^[${UCH}]' \
	  | munchlist -v -l nb.aff.munch \
	  >> munch1.tmp

## GENERELT
# De følgende linjene baserer seg på den virkelige munch1.tmp
# f.eks. så gjør linje 1 ingenting på en standard endelig fil munch1.tmp
# fordi funksjonene over går i løkke over variablene i CATHEGORIES.
# Den siste av dem er C som blir den endelige temp-filen
# Denne er veldig liten og lite egnet for testing, Endrer man variablene i CATHEGORIES
# kan man få en mere representativ fil. Før å gjøre testingen nedenfor endret vi  CATHEGORIES til bare B, 

## --- Linje 1
# så får vi at linje en endrer f.eks. «waterîgatezyzyzy» til «waterîgatezyzyzy/` »
# linje 2: Bayswater/J --> ----Bayswater/J*Bayswater/J
# linje 3: erstatt * med  \n (linjeskift)
# linje 4: linjer som starter med 4 streker fjern hatt i
# linje 5: erstatter linjeskiftet med ---- eks.
#          ----watergatezyzyzy/`  ----waterîgatezyzyzy/`
# linje 6: sort sorterer linjene i alfabetisk rekkefølge
# linje 7: fjerner alt foran siste oppføring av strekene på hver linje, inkludert strekene selv
#          Dermed blir ingen av ordene dobbeltoppført på samme linje lenger: eks. 
#          før:   ----waterproofene/R ----waterproofene/R
#          etter: waterproofene/R
# linje 8: i ord som slutter på et, og har en stor T etter skråstreken som er foran V, fjern V.
# linje 9: i ord som slutter på e, og har en stor T etter skråstreken som er foran W, fjern W.
# linje 10: i ord som slutter på er, og har en stor I etter skråstreken som er foran V, fjern V.
# linje 11: i ord som slutter på e, og har en stor B etter skråstreken som er foran W, fjern W.
# linje 12: i ord som slutter på um, men ikke har hverken e eller i foran seg,
#           og har en stor B etter skråstreken som er foran I, fjern I.
# linje 13: Dette er et mareritt
# $(SED) -e N -e  # betyr at den slår sammen 2 linjer  
# 's/^ # '^'-tegnet sier at vi skal begynne å sammenligne fra begynnelsen av uttrykket vi sammenligner med
# \(          # her starter første parentes, som inneholder parentes 2 og 3
#   \([${CH}=]\)* # dette er parentes 2, som betyr alle bokstaver og tegnene - og =
# \([^e][^r]\|[e][^r]\|[r][^e]\) # dette er parentes 3, som betyr
#                                # enten ikke e og ikke r, eller e og ikke r, eller r og ikke e.
# \) # her slutter parentes 1
# \/ # dette er tegnet skråstrek
# \([A-Zt-z]*\) # dette er 4. parentes, ordkoden for første linje
# \n # dette er tegnet linjeskift
# \1e # dette betyr at det som er foran tegnet '/' i første linje (som tilsvarer første parentes)
# skal være akkurat det samme i andre linje med bokstaven 'e' på slutten.
# \/ # dette er tegnet skråstrek
# \([A-Zt-z]*\) # første del av ordkoden i andre linje (parentes 5)
# R # tegnet R
# \([A-Zt-z]*\) # andre del av ordkoden i andre linje (parentes 6)
# $$/ # på grunn av make så betyr dette egentlig $/ som igjen betyr at vi må sammenligne 
# til slutten med uttrykket vi sammenligner med
# Heretter begynner vi med sett inn:
# \1\/\4\ # vi setter inn parentes 1, skråstreken og parentes 4
# * # tegnet stjerne settes inn
# \1e # sett inn igjen selve ordet for ord 2 (parentes 1 + e)
# \/\5\6/g' # vi setter inn skråstreken og ordkoden for ord 2 unntatt 'R*

# eksempel
# før:
# fy/CEJKLSVY
# fye/CEJMRSTY
# etter:
# fy/CEJKLSVY*fye/CEJMSTY

# linje 14:
#  sed -e '$$ p' -e '$$ d' -e P -e D
# kommandoen  '$ p' betyr: dupliser siste linje i fila
# kommandoen  '$ d' betyr: slett siste linje i fila
# D og P betyr det samme, men gjelder for situasjoner der 2 og 2 linjer er slått sammem.
# D og P kopierer og sletter dessuten alle linjer, ikke bare den siste.

#linje 15 se linje 3

# linje 16: Et nytt mareritt
# parentes 1 er selve ordet, parentes 3 er ordkoden
# $(SED) -e N -e  # betyr at den slår sammen 2 linjer  
# 's/^ # '^'-tegnet sier at vi skal begynne å sammenligne fra begynnelsen av uttrykket vi sammenligner med
# \(          # her starter første parentes, som inneholder parentes 2
#   \([${CH}=]\)* # dette er parentes 2, som betyr alle bokstaver og tegnene - og =
# parentes 3: \/ er tegnet skråstrek og (\/[AB]*\) betyr A eller B null eller flere ganger
# E betyr tegnet E (som altså fjernes)
# Parentes 4: \(.*\) er hvor mange tegn som helst etter hverandre uten mellomrom.
# \n er et linjeskift, som også fjernes
# \1er er at parentes 1 gjentas med "er" etterpå \/AI er en skråstrek og "AI" 
# Her begynner erstatningsuttrykket:
# \1\3\4\*\1er\/AI:
# parentes 1,3 og 4 settes inn igjen sammen med slutten av uttrykket
# det som tas bort er E og linjeskiftet
# en stjerne legges til etter parentes 4og parentes 
# slutte av uttrykket \1er\/AI settes inn igjen.

# linje 17 se linje 14
# linje 18 se linje 3
# linje 19 erstatt hatt i med likhetstegn, se variabelen STREKSUBSTSED
# linje 20, bytter om det som passer med SUFF og PRE i linja, se variablene SUFF og PRE
# linje 21 parentes 1 og 3 med skråstrek mellom settes inn 2 ganger med tegnet * mellom.
#          parentes 4 blir der den er. Se variablene CH, PRE og SUFF
# linje 22 Dersom en linje eksakt tilfredstiller denne frasen legg til en skråstrek etter uttrykket
# linje 23 se linje 3
# linje 24-26
# :START innleder egentlig en while-løkke der erstatningskommadoen i linje 25 gjentas helt til den ikke finner noe mer
# t START er slutten på denne løkka
# linje 25 parentes 1, 2 og 3 beholdes deretter settes det inn en stjerne, parentes 1, en skråstrek, 
#  parentes 2 og til slutt parentes 4.
# linje 27 parentes 1 skråstrek * foran selve uttrykket
# linje 28 se linje 3. I tillegg skrives resultatet til fila munch2.tmp

	cat munch1.tmp \
	  | $(SED) -e 's/\(zyzyzy\|ZYZYZY\)/\1\/\` /' \
	  | $(SED) -e 's/^\(.*\)$$/----\1\*\1/' \
	  | tr '*' '\n' \
	  | $(SED) -e '/----/ $(STREKREMSED)' \
	  | $(SED) -e N -e 's/\n/ ----/' \
	  | sort  '-t/' -u +0f -1 +0 \
	  | $(SED) -e 's/.*----//' \
	  | $(SED) -e 's/\(et\/.*T.*\)V/\1/' \
		-e 's/\(e\/.*T.*\)W/\1/' \
		-e 's/\(er\/.*I.*\)V/\1/' \
		-e 's/\(e\/.*B.*\)W/\1/' \
		-e 's/\([^ei]um\/.*B.*\)I/\1/' \
	  | $(SED) -e N -e 's/^\(\([${CH}=]\)*\([^e][^r]\|[e][^r]\|[r][^e]\)\)\/\([A-Zt-z]*\)\n\1e\/\([A-Zt-z]*\)R\([A-Zt-z]*\)$$/\1\/\4\*\1e\/\5\6/g' \
		 -e '$$ p' -e '$$ d' -e P -e D \
	  | tr '*' '\n' \
	  | $(SED) -e N -e 's/^\(\([${CH}=]\)*\)\(\/[AB]*\)E\(.*\)\n\1er\/AI/\1\3\4\*\1er\/AI/' \
		-e '$$ p' -e '$$ d' -e P -e D \
	  | tr '*' '\n' \
	  | $(SED) -e '$(STREKSUBSTSED)' \
		-e 's/\/\([${SUFF}]*\)\([${PRE}]*\)/\/\2\1/' \
		-e 's/\(\([${CH}=]\)*\)\/\([${PRE}]*\)\([${SUFF}]\+\)$$/\1\/\3\*\1\/\3\4/' \
		-e 's/^\([${CH}=]*\)$$/\1\/ /' \
	  | tr '*' '\n' \
	  | $(SED) -e ':START' \
		-e 's/^\([${CH}=]\+\)\/\([${PRE}]*\)\([${SUFF}]\+\)\([${SUFF}]\)/\1\/\2\3\*\1\/\2\4/' \
		-e 't START' \
		-e 's/^\([${CH}=]\+\)\/\([${PRE}]\+\)\(\*\|$$\)/\1\/\*\1\/\2\3/'\
	  |  tr '*' '\n' > munch2.tmp
# This pipe produce a file containing the a line number of munch2.tmp and
# the frequency indicator for that line.  Note that the summation rule
# is not the usual one.

#linje 1 slett blanke tegn
#linje 2  -e opsjonen betyr at ordene skrives helt ut fra en komprimert liste med ord
#         -d betyr at det neste som følger er filnavnet
#linje 3   Fjerner først ett tegn som stemmer med variabelen CH eller likhetstegn 
#(dvs. et hvilket sonm helst tegn unntatt mellomrom), ett plusstegn og til slutt ett mellomrom.
# kommando 2: erstatt hatt i med likhetstegn
# linje 4: --source har ingen synlig virkning
#          '{i=0; while (i<NF) {i=i+1;print $$i,NR}}' skriver ut raden + antallet rader lest så langt
# linje 5 leksikalsk sortering
# linje 6 linjer som starer med samme ord sammenslåes, resten droppes
# linje 7 stjerne og mellomrom skal bort
# linje 8 dette betyr at vi bare skal ta med kolonne 2 og 3
# linje 9 numerisk sortering
# linje 10  -e '$$ p' betyr skriv ut siste linje
# kommandoen  '$ p' betyr: dupliser siste linje i fila
# kommandoen  '$ d' betyr: slett siste linje i fila
# D og P betyr det samme, men gjelder for situasjoner der 2 og 2 linjer er slått sammem.
# D og P kopierer og sletter dessuten alle linjer, ikke bare den siste.
# linje 10-12
# :START innleder egentlig en while-løkke der erstatningskommadoen i linje 11 og12gjentas helt til den ikke finner noe mer
# t START er slutten på denne løkka
# -e '$$ ! N' betyr at to og to linjer ikke lenger skal slås sammen
#  linje 11 fjerner duplikater med å slå sammen 2 og 2 linjer
# linje 12, se over 
# linje 13 - 20 
# vi forklarer dette med et eksempel med en talkolonne etter selve ordet
# vi vil i det tilfellet gå en gang gjennom while-løkken og
# i vil alltid ha verdien 2 og $i vil alltid ha verdien til kolonne 2 
# hvis verdien til kolonne 2 er mindre enn 5 så vil ikke else i while-løkka slå til.
# Etter while løkken så sjekkes verdien av tallet, høye tall blir skalert ned
# til slutter skriver han ut linjen og beholder heltallsverdien av tallet

# Poenget med denne beregningen under er å beregne statistisk informasjon om forekomsten av hvert enkelt ord
# Resultatet lagres som et løpenummer som representerer ordet og tilhørende frekvens
           
	cat munch2.tmp \
	  | tr -d ' ' \
	  | ispell -e -d ./nb.munch.hash \
	  | $(SED) -e 's/^[${CH}=]\+ //' -e '$(STREKSUBSTSED)' \
	  | $(AWK) --source '{i=0; while (i<NF) {i=i+1;print $$i,NR}}' \
	  | sort \
	  | join - ${LANGUAGE}.words \
	  | $(SED) -e 's/\* //' \
	  | cut -d ' ' -f2,3 \
	  | sort -n \
	  | $(SED) -e '$$ p' -e '$$ D' -e ':START' -e '$$ ! N' \
		-e 's/^\([0-9]\+\)\([0-9 ]\+\)\n\1\( [0-9]\+\)$$/\1\2\3/' \
		-e 't START' -e P -e D \
	  | $(AWK) --source '\
		{i = 1;\
		s = 0;\
		{while (i<NF)\
		{i=i+1;\
		if ($$i<5) {s=s+$$i} else {s = s + exp(exp(($$i+9)/15)-1)}}};\
		if (s<=5) {t=s} else {t=-9+15*log(1+log(s))};\
		print $$1, int(t)}' \
	  > munch3.tmp
# This pipe produce the file containing the munched list of words,
# where the rare words we don't want are removed.  What we don't want
# depends on the category of words, and is defined at the start of
# this Makefile.

# linje 0 cat -n betyr at linjenummer skrives først på hver linje
# linje 1 
#      "For  each  pair of input lines with identical join fields, write a line
#       to standard output.  The default join field is the first, delimited  by
#       whitespace.   When FILE1 or FILE2 (not both) is -, read standard input."

#       Her slår en ordet sammen med den statistiske informasjonen. 
# linje 2 betyr at en fjerner linjenummerne foran, 
#         dermed sitter vi igjen med en ordliste med bare selve ordene og den statistiske informasjonen
# linje 3 --re-interval er for å muliggjøre bruke av intervalluttrykk
#         --source er for å gjøre det mulig å blande forskjellige biblioteker
#      
#           subst er en intern kommando i make 
#           $(subst munched.,CHOOSEFLAG,$@ ) betyr  å endre prefikset munched. til CHOOSEFLAG for innholdet i variabelen $@
# linje 4 uniq fjerner dobbeltoppføringer
# linje 5 slett blanke tegn
# linje 6 se linje 10 i den over
# linje 7
# mønster:'s/^\(\([${CH}=]\)\+\)\/\([0-9]*\)\n\1\/\([${SUFF}${PRE}0-9]*\)$$/ 
# erstatning: \1\/\3\4/' 
# vi ser at linjeskiftet fjernes
# linje 8
# mønster: 's/^\(\([${CH}=]\)\+\/\)\([0-9]*\)\([${PRE}]*\)\([${SUFF}0-9]*\)\n\1\4\([${SUFF}0-9]\+\)$$/
# erstatning: \1\3\4\5\6/' \
# den fjerner  gjentagelsen av parentesuttrykk 1 og 4 og linjeskiftet før dem ( \n\1\4\ fjernes ). 
# linje 9 dette er sluttdelen av løkka, se nærmere beskrivelse over
# linje 10 erstatningen er lik mønsteret stjernetegn mellomrom parentesuttrykk 1 (som er mønsteret minus første skråstrek)
# linje 11 erstatter '*' med linjeskift
# linje 12 der hvor et mellomrom etterfølges av ett eller flere tegn,
#          og ikke etterfølges av et tall, men av ett plusstegn: erstatt med mellomrom.
	cat -n munch2.tmp \
	  | join - munch3.tmp \
	  | cut -d ' ' -f2,3 \
	  | $(AWK) --re-interval --source ${$(subst munched.,CHOOSEFLAG,$@)} \
	  | uniq \
	  | tr -d ' ' \
	  | $(SED) -e '$$ p' -e '$$ D' -e ':START' -e '$$ ! N' \
		-e 's/^\(\([${CH}=]\)\+\)\/\([0-9]*\)\n\1\/\([${SUFF}${PRE}0-9]*\)$$/\1\/\3\4/' \
		-e 's/^\(\([${CH}=]\)\+\/\)\([0-9]*\)\([${PRE}]*\)\([${SUFF}0-9]*\)\n\1\4\([${SUFF}0-9]\+\)$$/\1\3\4\5\6/' \
		-e 't START' -e P -e D \
	  | $(SED) -e 's/\/\([${SUFF}0-9${PRE}]*\)/\/\1\* \1/' \
	  | tr '*' '\n' \
	  | $(SED) -e '/ .*/ s/[^0-9 ]\+/ /g' \
	  | $(SED) -e N -e 's/\n//' \
	  | $(AWK) --source '\
		{i = 1;\
		s = 0;\
		{while (i<NF)\
		{i++;\
		if ($$i<5) {s=s+$$i} else {s = s + exp(exp(($$i+9)/15)-1)}}};\
		if (s<=5) {t=s} else {t=-9+15*log(1+log(s))};\
		print $$1, int(t)}' \
	  | $(AWK) --re-interval --source ${$(subst munched.,CHOOSEROOT,$@)} \
	  | uniq \
	  > $@
#	Comment out the next line if you are debugging.
	rm munch[123].tmp


nb.mch: forkort-nb.txt $(patsubst %,munched.%,${CATHEGORIES}) nb.aff
# Here we make the dictionary that is read by the ispell's buildhash
# program.  The main difficulty is to delete compound words with
# frequency indicator less than COMPOUNDLIMIT accepted in controlled
# compoundwords mode.

# First make a list of words with some compound flag, and a hash-file.
	cat forkort-nb.txt $(patsubst %,munched.%,${CATHEGORIES}) \
	  | tr -d '\=0-9 ' \
	  | grep "\/.*[z\\_\`]" \
	  > comp1.tmp
	$(BUILDHASH) comp1.tmp nb.aff comp.hash

# Make a list of candidates to be removed.  Exclude all words with
# compound flags and those with frequency indicator bigger than
# COMPOUNDLIMIT.  This could be improved.  One could insist that the
# words forming a word that should be deleted are separated by a
# hyphen at the correct point.  That would complicate things.

	cat -n forkort-nb.txt $(patsubst %,munched.%,${CATHEGORIES}) \
	  | grep -v "\/.*[z\\_\`]" \
	  | $(AWK) --source '/=/ {if ($$3<${COMPOUNDLIMIT}) {print $$1,$$2,$$3}}' \
	  > comp2.tmp
# Test which words are accepted by ispell.  Output is a list of line
# numbers indicating the lines that can be removed from the munched
# file.
	cat comp2.tmp \
	  | tr -d '\=0-9 ' \
	  | ispell -e -d ./comp.hash \
	  | $(SED) -e 's/$$/ xyxyxyxy/' \
	  | ispell -l -d ./comp.hash \
	  | $(SED) -e 's/xyxyxyxy/î/' \
	  | tr '\nî' ' \n' \
	  | paste comp2.tmp - \
	  | grep '	 $$' \
	  | $(SED) -e 's/ .*//' \
	  > comp3.tmp
	@echo Removing `cat comp3.tmp | wc -l` compound root words
# Remove all the line numbers that is found twice, and all words
# containing xxxx and yyyy.  Those words didn't fit in in the munching,
# and since it is few words I don't want to fiddle with them.
	cat -n forkort-nb.txt $(patsubst %,munched.%,${CATHEGORIES}) \
	  | sort -n -m -s +0 -1  comp3.tmp - \
	  | $(SED) -e '/^[0-9]\+$$/,/.*/ D' -e '/\(xxxx\|yyyy\)\// D' \
	  | tr -d '\= 	0-9' \
	  | LC_COLLATE=C sort > $@
	rm -f comp.hash comp[123].tmp*

# TODO:
# If a rare word lies close to a common word, it might be wise to
# remove it from the dictionary.  One possible way is to use a patched
# version of ispell that tries to find matches for all words, also
# those in the dictionary.  Then find the frequency for those words,
# and produce a closeness index from this.  This shouldn't be too hard
# to implement.  The patch for the required ispell flag (-s) is only
# a few lines.  The trickery to use it is more.




nn.mch: ${LANGUAGE}.words nn.aff.munch forkort-nn.txt
	${CATNOHEADER} \
	  | grep '\*' \
	  | $(SED) -e 's/ .*//' \
	  | tr -d '=' \
	  | munchlist -v -l nn.aff.munch \
	  | cat forkort-nn.txt - \
	  | $(SED) -e N -e 's/^\(\([${CH}=]\)*\)er\/\(.*F.*\)\n\1rar\/M$$/\1er\/\3D/' \
		-e '$$ p' -e '$$ d' -e P -e D \
	  | LC_COLLATE=C sort > $@.new && mv $@.new $@

words.nb: ${LANGUAGE}.words
# Here is a rule to make a list of the most common Norwegian words.
# Which words to include is defined at the top of this Makefile.  Such
# a file is needed to make the word competition work for Norwegian.
# Stupid spell checkers might also want such a file.

# grep '[BANDS]$$' finner alle linjer som slutter på enten B, A, N, D eller S.
# $$ gjøres om til en enkelt $ av make når det sendes til bash
# Dermed får vi bare med bokmålsord og ikke nynorskordene.

# tr -d '*' fjerner '*' fra alle linjer

# $(AWK) --re-interval --source ${WORDSFILTER} betyr: skriv ut første kolonne av 
# alle linjer med minst to kolonner.

# tr -d '\"=' fjerner likhetstegn som er en plassholder for ordskille

# yyyy   Word is allowed as first part of a compound word, and all its
#        derived forms are allowed as the second part.
# xxxx   Word allowed as first part of a compound word.
# zyzyzy Word allowed as first part of a compound word, but not alone.

# grep -v '\(xxxx\|yyyy\|zyzyzy\)' tar alle ord unntatt de tre kategoriene som er beskrevet ovenfor.

# sort -f sorterer ordene alfabetisk uavhengig av store og små bokstaver

# $@ betyr argumentet på venstre side av kolontegnet
# det vil si words.nb

	${CATNOHEADER} \
	  | grep '[BANDS]$$' \
	  | tr -d '*' \
	  | $(AWK) --re-interval --source ${WORDSFILTER} \
	  | tr -d '\"=' \
	  | grep -v '\(xxxx\|yyyy\|zyzyzy\)' \
	  | sort -f \
	  > $@.new && mv $@.new $@

words.nn: ${LANGUAGE}.words
# No frequency information availiable yet for nynorsk.  So all we can
# do is poick the words marked with a star.
# grep '\*' velger ut alle linjer som inneholder en stjerne
# det vil si nynorske ord
# $(SED) -e 's/ .*//' fjerner alt etter første blanke tegn på en linje

	${CATNOHEADER} \
	  | grep '\*' \
	  | $(SED) -e 's/ .*//' \
	  | tr -d '\"=' \
	  | grep -v '\(xxxx\|yyyy\|zyzyzy\)' \
	  | sort -f \
	  > $@.new && mv $@.new $@

# Here is a target that picks words with given frequency.
#  Denne trengs ikke foreløpig
#words.${LANGUAGE}.%: #${LANGUAGE}.words
#	${CATNOHEADER} \
#	  | grep '[BANDS]$$' \
#	  | grep  ' $(patsubst words.${LANGUAGE}.%,%,$@) ' \
#	  | $(SED) -e 's/ .*//' \
#	  | tr -d = \
#	  | grep -v '\(xxxx\|yyyy\|zyzyzy\)' \
#	  | sort -f \
#	  > $@.new && mv $@.new $@


