#!/usr/bin/env ruby
 #
 # This file is part of the Anotatornia suite.
 # 
 # Copyright © 2007, 2008, 2009, 2010 by Instytut Podstaw Informatyki
 # Polskiej Akademii Nauk (IPI PAN; Institute of Computer Science, Polish
 # Academy of Sciences; cf. www.ipipan.waw.pl).  All rights reserved.
 # 
 # This file may be distributed and/or modified under the terms of the
 # GNU General Public License version 3 as published by the Free Software
 # Foundation and appearing in the file COPYING included in the packaging
 # of this file.  (See http://www.gnu.org/licenses/translations.html for
 # unofficial translations.)
 # 
 # A commercial license is available from IPI PAN (contact
 # Michal.Ciesiolka.waw.pl or ipi.waw.pl for more
 # information).  Licensees holding a valid commercial license from IPI
 # PAN may use this file in accordance with that license.
 # 
 # This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
 # THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 # PURPOSE.
 #

#
# written 2007/08/08 and 2007/09/12 by natror
# rewritten for NKJP on 2009/01/14–2010/2/28 by natror.

require 'date'
require 'ftools' # for File.copy etc.

require 'jcode' # doesn't redefine String functions but defines its own
$KCODE="UTF8" # or "UTF8" to be verbose

OUT_m = '/ann_morphosyntax.xml'
OUT_seg = '/ann_segmentation.xml'
OUT_wsd = '/ann_senses.xml'

class Array
  
  def iterate_nonnil( meth, &block )
    self.send( meth ) { |elt| block.call( elt ) if elt }
  end # of #{iterate_nonnil}
  
  def collect_nonnil( &block )
    self.iterate_nonnil( :collect, &block )
  end # of #{collect_nonnil}
  
  def each_nonnil( &block )
    self.iterate_nonnil( :each, &block )
  end # of #{each_nonnil}
  
end # of #{class Array}


# Dla każdej ścieżki wytworzymy w~niej właśnie parę plików \file{annkh_segmentation.xml} oraz \file{annkh_morphosyntax.xml}, zawierających wyniki anotacji, tj. wszystkie i~tylko zaanotowane akapity w~formacie \ac{TEI}.

$exclusive = true unless defined?( $exclusive )
puts "exclusiveness  is set to #{$exclusive}"

if $exclusive
  Akapit.connection.execute " pragma locking_mode = exclusive "
end

if defined?( $arg202 )
  if $arg202.kind_of?( Range )
    $akapit_range = $arg202
  elsif $arg202.kind_of?( Regexp )
    $path_regexp = $arg202
  elsif $arg202.kind_of?( Array )
    $path_ids = $arg202
  end
end # of oporządzenie argumentu sowy


if UNatrora.x and not defined?( $akapit_range ) and 
    not defined?( $path_regexp ) and 
    not defined?( $path_ids )
  $akapit_range = 41..47
end

AMinId = Akapit.minimum( :akapit_id )
AMaxID = Akapit.maximum( :akapit_id )

$akapit_range = AMinId..AMaxID unless defined?( $akapit_range )
unless defined?( $path_regexp )
  $path_regexp = //
end

AAntiRange = ( AMinId - 10 )..( AMinId - 10 )

def ara( p199 )
  $ara = $akapit_range & ( p199.akapit_range || AAntiRange ) 
  # przecięcie zakresów jest zdefiniowane w \file{ramkowanie.rb}
end

if defined?( $path_ids )
  $paths = [ Path.find( $path_ids[0] ) ].flatten
else
  $paths = Path.find_all.collect { |p|
    if p.path_text =~ $path_regexp
      p
    end
  }.compact
end

$leafs = $paths.collect { |p|
  if ara( p )
    z = Akapit.zaanotowane( :morphosyntactic, 
                            :where => " akapit.akapit_id between " +
                            " #{$ara.min} and #{$ara.max} " )
    if z[0] ## and $path_regexp =~ p.path_text
      # drugi warunek sprawdzony na początku
      [ p.path_text, z]
    else nil
    end
  else nil
  end
}.compact
  


puts Path.count
puts "3levs leafs: #{$leafs.size}"

# sleep 5


## puts $paths.join("\n")

WYPL = ("/tmp/wypluwka_" + `date +%F-%H%M`).chomp


puts WYPL

# sleep 5

`mkdir #{WYPL}`
` cp header.dtd #{WYPL} `
`cp NKJP_1M_header.xml #{WYPL}`

##require 'rubygems'
require 'builder' # , '~> 2.0'


 # File lib/builder/xmlmarkup.rb, line 198
class   Builder::XmlMarkup
  def comment!( comment_text )
    _ensure_no_block block_given?
    _special("<!-- ", " -->", 
             if comment_text.respond_to?( :gsub )
               comment_text.gsub('--', '\-\-')
             else comment_text
             end, nil)
    # my (GM) modification is this #{gsub}: double hyphen is not allowed in \ac{XML} comments and that's how we circumvent it.
  end
end



# inicjujemy buildery dla każdego pliku


class String
  def unescaped
    if self.length > 0 : self.intern else self end
    ##    self.to_xs( false ) wrong number of arguments (1 for 0)
  end # of #unescaped

##  def to_xs(escape=false)
##    unpack('U*').map {|n| n.xchr(escape)}.join # ASCII, UTF-8
##  rescue
##    unpack('C*').map {|n| n.xchr}.join # ISO-8859-1, WIN-1252
##  end


end # of #{class String}

$builder_proc = Proc.new { |target| 
  Builder::XmlMarkup.new( :target =>target, :indent =>1 )
}

  resp_seg, resp_sent, resp_m = nil, nil, nil

$pisz_string = Proc.new { |target, treść|
  target.__send__( :_indent )
  target << "<string>#{treść}</string>\n" # zawartość stringów ma być nieeskejpowana, bo została wyeskejpowana przy wlaniu danych do bazy. Podwójny cudzysłów nie wymaga uniku (sprawdzone przez MW 2010/2/17).
}


tokproc_morph = Proc.new { |b, tok| 
  attrs = { "xml:id" => "morph_#{tok.morphosyntactic_xmlid}-seg", 
    "xlink:href" => "ann_segmentation.xml#segm_#{tok.segmentation_xmlid}-seg" }
  ##  raise  'attrs[ "nkjp:rejected" ] = "true"' unless tok.chosen?
  
  if tok.chosen?
    
    b.seg( attrs.to_xml_attr_alpha ) { |b|
      b.fs( :type => "morph" ) { |b|
        b.f( :name => "orth" ) { |b|
          ##        b.string { |x| x << tok.orth }## 
          $pisz_string.call( b, tok.orth )
        } # #{</f>} [orth]
        b.comment!( # method modified by me (GM) in this file
                   tok.fs_morph_comment )# #{<!-- Nie [0,3] -->}
        
        if tok.ns_poprzedza?
          ## <f name="nps"><binary value="true"/></f>
          b.f( :name => "nps") { |b| b.binary( :value => "true" ) }
        end # of if nps
        
        b.f( :name => "interps" ) { |b|
          tok.lex_msd.each { |lex| # to jest tablica interpretacyj jednego leksemu, wzbogaconych o lematy i klasa_gram_ozn.
            
            ## <fs type="lex" xml:id="morph_1.1.1-lex">
            b.fs( {:type => "lex", "xml:id" => "morph_#{lex[0].lex_xmlid}-lex" # lex_xmlid bierzemy z #{interpretacja}, a nie z #{leksem}, bo w #{interpretacja} jest osobny dla każdej instancji (dla każdego \ac{XML}\dy owego eltu #{lex}.
                  }.to_xml_attr_alpha ) { |b|
            ## <f name="base">
              b.f( :name => "base" ) { |b|
                ## <string>nie</string>
                $pisz_string.call( b, lex[0].lemat # bierzemy msd-opis pierwszej z tych interpretacyj, czyli dowolnej z nich.
                                   )
              } # #{</f>} [base]
              ## <f name="ctag">
              b.f( :name => "ctag" ) { |b|
                ## <symbol value="conj"/>
                b.symbol( :value => if kg = lex[0].klasa_gram_ozn : kg.unescaped else raise( "@@@@ exml.rb l.149: klasa gramatyczna nie śmie być nieznana!")  end )
              }# #{</f>} [ctag]
              ## <f name="msd">
              b.f( :name => "msd" ) { |b|
                ## <symbol value="NULL" xml:id="morph_1.1.1.1-msd"/>
                msd_proc = Proc.new { |int|
                  int_attrs = {  :value => if rt = int.reszta_tagu : rt.unescaped else "" end, # ze względów technicznych wygodniej nam puste reszty tagu przechowywać jako Nulle, ale to nie oznacza naszej bazodanowej niewiedzy, tylko pustość takiej reszty tagu.
                    "xml:id" => "morph_#{int.msd_xmlid}-msd" }
                  int_attrs[ "nkjp:manual" ] = "true" if int.dodana?
                  b.symbol( int_attrs.to_xml_attr_alpha )
                } # of #{msd_proc}
                
                if lex.size == 1
              msd_proc.call( lex[0] )
                else
                  b.vAlt { |b|
                    lex.each { |l| msd_proc.call( l ) }
                  } # #{</vAlt>}
                end
              }# #{</f>} [msd]
            } # #{</fs>} [lex]
        } # of each lex
        }# of #{</f>} [interps]
        
        if di = tok.the_disambiguation
          ## <f name="disamb">
          b.f( :name => "disamb" ) { |b|
            ## <fs type="tool_report">
            b.fs( :type => "tool_report" ) { |b|
              ## <f name="tool"><string>Anotatornia v. X</string></f>
              b.f( :name => "tool" ) { |b| 
                $pisz_string.call(  b, "Anotatornia #{AnoVersion.export_text}" )
            }
              ## <f name="date"><string>15 stycznia 2009</string></f>
              b.f( :name => "date" ) { |b| 
                $pisz_string.call( b,  di.updated_at.to_s( :db ) ) 
              }
              ## <f name="resp"><string>Anotatorka Anotatorska</string></f>
              b.f( :name => "resp" ) {|b| 
                $pisz_string.call( b, resp_m )
              }
              ## <f name="choice" fVal="#morph_1.1.3.1-msd"/>
              b.f( {:name => "choice", :fVal =>"#morph_#{di.msd_xmlid}-msd"}.to_xml_attr_alpha )
            } # #{</fs>} [tool_report]
          } # #{</f>} [disamb]
        end # of #{if disambiguation}
      
      } # #{</fs>} [morph]
    }# #{</seg>}
    
  end # of if token is chosen    
} #of #{tokproc_morph}

  
tokproc_seg = Proc.new { |b, tok|
  ## 	<seg xml:id="segm_648.45-seg"><xi:include href="text.xml" xpointer="string-range(txt_648.1-ab,278,6)"/></seg>   <!-- Junior -->

  attrs = { "xml:id" => "segm_#{tok.segmentation_xmlid}-seg" }
  attrs[ "nkjp:rejected" ] = "true" unless tok.chosen?
  attrs[ "nkjp:nps" ] = "true" if tok.ns_poprzedza?
  
  b.seg( attrs.to_xml_attr_alpha ) { |b|
    b.xi( :include,  {:href => "text.xml", :xpointer => tok.xpointer # #{.to_s.gsub('–','-')}# gsub zapewne  niepotrzebne po migracji 50, ale nie na pewno.
          }.to_xml_attr_alpha  )
    # w pierwszym podejściu użyłem metody #{__send__}:
    ##      b.__send__( 'xi:include'  {:href => "text.xml", :xpointer => tok.xpointer} )
  } # #{</seg>}
  b.comment!( # method modified by me (GM) in this file
             tok.orth )
}# of #tokproc_seg


# Let the hunt begin

Token.popraw_xpointery_nullowe


$i=0

$leafs.each { |lea|
  puts "Kopiuję oryginały"
  skop = "cp -prL --parents  #{lea[0]} #{WYPL}/"
  # L jest aby podążało za linkami symbolicznymi.
  puts skop
  ` #{skop}`

  upto_root = '../' * lea[0].split('/').size

  ` rm -f   #{WYPL}/#{lea[0]}/header.dtd`
  ` rm -f  #{WYPL}/#{lea[0]}/NKJP_1M_header.xml`
  ` ln -s #{upto_root}header.dtd #{WYPL}/#{lea[0]}`
  ` ln -s #{upto_root}NKJP_1M_header.xml #{WYPL}/#{lea[0]}`

  

  ##  ` chmod -R +w #{WYPL}/#{lea[0]}`

  puts "ann_segmentation w ścieżce #{lea[0]}"

  # #{$trees3 = Hash.new} przechowywanie tych drzew w pamięci wydłużało wypluwkę.
  
  File.open( WYPL + '/' + lea[0] + OUT_seg, 'w' ) { |s|
    s.puts '<?xml version="1.0" encoding="UTF-8"?>
<?oxygen RNGSchema="NKJP_segmentation.rng" type="xml"?>'
    
    $xseg = $builder_proc.call( s )

    puts "Wypisuję segmentation"

    ## <teiCorpus xmlns:xi="http://www.w3.org/2001/XInclude" xmlns="http://www.tei-c.org/ns/1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:nkjp="http://www.nkjp.pl/ns/1.0">
      ## <xi:include href="NKJP_header-main.xml"/> obsoleted 2009/7/9
    ## <xi:include href="NKJP_1M_header.xml"/>
    ## <TEI>


    $xseg.teiCorpus( { 
                       "xmlns:xi" => "http://www.w3.org/2001/XInclude",
                       "xmlns" => "http://www.tei-c.org/ns/1.0",
                       "xmlns:xlink" => "http://www.w3.org/1999/xlink",
                       "xmlns:nkjp" => "http://www.nkjp.pl/ns/1.0"
                     }.to_xml_attr_alpha ) { |b|
      b.xi( :include,  :href =>"NKJP_1M_header.xml" ) 
      b.TEI {|b|
        ## <xi:include href="header.xml"/>
        b.xi( :include, :href =>"header.xml" )
        ##  <text xml:id="segm_text" xml:lang="pl">
        b.text( "xml:id" => "segm_text", "xml:lang"=> "pl" ) {|b|
          ##  <body xml:id="segm_body">
          b.body( "xml:id" => "segm_body" ) { |b|
            lea[1].each {|aka|
              tree = aka.tree3levels
              #   #{$trees3[ aka.id ] = tree}  żeby nie liczyć po raz drugi przy morfoskładni, bo to operacja dość kosztowna  — o dziwo wydłużało.
              segmid = "segm_#{aka.segmentation_xmlid}-p"
              ## <!-- morph_1-p is paragraph 54 in batch 10 -->
              b.comment!( # modified earlier in this file
                         "#{segmid} is akapit #{aka.id} with instances (akapit_transzy-s) #{aka.atrids_join} in batches (transza-s) #{aka.trids_join} resp." )
              ## <p xml:id="segm_1-p" xlink:href="text.xml#txt_1.1-ab">
              b.p( {"xml:id" => segmid, 
                     "xlink:href" => aka.segmentation_xlink_href.gsub( '–', '-') }.to_xml_attr_alpha ) { |b|
                tree.each { |s| # ident. jest numer
                  b.s( "xml:id" => "segm_#{s[-1].segmentation_xmlid}-s" ) { |b|
                    s.each { |x|
                      if x.kind_of?( Token )
                        tokproc_seg.call( b, x )
                      else # #x jest typu #SgChoice
                        b.choice { |b|
                          x.sg_variant.each{ |v|
                            ts = v.token
                            if ts.size == 1
                              tokproc_seg.call( b, ts[0] )
                            else
                              attribs = {}
                              attribs[ "nkjp:rejected" ] = true unless ts[0].chosen?
                              b.nkjp( :paren, attribs ) { |b|
                                ts.each { |t|
                                  tokproc_seg.call( b, t )
                                } # of each token of a~variant
                              } # #{</nkjp:paren>}
                            end
                          }# of each segmentation variant
                        } # #{</choice>}
                      end
                    } # of each element of a~sentence
                  } # #{</s>}
                } # of each sentence      
              }#  #{</p>}
              
            } # of each akapit
          }# </body>
        }# </text>
      }# </TEI>
    }# </teiCorpus>
  } # of segmentation file.

  puts "Wypisuję morphosyntactic"
  
  
  File.open( WYPL + '/' + lea[0] + OUT_m, 'w' ) { |m|
    m.puts '<?xml version="1.0" encoding="UTF-8"?>
<?oasis-xml-catalog catalog="catalog.xml"?>
<?oxygen RNGSchema="NKJP_morphosyntax.rng" type="xml"?>
<!-- w indeksach elementów wciąganych mogą zdarzyć się nieciągłości (z alternatyw segmentacyjnych)  -->'
    $xmorph = $builder_proc.call(m)    

    ##   <teiCorpus xmlns:xi="http://www.w3.org/2001/XInclude" xmlns="http://www.tei-c.org/ns/1.0"     
    ##    xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:nkjp="http://www.nkjp.pl/ns/1.0">
    $xmorph.teiCorpus( {"xmlns:xi" => "http://www.w3.org/2001/XInclude",
                       "xmlns" => "http://www.tei-c.org/ns/1.0",
                       "xmlns:xlink" => "http://www.w3.org/1999/xlink",
                         "xmlns:nkjp" => "http://www.nkjp.pl/ns/1.0"}.to_xml_attr_alpha ) {|b|
      ## <xi:include href="NKJP_header-main.xml"/>
      b.xi( :include, :href => "NKJP_1M_header.xml" )
      b.TEI { |b|
        b.xi( :include, :href => "header.xml" )
        b.text { |b|
          b.body { |b|
           
            lea[1].each { |aka|
              # #{tree = $trees3[ aka.id ]}  wydłużało
              tree = aka.tree3levels # aka.tree2levels # spowalniało. dlaczego????
              resp_seg, resp_sent, resp_m = aka.responsibles3levels

              morphid = "morph_#{aka.morphosyntactic_xmlid}-p"

              b.comment!( # modified earlier in this file
                         "#{morphid} is akapit #{aka.id} with instances (akapit_transzy-s) #{aka.atrids_join} in batches (transza-s) #{aka.trids_join} resp." )


              b.p( "xml:id" => morphid ) { |b|
                tree.each { |s| 
                  # xml:id zdania to ms-xmlid ostatniego jego tokenu
                  b.s( {"xml:id" => "morph_#{s[-1].morphosyntactic_xmlid}-s",
                       "xlink:href" => "ann_segmentation.xml#segm_#{s[-1].segmentation_xmlid}-s" 
                       }.to_xml_attr_alpha ) { |b|
                    s.each { |x| 
                      if x.kind_of?( Token )
                        tokproc_morph.call( b, x )
                      else # #x jest typu #SgChoice
                        ## b.choice { |b|
                        # morphosyntax nie śmie zawierać <choice>'ów.
                        x.sg_variant.each{ |v|
                          ts = v.token
                          attribs = {}
                          ##                              attribs[ "nkjp:rejected" ] = "true" unless ts[0].chosen?
                          ## b.nkjp( :paren, attribs ) { |b|
                          ts.each { |t|
                            tokproc_morph.call( b, t ) if t.chosen?
                          } # of each token of a~variant
                          ## } # #{</nkjp:paren>}
                        }# of each segmentation variant
                        ## } # #{</choice>}
                      end

                      # w drzewie 2-poziomowym to zawsze jest token, a w wypluwce ma nie być choice'ów. Ale wariant z drzewem 2-poziomowym działa wolniej. Dlaczego?
##                      if x.kind_of?( Token )
##                        tokproc_morph.call( b, x )
##                      else
##                        raise "nie token: #{x.inspect}!"
##                      end
                    } # of each element of a~sentence
                  } # #{</s>}
                } # of each sentence      
              }#  #{</p>}
              
            } # of each akapit
               
          }# </body>
        }# </text>
      }# </TEI>
    }# </teiCorpus>
  } # of morphosyntactic file

}# of a leaf


puts "Wypisuję word_senses"

$leafs = $paths.collect { |p|
  if ara( p )
    z = Akapit.zaanotowane( :word_senses,
                            :where => " akapit.akapit_id between " +
                            " #{$ara.min} and #{$ara.max} and " +
                            " exists (select interpretacja_id from interpretacja i " +
                            " inner join token tok using( token_id ) " +
                            " where i.disamb='t' and i.cz_m_leksem_id is not null " +
                            " and tok.akapit_id=akapit.akapit_id)"
                            )
    if z[0] 
      [ p.path_text, z]
    else nil
    end
  end
}.compact

puts Path.count
puts "wsd leafs: #{$leafs.size}"

$leafs.each { |lea|
  File.open( WYPL + '/' + lea[0] + OUT_wsd, 'w' ) { |sen|
    sen.puts  '<?xml version="1.0" encoding="UTF-8"?>
<?oasis-xml-catalog catalog="catalog.xml"?>
<?oxygen RNGSchema="NKJP_senses.rng" type="xml"?>'
    ## <?xml version="1.0" encoding="UTF-8"?>
    ##<?oxygen RNGSchema="NKJP_senses.rng" type="xml"?>
    
    $xsens = $builder_proc.call( sen )    
    
    ## <teiCorpus xmlns:xi="http://www.w3.org/2001/XInclude" xmlns="http://www.tei-c.org/ns/1.0" 
    ##  xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:nkjp="http://www.nkjp.pl/ns/1.0">
    $xsens.teiCorpus( {"xmlns:xi" => "http://www.w3.org/2001/XInclude",
                         "xmlns" => "http://www.tei-c.org/ns/1.0",
                         "xmlns:xlink" => "http://www.w3.org/1999/xlink",
                         "xmlns:nkjp" => "http://www.nkjp.pl/ns/1.0"}.to_xml_attr_alpha ) {|b|
      ## <xi:include href="NKJP_1M_header.xml"/>    
      b.xi( :include, :href => "NKJP_1M_header.xml" )
      ## <TEI>
      b.TEI { |b|
        ##  <xi:include href="header.xml"/>
        b.xi( :include, :href => "header.xml" )
        ##  <text xml:lang="pl">
        b.text( "xml:lang" => "pl") { |b|
          b.body { |b|
            lea[1].each { |aka|
              tree = aka.tree_word_senses
              resp_wsd = aka.responsibles_word_senses
## <p xml:id="senses_1-p" xlink:type="simple" xlink:href="ann_segmentation.xml#segm_1-p">               
              p_id = "senses_#{aka.morphosyntactic_xmlid}-p"

              b.comment!( # modified earlier in this file
                         "#{p_id} is akapit #{aka.id} with instances (akapit_transzy-s) #{aka.atrids_join} in batches (transza-s) #{aka.trids_join} resp." )

              b.p( "xml:id" => p_id ) { |b|
                tree.each { |s|              
                  ##     <s xml:id="senses_1.2-s" xlink:type="simple" xlink:href="ann_segmentation.xml#segm_1.1-s">
                  # xml:id zdania jak dla morfoskładni. Tym razem id końca zdania mamy na końcu tablicy #{s}. 
                  kz = s.delete_at(-1)
                  b.s( {"xml:id" => "senses_#{kz.morphosyntactic_xmlid}-s",
                         "xlink:href" => "ann_segmentation.xml#segm_#{kz.segmentation_xmlid}-s" 
                       }.to_xml_attr_alpha ) { |b|
                    s.each {|tok197| # tym razem wiemy, że to token
                      ## <seg xml:id="senses_1.2.1-seg" xlink:href="ann_segmentation.xml#segm_1.1-seg"> 
                      sens_xmlid = if sens197 = tok197.the_sens
                                     sens197.xmlid
                                   else
                                     ActiveRecord::Base.logger.info "!!!!!!! akapit #{aka.id}, token #{tok197.id} nie ma ozn. sensu !!!!!"
                                     "NULL"
                                   end
                      
                      b.seg(  {
                                "xml:id" => "senses_#{tok197.morphosyntactic_xmlid}-seg", 
                                "xlink:href" => 
                                "ann_segmentation.xml#segm_#{tok197.segmentation_xmlid}-seg"
                              }.to_xml_attr_alpha ) { |b|
                        ## <!-- AP: we don't repeat orth here. -->
                        b.comment!( # modified earlier in this file
                                   tok197.fs_morph_comment )# #{<!-- ważnegomu [0,3] -->}
                        ##       <fs type="sense">
                        b.fs( :type => "sense" ) { |b|
                          ##        <f name="sense" fVal="NKJP_WSI.xml#zostac.2"/>
                          b.f( { :name => "sense",
                                 :fVal => "NKJP_WSI.xml##{sens_xmlid}" }.
                               to_xml_attr_alpha )
                        } # #{</f>} [sense]
                      }# #</seg>
                    } # of each senseful token
                  }# #</s>
                }# of each senseible sentence
              }# #</p>
            }# of each #{lea[1]} czyli akapit sensibilny
          }# #</body>
        }# #</text>
      }# #</TEI>
    }# #</teiCorpus>
  }# of file
}# of each leaf of the tree.  

puts `chmod -R og+rX #{WYPL}`

puts "Wypisane zostało: #{Time.now.to_s( :db )}"
true

if $exclusive
  Akapit.connection.execute " pragma locking_mode = normal "
  exit
end
