#encoding: utf-8
#- Name: SiSU
#
#  - Description: documents, structuring, processing, publishing, search
#    xhtml
#
#  - Author: Ralph Amissah
#    <ralph.amissah@gmail.com>
#
#  - Copyright: (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
#    2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2019,
#    2020, 2021, Ralph Amissah,
#    All Rights Reserved.
#
#  - License: GPL 3 or later:
#
#    SiSU, a framework for document structuring, publishing and search
#
#    Copyright (C) Ralph Amissah
#
#    This program is free software: you can redistribute it and/or modify it
#    under the terms of the GNU General Public License as published by the Free
#    Software Foundation, either version 3 of the License, or (at your option)
#    any later version.
#
#    This program is distributed in the hope that it will be useful, but WITHOUT
#    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
#    FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
#    more details.
#
#    You should have received a copy of the GNU General Public License along with
#    this program. If not, see <http://www.gnu.org/licenses/>.
#
#    If you have Internet connection, the latest version of the GPL should be
#    available at these locations:
#    <http://www.fsf.org/licensing/licenses/gpl.html>
#    <http://www.gnu.org/licenses/gpl.html>
#
#    <http://www.sisudoc.org/sisu/en/manifest/gpl.fsf.html>
#
#  - SiSU uses:
#    - Standard SiSU markup syntax,
#    - Standard SiSU meta-markup syntax, and the
#    - Standard SiSU object citation numbering and system
#
#  - Homepages:
#    <http://www.sisudoc.org>
#
#  - Git
#    <https://git.sisudoc.org/projects/>
#    <https://git.sisudoc.org/projects/sisu>
#    <https://git.sisudoc.org/projects/sisu-markup>
module SiSU_XHTML_EPUB2
  begin
    require 'pstore'
  rescue LoadError
    SiSU_Utils::CodeMarker.new(__LINE__,__FILE__,:fuchsia).
      error('pstore NOT FOUND (LoadError)')
  end
  require_relative 'se_hub_particulars'                 # se_hub_particulars.rb
    include SiSU_Particulars
  require_relative 'xml_shared'                         # xml_shared.rb
    include SiSU_XML_Munge
  require_relative 'xhtml_table'                        # xhtml_table.rb
  require_relative 'xhtml_epub2_format'                 # xhtml_epub2_format.rb
    include SiSU_XHTML_EPUB2_Format
  require_relative 'xhtml_epub2_segments'               # xhtml_epub2_segments.rb
    include SiSU_XHTML_EPUB2_Seg
  require_relative 'xhtml_epub2_tune'                   # xhtml_epub2_tune.rb
    include SiSU_XHTML_EPUB2_Tune
  require_relative 'xhtml_epub2_concordance'            # xhtml_epub2_concordance.rb
  require_relative 'xhtml_epub2_persist'                # xhtml_epub2_persist.rb
  class Source
    def initialize(opt)
      @opt=opt
      @particulars=SiSU_Particulars::CombinedSingleton.instance.get_all(opt)
    end
    def read
      begin
        songsheet
      ensure
        Dir.chdir(@opt.f_pth[:pth])
      end
    end
    def songsheet
      begin
        @md=@particulars.md
        @fnb=@md.fnb
        @env=@particulars.env
        unless @opt.act[:quiet][:set]==:on
          tool=(@opt.act[:verbose][:set]==:on \
          || @opt.act[:verbose_plus][:set]==:on \
          || @opt.act[:maintenance][:set]==:on) \
          ? "#{@env.program.epub_viewer} #{@md.file.output_path.epub.dir}/#{@md.file.base_filename.epub}"
          : "[#{@opt.f_pth[:lng_is]}] #{@opt.fno}"
          (@opt.act[:verbose][:set]==:on \
          || @opt.act[:verbose_plus][:set]==:on \
          || @opt.act[:maintenance][:set]==:on) \
          ? SiSU_Screen::Ansi.new(
              @opt.act[:color_state][:set],
              'EPUB',
              tool
            ).green_hi_blue
          : SiSU_Screen::Ansi.new(
              @opt.act[:color_state][:set],
              'EPUB',
              tool
            ).green_title_hi
          if (@opt.act[:verbose_plus][:set]==:on \
          || @opt.act[:maintenance][:set]==:on)
            SiSU_Screen::Ansi.new(
              @opt.act[:color_state][:set],
              @opt.fns,
              "#{@md.file.output_path.epub.dir}/#{@md.file.base_filename.epub}"
            ).flow
          end
        end
        @env.processing_path.epub_bld #(@md)
        @env.processing_path.epub_cp_images(@md)
        data=nil
        SiSU_Env::FileOp.new(@md).mkdir.output.epub
        @tuned_file_array=SiSU_XHTML_EPUB2::Source::XHTML_Environment.new(@particulars).tuned_file_instructions
        data=@tuned_file_array
        per=SiSU_XHTML_EPUB2::Source::Toc.new(@md,data).songsheet
        data=@tuned_file_array
        SiSU_XHTML_EPUB2::Source::ScrollHeadAndSegToc.new(@md,per).in_common #watch
        SiSU_XHTML_EPUB2::Source::Seg.new(@md,data).songsheet
        SiSU_XHTML_EPUB2::Source::Output.new(@md).songsheet
      rescue
        SiSU_Errors::Rescued.new($!,$@,@opt.selections.str,@opt.fns).location do
          __LINE__.to_s + ':' + __FILE__
        end
      ensure
        unless (@opt.act[:verbose_plus][:set]==:on \
        || @opt.act[:maintenance][:set]==:on)
          texfiles=Dir["#{@env.processing_path.tune}/#{@opt.fns}*"]
          texfiles.each do |f|
            if FileTest.file?(f)
              File.unlink(f)
            end
          end
        end
        SiSU_Env::Clear.new(@opt.selections.str,@opt.fns).param_instantiate
        @@flag,@@scr,@@seg,@@seg_endnotes,@@seg_subtoc={},{},{},{},{}
        @@tracker=0
        @@seg_name,@@seg_name_html,@@seg_subtoc_array,@@seg_endnotes_array,@@tablefoot=Array.new(5){[]}
        @@filename_seg,@@seg_url,@@to_lev4,@@get_hash_to,@@get_hash_fn='','','','',''
      end
    end
    private
    class XHTML_Environment
      def initialize(particulars)
        @particulars=particulars
        @md,@env=particulars.md,particulars.env
        @env,@css=particulars.env,SiSU_Style::CSS.new
      end
      def directories
        SiSU_Env::FileOp.new(@md).mkdir.output.epub
      end
      def tuned_file_instructions
        @tell=SiSU_Screen::Ansi.new(@md.opt.act[:color_state][:set])
        directories
        ao_array=@particulars.ao_array # ao file drawn here
        @tuned_file_array=SiSU_XHTML_EPUB2_Tune::Tune.new(ao_array,@md).songsheet
        @tuned_file_array
      end
    end
    class Endnotes
      include SiSU_XHTML_EPUB2_Format
      def initialize(md,data)
        @md,@data=md,data
      end
      def scroll
        @scr_endnotes=[]
        @data.each do |dob|
          pg=dob.dup
          unless pg.is ==:code
            if pg.obj =~/(?:#{Mx[:en_a_o]}|#{Mx[:en_b_o]})[\d*+]+ /
              endnote_array=[]
              if pg.obj=~/#{Mx[:en_a_o]}[\d*+].+?#{Mx[:en_a_c]}/m
                endnote_array = pg.obj.scan(/#{Mx[:en_a_o]}[\d*+]+(.+?)#{Mx[:en_a_c]}/m)
              end
              if pg.obj=~/#{Mx[:en_b_o]}[\d*]+\s.+?#{Mx[:en_b_c]}/m
                endnote_array = pg.obj.scan(/#{Mx[:en_b_o]}[\d*]+(.+?)#{Mx[:en_b_c]}/m)
              end
              if pg.obj=~/#{Mx[:en_b_o]}[\d+]+\s.+?#{Mx[:en_b_c]}/m
                endnote_array = pg.obj.scan(/#{Mx[:en_b_o]}[\d+]+(.+?)#{Mx[:en_b_c]}/m)
              end
              endnote_array.flatten.each do |note|
                txt_obj={ txt: note }
                format_scroll=SiSU_XHTML_EPUB2_Format::FormatScroll.new(@md,txt_obj)
                @scr_endnotes << format_scroll.endnote_body
              end
            end
          end
        end
        @scr_endnotes
      end
    end
    class Toc
      @@seg_url=''
      @@firstseg=nil
      def initialize(md=nil,data='')
        @md,@data=md,data
        @epub=SiSU_XHTML_EPUB2_Format::HeadInformation.new(@md)
        @tell=SiSU_Screen::Ansi.new(@md.opt.act[:color_state][:set]) if @md
        @make=SiSU_Env::ProcessingSettings.new(@md)
        @per=SiSU_XHTML_EPUB2_Persist::PersistTOC.new
      end
      def songsheet #extracts toc for scroll & seg
        begin
          if (@md.opt.act[:verbose][:set]==:on \
          || @md.opt.act[:verbose_plus][:set]==:on \
          || @md.opt.act[:maintenance][:set]==:on)
            SiSU_Screen::Ansi.new(
              @md.opt.act[:color_state][:set],
              'Toc'
            ).txt_grey
          end
          toc=nil
          @@firstseg=nil
          SiSU_XHTML_EPUB2_Persist::PersistTOC.new.persist_init
          md_opf_a_content,md_opf_a_spine,md_opf_a_guide=[],[],[]
          @nav_no=0
          @s_a_no,@s_b_no,@s_c_no,@s_d_no,@lv5_no,@lv6_no=0,0,0,0,0,0
          @per.ncx << @epub.toc_ncx.open #epub ncx navmap
          @per.ncx << @epub.toc_ncx.head_open << @epub.toc_ncx.head << @epub.toc_ncx.head_close
          @per.ncx << @epub.toc_ncx.doc_title << @epub.toc_ncx.doc_author
          @per.ncx << @epub.toc_ncx.navmap_open
          @per.opf << @epub.metadata_opf.package_open
          @per.opf << @epub.metadata_opf.metadata
          @per.opf << @epub.metadata_opf.manifest_open
          @per.seg << %{<div class="content">\n<div class="substance">}
          @per.scr << %{<div class="content">\n<div class="substance">}
          if defined? @md.make.cover_image \
          and @md.make.cover_image.is_a?(Hash) \
          and @md.make.cover_image[:cover] =~/\S+/
            md_opf_a_content << @epub.metadata_opf.manifest_cover_image_information(@md)
            md_opf_a_spine << @epub.metadata_opf.spine_cover_image
            md_opf_a_guide << @epub.metadata_opf.guide_cover_image
          end
          md_opf_a_content << @epub.metadata_opf.manifest_content_sisu_toc
          if @make.build.toc?
            md_opf_a_spine << @epub.metadata_opf.spine_sisu_toc
            md_opf_a_guide << @epub.metadata_opf.guide_sisu_toc
          end
          @ncxo=[false,false,false,false,false,false,false]
          @dob_toc2,@dob_toc3=nil,nil
          @ncx_cls=[]
          @level_a_first_occurrence=true
          @data.each do |dob|
            if dob.is==:heading \
            || dob.is==:heading_insert
              dob_toc=dob.dup
              toc=case dob_toc.ln
              when 0
                @s_a_no +=1
                lv_name='section_a' + @s_a_no.to_s
                @nav_no+=1
                @nav_no2=@nav_no
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[7]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[6]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[5]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[4]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[3]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[2]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[1]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[0]
                @ncxo[0],@ncxo[1],@ncxo[2],@ncxo[3],@ncxo[4],@ncxo[5],@ncxo[6],@ncxo[7]=
                  true,  false,   false,   false,   false,   false,   false,   false
                @epub.sections(dob_toc,lv_name)
                if @level_a_first_occurrence \
                && @make.build.toc?
                  @per.ncx << @epub.toc_ncx.navmap_sisu_toc(@nav_no) #epub ncx navmap, toc
                  @nav_no+=1
                  @level_a_first_occurrence=false
                end
                @per.ncx << @epub.toc_ncx.navpoint(dob_toc,@nav_no,lv_name) if dob_toc
                md_opf_a_content << @epub.metadata_opf.manifest_content(dob_toc,lv_name)
                md_opf_a_spine << @epub.metadata_opf.spine(dob_toc,lv_name)
                md_opf_a_guide << @epub.metadata_opf.guide(dob_toc,lv_name)
                SiSU_XHTML_EPUB2::Source::Toc.new(@md,dob_toc).level_0
              when 1
                @s_b_no +=1
                lv_name='section_b' + @s_b_no.to_s
                @nav_no+=1
                @nav_no2=@nav_no
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[7]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[6]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[5]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[4]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[3]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[2]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[1]
                @ncxo[1],@ncxo[2],@ncxo[3],@ncxo[4],@ncxo[5],@ncxo[6],@ncxo[7]=
                  true,  false,   false,   false,   false,   false,   false
                @epub.sections(dob_toc,lv_name)
                @per.ncx << @epub.toc_ncx.navpoint(dob_toc,@nav_no,lv_name) if dob_toc
                md_opf_a_content << @epub.metadata_opf.manifest_content(dob_toc,lv_name)
                md_opf_a_spine << @epub.metadata_opf.spine(dob_toc,lv_name)
                md_opf_a_guide << @epub.metadata_opf.guide(dob_toc,lv_name)
                SiSU_XHTML_EPUB2::Source::Toc.new(@md,dob_toc).level_1
              when 2
                @s_c_no +=1
                lv_name='section_c' + @s_c_no.to_s
                @nav_no+=1
                @nav_no2=@nav_no
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[7]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[6]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[5]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[4]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[3]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[2]
                @ncxo[2],@ncxo[3],@ncxo[4],@ncxo[5],@ncxo[6],@ncxo[7]=
                  true,  false,   false,   false,   false,   false
                @epub.sections(dob_toc,lv_name)
                @per.ncx << @epub.toc_ncx.navpoint(dob_toc,@nav_no,lv_name) if dob_toc
                md_opf_a_content << @epub.metadata_opf.manifest_content(dob_toc,lv_name)
                md_opf_a_spine << @epub.metadata_opf.spine(dob_toc,lv_name)
                md_opf_a_guide << @epub.metadata_opf.guide(dob_toc,lv_name)
                SiSU_XHTML_EPUB2::Source::Toc.new(@md,dob_toc).level_2
              when 3
                @s_d_no +=1
                lv_name='section_d' + @s_d_no.to_s
                @nav_no+=1
                @nav_no3=@nav_no
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[7]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[6]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[5]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[4]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[3]
                @ncxo[3],@ncxo[4],@ncxo[5],@ncxo[6],@ncxo[7]=
                  true,  false,   false,   false,   false
                @epub.sections(dob_toc,lv_name)
                @per.ncx << @epub.toc_ncx.navpoint(dob_toc,@nav_no,lv_name) if dob_toc
                md_opf_a_content << @epub.metadata_opf.manifest_content(dob_toc,lv_name)
                md_opf_a_spine << @epub.metadata_opf.spine(dob_toc,lv_name)
                md_opf_a_guide << @epub.metadata_opf.guide(dob_toc,lv_name)
                SiSU_XHTML_EPUB2::Source::Toc.new(@md,dob_toc).level_3
              when 4
                @ncx_cls=[]
                lv_name=dob_toc.name
                @nav_no+=1
                @dob_name=dob.name
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[7]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[6]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[5]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[4]
                @ncxo[4],@ncxo[5],@ncxo[6],@ncxo[7]=
                  true,  false,   false,   false
                @per.ncx << @epub.toc_ncx.navpoint(dob_toc,@nav_no,lv_name) if dob_toc
                md_opf_a_content << @epub.metadata_opf.manifest_content(dob_toc,lv_name)
                md_opf_a_spine << @epub.metadata_opf.spine(dob_toc,lv_name)
                md_opf_a_guide << @epub.metadata_opf.guide(dob_toc,lv_name)
                SiSU_XHTML_EPUB2::Source::Toc.new(@md,dob_toc).level_4
              when 5
                @ncx_cls=[]
                hashtag='#o' + dob_toc.ocn.to_s
                lv_name=@dob_name
                @nav_no+=1
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[7]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[6]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[5]
                @ncxo[5],@ncxo[6],@ncxo[7]=
                  true,  false, false
                @per.ncx << @epub.toc_ncx.navpoint(dob_toc,@nav_no,lv_name,hashtag) if dob_toc
                md_opf_a_content << @epub.metadata_opf.manifest_content(dob_toc,lv_name,hashtag)
                md_opf_a_spine << @epub.metadata_opf.spine(dob_toc,lv_name,hashtag)
                md_opf_a_guide << @epub.metadata_opf.guide(dob_toc,lv_name,hashtag)
                SiSU_XHTML_EPUB2::Source::Toc.new(@md,dob_toc).level_5
              when 6
                @ncx_cls=[]
                hashtag='#o' + dob_toc.ocn.to_s
                lv_name=@dob_name
                @nav_no+=1
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[7]
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[6]
                @ncxo[6],@ncxo[7]=
                  true,  false
                @per.ncx << @epub.toc_ncx.navpoint(dob_toc,@nav_no,lv_name,hashtag) if dob_toc
                md_opf_a_content << @epub.metadata_opf.manifest_content(dob_toc,lv_name,hashtag)
                md_opf_a_spine << @epub.metadata_opf.spine(dob_toc,lv_name,hashtag)
                md_opf_a_guide << @epub.metadata_opf.guide(dob_toc,lv_name,hashtag)
                SiSU_XHTML_EPUB2::Source::Toc.new(@md,dob_toc).level_6
              when 7
                @ncx_cls=[]
                hashtag='#o' + dob_toc.ocn.to_s
                lv_name=@dob_name
                @nav_no+=1
                @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[7]
                @ncxo[7]=true
                @per.ncx << @epub.toc_ncx.navpoint(dob_toc,@nav_no,lv_name,hashtag) if dob_toc
                md_opf_a_content << @epub.metadata_opf.manifest_content(dob_toc,lv_name,hashtag)
                md_opf_a_spine << @epub.metadata_opf.spine(dob_toc,lv_name,hashtag)
                md_opf_a_guide << @epub.metadata_opf.guide(dob_toc,lv_name,hashtag)
                SiSU_XHTML_EPUB2::Source::Toc.new(@md,dob_toc).level_7
              else nil
              end
              toc.each do |k,d|
                d.gsub!(/(?:#{Mx[:en_a_o]}.+?#{Mx[:en_a_c]}|#{Mx[:en_b_o]}.+?#{Mx[:en_b_c]})\s*/m,' ')
              end if toc
              if @@firstseg.nil? \
              and dob.ln==4 \
              and dob.name =~/\S+/
                @@firstseg=dob.name
              end
              if toc
                begin
                  @per.seg << toc[:seg]
                  @per.scr << toc[:seg]
                rescue
                  SiSU_Errors::Rescued.new($!,$@,@md.opt.selections.str,@md.fns).location do
                    __LINE__.to_s + ':' + __FILE__
                  end
                end
              end
            end
          end
          @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[6]
          @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[5]
          @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[4]
          @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[3]
          @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[2]
          @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[1]
          @per.ncx << @epub.toc_ncx.navpoint_close if @ncxo[0]
          @ncxo[0],@ncxo[1],@ncxo[2],@ncxo[3],@ncxo[4],@ncxo[5],@ncxo[6]=false,false,false,false,false,false,false
          md_opf_a_content << @epub.metadata_opf.manifest_images(@md.ec[:image])
          @per.seg << "</div>\n</div>"
          @per.scr << "</div>\n</div>"
          @per.ncx << @epub.toc_ncx.navmap_close
          @per.ncx << @epub.toc_ncx.close
          @per.opf << md_opf_a_content << @epub.metadata_opf.manifest_close
          @per.opf << @epub.metadata_opf.spine_open << md_opf_a_spine << @epub.metadata_opf.spine_close
          @per.opf << @epub.metadata_opf.guide_open << md_opf_a_guide << @epub.metadata_opf.guide_close
          @per.opf << @epub.metadata_opf.package_close
          @per.opf=@per.opf.flatten
          SiSU_XHTML_EPUB2::Source::Output.new(@md,@per.opf).epub_metadata_opf
          SiSU_XHTML_EPUB2::Source::Output.new(@md,@per.ncx).epub_toc_ncx
          @md.firstseg=@@firstseg
          @per
        ensure
          SiSU_XHTML_EPUB2_Persist::Persist.new.persist_init
        end
      end
    protected
      def level_0
        dob=@data
        linkname=dob.obj.gsub(/#{Mx[:en_a_o]}.+?#{Mx[:en_a_c]}|#{Mx[:en_b_o]}.+?#{Mx[:en_b_c]}/,'').strip
        link=dob.ocn
        title=linkname
        toc={}
        txt_obj={ txt: title }
        format_toc=SiSU_XHTML_EPUB2_Format::FormatToc.new(@md,txt_obj)
        toc[:seg]=format_toc.lev1
        title=if dob.ocn ==0 then linkname
        else
          @per.scr <<  '<br />'
          link=(dob.ln) \
          ? dob.ln
          : ''
          %{<b><a href="##{link}">#{linkname}</a></b>}
        end
        txt_obj={ txt: title }
        format_toc=SiSU_XHTML_EPUB2_Format::FormatToc.new(@md,txt_obj)
        toc[:scr]=format_toc.lev1
        toc
      end
      def level_1
        dob=@data
        linkname=dob.obj.gsub(/#{Mx[:en_a_o]}.+?#{Mx[:en_a_c]}|#{Mx[:en_b_o]}.+?#{Mx[:en_b_c]}/,'').strip
        link=dob.ocn
        title=if dob.obj !~/Document Information/
          linkname
        else
          link='metadata'
          %{<b><a href="#{link}#{Sfx[:epub_xhtml]}">#{linkname}</a></b>}
        end
        toc={}
        txt_obj={ txt: title }
        format_toc=SiSU_XHTML_EPUB2_Format::FormatToc.new(@md,txt_obj)
        toc[:seg]=if dob.name =~/^meta/ \
        and dob.obj =~/Document Information/ #check
          format_toc.lev0
        else format_toc.lev1
        end
        title=if dob.ocn ==0
          if dob.name =~/^meta/ \
          and dob.obj =~/Document Information/
            %{<a href="#docinfo">#{linkname}</a>}
          else linkname
          end
        else
          @per.scr <<  '<br />'
          link=(dob.ln) \
          ? dob.ln
          : ''
          %{<b><a href="##{link}">#{linkname}</a></b>}
        end
        txt_obj={ txt: title }
        format_toc=SiSU_XHTML_EPUB2_Format::FormatToc.new(@md,txt_obj)
        toc[:scr]=if dob.name =~/^meta/ \
        and dob.obj =~/Document Information/
          format_toc.lev0
        else format_toc.lev1
        end
        toc
      end
      def level_2
        dob=@data
        linkname=dob.obj.gsub(/#{Mx[:en_a_o]}.+?#{Mx[:en_a_c]}|#{Mx[:en_b_o]}.+?#{Mx[:en_b_c]}/,'').strip
        ocn=dob.ocn
        if ocn \
        and ocn !~/#/
          p_num=SiSU_XHTML_EPUB2_Format::ParagraphNumber.new(@md,ocn)
        end
        txt_obj={ txt: linkname }
        format_toc=SiSU_XHTML_EPUB2_Format::FormatToc.new(@md,txt_obj)
        toc={}
        toc[:seg]=format_toc.lev2
        if p_num
          title=%{#{p_num.goto}#{linkname}</a>}
          txt_obj={ txt: title }
          format_toc=SiSU_XHTML_EPUB2_Format::FormatToc.new(@md,txt_obj)
          toc[:scr]=format_toc.lev2
        end
        toc
      end
      def level_3
        dob=@data
        linkname=dob.obj.gsub(/#{Mx[:en_a_o]}.+?#{Mx[:en_a_c]}|#{Mx[:en_b_o]}.+?#{Mx[:en_b_c]}/,'').strip
        ocn=dob.ocn
        if ocn \
        and ocn !~/#/
          p_num=SiSU_XHTML_EPUB2_Format::ParagraphNumber.new(@md,ocn)
        end
        txt_obj={ txt: linkname }
        format_toc=SiSU_XHTML_EPUB2_Format::FormatToc.new(@md,txt_obj)
        toc={}
        toc[:seg]=format_toc.lev3
        if p_num
          title=%{#{p_num.goto}#{linkname}</a>}
          txt_obj={ txt: title }
          format_toc=SiSU_XHTML_EPUB2_Format::FormatToc.new(@md,txt_obj)
          toc[:scr]=format_toc.lev3
        end
        toc
      end
      def level_4
        dob=@data
        linkname=dob.obj.gsub(/#{Mx[:en_a_o]}.+?#{Mx[:en_a_c]}|#{Mx[:en_b_o]}.+?#{Mx[:en_b_c]}/,'').strip
        ocn=dob.ocn
        p_num=SiSU_XHTML_EPUB2_Format::ParagraphNumber.new(@md,ocn) if ocn
        if dob.ln==4
          seg_link=%{  <a href="#{dob.name}#{Sfx[:epub_xhtml]}">
    #{dob.obj}
  </a> }
          @@seg_url=dob.name
        elsif dob.obj =~/\d+.\d+.\d+.\d+|\d+.\d+.\d+|\d+.\d+|\d+/
          seg_link=dob.obj.gsub(/^(\d+.\d+.\d+.\d+|\d+.\d+.\d+|\d+.\d+|\d+)(.*)/,
            %{<a href="\\1#{Sfx[:epub_xhtml]}">} +
            %{\\1 \\2</a> })
        end
        p_num=SiSU_XHTML_EPUB2_Format::ParagraphNumber.new(@md,ocn) if ocn
        txt_obj={ txt: seg_link }
        format_toc=SiSU_XHTML_EPUB2_Format::FormatToc.new(@md,txt_obj)
        toc={}
        toc[:seg]=format_toc.lev4
        title=%{#{p_num.goto}#{linkname}</a>} if p_num
        txt_obj={ txt: title }
        format_toc=SiSU_XHTML_EPUB2_Format::FormatToc.new(@md,txt_obj)
        toc[:scr]=format_toc.lev4
        toc
      end
      def level_5
        dob=@data
        linkname=dob.obj.gsub(/#{Mx[:en_a_o]}.+?#{Mx[:en_a_c]}|#{Mx[:en_b_o]}.+?#{Mx[:en_b_c]}/,'').strip
        ocn=dob.ocn
        toc={}
        if ocn \
        and ocn.to_s !~/#/
          p_num=SiSU_XHTML_EPUB2_Format::ParagraphNumber.new(@md,ocn)
          lnk_n_txt=%{  <a href="#{@@seg_url}#{Sfx[:epub_xhtml]}#o#{ocn}">
    #{linkname}
  </a>}
          txt_obj={ txt: lnk_n_txt }
          format_toc=SiSU_XHTML_EPUB2_Format::FormatToc.new(@md,txt_obj)
          toc[:seg]=format_toc.lev5
          title=%{#{p_num.goto}#{linkname}</a>}
          txt_obj={ txt: title }
          format_toc=SiSU_XHTML_EPUB2_Format::FormatToc.new(@md,txt_obj)
          toc[:scr]=format_toc.lev5
        end
        toc
      end
      def level_6
        dob=@data
        linkname=dob.obj.gsub(/#{Mx[:en_a_o]}.+?#{Mx[:en_a_c]}|#{Mx[:en_b_o]}.+?#{Mx[:en_b_c]}/,'').strip
        ocn=dob.ocn
        toc={}
        if ocn \
        and ocn.to_s !~/#/
          p_num=SiSU_XHTML_EPUB2_Format::ParagraphNumber.new(@md,ocn)
          lnk_n_txt=%{  <a href="#{@@seg_url}#{Sfx[:epub_xhtml]}#o#{ocn}">
  #{linkname}
</a>}
          txt_obj={ txt: lnk_n_txt }
          format_toc=SiSU_XHTML_EPUB2_Format::FormatToc.new(@md,txt_obj)
          toc[:seg]=format_toc.lev6
          title=%{#{p_num.goto}#{linkname}</a>}
          txt_obj={ txt: title }
          format_toc=SiSU_XHTML_EPUB2_Format::FormatToc.new(@md,txt_obj)
          toc[:scr]=format_toc.lev6
        end
        toc
      end
      def level_7
        dob=@data
        linkname=dob.obj.gsub(/#{Mx[:en_a_o]}.+?#{Mx[:en_a_c]}|#{Mx[:en_b_o]}.+?#{Mx[:en_b_c]}/,'').strip
        ocn=dob.ocn
        toc={}
        if ocn \
        and ocn.to_s !~/#/
          p_num=SiSU_XHTML_EPUB2_Format::ParagraphNumber.new(@md,ocn)
          lnk_n_txt=%{  <a href="#{@@seg_url}#{Sfx[:epub_xhtml]}#o#{ocn}">
  #{linkname}
</a>}
          txt_obj={ txt: lnk_n_txt }
          format_toc=SiSU_XHTML_EPUB2_Format::FormatToc.new(@md,txt_obj)
          toc[:seg]=format_toc.lev7
          title=%{#{p_num.goto}#{linkname}</a>}
          txt_obj={ txt: title }
          format_toc=SiSU_XHTML_EPUB2_Format::FormatToc.new(@md,txt_obj)
          toc[:scr]=format_toc.lev7
        end
        toc
      end
    end
    class ScrollHeadAndSegToc < Toc
      def initialize(md='',per='',links_guide_toc='')
        @md,@per,@links_guide_toc=md,per,links_guide_toc
      end
      def in_common
        toc_shared=[]
        segtoc=[]
        if (@md.opt.act[:verbose][:set]==:on \
        || @md.opt.act[:verbose_plus][:set]==:on \
        || @md.opt.act[:maintenance][:set]==:on)
          SiSU_Screen::Ansi.new(
            @md.opt.act[:color_state][:set],
            'Scroll & Segtoc'
          ).txt_grey
        end
        format_head_toc=SiSU_XHTML_EPUB2_Format::HeadToc.new(@md)
        dochead=format_head_toc.head
        dochead=dochead.gsub(/toc\.(html)/,'doc.\1') #kludge
        toc_shared << dochead #<< ads.div.major
        segtoc << format_head_toc.head #<< ads.div.major
        if defined? @md.rights.all \
        and @md.rights.all
          rights=format_head_toc.rights.all
          rights=SiSU_XHTML_EPUB2_Tune::CleanXHTML.new(rights).clean
        end
        if defined? @md.notes.prefix_b \
        and @md.notes.prefix_b
          prefix_b=format_head_toc.prefix_b
          prefix_b=SiSU_XHTML_EPUB2_Tune::CleanXHTML.new(prefix_b).clean
        end
        tmp_head=nil
        doc_title_endnote=@md.title.full.gsub(/(\*+)/,'<sup><a href="#endnotes">\1</a></sup>')
        tmp_head=doc_title_endnote + "\n"
        txt_obj={ txt: tmp_head }
        format_txt_obj=SiSU_XHTML_EPUB2_Format::FormatTextObject.new(@md,txt_obj)
        toc_shared << format_txt_obj.center_bold
        segtoc << format_txt_obj.center_bold
        if defined? @md.creator.author \
        and @md.creator.author
          creator_endnote=@md.creator.author.gsub(/(\*+)/,%{#{$ep[:hsp]}<sup><a href="#notes">\\1</a></sup>})
          tmp_head=creator_endnote + "\n"
          txt_obj={ txt: tmp_head }
          format_txt_obj=SiSU_XHTML_EPUB2_Format::FormatTextObject.new(@md,txt_obj)
          toc_shared << format_txt_obj.center_bold
          segtoc << format_txt_obj.center_bold
        end
        tmp_head=nil
        if defined? @md.prefix_a \
        and @md.prefix_a
          tmp_head ||= %{#{@md.prefix_a}\n}
          toc_shared << tmp_head.dup
          segtoc << tmp_head.dup
        end
        tmp_head=nil
        toc_shared << @links_guide_toc
        if defined? @md.rights.all \
        and @md.rights.all
          toc_shared << rights
        end
        if defined? @md.prefix_b \
        and @md.prefix_b
          toc_shared << prefix_b
        end
        #Table of Contents added/appended here
        toc_shared << @per.scr
        segtoc << @links_guide_toc
        segtoc << @per.seg
        if defined? @md.rights.all \
        and @md.rights.all
          segtoc << rights
        end
        if defined? @md.prefix_b \
        and @md.prefix_b
          segtoc << prefix_b
        end
        #Segtoc tail added here
        segtoc << format_head_toc.xhtml_close
        segtoc=segtoc.flatten.compact #watch
        SiSU_XHTML_EPUB2::Source::Output.new(@md).make_cover_image
        SiSU_XHTML_EPUB2::Source::Output.new(@md,segtoc).make_segtoc
        segtoc=[]
        @per.scr,@per.seg=[],[]
        toc_shared
      end
    end
    class Table < SiSU_XHTML_Table::TableXHTML
    end
    class Seg < SiSU_XHTML_EPUB2_Seg::Seg
    end
    class Output
      def initialize(md,output='')
        @md,@output=md,output
        @epub_doc="#{@md.fnb}.epub"
        @epub_header=SiSU_XHTML_EPUB2_Format::HeadInformation.new(@md)
        @make=SiSU_Env::ProcessingSettings.new(@md)
        @make_file=SiSU_Env::CreateFile.new(@md.fns)
      end
      def songsheet
        mimetype
        metainf_container
        css
        images if @md.ec[:image]
       #concordance #uncomment to enable inclusion of concordance file
        output_zip
      end
      def mimetype
        out=@make_file.epub.mimetype
        out<<@epub_header.mimetype
        out.close
      end
      def metainf_container #container.xml file in META-INF directory
        out=@make_file.epub.metainf_cont
        out<<@epub_header.metainf_container
        out.close
      end
      def css
        out=@make_file.epub.xhtml_css
        out << SiSU_XHTML_EPUB2_Format::CSS.new.css_epub_xhtml
        out.close
      end
      def epub_toc_ncx
        begin
          out=@make_file.epub.toc_ncx
          @output.each do |para|
            unless para =~/\A\s*\Z/
              out.puts para
            end
          end
          out.close
        rescue
          SiSU_Errors::Rescued.new($!,$@,@md.opt.selections.str,@md.fns).location do
            __LINE__.to_s + ':' + __FILE__
          end
        end
      end
      def epub_metadata_opf
        begin
          out=@make_file.epub.metadata
          @output.each do |para|
            unless para =~/\A\s*\Z/
              out.puts para
            end
          end
          out.close
        rescue
          SiSU_Errors::Rescued.new($!,$@,@md.opt.selections.str,@md.fns).location do
            __LINE__.to_s + ':' + __FILE__
          end
        end
      end
      def images
#puts @md.env.path.image_source_include
#puts @md.env.processing_path.epub
#puts @md.env.path.image_source_include_local
puts @md.file.output_path.epub.rel_image
        #img_pth=$sisu_base_data + '/image'
        img_pth=@md.env.path.image_source_include
        img_src_pth=unless @md.opt.f_pth[:pth] =~/\/\S+?\/sisupod\/\S+?\/sisupod\/doc/
          @md.file.output_path.epub.rel_image
        else
          pt=/(\/\S+?\/sisupod\/\S+?\/sisupod)\/doc/.match(@md.opt.f_pth[:pth])[1]
          pt + '/image'
        end
        @md.ec[:image].each do |x|
          if FileTest.directory?("#{@md.env.processing_path.epub}/#{Ep[:d_oebps]}/image") \
          && FileTest.file?("#{img_src_pth}/#{x}")
            FileUtils::cp("#{img_src_pth}/#{x}","#{@md.env.processing_path.epub}/#{Ep[:d_oebps]}/image")
          #elsif FileTest.directory?("#{$sisu_base_data}/image") \
          #&& FileTest.file?("#{img_pth}/#{x}")
          #  FileUtils::cp("#{img_pth}/#{x}","#{@md.env.processing_path.epub}/#{Ep[:d_oebps]}/image")
          elsif FileTest.directory?("#{@md.env.processing_path.epub}/#{Ep[:d_oebps]}/image") \
          && FileTest.file?("#{img_pth}/#{x}")
            FileUtils::cp("#{img_pth}/#{x}","#{@md.env.processing_path.epub}/#{Ep[:d_oebps]}/image")
          else STDERR.puts %{\t*WARN* did not find image - "#{x}" in #{img_src_pth} or #{img_pth} [#{__FILE__}:#{__LINE__}]}
          end
        end
      end
      def concordance
        SiSU_XHTML_EPUB2_Concordance::Source.new(@md.opt).read
      end
      def output_zip
        FileUtils::mkdir_p(@md.file.output_path.epub.dir) unless FileTest.directory?(@md.file.output_path.epub.dir)
        if FileTest.directory?(@md.env.processing_path.epub) \
        and SiSU_Env::SystemCall.new.zip
          pwd=Dir.pwd
          Dir.chdir(@md.env.processing_path.epub)
          system("
            zip -qXr9D #{@epub_doc} *
          ")
          FileUtils::mv(@epub_doc, @md.file.place_file.epub.dir)
          Dir.chdir(pwd)
          unless @md.opt.act[:maintenance][:set]==:on
            FileUtils::rm_r(@md.env.processing_path.epub)
          end
        else
          SiSU_Utils::CodeMarker.new(__LINE__,__FILE__,:fuchsia).mark('*EXITED epub* zip program not found') unless SiSU_Env::SystemCall.new.zip
        end
      end
      def make_cover_image
        begin
          if @md.make.cover_image? \
          and @md.make.cover_image.is_a?(Hash) \
          and @md.make.cover_image[:cover] =~/\S+/
            filename_xhtml=@make_file.epub.xhtml_cover_image
            cover_image=<<WOK
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
   "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Cover</title>
    <meta http-equiv="Content-Type" content='text/html; charset=utf-8' />
    <link rel="stylesheet" href="css/xhtml.css" type="text/css" />
    <style type="text/css"> img { max-width: 100%; } </style>
  </head>
  <body xml:lang="en">
    <div class="svg_outer">
      <div class="svg_inner">
        <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xl="http://www.w3.org/1999/xlink" width="100%" height="100%" viewBox="0 0 #{@md.make.cover_image[:w]} #{@md.make.cover_image[:h]}" preserveAspectRatio="xMidYMid meet">
        <image width="#{@md.make.cover_image[:w]}" height="#{@md.make.cover_image[:h]}" xl:href="image/#{@md.make.cover_image[:cover]}" />
        </svg>
      </div>
    </div>
  </body>
</html>
WOK
            filename_xhtml.puts cover_image,"\n"
            filename_xhtml.close
          end
        rescue
          SiSU_Errors::Rescued.new($!,$@,@md.opt.selections.str,@md.fns).location do
            __LINE__.to_s + ':' + __FILE__
          end
        end
      end
      def make_segtoc
        begin
          if @make.build.toc?
            filename_xhtml=@make_file.epub.xhtml_index
            @output.each do |para|
              para=para.strip
              unless para =~/\A\s*\Z/
                filename_xhtml.puts para,"\n"
              end
            end
            filename_xhtml.close
          end
        rescue
          SiSU_Errors::Rescued.new($!,$@,@md.opt.selections.str,@md.fns).location do
            __LINE__.to_s + ':' + __FILE__
          end
        end
      end
    end
  end
end
__END__
