# coding: utf-8
=begin

 * Name: SiSU

 * Description: a framework for document structuring, publishing and search

 * Author: Ralph Amissah

 * Copyright: (C) 1997 - 2010, 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.jus.uio.no/sisu/gpl.fsf/toc.html>
   <http://www.jus.uio.no/sisu/gpl.fsf/doc.html>
   <http://www.jus.uio.no/sisu/gpl.fsf/plain.txt>

 * SiSU uses:
   * Standard SiSU markup syntax,
   * Standard SiSU meta-markup syntax, and the
   * Standard SiSU object citation numbering and system

 * Hompages:
   <http://www.jus.uio.no/sisu>
   <http://www.sisudoc.org>

 * Download:
   <http://www.jus.uio.no/sisu/SiSU/download.html>

 * Ralph Amissah
   <ralph@amissah.com>
   <ralph.amissah@gmail.com>

 ** Description: LaTeX generation

=end
module SiSU_TeX
  require 'pstore'
  require "#{SiSU_lib}/defaults"                           # defaults.rb
    include SiSU_Viz
  require "#{SiSU_lib}/particulars"                        # particulars.rb
    include SiSU_Particulars
  require "#{SiSU_lib}/texpdf_format"                      # texpdf_format.rb
    include SiSU_TeX_Pdf
  require "#{SiSU_lib}/shared_metadata"                    # shared_metadata.rb
  @tex_file=@@tex_footnote_array=@@tex_col_w=[]
  @@tabular="{tabular}"
  @@column_instruct=@@squigle_close=@@tex_line_mode=@@tex_word_mode=@@line_mode=''
  @@tex_debug_counter=@@table_pagebreak_counter=@@tex_footnote_call_counter=@@tex_table_flag=@@tex_counter=@@tex_column=@@tex_columns=@@tex_columns=@@counting=0
  @@tex_pattern_margin_number=/\\\\begin\\\{tiny\\\}\\\\hspace\\\{0mm\\\}\\\\end\\\{tiny\\\}\\\{\\\\marginpar.+?\s+/
  @@n=@@tableheader=@@rights=nil
  @@date ||=SiSU_Env::Info_date.new
  class Source
    require 'pstore'
    require "#{SiSU_lib}/sysenv"                           # sysenv.rb
      include SiSU_Env
    include SiSU_Viz
    require "#{SiSU_lib}/dal"                              # dal.rb
      include SiSU_DAL
    include SiSU_TeX
    def initialize(opt)
      @opt=opt
      @particulars=SiSU_Particulars::Combined_singleton.instance.get_all(opt)
      @md=@particulars.md
      @env=@particulars.env
    end
    def directories
      begin
        @dir_out_root=@env.path.output
        case @opt.fns
        when /\.(?:-|ssm\.)?sst$/
          SiSU_Env::SiSU_file.new(@md).mkdir
          Dir.mkdir(@env.path.tex) unless FileTest.directory?(@env.path.tex)
        end
      rescue; SiSU_Errors::Info_error.new($!,$@,@opt.cmd,@opt.fns).error
      ensure
      end
    end
    def read
      song
    end
    def song
      begin
        @md=@particulars.md
        SiSU_Screen::Ansi.new(@opt.cmd,'LaTeX/PDF',@md.fns).green_title_hi unless @opt.cmd =~/q/
        if @opt.cmd =~/[MVv]/
          path=@env.url.output_tell
          SiSU_Screen::Ansi.new(@opt.cmd,@opt.fns,"#{@env.program.pdf_viewer} #{path}/#{@md.fnb}/#{@md.fn[:pdf_l]}").flow
          SiSU_Screen::Ansi.new(@opt.cmd,@opt.fns,"#{@env.program.pdf_viewer} #{path}/#{@md.fnb}/#{@md.fn[:pdf_p]}").flow
        end
        @md=@particulars.md
        SiSU_Env::Create_file.new(@opt.cmd,@opt.fns)
        $flag=@md.cmd                                                         #introduced to pass 0 for no object citation numbers... to texpdf_format
        @dir_o="#{@env.path.output}/#{@opt.fnb}"
        directories
                                                                             #% needed needs to be reprogrammed !!!
        SiSU_Env::Info_skin.new(@md).select
        dal_array=SiSU_DAL::Source.new(@opt).get # dal file drawn here
        SiSU_TeX::Source::LaTeX_create.new(@particulars).songsheet
        dal_array=''
        pwd=Dir.pwd
        SiSU_TeX::Source::LaTeX_to_pdf.new(@md,@particulars.env).latexrun_selective
        Dir.chdir(pwd)
      rescue; SiSU_Errors::Info_error.new($!,$@,@opt.cmd,@opt.fns).error
      ensure
        unless @opt.cmd =~/[MV]/ #check maintenance flag
          texfiles=Dir["#{@env.path.tex}/#{@opt.fns}*"]
          texfiles.each do |f|
            if FileTest.file?(f)
              File.unlink(f)
            end
          end
        end
        @tex_file=@@tex_footnote_array=[]
        @@column_instruct=''
        @@squigle_close=@@tex_line_mode=@@tex_word_mode=@@line_mode=''
        @@tex_debug_counter=@@table_pagebreak_counter=@@tex_footnote_call_counter=@@tex_table_flag=@@tex_counter=@@tex_column=@@tex_columns=@@tex_columns=@@counting=0
        @@tex_col_w=[]
        @@n=@@tableheader=@@rights=nil
        @@date=SiSU_Env::Info_date.new
        @@flag={}
        $flag=1 #remove at some stage
        SiSU_Env::Create_file.new(@opt.cmd,@opt.fns).param_instantiate
      end
    end
    private
    class LaTeX_to_pdf
      require 'fileutils'
      include FileUtils #::Verbose
      @@n_lpdf||=0 #change
      def initialize(md,env)
        @md,@env=md,env
      end
      def latex_do(texfilename,papersize)
        @texfilename=texfilename
        @@n_lpdf=@@n_lpdf+1
        SiSU_Screen::Ansi.new(@md.cmd,"#{papersize} portrait ->").dark_grey_title_hi if @md.cmd =~/[MVv]/
        tex_fn_base=@texfilename.gsub(/\.tex$/,'')
        cmd=SiSU_Env::System_call.new("#{tex_fn_base}.tex",'',@md.cmd)
        tell=SiSU_Screen::Ansi.new(@md.cmd)
        tell.grey_open if @md.cmd =~/[MVv]/
        if "#{tex_fn_base}" =~/\w+/ \
        and "#{papersize}" =~/\w+/
          2.times { |i| cmd.latex2pdf(@md,papersize) }
        end
        tell.p_off if @md.cmd =~/[MVv]/
        SiSU_Screen::Ansi.new(@md.cmd,"#{papersize} landscape ->").dark_grey_title_hi if @md.cmd =~/[MVv]/
        cmd=SiSU_Env::System_call.new("#{tex_fn_base}.landscape.tex",'',@md.cmd)
        tell.grey_open if @md.cmd =~/[MVv]/
        if "#{tex_fn_base}" =~/\w+/ \
        and "#{papersize}" =~/\w+/
          2.times { |i| cmd.latex2pdf(@md,papersize) }
        end
        tell.p_off if @md.cmd =~/[MVv]/
        pwd=Dir.pwd
        portrait_pdf="#{pwd}/#{tex_fn_base}.pdf"
        landscape_pdf="#{pwd}/#{tex_fn_base}.landscape.pdf"
        case papersize
        when /a4/;     pdf_p=@md.fn[:pdf_p_a4];     pdf_l=@md.fn[:pdf_l_a4]
        when /a5/;     pdf_p=@md.fn[:pdf_p_a5];     pdf_l=@md.fn[:pdf_l_a5]
        when /b5/;     pdf_p=@md.fn[:pdf_p_b5];     pdf_l=@md.fn[:pdf_l_b5]
        when /letter/; pdf_p=@md.fn[:pdf_p_letter]; pdf_l=@md.fn[:pdf_l_letter]
        when /legal/;  pdf_p=@md.fn[:pdf_p_legal];  pdf_l=@md.fn[:pdf_l_legal]
        else           pdf_p=@md.fn[:pdf_p_a4];     pdf_l=@md.fn[:pdf_l_a4]
        end
        if FileTest.file?(portrait_pdf)
          cp(portrait_pdf,"#{@dir_sisu}/#{@md.fnb}/#{pdf_p}")
          rm(portrait_pdf)
        else p "#{__FILE__}:#{__LINE__} NOT FOUND: #{portrait_pdf}" if @md.cmd.inspect =~/M/
        end
        if FileTest.file?(landscape_pdf)
          cp(landscape_pdf,"#{@dir_sisu}/#{@md.fnb}/#{pdf_l}")
          rm(landscape_pdf)
        else p "#{__FILE__}:#{__LINE__} NOT FOUND: #{landscape_pdf}" if @md.cmd.inspect =~/M/
        end
        SiSU_Screen::Ansi.new(@md.cmd,@@n_lpdf,'processed (SiSU LaTeX to pdf - using pdfetex aka. pdftex or pdflatex)').generic_number if @md.cmd =~/[MVv]/
      end
      def latexrun_selective
        begin
          pwd=Dir.pwd
          Dir.chdir(pwd) #watch
          @tex_f_no=0
          info={}
          if FileTest.file?(@env.source_file_with_path)
            @md.papersize_array.each do |ps|
              if @md.fns =~/\.(?:-|ssm\.)?sst$/
                @dirout=SiSU_Env::Info_env.new(@md.fns)
                case @md.fns
                when /\.(?:-|ssm\.)?sst$/
                  if FileTest.directory?(@env.path.tex)==true
                    Dir.chdir(@env.path.tex)
                    @dir_sisu=@dirout.path.output
                    texfile=@md.fns.gsub(/$/,".#{ps}.tex")
                    texfile=texfile.gsub(/~/,'-')
                    if File.exist?(texfile) \
                    and File.size(texfile) > 0
                      @tex_f_no+=1
                      #p "#{__FILE__}:#{__LINE__} texpdf generation disabled" if @md.cmd.inspect =~/M/ #%% disable temporarily, re-enable
                      latex_do(texfile,ps)
                    else
                      puts "\tzero file size #{@env.path.tex}/#{texfile}"
                    end
                  end
                end
              end
            end
            outputdir="#{@dir_sisu}/#{@md.fnb}"
            case @md.papersize_array[0] #default pdf
            when /a4/;     pdf_p=@md.fn[:pdf_p_a4];     pdf_l=@md.fn[:pdf_l_a4]
            when /a5/;     pdf_p=@md.fn[:pdf_p_a5];     pdf_l=@md.fn[:pdf_l_a5]
            when /b5/;     pdf_p=@md.fn[:pdf_p_b5];     pdf_l=@md.fn[:pdf_l_b5]
            when /letter/; pdf_p=@md.fn[:pdf_p_letter]; pdf_l=@md.fn[:pdf_l_letter]
            when /legal/;  pdf_p=@md.fn[:pdf_p_legal];  pdf_l=@md.fn[:pdf_l_legal]
            else           pdf_p=@md.fn[:pdf_p_a4];     pdf_l=@md.fn[:pdf_l_a4]
            end
            if FileTest.file?("#{outputdir}/#{pdf_p}")
              system("
                cd #{outputdir}
                rm portrait.pdf
                ln -s #{pdf_p} portrait.pdf
              ")
            end
            if FileTest.file?("#{outputdir}/#{pdf_l}")
              system("
                cd #{outputdir}
                rm landscape.pdf
                ln -s #{pdf_l} landscape.pdf
              ")
            end
          else
            SiSU_Screen::Ansi.new(@md.cmd,"FILE NOT FOUND: << #{@md.fns} >> - requested latex system processing skipped").warn
          end
          lst=Dir["*.{aux,log,out}"]
          lst.each {|file| File.unlink(file)} if lst
        rescue; SiSU_Errors::Info_error.new($!,$@,@md.cmd,@md.fns).error
        end
      end
    end
    class LaTeX_create
      @@tex_head={
        'a4'=>    {:p => nil, :l => nil},
        'a5'=>    {:p => nil, :l => nil},
        'b5'=>    {:p => nil, :l => nil},
        'letter'=>{:p => nil, :l => nil},
        'legal'=> {:p => nil, :l => nil},
        'book'=>  {:p => nil, :l => nil}
      }
      @@prefix_b=nil
      def initialize(particulars)
        @particulars=particulars
        @md=@particulars.md
        @env=@particulars.env
        @data=@particulars.dal_array # dal file drawn here
        @st={ :tex=>{} }
        @tex_ml=SiSU_TeX_Pdf::Use_TeX.new(@md)
        @vz=SiSU_Env::Get_init.instance.skin
        @dp=@@dp ||=SiSU_Env::Info_env.new.digest.pattern
        @brace_url=SiSU_Viz::Skin.new.url_decoration
        vz=SiSU_Env::Get_init.instance.skin
        @skin_no_ocn=if defined? vz.ocn_display_off \
        and vz.ocn_display_off==true
          true
        else false
        end
      end
      def songsheet
        begin
          data=@data
          @@tex_footnote_array=[]
          @@rights=nil
          SiSU_Screen::Ansi.new(@md.cmd,"pdfTex portrait & landscape").txt_grey if @md.cmd=~/[MVvz]/
          if defined? @md.rights.all \
          and not @md.rights.all.empty?
            rght=@md.rights #.author.dup #dup is necessary, else contents of :rights changed
            sp_char=SiSU_TeX_Pdf::Special_characters.new(@md,rght.copyright.all)
            copymark=@md.author_copymark \
            ? '{\begin{small}\copyright\end{small}} ' \
            : ''
            copymark='Copyright {\begin{small}\copyright\end{small}} '
            copyright=sp_char.special_characters_safe.gsub(/^\s*Copyright \(C\)/, copymark)
            @@rights||="\n #{Tex[:backslash]*2}[3]\\ \\linebreak #{copyright}"
          end
          if defined? @md.notes.prefix_b \
          and not @md.notes.prefix_b.empty?
            sp_char=SiSU_TeX_Pdf::Special_characters.new(@md,@md.notes.prefix_b)
            prefix_b=sp_char.special_characters_safe
            @@prefix_b="\n #{Tex[:backslash]*2}[3]\\ \\linebreak \\ #{prefix_b}\n" unless @@prefix_b
          end
          data=pre(data)
          data=footnote(data)
          if @md.flag_tables #WORK ON 2009
            data=tables(data) #uncomment to start experimenting with tables
          end
          ocn=if @md.markup.inspect =~/no_ocn/ \
          or @md.mod.inspect =~/--no-ocn/ \
          or @skin_no_ocn
            false
          else true
          end
          data=number_paras(data)
          data=markup(data)
          output(data)
        rescue; SiSU_Errors::Info_error.new($!,$@,@md.cmd,@md.fns).error
        ensure
        end
      end
    protected
      def pre(data)
        @tex_file=[]
        data.each do |dob|
          # DEBUG 2003w16 this is a kludge, because i could not get parameters
          # from param, Sort out ... revert to more elegant solution
          # even more of a kludge as had to insert newlines where code is used not satisfactory, think about
          dob.tmp=dob.obj #.dup
          if dob.is=='para' \
          or dob.is=='heading'
            dob.tmp.gsub!(/#{Mx[:mk_o]}:name#\S+?#{Mx[:mk_c]}/,'')
            dob.tmp=SiSU_TeX_Pdf::Special_characters.new(@md,dob.tmp).special_characters
            if dob.tmp =~/#{Mx[:lnk_o]}.+?#{Mx[:lnk_c]}#{Mx[:rel_o]}\S+?#{Mx[:rel_c]}/
              dob.tmp=SiSU_TeX_Pdf::Format_text_object.new(@md,dob.tmp).url_str_internal(dob.tmp)
            end
          elsif dob.is =='code'
            dob.tmp=SiSU_TeX_Pdf::Special_characters.new(@md,dob.tmp).special_characters_code
          elsif dob.is =='break'
            if dob.obj==Mx[:br_page]; dob.tmp='\newpage'
            elsif dob.obj==Mx[:br_page_new]; dob.tmp='\clearpage'
            elsif dob.obj==Mx[:obj_ln_sep]; dob.tmp='\parasep'
            end
          elsif dob.is=='comment' \
          or dob.is=='meta'
            dob.tmp='' #dob.tmp=nil
          end
        end
        data
      end
      def footnote(data)
        data.each do |dob|
          # EMBEDDED FOOTNOTES / ENDNOTES should be straightforward but not quite a synch.
          if dob.tmp =~/#{Mx[:en_a_o]}[\d*+]+\s|#{Mx[:en_b_o]}([*+]\d+)\s/
            dob.tmp.gsub!(/#{Mx[:en_a_o]}(\d+)\s+(.+?)#{Mx[:en_a_c]}/m,"\\footnote[\\1]{%\n \\2} ")
            dob.tmp.gsub!(/#{Mx[:en_b_o]}([*+]\d+)\s+(.+?)#{Mx[:en_b_c]}/m,"\\FootnoteA{\\1}{%\n \\2} ")
            dob.tmp.gsub!(/#{Mx[:en_a_o]}([*+]+)\s+(.+?)#{Mx[:en_a_c]}/m,"\\FootnoteA{\\1}{%\n \\2} ")
          end
        end
        data
      end
      def tables_hash(md,dob)
        @block={}
        @dob=dob
        @md.papersize_array.each do |ps|
          @@tableheader={ ps => { :p => 0, :l => 0 }}
          dob.tmp={:tmp =>dob.tmp,:paper_size =>ps}
          format_l=SiSU_TeX_Pdf::Format_text_object.new(md,dob)
          dob.tmp={:tmp =>dob.tmp,:paper_size =>ps}
          format_p=SiSU_TeX_Pdf::Format_text_object.new(md,dob)
          @block[ps]={
            :l => format_l.longtable_landscape,
            :p => format_p.longtable_portrait
          }
        end
        @dob.tmp=@block
        @dob
      end
      def tables(data)
        @tex_file=[]
        data.each do |dob|
          @tex_file << if dob.class==String \
          or dob.class==Hash; dob
          elsif dob.is=='table'
            tables_hash(@md,dob) #Hash result
          else dob
          end
        end
        @tex_file
      end
      def enclose(dob)
        dob
      end
      def markup_common(dob)
        tex_f=nil
        txt_obj={:dal =>dob}
        if dob.of=='group'
          @lineone=case dob.is
          when /alt|group|verse/
            dob.tmp.gsub!(/#{Mx[:nbsp]}/m,'{~}')
            dob.tmp.gsub!(/#{Mx[:gl_bullet]}/m,'$\txtbullet$\hspace{\enspace}') #Bullet environment not used for grouped text, ∴ no hanging indent here
            dob.tmp.gsub!(/#{Mx[:br_nl]}+/m,"\n\n") #match not ideal, but currently not inserting extra newlines anyway
            ocn=SiSU_TeX_Pdf::Format_text_object.new(@md).ocn_display(dob)
            dob.tmp=if dob.is=='group' \
            or dob.is=='alt'
              ocn \
              + @tex_ml.paraskip_small \
              + "\n" \
              + ' \\begin{footnotesize}' \
              + "\n\n" \
              + dob.tmp \
              + '\\end{footnotesize}' \
              + "\n" \
              + @tex_ml.paraskip_normal
            elsif  dob.is=~/verse/
              ocn \
              + @tex_ml.paraskip_tiny \
              + "\n" \
              + ' \\begin{footnotesize}' \
              + "\n\n" \
              + dob.tmp \
              + '\\end{footnotesize}' \
              + "\n" \
              + @tex_ml.paraskip_normal \
              + "\n\\linebreak\n"
            end
            dob
          when /code/
            sp_char=SiSU_TeX_Pdf::Special_characters.new(@md,dob.tmp,dob.is)
            dob.tmp=sp_char.special_characters_safe
            dob.tmp.gsub!(/#{Mx[:nbsp]}/,'{~}') #dob.tmp.gsub!(/#{Mx[:nbsp]}\s*/,'{~}')
            dob.tmp.gsub!(/#{Mx[:vline]}/m,'\vline')
            dob.tmp.gsub!(/ \\( |#{Mx[:br_nl]})/,' {\textbackslash}\1')
            dob.tmp.gsub!(/#{Mx[:br_nl]}\s*\Z/m,'')
            dob.tmp.gsub!(/#{Mx[:br_nl]}{2}/,'\newline \\\\\\ ')
            dob.tmp.gsub!(/#{Mx[:br_nl]}/,' \\\\\\ ')
            dob.tmp.gsub!(/\n\n\n/m," \\newline\n\n")
            ocn=SiSU_TeX_Pdf::Format_text_object.new(@md).ocn_display(dob)
            dob.tmp = ocn \
            + @tex_ml.paraskip_small \
            + '\begin{Codeblock}' \
            + dob.tmp \
            + ' \end{Codeblock}' \
            + "\n" \
            + @tex_ml.paraskip_normal
            dob
          else 'error' #should never occur
          end
          if dob.tmp =~/<=curly/ #takes care of escaped curly braces, expand
            sp_char=SiSU_TeX_Pdf::Special_characters.new(@md,dob)
            dob.tmp=sp_char.special_characters_curly(dob.tmp)
          end
          dob=enclose(dob) unless dob.tmp =~/^$/
          dob
        else
          tst=SiSU_TeX_Pdf::Format_text_object.new(@md,dob)
          case dob.is
          when 'heading'
            case dob.ln
            when 1..3
              tst.heading_major
            when 4
              tst.level4
            when 5
              tst.level5
            when 6
              tst.level6
            else dob
            end
          when 'heading_insert'
            br="\n\\\\\n"
            if dob.name=='book_index'
              h=tst.heading_major
              heading="\\clearpage\n" + h.tmp
              idx_arr=[]
              idx=SiSU_Particulars::Combined_singleton.instance.get_idx_tex(@md.opt).tex_idx
              idx.each do |x|
                x=if x.class==String
                  x=SiSU_TeX_Pdf::Special_characters.new(@md,x).special_characters
                  x=SiSU_TeX_Pdf::Format_text_object.new(@md,x).url_str_internal(x,true)
                else x=nil
                end
                idx_arr << x.sub(/,$/,'') if x.class==String
              end
              idx_str=idx_arr.join(br)
              l=heading + br + idx_str
              p=heading + br +
                '\begin{multicols}{2}' + br +
                idx_str + br +
                '\end{multicols}'
              dob.tmp={:l =>l,:p =>p}
            elsif dob.ln==2 \
            and dob.obj=~/Metadata\b/
              tst.heading_major
            elsif dob.ln==4 \
            and dob.obj=~/Metadata\b/
              h=tst.level4
              metadata=Metadata::TeX_metadata.new(@md).metadata_tex
              dob.tmp=h.tmp + ' ' + '\begin{scriptsize}' + metadata.join(br) + '\end{scriptsize}'
            else dob.tmp='' # dob.tmp={:l =>'',:p =>''}
            end
          when 'para'
            if dob.bullet_
              dob.tmp=tst.bullet
            elsif dob.indent \
            and dob.indent =~/[1-9]/
              dob.tmp=tst.indent
            else
              dob.tmp.strip!
              dob=enclose(dob) unless dob.tmp =~/^$/
            end
          else
            dob.tmp.strip!
            dob=enclose(dob) unless dob.tmp =~/^$/
          end
          if dob.class==String
            dob.tmp.gsub!(/\s*(?:#{Mx[:br_line]}|#{Mx[:br_nl]})\s*/,' \newline ')   #% tread with care
            dob.tmp.gsub!(/(\.#{Tex[:tilde]}\S*\s*|<:\S+>|#{Mx[:fa_o]}.*?#{Mx[:fa_c]}|#{Mx[:gr_o]}.*?#{Mx[:gr_c]}|<!.*?!>|<!>)/,' ')   #% tread with care
          end
          if dob.tmp =~/<=curly/ #takes care of escaped curly braces, expand
            sp_char=SiSU_TeX_Pdf::Special_characters.new(@md,dob)
            dob.tmp=sp_char.special_characters_curly(dob.tmp)
          end
          dob
        end
        if dob.tmp =~/(?:#{Mx[:url_o]}\S+?#{Mx[:url_c]}|image\b)/m \
        and dob.is !='code'
          dob=SiSU_TeX_Pdf::Bare_urls.new(@md,dob).bare_urls
          tst=SiSU_TeX_Pdf::Format_text_object.new(@md,dob)
          dob=tst.urls_txt_and_images
          dob
        elsif dob.tmp =~/https?:\/\/\S+\b/m \
        and dob.is =='code'
          dob=SiSU_TeX_Pdf::Bare_urls.new(@md,dob).bare_urls_in_code
          dob
        end
        if dob.class !=Hash and dob.tmp =~/#{Mx[:lnk_o]}.+?#{Mx[:lnk_c]}image\b/ \
        and dob.is !='code'
          tst=SiSU_TeX_Pdf::Format_text_object.new(@md,dob)
        end
        dob
      end
      def markup(data)
        @tex_file=[]
        md={}
        home=@vz.txt_home.gsub(/#{Mx[:br_line]}|#{Mx[:br_nl]}|#{Mx[:br_paragraph]}|\\\\/,' - ') #no line splitting in heading neither html nor latex
        title=@md.title.full.gsub(/#{Mx[:br_line]}|#{Mx[:br_nl]}|#{Mx[:br_paragraph]}|\\\\/,' - ') #no line splitting in heading neither html nor latex
        @md.papersize_array.each do |ps|
          txt_obj={:txt =>"#{home}: - #{title}",:paper_size =>ps,:orientation =>'portrait'}
          orient_portrait=SiSU_TeX_Pdf::Format_head.new(@md,txt_obj)
          txt_obj={:txt =>"#{home}: - #{title}",:paper_size =>ps,:orientation =>'landscape'}
          orient_landscape=SiSU_TeX_Pdf::Format_head.new(@md,txt_obj)
          @@tex_head[ps][:p]=orient_portrait.document_head_with_orientation
          @@tex_head[ps][:l]=orient_landscape.document_head_with_orientation
        end
        @tex_file <<<<WOK
#{@tex_ml.header}#{@tex_ml.footer}
\\tolerance=300
\\clubpenalty=300
\\widowpenalty=300
\\makeatother
\\makeatother
\\chardef\\txtbullet="2022
\\chardef\\tilde="7E
%\\chardef\\asterisk="2A
\\def\\asterisk{{\\rm \\char42} }
\\definecolor{Light}{gray}{.92}
\\newcommand{\\Codeblock}[1]{\\normaltext\\raggedright\\small\\ttfamily\\texbackslash#1}
\\newcommand{\\monosp}[1]{\\normaltext\\ttfamily\\texbackslash#1}
\\newcommand{\\parasep}{\\\\ \\begin{center}*\\hspace{2em}*\\hspace{2em}*\\end{center} \\\\}
\\newcommand{\\hardspace}{{~}}
%\\newcommand{\\hardspace}{\\hspace{.5em}}
% \\sloppy
\\begin{document}
WOK
        sisu_rc_footnote=if @md.sc_info; @tex_ml.doc_sc_info_footnote_full
        else                             @tex_ml.doc_sc_info_footnote_brief
        end
        @copymark='' #check and remove as now is superflous
        x={}
        txt_obj={:title =>@md.title.full}
        x[:l]=SiSU_TeX_Pdf::Format_text_object.new(@md,txt_obj).title_landscape
        x[:p]=SiSU_TeX_Pdf::Format_text_object.new(@md,txt_obj).title_portrait
        @tex_file << x
        x=nil
        if defined? @md.creator.author \
        and @md.creator.author
          sp_char=SiSU_TeX_Pdf::Special_characters.new(@md,@md.creator.author)
          author=sp_char.special_characters
          @tex_file << if @md.author_home
            <<WOK

\\author{\\href{#{@md.author_home}}{#{@copymark} \\textnormal{#{author}}}}
WOK
          else "\n\\author{#{@copymark} \\textnormal{#{author}}}"
          end
        end
        @tex_file << unless @md.fnb =~/^mail\s*$/; @tex_ml.site
        else                                       '\date'
        end
        @tex_file <<<<WOK
\\pagenumbering{roman}\\maketitle
\\pagestyle{fancy}
WOK
        if defined? @md.rights.all \
        and @md.rights.all
          @tex_file << "\\newpage\n"
          @tex_file << @@rights
          @tex_file << @@prefix_b if defined? @md.creator.prefix_b and @md.creator.prefix_b
        end
        x={}
        x[:l] =<<WOK
#{@tex_ml.newpage('landscape')}
\\pagestyle{fancy}
\\tableofcontents
#{@tex_ml.newpage('landscape')}
\\pagenumbering{arabic}
#{@tex_ml.paraskip_normal}
#{@tex_ml.newpage('landscape')}
WOK
        x[:p] =<<WOK
#{@tex_ml.newpage('portrait')}
\\pagestyle{fancy}
\\tableofcontents
#{@tex_ml.newpage('portrait')}
\\pagenumbering{arabic}
#{@tex_ml.paraskip_normal}
#{@tex_ml.newpage('portrait')}
WOK
        @tex_file << x
        x=nil
        data.each do |dob|                                                      #% case follows with levels 1-6 indents & graphics
          if dob.class==Hash
          elsif dob.of=='para' \
          or dob.of=='group' #GATEWAY FIX FIX stuff
            dob=markup_common(dob)
          elsif dob.is=='table'
            if ( dob.tmp['a4'] \
            or dob.tmp['a5'] \
            or dob.tmp['b5'] \
            or dob.tmp['letter'] \
            or dob.tmp['legal'])
              @md.papersize_array.each do |ps|
                if dob.tmp[ps]
                  if (dob.tmp[ps][:p] and dob.tmp[ps][:l])
                    dob.tmp[ps]={
                      :p => markup_common(dob.tmp[ps][:p]),
                      :l => markup_common(dob.tmp[ps][:l])
                    }
                  else p "#{__FILE__}:#{__LINE__}" if @md.cmd.inspect =~/M/
                  end
                end
              end
            elsif dob.tmp.class==Hash \
            and (dob.tmp[:p] and dob.tmp[:l])
              dob = {
                :p => markup_common(dob.tmp[:p]),
                :l => markup_common(dob.tmp[:l])
              }
            else p "#{__FILE__}:#{__LINE__}" if @md.cmd.inspect =~/M/
            end
          end
          @tex_file << dob
        end
        @st[:tex][:stmp]||=@md.stmpd
        stamp=@st[:tex][:stmp] if @st[:tex][:stmp]
        if stamp
          use=stamp.gsub(/\n/,"#{Tex[:backslash]*2}\n")
          @tex_file << "\n\\newpage\n"
          @tex_file << "\\section*" +
            "{#{@tex_ml.owner_chapter}}\n" +
            "\\addcontentsline{toc}" +
            "{section}{#{@tex_ml.owner_chapter}}\n"
          @tex_file << "#{use}\n"
          @tex_file << @@rights if @@rights
        end
        @tex_file << "\n\\end{document}"
      end
      def number_paras_numbering(dob) # need tables and other types of object
        if dob.of =~/para/ #\
          paranum=dob.ocn ? dob.ocn : ''
          paranum = '' if paranum.to_i==0
          paranumber_display=if @md.markup.inspect =~/no_ocn/ \
          or @md.mod.inspect =~/--no-ocn/ \
          or not dob.ocn_
            ''
          else
            tags=''
            #[keep] code that follows inserts "name tags" as hypertargets, currently using ocn (converting nametags to ocn) for internal linking, related code: |texpdf_format.rb|@|uses nametags directly|
            #if dob.tags.length > 0 # insert tags "hypertargets"
            #  dob.tags.each do |t|
            #    tags=tags +"\\hspace{0mm}\\hypertarget{#{t}}{\\hspace{0mm}}"
            #  end
            #end
            "\\begin{tiny}\\hspace{0mm}\\end{tiny}{\\marginpar{\\begin{tiny}\\hspace{0mm}\\hypertarget{#{dob.ocn}}{#{dob.ocn}}#{tags}\\end{tiny}}}" #ocn object citation numbering
          end
          dob.tmp = paranumber_display + dob.tmp
        end
        dob
      end
      def number_paras(data)
        tex_file=[]
        data.each do |dob|
          dob=if dob.class==Hash
            if ( dob['a4'] \
            or dob['a5'] \
            or dob['b5'] \
            or dob['letter'] \
            or dob['legal'])
              para_hash={}
              @md.papersize_array.each do |ps|
                if defined? dob.tmp and dob.tmp[ps]
                  if (dob.tmp[ps][:p] and dob.tmp[ps][:l])
                    para_hash[ps]={
                      :p => number_paras_numbering(dob.tmp[ps][:p]),
                      :l => number_paras_numbering(dob.tmp[ps][:l])
                    }
                    dob.tmp=para_hash
                  else p "#{__FILE__}:#{__LINE__}" if @md.cmd.inspect =~/M/
                  end
                end
              end
            elsif (dob.tmp[:p] and dob.tmp[:l])
              dob.tmp = {
                :p => number_paras_numbering(dob.tmp[:p]),
                :l => number_paras_numbering(dob.tmp[:l])
              }
            else p "#{__FILE__}:#{__LINE__}" if @md.cmd.inspect =~/M/
            end
          else
            dob=if dob.of !~/comment|meta|layout/
              number_paras_numbering(dob)
            else dob
            end
          end
        end
        data
      end
      def output_morph_hash(o)
        ps,h,fn=o[:ps],o[:h],o[:filename]
        if h[ps] \
        and (h[ps][:p] and h[ps][:l])
          h[ps][:p].gsub!(/(?:^[ ]+|[ ]+$)/m,'') if h[ps][:p]
          h[ps][:l].gsub!(/(?:^[ ]+|[ ]+$)/m,'') if h[ps][:l]
          h[ps][:p].gsub!(/\n\n\n+/m,"\n\n") if h[ps][:p]
          h[ps][:l].gsub!(/\n\n\n+/m,"\n\n") if h[ps][:l]
          if h[ps][:p] !~/\A\s*\Z/
            fn[:portrait].puts h[ps][:p],"\n"
          end
          if h[ps][:l] !~/\A\s*\Z/
            fn[:landscape].puts h[ps][:l],"\n"
          end
        elsif (h[:p] and h[:l])
          h[:p].gsub!(/(?:^[ ]+|[ ]+$)/m,'') if h[:p]
          h[:l].gsub!(/(?:^[ ]+|[ ]+$)/m,'') if h[:l]
          h[:p].gsub!(/\n\n\n+/m,"\n\n") if h[:p]
          h[:l].gsub!(/\n\n\n+/m,"\n\n") if h[:l]
          if h[:p] !~/\A\s*\Z/
            fn[:portrait].puts h[:p],"\n"
          end
          if h[:l] !~/\A\s*\Z/
            fn[:landscape].puts h[:l],"\n"
          end
        else p "#{__FILE__}:#{__LINE__}" if @md.cmd.inspect =~/M/
        end
      end
      def output(array)
        array.flatten!
        array.compact!
        @array=array
        fns_l=@md.fns.gsub(/~/,'-') #this is a sorry fix, but necessary as it appears latex programs like not ~
        @md.papersize_array.each do |ps|
          file={
            :landscape =>File.new("#{@env.path.tex}/#{fns_l}.#{ps}.landscape.tex",'w+'),
            :portrait =>File.new("#{@env.path.tex}/#{fns_l}.#{ps}.tex",'w+')
          }
          file[:portrait] << @@tex_head[ps][:p]
          file[:landscape] << @@tex_head[ps][:l]
          array.each do |morph|
            if morph.class==String
              morph.gsub!(/^\s+/,'')
              if morph !~/\A\s*\Z/
                file[:portrait].puts morph,"\n"
                file[:landscape].puts morph,"\n"
              end
            elsif morph.class.inspect =~ /SiSU_document_structure/ \
            and morph.tmp \
            and morph.tmp.class==String
              unless morph.of=='group'
                morph.tmp.gsub!(/^\s+/,'')
              else morph.tmp.gsub!(/^ +/,'')
              end
              if morph.tmp !~/\A\s*\Z/ \
              or morph.is=='code'
                file[:portrait].puts morph.tmp,"\n"
                file[:landscape].puts morph.tmp,"\n"
              end
            elsif morph.class==Hash            #inserted headers and the like, only
              h={:ps =>ps,:h =>morph,:filename =>file}
              output_morph_hash(h)
            elsif morph.tmp.class==Hash       #tables & images?
              h={:ps =>ps,:h =>morph.tmp,:filename =>file}
              output_morph_hash(h)
            end
          end
          array=@array
          file[:portrait].close
          file[:landscape].close
        end
        @@tex_head={
          'a4'=>    {:p => nil, :l => nil},
          'a5'=>    {:p => nil, :l => nil},
          'b5'=>    {:p => nil, :l => nil},
          'letter'=>{:p => nil, :l => nil},
          'legal'=> {:p => nil, :l => nil},
          'book'=>  {:p => nil, :l => nil}
        }
        array=[]
      end
    end
  end
end
__END__
