# encoding: utf-8
=begin

 * Name: SiSU

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

 * Author: Ralph Amissah

 * Copyright: (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
   2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 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

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

 * Git
   <http://git.sisudoc.org/gitweb/?p=code/sisu.git;a=summary>
   <http://git.sisudoc.org/gitweb/?p=code/sisu.git;a=blob;f=lib/sisu/v5/se_info_env.rb;hb=HEAD>

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

 ** Description: system environment, resource control and configuration details

=end
@@current_document=Dir.pwd #nil #''
module SiSU_Info_Env
  require_relative 'se_envcall'                            # se_envcall.rb
  require_relative 'html_parts'                            # html_parts.rb
  begin
    require 'singleton'
    require 'fileutils'
      include FileUtils::Verbose
  rescue LoadError
    SiSU_Utils::CodeMarker.new(__LINE__,__FILE__,:fuchsia).
      error('singleton or fileutils NOT FOUND (LoadError)')
  end
  class InfoEnv < SiSU_Env_Call::EnvCall                   # se_envcall.rb
    begin
      require 'pathname'
      require 'fileutils'
        include FileUtils
    rescue LoadError
      SiSU_Utils::CodeMarker.new(__LINE__,__FILE__,:fuchsia).
        error('pathname or fileutils NOT FOUND (LoadError)')
    end
    attr_accessor :filename,:sys,:home,:hostname,:user,:env,:rc,:www,:fnb,:fnn,:fnt,:flv,:webserv_path,:stub_pwd,:base_markup_dir_stub,:stub_src,:webserv_host_cgi,:webserv_port_cgi,:processing,:processing_git,:etc,:yamlrc_dir
    @@image_flag,@@local_image=true,true   #warning on @@image_flag
    @@fb,@@man_path=nil,nil
    def initialize(fns='',md=nil)
      super() #you may not want to re-execute this static info so frequently!
      @init=SiSU_Env::GetInit.new #SiSU_Get_Init::GetInit
      @fns,@md=fns,md
      @env=SiSU_Env::EnvCall.new(fns) if fns #SiSU_Env_Call::EnvCall
      fnb=if @md \
      and defined? @md.fnb
        @md.fnb
      elsif defined? @env.fnb \
      and @env.fnb
        @env.fnb
      elsif @fns.is_a?(String) \
      and not @fns.empty?
        m=/(.+)?\.(?:(?:-|ssm\.)?sst|ssm)$/m
        @fns[m,1] if not @fns.empty?
      end
      if fnb; @@fb ||=fnb
      end
      @sys=SiSU_Info_Sys::InfoSystem.instance
      @fnb ||=@@fb #clean up this... used primarily for zap which is not passed normal parameters
      @fixed_websev_root='' # @home
      @pwd=@@pwd=Dir.pwd
      @base_markup_dir_stub=SiSU_Utils::Path.new.base_markup_stub
      @stub_src=     @base_markup_dir_stub + '/src'
      @stub_pod=     @base_markup_dir_stub + '/pod'
      @stub_epub=    @base_markup_dir_stub + '/epub'
      m=/.+\/(?:src\/)?(\S+)/m # m=/.+?\/(?:src\/)?([^\/]+)$/im # m=/.+\/(\S+)/m
      @stub_pwd=@@pwd[m,1] || '' #; p __LINE__; #p @pwd; #p m; #p @stub_pwd
      pt=Pathname.new(Dir.pwd)
      stub=if output_dir_structure.by_language_code?
        r=Px[:lng_lst_rgx]
        stub=if Dir.pwd =~/.+?\/([^\/]+)(?:\/(#{r})$)/
          lng=pt.split[-1].to_s
          lng_part='/' + lng
          base=pt.split[0].split[-1].to_s
        else
          lng_part='/' + language_default_set
          base=pt.split[-1].to_s
        end
        base + lng_part
      elsif output_dir_structure.by_filetype?
        pt.split[-1].to_s
      elsif  output_dir_structure.by_filename?
        ''
      else
        SiSU_Utils::CodeMarker.new(__LINE__,__FILE__,:fuchsia).
          warn('set output type, by: language, filetype or filename')
      end
      @stub_set_manifest=stub + '/manifest'
    end
    def user
      @sys.user
    end
    def hostname
      @sys.hostname
    end
    def host
      @sys.host
    end
    def arch
      @sys.arch
    end
    def rbver
      @sys.rbver
    end
    def locale
      @sys.locale
    end
    def concord_max
      ((defined? @rc['processing']['concord_max']) \
      && @rc['processing']['concord_max']) \
      ? @rc['processing']['concord_max']
      : (defaults[:concord_max])
    end
    def language_default_set           #set directory (default) language
      ((defined? @rc['default']['language']) \
      && @rc['default']['language'] =~/\S+/) \
      ? @rc['default']['language']
      : 'en'
    end
    def markup_emphasis
      if defined? @rc['default']['emphasis'] \
      and @rc['default']['emphasis'] \
      and @rc['default']['emphasis']=~/bold/
        'bold'
      elsif defined? @rc['default']['emphasis'] \
      and @rc['default']['emphasis'] \
      and @rc['default']['emphasis']=~/italic/
        'italics'
      elsif defined? @rc['default']['emphasis'] \
      and @rc['default']['emphasis'] \
      and @rc['default']['emphasis']=~/underscore/
        'underscore'
      else 'bold'
      end
    end
    def plaintext_wrap
      ((defined? @rc['default']['text_wrap']) \
      && (@rc['default']['text_wrap']) \
      && (@rc['default']['text_wrap'].to_s=~/\d\d+/) \
      && (@rc['default']['text_wrap'].to_i > 19) \
      && (@rc['default']['text_wrap'].to_i < 201)) \
      ? @rc['default']['text_wrap'].to_i
      : 78
    end
    def current_document
      @@current_document||=Dir.pwd
      @@current_document
    end
    def stub_pwd                       #200412
      @stub_pwd
    end
    def base_markup_dir_stub
      @base_markup_dir_stub
    end
    def stub_md_harvest                #watch
      @stub_set_manifest
    end
    def stub_src
      @stub_src
    end
    def stub_pod
      @stub_pod
    end
    def sisupod_v4(opt)
      #processing_path.processing
      #  sisupod
      #    doc/
      #      manifest.txt
      #      en/content.sst                [file content]
      #      fr/content.sst
      #      _sisu
      #        sisu_document_make
      #        image@ (ln -s ../../image)
      #        audio@ (ln -s ../../audio)
      #        video@ (ln -s ../../video)
      #    image/                          [all images for specific document gathered here]
      #    audio/
      #    video/
      spp="#{processing_path.processing}/#{Gt[:sisupod]}"
      sppc="#{spp}/doc/_sisu"
      lng_dirs=[]
      if FileTest.directory?(spp) \
      or FileTest.file?(spp)
        FileUtils::rm_rf(spp)
      end
      paths=[]
      flv=SiSU_Env::EnvCall.new(opt.fns).
        document_language_versions_found
      flv[:f].each {|l| lng_dirs << l[:l] }
      lng_dirs.uniq.each do |lng|
        paths << "#{spp}/doc/#{lng}"
      end
      paths \
      << "#{spp}/image"
     #<< "#{spp}/audio" \
     #<< "#{spp}/video" \
      paths.each do |x|
        unless FileTest.directory?(x)
          FileUtils::mkdir_p(x)
        end
      end
      if FileTest.directory?(sppc)
        pwd=Dir.pwd
        Dir.chdir(sppc)
        FileUtils::ln_s('../../image', 'image')
       #FileUtils::ln_s('../../audio', 'audio')
       #FileUtils::ln_s('../../video', 'video')
        Dir.chdir(pwd)
      end
    end
    def sisupod_v3(opt)
      #processing_path.processing
      #  sisupod
      #    doc/
      #      manifest.txt
      #      en/content.sst                [file content]
      #      fr/content.sst
      #      _sisu
      #        skin/
      #          doc                       [relevant skin if any other than default]
      #        image@ (ln -s ../../image)
      #        audio@ (ln -s ../../audio)
      #        video@ (ln -s ../../video)
      #    image/                          [all images for specific document gathered here]
      #    audio/
      #    video/
      spp="#{processing_path.processing}/#{Gt[:sisupod]}"
      sppc="#{spp}/doc/_sisu"
      lng_dirs=[]
      if FileTest.directory?(spp) \
      or FileTest.file?(spp)
        FileUtils::rm_rf(spp)
      end
      paths=[]
      flv=SiSU_Env::EnvCall.new(opt.fns).
        document_language_versions_found
      flv[:f].each {|l| lng_dirs << l[:l] }
      lng_dirs.uniq.each do |lng|
        paths << "#{spp}/doc/#{lng}"
      end
      paths \
      << "#{spp}/image" \
      << "#{sppc}/skin/doc" \
      << "#{sppc}/skin/dir" \
      << "#{sppc}/skin/site"
     #<< "#{spp}/audio" \
     #<< "#{spp}/video" \
      paths.each do |x|
        unless FileTest.directory?(x)
          FileUtils::mkdir_p(x)
        end
      end
      if FileTest.directory?(sppc)
        pwd=Dir.pwd
        Dir.chdir(sppc)
        FileUtils::ln_s('../../image', 'image')
       #FileUtils::ln_s('../../audio', 'audio')
       #FileUtils::ln_s('../../video', 'video')
        Dir.chdir(pwd)
      end
    end
    def sisupod_v2
      #processing_path.processing
      #  sisupod
      #    content.sst              [file content]
      #    filename.sst             [link to content.sst]
      #    _sisu
      #      skin/
      #        doc                  [relevant skin if any other than default]
      #      image                  [all images for specific document gathered here]
      sisupod_processing_path="#{processing_path.processing}/#{Gt[:sisupod]}"
      if FileTest.directory?(sisupod_processing_path) \
      or FileTest.file?(sisupod_processing_path)
        FileUtils::rm_rf(sisupod_processing_path)
      end
      paths=[]
      paths=[
        "#{processing_path.processing}/#{Gt[:sisupod]}/_sisu/skin/doc",
        "#{processing_path.processing}/#{Gt[:sisupod]}/_sisu/skin/dir",
        "#{processing_path.processing}/#{Gt[:sisupod]}/_sisu/skin/site",
        "#{processing_path.processing}/#{Gt[:sisupod]}/_sisu/image"
      ]
      paths.each {|x| FileUtils::mkdir_p(x) unless FileTest.directory?(x) }
    end
    def defaults                       #multiple default directories
      @default_dir ||=@sys.default_dir #DEFAULT_DIR
    end
    def html_seg_title_banner?
      ((defined? @rc['html']['seg_title_banner']) \
      && @rc['html']['seg_title_banner']==true) \
      ? @rc['html']['seg_title_banner']
      : false
    end
    def html_quick_ref?
      ((defined? @rc['html']['quick_ref']) \
      && @rc['html']['quick_ref']==true) \
      ? @rc['html']['quick_ref']
      : false
    end
    def html_minitoc?
      if defined? @rc['html']['minitoc'] \
      and @rc['html']['minitoc'].is_a?(String)
        @rc['html']['minitoc']
      else false
      end
    end
    def manifest_minitoc?
      if defined? @rc['manifest']['minitoc'] \
      and @rc['manifest']['minitoc'].is_a?(String)
        @rc['manifest']['minitoc']
      else false
      end
    end
    def build
      def omit_list
        @off_list ||=if defined? @rc['omit_list'] \
        and @rc['omit_list'].is_a?(String)
          @rc['omit_list']
        elsif defined? @rc['omit']['list'] \
        and @rc['omit']['list'].is_a?(String)
          @rc['omit']['list']
        else
          nil
        end
      end
      def listed?(test) #fix
        listed=if omit_list
          x=(omit_list.scan(/\b#{test}\b/)).join
          test==x \
          ? true
          : false
        else
          false
        end
        listed
      end
      def ocn?
        if (defined? @rc['omit']['ocn'] \
        and not @rc['omit']['ocn'].nil?) \
        or listed?('ocn')
          :off
        else
          :na
        end
      end
      def toc?
        if (defined? @rc['omit']['toc'] \
        and not @rc['omit']['toc'].nil?) \
        or listed?('toc')
          :off
        else
          :na
        end
      end
      def manifest?
        if (defined? @rc['omit']['manifest'] \
        and not @rc['omit']['manifest'].nil?) \
        or listed?('manifest')
          :off
        else
          :na
        end
      end
      def links_to_manifest?
        if (defined? @rc['omit']['links_to_manifest'] \
        and not @rc['omit']['links_to_manifest'].nil?) \
        or (listed?('links_to_manifest') \
        ||  listed?('manifest_links'))
          :off
        else
          :na
        end
      end
      def metadata?
        if (defined? @rc['omit']['metadata'] \
        and not @rc['omit']['metadata'].nil?) \
        or listed?('metadata')
          :off
        else
          :na
        end
      end
      def minitoc?
        if (defined? @rc['omit']['minitoc'] \
        and not @rc['omit']['minitoc'].nil?) \
        or (listed?('minitoc'))
          :off
        else
          :na
        end
      end
      def manifest_minitoc?
        if (defined? @rc['omit']['manifest_minitoc'] \
        and not @rc['omit']['manifest_minitoc'].nil?) \
        or listed?('manifest_minitoc')
          :off
        else
          :na
        end
      end
      def html_minitoc?
        if (defined? @rc['omit']['html_minitoc'] \
        and not @rc['omit']['html_minitoc'].nil?) \
        or (listed?('html_minitoc') \
        || listed?('minitoc'))
          :off
        else
          :na
        end
      end
      def html_navigation?
        if (defined? @rc['omit']['html_navigation'] \
        and not @rc['omit']['html_navigation'].nil?) \
        or listed?('html_navigation')
          :off
        else
          :na
        end
      end
      def html_navigation_bar?
        if (defined? @rc['omit']['html_navigation_bar'] \
        and not @rc['omit']['html_navigation_bar'].nil?) \
        or listed?('html_navigation_bar')
          :off
        else
          :na
        end
      end
      def segsubtoc?
        if (defined? @rc['omit']['segsubtoc'] \
        and not @rc['omit']['segsubtoc'].nil?) \
        or listed?('segsubtoc')
          :off
        else
          :na
        end
      end
      def html_right_pane?
        if (defined? @rc['omit']['html_right_pane'] \
        and not @rc['omit']['html_right_pane'].nil?) \
        or listed?('html_right_pane')
          :off
        else
          :na
        end
      end
      def html_top_band?
        if (defined? @rc['omit']['html_top_band'] \
        and not @rc['omit']['html_top_band'].nil?) \
        or listed?('html_top_band')
          :off
        else
          :na
        end
      end
      def search_form? #decide later, as is configured here (in sisurc) and can be turned off on command line
        if (defined? @rc['omit']['search_form'] \
        and not @rc['omit']['search_form'].nil?) \
        or listed?('search_form')
          :off
        else
          :na
        end
      end
      def html_search_form? #decide later, as is configured here (in sisurc) and can be turned off on command line
        if (defined? @rc['omit']['html_search_form'] \
        and not @rc['omit']['html_search_form'].nil?) \
        or listed?('html_search_form')
          :off
        else
          :na
        end
      end
      self
    end
    def odt_ocn?
      ((defined? @rc['odt']['ocn']) \
      && @rc['odt']['ocn']==false) \
      ? @rc['odt']['ocn']
      : true
    end
    def xml_docbook_ocn?
      ((defined? @rc['xml_docbook']['ocn']) \
      && @rc['xml_docbook']['ocn']==false) \
      ? @rc['xml_docbook']['ocn']
      : true
    end
    def xml_fictionbook_ocn?
      ((defined? @rc['xml_fictionbook']['ocn']) \
      && @rc['xml_fictionbook']['ocn']==false) \
      ? @rc['xml_fictionbook']['ocn']
      : true
    end
    def xml_scaffold_ocn?
      ((defined? @rc['xml_scaffold']['ocn']) \
      && @rc['xml_scaffold']['ocn']==false) \
      ? @rc['xml_scaffold']['ocn']
      : true
    end
    def plaintext_ocn?
      ((defined? @rc['plaintext']['ocn']) \
      && @rc['plaintext']['ocn']==false) \
      ? @rc['plaintext']['ocn']
      : true
    end
    def textile_ocn?
      ((defined? @rc['textile']['ocn']) \
      && @rc['textile']['ocn']==true) \
      ? @rc['textile']['ocn']
      : false
    end
    def asciidoc_ocn?
      ((defined? @rc['asciidoc']['ocn']) \
      && @rc['asciidoc']['ocn']==true) \
      ? @rc['asciidoc']['ocn']
      : false
    end
    def markdown_ocn?
      ((defined? @rc['markdown']['ocn']) \
      && @rc['markdown']['ocn']==true) \
      ? @rc['markdown']['ocn']
      : false
    end
    def rst_ocn?
      ((defined? @rc['rst']['ocn']) \
      && @rc['rst']['ocn']==true) \
      ? @rc['rst']['ocn']
      : false
    end
    def widget #needs (md) #move
      @rc=SiSU_Env::GetInit.new.sisu_yaml.rc
      @ad=SiSU_Env::GetInit.new.ads
      @html_bits=SiSU_Proj_HTML::Bits.new
      @flag={
        ad: false,
        md: false,
        sk: false,
        rc: false
      }
      def promo?
        @flag[:ad]=if @md.flag_promo \
        && @ad[:flag_promo]
          @flag[:md]=true
          true
        elsif defined? @html_bits.widget_promo \
        and not @html_bits.widget_promo.nil? \
        and @html_bits.widget_promo.is_a?(Array) \
        and @html_bits.widget_promo.length > 0
          @flag[:sk]=true
          true
        elsif defined? @rc['html']['promo'] \
        and not @rc['html']['promo'].nil? \
        and @rc['html']['promo'].length > 0
          @flag[:rc]=true
          true
        else false
        end
        @flag
      end
      def search?
        searches=['sisu']
        flag=false
        if defined? @rc['search']
          searches.each do |type|
            flag=if defined? @rc['search'][type] \
            and defined? @rc['search'][type]['action'] \
            and @rc['search'][type]['flag']==true \
            and @rc['search'][type]['action'] =~/https?:\/\//
              flag=if promo?[:ad]
                false
              elsif defined? @html_bits.widget_search \
              and @html_bits.widget_search==true
                true
              elsif defined? @rc['search'][type]['flag'] \
              and @rc['search'][type]['flag']==true
                true
              else false
              end
            else false
            end
          end
        else false
        end
        flag
      end
      def search_fixed?
        searches=['sisu','hyperestraier']
        flag=if defined? @rc['search']
          searches.each do |type|
            if defined? @rc['search'][type] \
            and defined? @rc['search'][type]['action'] \
            and @rc['search'][type]['action'] =~/https?:\/\// \
            and defined? @rc['search'][type]['db'] \
            and @rc['search'][type]['db'] =~/\S+/
              flag=if promo?[:ad]
                false
              elsif defined? @html_bits.widget_search \
              and @html_bits.widget_search==true
                true
              elsif defined? @rc['search'][type]['flag'] \
              and @rc['search'][type]['flag']==true
                true
              else false
              end
            else false
            end
          end
        else false
        end
      end
      def search_form(type='sisusearch',action=nil,db=nil,table=false)
        rc=SiSU_Env::GetInit.new.sisu_yaml.rc
        create_form_sisu=if action \
        and db \
        and action =~/https?:\/\// \
        and db =~/\S+/
          true
        elsif widget.search?
          db=if rc['search']['sisu']['flag']==true \
          and rc['search']['sisu']['db']=~/\S+/
            (rc['search']['sisu']['db']=~/^#{Db[:name_prefix]}\S+/) \
            ? rc['search']['sisu']['db']
            : "#{Db[:name_prefix]}#{rc['search']['sisu']['db']}"
          else nil
          end
          action=rc['search']['sisu']['action']
          true
        elsif defined? rc['search']['sisu']['flag'] \
        and defined? rc['search']['sisu']['action'] \
        and rc['search']['sisu']['flag']==true \
        and rc['search']['sisu']['action'] =~/https?:\/\//
          true
        else false
        end
        if table
          table_open='<td align="center" bgcolor="#ffffff">'
          table_close='</td>'
        else
          table_open=''
          table_close='<br />'
        end
        form=if create_form_sisu \
        and type=~/sisusearch/ \
        and defined? rc['search']['sisu'] \
        and defined? rc['search']['sisu']['action']
          <<WOK
<!-- SiSU Search -->
#{table_open}
<a name="search"></a>
<form method="get" action="#{rc['search']['sisu']['action']}" target="_top">
<font size="2">
<input type="text" name="s1" size="24" maxlength="255" />
<input type="hidden" name="db" value="#{db}" />
<input type="hidden" name="ltd" value="1000" />
<input type="hidden" name="off" value="0" />
<input type="hidden" name="doc" value="#{@md.fnb}" /><br />
<input type="submit" name="search" value="search doc" />
<input type="submit" name="search" value="search db" />
</font></form>
#{table_close}
<!-- SiSU Search -->
WOK
        else ''
        end
        form
      end
      def search_form_static(action=nil,db=nil)
        rc=SiSU_Env::GetInit.new.sisu_yaml.rc
        create_form=if rc['search']['sisu']['flag']==true \
        and action \
        and db \
        and action =~/https?:\/\// \
        and db =~/\S+/
          true
        elsif widget.search_fixed?
          db=if rc['search']['sisu']['flag']==true \
          and rc['search']['sisu']['db']=~/\S+/
            (rc['search']['sisu']['db']=~/^#{Db[:name_prefix]}\S+/) \
            ? rc['search']['sisu']['db']
            : "#{Db[:name_prefix]}#{rc['search']['sisu']['db']}"
          else nil
          end
          action=rc['search']['sisu']['action']
          true
        else false
        end
        if create_form
          %{<td align="center" bgcolor="#ffffff">
<!-- SiSU Search -->
<a name="search"></a>
<form method="get" action="#{rc['search']['sisu']['action']}" target="_top">
<font size="2">
<input type="text" name="s1" size="24" maxlength="255" />
<br />
<input type="hidden" name="db" value="#{db}" />
<input type="hidden" name="ltd" value="1000" />
<input type="hidden" name="off" value="0" />
<input type="hidden" name="doc" value="#{@md.fnb}" />
<input type="submit" name="search" value="search doc" />
<input type="submit" name="search" value="search db" />
</font>
</form>
<!-- SiSU Search -->
</td> }
        else ''
        end
      end
      def search_action #check
        if search?
        else ''
        end
      end
      self
    end
    def widget_static
      @rc=SiSU_Env::GetInit.new.sisu_yaml.rc
      @html_bits=SiSU_Proj_HTML::Bits.new
      @flag={ ad: false, md: false, sk: false, rc: false }
      def search?
        flag=if defined? @rc['search'] \
        and defined? @rc['search']['sisu'] \
        and defined? @rc['search']['sisu']['action'] \
        and @rc['search']['sisu']['action'] =~/https?:\/\// \
        and defined? @rc['search']['sisu']['db'] \
        and @rc['search']['sisu']['db'] =~/\S+/
          flag=if defined? @html_bits.widget_search \
          and @html_bits.widget_search==true
            true
          elsif defined? @rc['search']['sisu']['flag'] \
          and @rc['search']['sisu']['flag']==true
            true
          else
            false
          end
        else
          false
        end
      end
      def search_fixed?
        flag=if defined? @rc['search'] \
        and defined? @rc['search']['sisu'] \
        and defined? @rc['search']['sisu']['action'] \
        and @rc['search']['sisu']['action'] =~/https?:\/\// \
        and defined? @rc['search']['sisu']['db'] \
        and @rc['search']['sisu']['db'] =~/\S+/ \
        and defined? @rc['search']['sisu']['db'] \
        and @rc['search']['sisu']['db'] =~/\S+/
          flag=if defined? @html_bits.widget_search \
          and @html_bits.widget_search==true
            true
          elsif defined? @rc['search']['sisu']['flag'] \
          and @rc['search']['sisu']['flag']==true
            true
          else
            false
          end
        else
          false
        end
      end
      def search_form(action=nil,db=nil)
        rc=SiSU_Env::GetInit.new.sisu_yaml.rc
        create_form=if defined? rc['search']['sisu']['flag'] \
        and rc['search']['sisu']['flag']==true \
        and action \
        and db \
        and action =~/https?:\/\// \
        and db =~/\S+/
          true
        elsif widget_static.search? \
        and rc['search']['sisu']['flag']==true
          db=if rc['search']['sisu']['db']=~/\S+/
            (rc['search']['sisu']['db']=~/^#{Db[:name_prefix]}\S+/) \
            ? rc['search']['sisu']['db']
            : "#{Db[:name_prefix]}#{rc['search']['sisu']['db']}"
          else nil
          end
          action=rc['search']['sisu']['action']
          true
        else false
        end
        if create_form \
        and @fnb \
        and @fnb=~/\S+/
          %{<!-- SiSU Search -->
<a name="search"></a>
<form method="get" action="#{rc['search']['sisu']['action']}" target="_top">
<font size="2">
<input type="text" name="s1" size="24" maxlength="255" />
<br />
<input type="hidden" name="db" value="#{db}" />
<input type="hidden" name="doc" value="#{@fnb}" />
<input type="submit" name="search" value="search doc" />
<input type="submit" name="search" value="search db" />
</font>
</form>
<!-- SiSU Search --> }
        elsif create_form
          %{<!-- SiSU Search -->
<a name="search"></a>
<form method="get" action="#{rc['search']['sisu']['action']}" target="_top">
<font size="2">
<input type="text" name="s1" size="24" maxlength="255" />
<br />
<input type="hidden" name="db" value="#{db}" />
<input type="submit" name="search" value="search db" />
</font>
</form>
<!-- SiSU Search --> }
        else ''
        end
      end
      def search_action #check
        if search?
        else ''
        end
      end
      self
    end
    def source_file_path
      file=@fns.gsub(/\.ssm(?:\.sst)?/,'.ssm.sst')
      unless file =~/\.ssm\.sst$/; "#{Dir.pwd}"
      else "#{processing_path.composite_file}"
      end
    end
    def source_file_with_path
      file=@fns.gsub(/\.ssm(?:\.sst)?/,'.ssm.sst')
      "#{source_file_path}/#{file}"
    end
    def texpdf_hyperlinks(cli)
      @cli=cli
      @hyplnks=if cli != :na
        cli
      elsif (defined? @rc['default']['pdf_hyperlinks']) \
      && (@rc['default']['pdf_hyperlinks']=~/color/)
        :color
      elsif (defined? @rc['default']['pdf_hyperlinks']) \
      && (@rc['default']['pdf_hyperlinks'] \
      =~/(?:no-color|color-off|mono(?:chrome)?)/)
        :mono
      else :na
      end
      def landscape
        if @cli != :na
          @cli
        elsif (defined? @rc['default']['pdf_hyperlinks_landscape']) \
        && (@rc['default']['pdf_hyperlinks_landscape']=~/color/)
          :color
        elsif (defined? @rc['default']['pdf_hyperlinks_landscape']) \
        && (@rc['default']['pdf_hyperlinks_landscape'] \
        =~/(?:no-color|color-off|mono(?:chrome)?)/)
          :mono
        elsif @hyplnks != :na
          @hyplnks
        else :na
        end
      end
      def portrait
        if @cli != :na
          @cli
        elsif (defined? @rc['default']['pdf_hyperlinks_portrait']) \
        && (@rc['default']['pdf_hyperlinks_portrait']=~/color/)
          :color
        elsif (defined? @rc['default']['pdf_hyperlinks_portrait']) \
        && (@rc['default']['pdf_hyperlinks_portrait'] \
        =~/(?:no-color|color-off|mono(?:chrome)?)/)
          :mono
        elsif @hyplnks != :na
          @hyprlnks
        else :na
        end
      end
      self
    end
    def font
      def size(pt=nil)
        if pt && pt != :na
          pt
        elsif defined? @rc['default']['fontsize'] \
        && @rc['default']['fontsize']=~/\d{1,2}/
          @rc['default']['fontsize']
        else :na
        end
      end
      def texpdf
        # you may wish to check selected font against available fonts:
        # fc-list :outline -f "%{family}\n"
        # fc-list :lang=ja
        def main
          (defined? @rc['default']['texpdf_fontface']) \
          && (@rc['default']['texpdf_fontface']=~/\S{3,}/)  \
          ? @rc['default']['texpdf_fontface']
          : 'Liberation Sans'
        end
        def sans                       # not used
          (defined? @rc['default']['texpdf_fontface_sans']) \
          && (@rc['default']['texpdf_fontface_sans']=~/\S{3,}/)  \
          ? @rc['default']['texpdf_fontface_sans']
          : 'Liberation Sans'
        end
        def serif                      # not used
          (defined? @rc['default']['texpdf_fontface_serif']) \
          && (@rc['default']['texpdf_font_serif']=~/\S{3,}/)  \
          ? @rc['default']['texpdf_fontface_serif']
          : 'Liberation Serif'
        end
        def mono
          (defined? @rc['default']['texpdf_fontface_mono']) \
          && (@rc['default']['texpdf_fontface_mono']=~/\S{3,}/)  \
          ? @rc['default']['texpdf_fontface_mono']
          : 'Liberation Mono'
        end
        def cjk
          (defined? @rc['default']['texpdf_fontface_cjk']) \
          && (@rc['default']['texpdf_fontface_cjk']=~/\S{3,}/)  \
          ? @rc['default']['texpdf_fontface_cjk']
          : 'IPAGothic' # 'IPAGothic' # 'IPAMincho' # 'TakaoMincho' # 'VL Gothic'
        end
        def cjk_zh
          (defined? @rc['default']['texpdf_fontface_cjk_zh']) \
          && (@rc['default']['texpdf_fontface_cjk_zh']=~/\S{3,}/)  \
          ? @rc['default']['texpdf_fontface_cjk_zh']
          : 'IPAGothic'
        end
        def cjk_ja
          (defined? @rc['default']['texpdf_fontface_cjk_ja']) \
          && (@rc['default']['texpdf_fontface_cjk_ja']=~/\S{3,}/)  \
          ? @rc['default']['texpdf_fontface_cjk_ja']
          : 'IPAGothic'
        end
        def cjk_ko
          (defined? @rc['default']['texpdf_fontface_cjk_ko']) \
          && (@rc['default']['texpdf_fontface_cjk_ko']=~/\S{3,}/)  \
          ? @rc['default']['texpdf_fontface_cjk_ko']
          : 'IPAGothic'
        end
        def size(pt=nil)
          if pt && pt != :na
            pt
          elsif (defined? @rc['default']['texpdf_fontsize']) \
          && (@rc['default']['texpdf_fontsize']=~/\d{1,2}/)
            @rc['default']['texpdf_fontsize']
          elsif (defined? @rc['default']['fontsize']) \
          && (@rc['default']['fontsize']=~/\d{1,2}/)
            @rc['default']['fontsize']
          else
            :na
          end
        end
        self
      end
      self
    end
    def path_rel_links
      def html_scroll_2
        if @env.output_dir_structure.by_language_code?
          '../../'
        elsif @env.output_dir_structure.by_filetype?
          '../'
        else
          '../'
        end
      end
      def html_seg_2
        if @env.output_dir_structure.by_language_code?
          '../../../'
        elsif @env.output_dir_structure.by_filetype?
          '../../'
        else
          '../'
        end
      end
      def html_scroll_1
        if @env.output_dir_structure.by_language_code?
          '../'
        elsif @env.output_dir_structure.by_filetype?
          '../'
        else
          './'
        end
      end
      def html_seg_1
        if @env.output_dir_structure.by_language_code?
          '../../'
        elsif @env.output_dir_structure.by_filetype?
          '../../'
        else
          './'
        end
      end
      self
    end
    def read_source_file_array(fns)
      (fns !~/\.ssm.sst$/) \
      ? (IO.readlines(fns, mode: 'r:utf-8', cr_newline: true))
      : (IO.readlines(
           "#{processing_path.composite_file}/#{fns}",
           mode: 'r:utf-8',
           cr_newline: true
        ))
    end
    def read_source_file(fns)
      read_source_file_array(fns)
    end
    def read_source_file_string(fns)
      (fns !~/\.ssm.sst$/) \
      ? (IO.read(fns, mode: 'r:utf-8', cr_newline: true))
      : (IO.read(
           "#{processing_path.composite_file}/#{fns}",
           mode: 'r:utf-8',
           cr_newline: true
        ))
    end
    def source_file_processing_array(fns)
      read_source_file_string(fns).split(/\s*\n\s*\n/m)
    end
    def path                           #dir
      def home
        @sys.home
      end
      def sisurc_path
        GetInit.new.sisu_yaml.rc_path
      end
      def pwd
        @sys.pwd
      end
      def stub_pwd
        @stub_pwd
      end
      def base_markup_dir_stub
        @base_markup_dir_stub
      end
      def stub_epub
        @stub_epub
      end
      def stub_src
        @stub_src
      end
      def stub_pod
        @stub_pod
      end
      def etc
        defaults[:sisu_etc]                                                      #live/dynamic
      end
      def arch
        @sys.dir_arch
      end
      def sitearch
        @sys.dir_sitearch
      end
      def bin
        @sys.dir_bin
      end
      def share                        #shared data repository source directory
        #SiSU_Utils::CodeMarker.new(__LINE__,__FILE__,:green).
        #  mark(defaults[:sisu_share])
        defaults[:sisu_share]
      end
      def style
        if @md \
        && ((@md.opt.opt_act[:dump][:bool] \
        &&   @md.opt.opt_act[:dump][:inst]) \
        ||  (@md.opt.opt_act[:redirect][:bool] \
        &&   @md.opt.opt_act[:redirect][:inst]))
          'css'
        else
         defaults[:stylesheet_stub]
        end
      end
      def sample_data                  #sample data repository source directory
        defaults[:sample_data_path]
      end
      def rc
        @init.rc_path
      end
      def yamlrc
        GetInit.new.sisu_yaml.rc_path
      end
      def man #check use
        (defined? @rc['webserv']['man']) \
        ? "#{webserv}/#{@rc['webserv']['man']}"
        : defaults[:webserv_man]
      end
      def webserv_path #testing, check need, remove
        webserv
      end
      def webserv               #separation required for webrick which cannot use path.output (different requirements as no file is passed)
        man_path=if @@man_path.nil?
          man_path=if defined? @rc['webserv']['path'] \
          and @rc['webserv']['path'] =~/\S\S+/
            pwd=Dir.pwd
            Dir.chdir(SiSU_Utils::Path.new.base_markup)
            man_path=@@man_path=File.expand_path(@rc['webserv']['path'])
            Dir.chdir(pwd)
            man_path
          else defaults[:webserv_path]
          end
        else @@man_path
        end
        man_path_head=man_path.gsub(/(\S+)\/[^\/\s]+$/,'\1')
        unless FileTest.directory?(man_path)
          FileUtils::mkdir_p(man_path) if File.writable?("#{man_path_head}/.")
        end
        @webserv_path=if defined? man_path \
        and File.writable?("#{man_path}/.")
          man_path #web server path as configured in rc file
        elsif FileTest.directory?(defaults[:webserv_path]) \
        and File.writable?("#{defaults[:webserv_path]}/.") #web server path default
          defaults[:webserv_path]
        else #create default directory under home and place output there
          unless FileTest.directory?(defaults[:output_local])
            FileUtils::mkdir_p(defaults[:output_local])
          end
          defaults[:output_local]
        end
      end
      def webserv_stub_ensure
        FileUtils::mkdir_p(path.webserv) unless FileTest.directory?(path.webserv)
        FileUtils::mkdir_p("#{path.webserv}/#{@base_markup_dir_stub}") \
          unless FileTest.directory?("#{path.webserv}/#{@base_markup_dir_stub}")
      end
      def webserv_map_pwd #dir
        "#{path.webserv}/#{base_markup_dir_stub}"
      end
      def webserv_dir           #fixed/hard path to /www web/presentation directory, on Debian /var/www subdirectories are created within it, depending on markup directory stub-name (last segment of markup directory name)
        defaults[:webserv_dir]
      end
      def webserv_image         #web/presentation directory, subdirectories are created within it, depending on markup directory stub-name (last segment of markup directory name)
        images=if defined? @rc['webserv']['images']
          @rc['webserv']['images']
        else defaults[:images]
        end
        "#{path.webserv}/#{images}"
      end
      def output                #web/webserv output directory... subdirectory into which further subdirectories are made based on file names
        r=Px[:lng_lst_rgx]
        u=/.+?\/([^\/]+)(?:\/(?:#{r})$|$)/
        base_stub=@sys.pwd.gsub(u,'\1')
        if Dir.pwd =~/\/#{Gt[:sisupod]}\/[^\/]+\/#{Gt[:pod]}\/#{Gt[:doc]}/
          "#{path.webserv}/#{Gt[:doc]}"
        else
          "#{path.webserv}/#{base_stub}"
        end
      end
      def feed
        (defined? @rc['webserv']['feed']) \
        ? ("#{public_output}/#{@rc['webserv']['feed']}")
        : (defaults[:webserv_feed])
      end
      def feed_home
        "#{public_output}/#{@rc['webserv']['feed_home']}"
      end
      def scripts                                                                #used previously only to include tla version info
        if defined? @rc['project']['path']
          "#{home}/#{@rc['project']['path']}"
        end
      end
      def cgi
        (defined? @rc['webserv']['cgi']) \
        ? "#{@rc['webserv']['cgi']}"
        : (defaults[:webserv_cgi])
      end
      def php
        (defined? @rc['webserv']['php']) \
        ? "#{public_output}/#{@rc['webserv']['php']}"
        : (defaults[:webserv_php])
      end
      #% programs
      def output_tell
        url.webserv_map_pwd
      end
      def image_source                 #image repository source directory
        if defined? @rc['image']['path'] \
        and defined? @rc['image']['public']
          pth="#{@rc['image']['path']}"
          "#{pth}/#{@rc['image']['public']}"
        else
          "#{share}/image"
        end
      end
      def image_source_sisu_includes
        "#{share}/image"
      end
      def image_source_include         #image repository source directory
        if defined? @rc['image']['path'] \
        and defined? @rc['image']['public'] \
        and FileTest.directory?(
          "#{@rc['image']['path']}/#{@rc['image']['public']}"
        )==true
          "#{@rc['image']['path']}/#{@rc['image']['public']}"
        elsif FileTest.directory?("#{@@pwd}/#{defaults[:image_stub]}")==true
          "#{@@pwd}/#{defaults[:image_stub]}"
        elsif FileTest.directory?(
          "#{SiSU_Utils::Path.new.base_markup}/#{defaults[:image_stub]}"
        )==true
          "#{SiSU_Utils::Path.new.base_markup}/#{defaults[:image_stub]}"
        else
          "#{share}/image"
        end
      end
      def image_external
        "#{processing}/external_document/image"
      end
      def image_source_include_local
        if FileTest.directory?(defaults[:image_local])
          defaults[:image_local]
        end
      end
      def image_source_include_remote
        if FileTest.directory?(image_external); image_external
        end
      end
      self
    end
    def processing_path
      def encoding
        pth="#{processing}/#{defaults[:processing_encoding]}"
        FileUtils::mkdir_p(pth) unless FileTest.directory?(pth)
        pth
      end
      def processing_base_tmp
        defaults[:processing_path_tmp_base]
      end
      def tmp_root_dir
        defaults[:processing_dir_tmp_root]
      end
      def root_dir
        proposed_path_base=if defined? @rc['processing']['path'] \
        and not @rc['processing']['path'].nil? \
        and not @rc['processing']['path'].empty?
          x=if @rc['processing']['path'] =~/^(?:~|home)$/
            home #fix
          else @rc['processing']['path']
          end
        else nil
        end
        proposed_dir=if defined? @rc['processing']['dir'] \
        and not @rc['processing']['dir'].nil? \
        and not @rc['processing']['dir'].empty?
          @rc['processing']['dir']
        else defaults[:processing_dir]
        end
        v=SiSU_Env::InfoVersion.instance.get_version
        v_dev=(DEVELOPER[:maintenance]==:true) \
        ? "_#{v[:version]}"
        : ''
        path=if proposed_path_base \
        and FileTest.directory?(proposed_path_base) \
        and File.writable?("#{proposed_path_base}/.")
          x=proposed_dir \
          ? "#{proposed_path_base}/#{proposed_dir}"
          : "#{proposed_path_base}/#{defaults[:processing_dir]}"
        else defaults[:processing_dir_tmp_root]
        end
        path = path + v_dev
      end
      def usr_dir?
        case root_dir
        when /^\/home/ then false
        else                true
        end
      end
      def stub_dir
        (usr_dir?) \
        ? ("#{root_dir}/#{user}/#{stub_pwd}")
        : ("#{root_dir}/#{stub_pwd}") # see defaults[:processing_path]
      end
      def stub_dir_orig # ends up with lang, if lang dir
        (usr_dir?) \
        ? ("#{root_dir}/#{user}/#{stub_pwd}")
        : ("#{root_dir}/#{stub_pwd}") # see defaults[:processing_path]
      end
      def processing_sisupod(opt=nil)  #processing directory, used/needed for sisu work files, has sub-directories (ao,tex etc)
        @opt=opt
        def paths
          processing_path_usr="#{root_dir}/#{user}"
          processing_path_fnb=processing_path_usr \
            + '/' + Gt[:pods] \
            + '/' + @opt.fng
          processing_path_sisupod=processing_path_fnb \
            + '/' + Gt[:sisupod]
          {
            fnb: processing_path_fnb,
            sisupod: processing_path_sisupod,
          }
        end
        def make
          unless FileTest.directory?(root_dir)
            FileUtils::mkdir_p(root_dir)
            File.chmod(0777,root_dir)
          end
          if usr_dir?
            processing_path_usr="#{root_dir}/#{user}"
            FileUtils::mkdir_p(processing_path_usr) \
              unless FileTest.directory?(processing_path_usr)
            File.chmod(0700,processing_path_usr)
          end
          sisupod_processing_path=paths[:sisupod]
          FileUtils::mkdir_p(sisupod_processing_path) \
            unless FileTest.directory?(sisupod_processing_path)
          sisupod_processing_path_lng=if defined? @opt.lng
            sisupod_processing_path \
              + '/' + Gt[:doc] \
              + '/' + @opt.lng
          else
            sisupod_processing_path \
              + '/' + Gt[:doc]
          end
          unless FileTest.directory?(sisupod_processing_path_lng)
            #puts "a processing directory (#{sisupod_processing_path_lng}) is being created for use by sisu"
            FileUtils::mkdir_p(sisupod_processing_path_lng)
            File.chmod(0700,sisupod_processing_path_lng)
          end
          sisupod_processing_path
        end
        self
      end
      def processing                   #processing directory, used/needed for sisu work files, has sub-directories (ao,tex etc)
        unless FileTest.directory?(root_dir)
          FileUtils::mkdir_p(root_dir)
          File.chmod(0777,root_dir)
        end
        if usr_dir?
          processing_path_usr="#{root_dir}/#{user}"
          FileUtils::mkdir_p(processing_path_usr) \
            unless FileTest.directory?(processing_path_usr)
          File.chmod(0700,processing_path_usr)
        end
        FileUtils::mkdir_p(stub_dir) \
          unless FileTest.directory?(stub_dir)
        File.chmod(0700,stub_dir)
        path_processing=[
          stub_dir,
          defaults[:processing_path],
          defaults[:processing_path_home]
        ]
        processing=nil
        path_processing.each do |v|                                              #
          processing=v
          unless FileTest.directory?(processing)
            FileUtils::mkdir_p(processing)
            File.chmod(0700,processing)
          end
          break
        end
        processing
      end
      def ao
        pth=if defined? @rc['processing']['dal'] \
          and @rc['processing']['dal'].is_a?(String)
          "#{processing}/#{@rc['processing']['dal']}"
        else "#{processing}/#{defaults[:processing_ao]}"
        end
        FileUtils::mkdir_p(pth) unless FileTest.directory?(pth)
        pth
      end
      def tune
        pth=if defined? @rc['processing']['tune'] \
          and @rc['processing']['tune'].is_a?(String)
          "#{processing}/#{@rc['processing']['tune']}"
        else "#{processing}/#{defaults[:processing_tune]}"
        end
        FileUtils::mkdir_p(pth) unless FileTest.directory?(pth)
        pth
      end
      def composite_file
        pth=processing_path.ao  #"#{processing}/composite"
        FileUtils::mkdir_p(pth) unless FileTest.directory?(pth)
        pth
      end
      def git
        pth=if defined? @rc['git']['dir'] \
        and @rc['git']['dir'].is_a?(String)
          (@rc['git']['dir'] =~/^(?:~|home)$/) \
          ? home + '/' + Gt[:git]
          : @rc['git']['dir'] + '/' + Gt[:git]
        else defaults[:processing_git]
        end
        unless FileTest.directory?(pth)
          FileUtils::mkdir_p(pth)
          File.chmod(0700,pth)
        end
        pth
      end
      def odf_pth
        pth="#{processing}/odf/#{@fns}"
        pth
      end
      def odf
        odt
      end
      def odt
        pth=odf_pth + '/odt'
        FileUtils::mkdir_p(pth) unless FileTest.directory?(pth)
        pth
      end
      def odf
        pth="#{processing}/odf"
        FileUtils::mkdir_p(pth) unless FileTest.directory?(pth)
        pth
      end
      def odt_bld
        FileUtils::rm_rf(processing_path.odt)
        FileUtils::mkdir_p(processing_path.odt) \
          unless FileTest.directory?(processing_path.odt)
        FileUtils::mkdir_p("#{processing_path.odt}/Configurations2") \
          unless FileTest.directory?("#{processing_path.odt}/Configurations2")
        FileUtils::mkdir_p("#{processing_path.odt}/META-INF") \
          unless FileTest.directory?("#{processing_path.odt}/META-INF")
        FileUtils::mkdir_p("#{processing_path.odt}/Pictures") \
          unless FileTest.directory?("#{processing_path.odt}/Pictures")
        FileUtils::mkdir_p("#{processing_path.odt}/Thumbnails") \
          unless FileTest.directory?("#{processing_path.odt}/Thumbnails")
        processing_path.odt
      end
      def epub
        "#{processing}/epub/#{@fnb}"
      end
      def epub_bld #(md)
        FileUtils::rm_rf(processing_path.epub) \
          if FileTest.directory?(processing_path.epub)
        FileUtils::mkdir_p(processing_path.epub) \
          unless FileTest.directory?(processing_path.epub)
        FileUtils::mkdir_p("#{processing_path.epub}/META-INF") \
          unless FileTest.directory?("#{processing_path.epub}/META-INF")
        FileUtils::mkdir_p("#{processing_path.epub}/#{Ep[:d_oebps]}/image") \
          unless FileTest.directory?("#{processing_path.epub}/#{Ep[:d_oebps]}/image")
        FileUtils::mkdir_p("#{processing_path.epub}/#{Ep[:d_oebps]}/css") \
          unless FileTest.directory?("#{processing_path.epub}/#{Ep[:d_oebps]}/css")
        processing_path.epub
      end
      def epub_cp_images(md)
        pth="#{processing_path.epub}/#{Ep[:d_oebps]}/image"
        FileUtils::mkdir_p(pth) unless FileTest.directory?(pth)
        src="#{path.share}/image"
        images=%W[bullet_09.png arrow_next_red.png arrow_prev_red.png arrow_up_red.png]
        images.each do |i| #move to avoid repeated tests
          if FileTest.file?("#{src}/#{i}")
            FileUtils::cp("#{src}/#{i}","#{pth}/#{i}") \
              unless FileTest.file?("#{pth}/#{i}")
          else STDERR.puts %{\t*WARN* did not find image - "#{i}" [#{__FILE__}:#{__LINE__}]}
          end
        end
        pth
      end
      def tex
        pth=if defined? @rc['processing']['latex'] \
        and @rc['processing']['latex'].is_a?(String)
          "#{processing}/#{@rc['processing']['latex']}"
        else "#{processing}/#{defaults[:processing_latex]}"
        end
        FileUtils::mkdir_p(pth) unless FileTest.directory?(pth)
        pth
      end
      def texi
        pth=if defined? @rc['processing']['texinfo'] \
        and @rc['processing']['texinfo'].is_a?(String)
          "#{processing}/#{@rc['processing']['texinfo']}"
        else "#{processing}/#{defaults[:processing_texinfo]}"
        end
        FileUtils::mkdir_p(pth) unless FileTest.directory?(pth)
        pth
      end
      def texinfo                      #texinfo webserv, check
        "#{processing}/#{defaults[:processing_texinfo]}"
      end
      def manpage
        "#{path.output}/man"
      end
      def lout
        pth=if defined? @rc['processing']['lout'] \
        and @rc['processing']['lout'].is_a?(String)
          "#{processing}/#{@rc['processing']['lout']}"
        else "#{processing}/#{defaults[:processing_lout]}"
        end
        FileUtils::mkdir_p(pth) unless FileTest.directory?(pth)
        pth
      end
      def sql
        pth="#{processing}/sql"
        FileUtils::mkdir_p(pth) unless FileTest.directory?(pth)
        pth
      end
      def sqlite
        pth=if defined? @rc['processing']['sqlite'] \
        and @rc['processing']['sqlite'].is_a?(String)
          "#{processing}/#{@rc['processing']['sqlite']}"
        else "#{processing}/#{defaults[:processing_sqlite]}"
        end
        FileUtils::mkdir_p(pth) unless FileTest.directory?(pth)
        pth
      end
      def postgresql
        pth=if defined? @rc['processing']['postgresql'] \
        and @rc['processing']['postgresql'].is_a?(String)
          "#{processing}/#{@rc['processing']['postgresql']}"
        else "#{processing}/#{defaults[:processing_postgresql]}"
        end
        FileUtils::mkdir_p(pth) unless FileTest.directory?(pth)
        pth
      end
      self
    end
    def url
      def hostname
        "http://#{@sys.hostname}"
      end
      def dir_url
        "file://#{path.webserv}/#{stub_pwd}"
      end
      def localhost
        "http://localhost/#{stub_pwd}"
      end
      def local
        "http://#{hostname}/#{@stub_pwd}"
      end
      def root
        if defined? @rc['webserv']['url_root'] \
        and @rc['webserv']['url_root'] =~/https?:\/\//
          "#{@rc['webserv']['url_root']}/#{@stub_pwd}"
        elsif defined? @rc['webserv']['url_root'] \
        and @rc['webserv']['url_root'] =~/localhost/
          "http://localhost/#{@stub_pwd}"
        else "file://#{path.output}"
        end
      end
      def remote
        root
      end
      def txt
        "#{root}/txt"
      end
      def html
        "#{root}/html"
      end
      def epub
        "#{root}/epub"
      end
      def odt
        "#{root}/odt"
      end
      def pdf
        "#{root}/pdf"
      end
      def src_txt
        "#{root}/src"
      end
      def src_pod
        "#{root}/pod"
      end
      def pot
        "#{root}/po4a/pot"
      end
      def po
        "#{root}/po4a/po"
      end
      def webserv_host_base(opt=nil)
        if defined? @rc['webserv']['host']
          case  @rc['webserv']['host']
          when /https?:\/\// then @rc['webserv']['host']
          when /\S+/         then "http://#{@rc['webserv']['host']}"
          else                    defaults[:webserv_host_cgi]
          end
        else                      defaults[:webserv_host_cgi]
        end
      end
      def webserv_cgi(opt=nil)         #web url for local webserv (localhost, or hostname)
        http=if defined? @rc['webserv_cgi']['host'] \
        and @rc['webserv_cgi']['host'].is_a?(String)
          http=((@rc['webserv_cgi']['host'] =~ /https?:\/\//) ? '' : 'http://') #check https? missing
          if port.webserv_port_cgi
            http + @rc['webserv_cgi']['host'] + ':' \
            + port.webserv_port_cgi + '/' \
            + @stub_pwd
          else
            http + @rc['webserv_cgi']['host'] + '/' \
            + @stub_pwd
          end
        else
          http=((webserv_host_base=~/https?:\/\//) ? '' : 'http://')
          if port.webserv_port_cgi(opt)
            http + webserv_host_base + ':' \
            + port.webserv_port_cgi(opt) + '/'\
            + @stub_pwd
          else
            http + webserv_host_base + '/' \
            + @stub_pwd
          end
        end
        http=http.strip
      end
      def webserv_base_cgi(opt=nil)    #web url for local webserv (localhost, or hostname)
        http_cgi=if opt.selections.str =~/--webserv-(?:cgi|db|search)[=-]["']?(\S+)["']+/
          m=$1
          (m=~/http\/\/:/) ? m : %{http://#{m}}
        elsif defined? @rc['webserv_cgi']['host'] \
        and @rc['webserv_cgi']['host'].is_a?(String)
          http=((@rc['webserv_cgi']['host'] =~ /https?:\/\//) ? '' : 'http://')
          if port.webserv_port_cgi(opt)
            http + @rc['webserv_cgi']['host'] + ':' \
            + port.webserv_port_cgi(opt).to_s
          else
            http + @rc['webserv_cgi']['host']
          end
        else
          http=((webserv_host_base=~/https?:\/\//) ? '' : 'http://')
          if port.webserv_port_cgi(opt)
            http + webserv_host_base + ':' \
            + port.webserv_port_cgi(opt).to_s
          else http + webserv_host_base
          end
        end
        http_cgi=http_cgi.strip
        #%q{http://#{ENV['HTTP_HOST']}}
      end
      def webrick #must have a port    #REMOVE
        if defined? @rc['webserv_cgi']['host'] \
        and @rc['webserv_cgi']['host'].is_a?(String)
          http=if @rc['webserv_cgi']['host'] =~/http:\/\//
            'http://'
          elsif @rc['webserv_cgi']['host'] =~/https:\/\//
            'https://'
          else defaults
          end
          http + @rc['webserv_cgi']['host']
        elsif webserv_host_base \
        and webserv_host_base.is_a?(String)
          webserv_host_base
        else
          #http + 'localhost'
          'localhost'
        end
      end
      def webserv                      #web url for local webserv (localhost, or hostname)
        if defined? @rc['webserv']['url_root'] \
        and @rc['webserv']['url_root'] =~/http/
          # needed for alternative output dir structures, fixes manifest url links, check may cause problems elsewhere
          @rc['webserv']['url_root']
        elsif path.webserv_dir \
        and path.webserv =~ /#{path.webserv_dir}/ #revisit
          path.webserv + '/' \
            + @base_markup_dir_stub.
              gsub(/#{path.webserv_dir}/,
                "#{url.hostname}/#{@stub_pwd}")
        elsif defined? @rc['webserv']['webrick_url'] \
        and @rc['webserv']['webrick_url']==false
          'file://' + path.webserv
        elsif port.webserv_port_cgi =~/\S+/
          url.hostname + ':' + port.webserv_port_cgi
        else
          url.hostname
        end
      end
      def webserv_base                 #web url for local webserv (localhost, or hostname)
        if path.webserv_dir \
        and path.webserv =~ /#{path.webserv_dir}/ #revisit
          path.webserv + '/' \
          + @stub_pwd.
            gsub(/#{path.webserv_dir}/,
              "#{url.hostname}")
        elsif defined? @rc['webserv']['webrick_url'] \
        and @rc['webserv']['webrick_url']==false
          "file://#{path.webserv}"
        else "#{url.webrick_base}"
        end
      end
      def webserv_files_from_db(opt=nil) #sort this out, messy
        if opt.selections.str =~/--webserv-output[=-]["']?(\S+)["']+/
          m=$1
          (m=~/(?:http|file\/)\/\/:/) ? m : %{http://#{m}}
        else
          show_output_on=if defined? @rc['webserv_cgi']['show_output_on']
            @rc['webserv_cgi']['show_output_on']
          elsif  defined? @rc['webserv_cgi']['file_links']
            @rc['webserv_cgi']['file_links']
          else ''
          end
          m=case show_output_on
          when /webserv_cgi/ then url.webserv_base_cgi(opt)
          when /webserv/     then @rc['webserv']['url_root']
          when /https?:\/\// then @rc['webserv_cgi']['file_links']
          when /\S+/         then 'http://' + @rc['webserv_cgi']['file_links']
          else                     webserv_base_cgi(opt)
          end
        end
        #%q{http://#{ENV['HTTP_HOST']}/cgi-bin}
      end
      def cgi_sample_search_form_name(opt=nil)
        if opt.selections.str \
        =~/--(?:cgi-)?search-form-name[=-]["']?(\S+?\.cgi)/
          $1
        elsif not opt.selections.str =~/--db[=-]["']?sqlite/ \
        and defined? @rc['search'] \
        and defined? @rc['search']['sisu'] \
        and defined? @rc['search']['sisu']['action'] \
        and @rc['search']['sisu']['action'] =~/https?:\/\/\S+?\.cgi/
          /(?:https?:\/\/\S+?)\/([^\/]+?\.cgi)$/.
            match(@rc['search']['sisu']['action'])[1]
        else
          (opt.selections.str =~/--db[=-]["']?sqlite/) \
          ? "#{Db[:name_prefix_db]}sqlite.cgi" \
          :  "#{Db[:name_prefix_db]}pg.cgi"
        end
      end
      def sample_search_form_title(organised_by=:language)
        title=if defined? @rc['search']['sisu']['title'] \
        and @rc['search']['sisu']['title'] =~/\S+/
          @rc['search']['sisu']['title']
        else %{SiSU (generated sample) search form}
        end
        title=title + " (content organised by #{organised_by})"
      end
      def output_tell                  #BROKEN Revisit 2011-02
        output_type=if defined? @rc['show_output_on'] \
        and @rc['show_output_on'] \
        =~/^(?:filesystem|webserv|(?:local|remote)(?:_webserv)?|webrick)/
          @rc['show_output_on']
        else 'filesystem'
        end
        case output_type
        when /^filesystem(?:_url)?/       then url.dir_url
        when /^remote(?:_webserv)?/       then url.remote
        when /^(?:webserv|local_webserv)/ then url.local
        when /^local(:\d+)/               then url.hostname + $1 + '/' + stub_pwd
        when /^localhost(:\d+)/           then url.localhost + $1 +  '/' + stub_pwd
        when /^localhost/                 then url.localhost
        when /^webrick/                   then url.webrick
        when /^path/                      then url.webserv_map_pwd
        else                                   url.webserv_map_pwd
        end
      end
      def images
        "#{Xx[:html_relative2]}/_sisu/image"
      end
      #def images
      #  '../_sisu/image'
      #end
      def images_local
        if FileTest.directory?(path.image_source_include)
          path.image_source_include
        else
          if @@local_image==true
            cmd=@md.opt.selections.str ? @md.opt.selections.str : ''
            SiSU_Screen::Ansi.new(
              cmd,
              "WARNING - no local image directory or images:",
              defaults[:image_local]
            ).warn unless @md.opt.act[:quiet][:set]==:on
            @@local_image=false
          end
          url.images
        end
      end
      def images_external
        if FileTest.directory?(image_external)
          if @@image_flag
            images=Dir.glob("#{image_external}/*.{png,jpg,gif}")
            pth=path.webserv + '/' \
            + @stub_pwd
            FileUtils::mkdir_p("#{pth}/_sisu/image_external") \
              unless FileTest.directory?("#{pth}/_sisu/image_external")
            images.each { |i| File.install(i,"#{pth}/#{i}") } \
              unless images.length > 0
            @@image_flag=false
          end
          "#{Xx[:html_relative2]}/_sisu/image_external"
        else
          if @@local_image==true
            SiSU_Screen::Ansi.new(
              @cmd,
              'WARNING - image directory for external images or no such images:',
              :image_external
            ).warn unless @md.opt.act[:quiet][:set]==:on
            @@local_image=false
          end
          url.images_external
        end
      end
      def images_epub
        './image'
      end
      self
    end
    def port
      def webrick_port
        if @md \
        and @md.opt.act[:sample_search_form][:set]==:on \
        and @md.opt.selections.str=~/port=(\d+)/
           $1
        else
          if defined? @rc['webserv_cgi']['port']
            if @rc['webserv_cgi']['port'].nil? \
            and (defined? @md.opt.selections \
            and @md.opt.selections.str=~/webrick/)
              defaults[:webserv_port_cgi]
            elsif not @rc['webserv_cgi']['port'].nil?
              @rc['webserv_cgi']['port']
            else defaults[:webserv_port_cgi]
            end
          else   defaults[:webserv_port_cgi]
          end
        end
      end
      def webserv_port_cgi(opt=nil)
        port=if opt \
        and opt.act[:sample_search_form][:set]==:on \
        and opt.selections.str=~/port[=-](\d+)/
           $1
        else
          port=if defined? @rc['webserv_cgi']['port']
            if @rc['webserv_cgi']['port'].nil? \
            and (defined? opt.selections \
            and opt.selections.str=~/webrick/)
              defaults[:webserv_port_cgi]
            elsif not @rc['webserv_cgi']['port'].nil?
              @rc['webserv_cgi']['port']
            else nil
            end
          else
            if (defined? opt.selections \
            and opt.selections.str=~/webrick/)
              defaults[:webserv_port_cgi]
            else nil
            end
          end
        end
        port.to_s
      end
      self
    end
    def digest_conf?
      if defined? @rc['default']['digest'] \
      and @rc['default']['digest'] != nil
        case @rc['default']['digest']
        when /^sha(?:5|512)?$/ then :sha512
        when /^sha(?:2|256)?$/ then :sha256
        when /^md5$/           then :md5
        else                        :sha256
        end
      else                          :sha256
      end
    end
    def digest(opt=nil)
      @opt=opt
      def type
        if @opt
          case @opt.act[:hash_digest_algo]
          when :sha512 then :sha512
          when :sha256 then :sha256
          when :md5    then :md5
          else              digest_conf?
          end
        else                digest_conf?
        end
      end
      def length
        case digest(@opt).type
        when :sha512 then 128
        when :sha256 then  64
        when :md5    then  32
        else               64
        end
      end
      def pattern
        "[0-9a-f]{#{digest(@opt).length}}" #/[0-9a-f]{#{digest.length}}/
      end
      self
    end
    def program
      def text_editor
        if defined? @rc['program_select']['editor'] \
        and @rc['program_select']['editor'] =~/\S\S+/
          @rc['program_select']['editor']
        elsif defined? @rc['program_select']['text_editor'] \
        and @rc['program_select']['text_editor'] =~/\S\S+/
          @rc['program_select']['text_editor']
        else 'editor'                                                            #'gvim -c :R -c :S'
        end
      end
      def pdf_viewer
        ((defined? @rc['program_select']['pdf_viewer']) \
        && @rc['program_select']['pdf_viewer'] =~/\S\S+/) \
        ? @rc['program_select']['pdf_viewer']
        : 'pdf-viewer'                                                        #'evince'
      end
      def web_browser
        if defined? @rc['program_select']['www_browser'] \
        and @rc['program_select']['www_browser'] =~/\S\S+/
          @rc['program_select']['www_browser']
        elsif defined? @rc['program_select']['web_browser'] \
        and @rc['program_select']['web_browser'] =~/\S\S+/
          @rc['program_select']['web_browser']
        else 'x-www-browser'                                                      #'firefox' 'iceweasel' 'kazehakase' 'galeon'
        end
      end
      def www_browser
        web_browser
      end
      def console_web_browser
        if defined? @rc['program_select']['console_www_browser'] \
        and @rc['program_select']['console_www_browser'] =~/\S\S+/
          @rc['program_select']['console_www_browser']
        elsif defined? @rc['program_select']['console_web_browser'] \
        and @rc['program_select']['console_web_browser'] =~/\S\S+/
          @rc['program_select']['console_web_browser']
        else 'console-www-browser'                                             #'lynx' 'links' 'links2' 'elinks' 'w3m'
        end
      end
      def console_www_browser
        web_browser
      end
      def epub_viewer
        ((defined? @rc['program_select']['epub_viewer']) \
        && @rc['program_select']['epub_viewer'] =~/\S\S+/) \
        ? @rc['program_select']['epub_viewer']
        : 'ebook-viewer'                                                    #'calibre' 'fbreader'
      end
      def xml_viewer
        ((defined? @rc['program_select']['xml_viewer']) \
        && @rc['program_select']['xml_viewer'] =~/\S\S+/) \
        ? @rc['program_select']['xml_viewer']
        : text_editor
      end
      def docbook_viewer
        ((defined? @rc['program_select']['xml_viewer']) \
        && @rc['program_select']['xml_viewer'] =~/\S\S+/) \
        ? @rc['program_select']['xml_viewer']
        : text_editor
      end
      def fictionbook_viewer
        ((defined? @rc['program_select']['xml_viewer']) \
        && @rc['program_select']['xml_viewer'] =~/\S\S+/) \
        ? @rc['program_select']['xml_viewer']
        : text_editor
      end
      def xml_editor
        xml_viewer
      end
      def odf_viewer
        ((defined? @rc['program_select']['odf_viewer']) \
        && @rc['program_select']['odf_viewer'] =~/\S\S+/) \
        ? @rc['program_select']['odf_viewer']
        : 'lowriter'                                                           #'odf-viewer','oowriter'
      end
      def manpage_viewer
        'man'
      end
      def manpage_generator
        ((defined? @rc['program_select']['man']) \
        && @rc['program_select']['man'] =~/\S\S+/) \
        ? @rc['program_select']['man']
        : 'nroff -man'                                                        #'nroff -man' #'groff -man -Tascii'
      end
      def texinfo
        ((defined? @rc['program_select']['info_viewer']) \
        && @rc['program_select']['info_viewer'] =~/\S\S+/) \
        ? @rc['program_select']['info_viewer']
        : 'pinfo -f'                                                          #'pinfo -f' 'info' 'tkinfo'
      end
      def file_encoding
        is=(defined? @rc['program_set']['file_encoding']) \
        ? @rc['program_set']['encoding'] : ''
        (is.nil? || is==true) ? 'encoding' : is
      end
      def wc #wordcount
        is=(defined? @rc['program_set']['wc']) \
          ? @rc['program_set']['wc'] : ''
        (is.nil? || is==true) ? 'wc' : is
      end
      def tidy
        is=(defined? @rc['program_set']['tidy']) \
          ? @rc['program_set']['tidy'] : nil
        (is.nil? || is==true) ? 'tidy' : is
      end
      def rmagick
        is=(defined? @rc['program_set']['rmagick']) \
          ? @rc['program_set']['rmagick'] : nil
        (is.nil? || is==true) ? 'rmagick' : is
      end
      def rexml                        #should be part of ruby 1.8 but apparently not always
        is=(defined? @rc['program_set']['rexml']) ? \
          @rc['program_set']['rexml'] : ''
        (is.nil? || is==true) ? 'rexml' : is
      end
      def pdflatex
        is=(defined? @rc['program_set']['pdflatex']) ? \
          @rc['program_set']['pdflatex'] : ''
        (is.nil? || is==true) ? 'pdflatex' : is
      end
      def postgresql
        is=(defined? @rc['program_set']['postgresql']) ? \
          @rc['program_set']['postgresql'] : ''
        (is.nil? || is==true) ? 'postgresql' : is
      end
      def sqlite
        is=(defined? @rc['program_set']['sqlite']) ? \
          @rc['program_set']['sqlite'] : ''
        (is.nil? || is==true) ? 'sqlite' : is
      end
      self
    end
    def i18n
      def language                     # language settings
        m=/.+\/\S+?\~(\S+)/
        pwd=Dir.pwd
        conf=(defined? @rc['default']['language']) \
        ? @rc['default']['language'] : nil
        l=if pwd=~ m    then pwd[m,1]                                        #2 directory: by visible directory name
        elsif conf      then @rc['default']['language']                      #3 config: from sisurc.yaml
        else            defaults[:language]                                  #4 sisu: program default
        end                                                                  #1 document: param gets
        SiSU_Env::StandardiseLanguage.new(l)
      end
      #def multilingual
      #  x=(defined? @rc['output_structure']['multilingual'] \
      #  && @rc['output_structure']['multilingual'] ==true) \
      #  ? true : false
      #end
      #def bundle
      #  x=(defined? @rc['output_structure']['bundle'] \
      #  && @rc['output_structure']['bundle'] ==true) \
      #  ? true : false
      #end
      def lang_filename(l)
        @lang={}
        x=if output_dir_structure.by_language_code?
          (( defined? @rc['default']['language_file']) \
          && @rc['default']['language_file'] != nil) \
          ? @rc['default']['language_file']
          : 1
        else 0
        end
        if (l != defaults[:language_code]) \
        or (language.code != defaults[:language_code]) #watch
          if x==1    then @lang[:pre],@lang[:mid],@lang[:post]="#{l}.",'',''
          elsif x==2 then @lang[:pre],@lang[:mid],@lang[:post]='',".#{l}",''
          elsif x==3 then @lang[:pre],@lang[:mid],@lang[:post]='','',".#{l}"
          else            @lang[:pre],@lang[:mid],@lang[:post]='','',''
          end
        else              @lang[:pre],@lang[:mid],@lang[:post]='','',''
        end
        @lang
      end
      self
    end
    def file_encoding
      is=''
      if defined? @rc['program_set']['file_encoding']
        is=@rc['program_set']['encoding']
      end
      if is.nil? \
      or is==true
        is='encoding'
      end
      is
    end
    def papersize                      # paper settings, default overidden in param if set within document
      (defined? @rc['default']['papersize']) \
      ? @rc['default']['papersize'].downcase
      : (defaults[:papersize].downcase)
    end
    def odf_structure
      FileUtils::rm_rf(processing_path.processing_path.odf_pth)
      FileUtils::mkdir_p(processing_path.processing_path.odf_pth)
      system(
        "unzip -q #{path.share}/#{SiSU_is[:version_dir]}/odf/odt.zip -d #{processing_path.odf_pth}"
      )
    end
    def sisupod_gen(fns_pod)
      sisupod_gen_v3(fns_pod)
    end
    def sisupod_gen_v3(fns_pod)
      pwd=Dir.pwd
      sisupod_processing_path=
        processing_path.processing + '/' + Gt[:sisupod]
      if FileTest.directory?(sisupod_processing_path) \
      or FileTest.file?(sisupod_processing_path)
        FileUtils::rm_rf(sisupod_processing_path)
      end
      unless FileTest.directory?(sisupod_processing_path)
        FileUtils::mkdir_p(sisupod_processing_path)
      end
      f_pod=if FileTest.file?("#{Dir.pwd}/#{fns_pod}")
        "#{Dir.pwd}/#{fns_pod}"
      elsif FileTest.file?(fns_pod)
        fns_pod
      end
      if f_pod \
      && FileTest.file?(f_pod)
        (SiSU_Env::SystemCall.new.program_found?('tree')) \
        ? 'tree ' + processing_path.processing + '/' + Gt[:sisupod]
        : ''
        if FileTest.directory?(processing_path.processing)
          Dir.chdir(processing_path.processing)
          system(%{tar xJf #{f_pod}})
          Dir.chdir(pwd)
        end
        #system(tree)                                                          #enable if (/[vVM]/)
      else
        SiSU_Screen::Ansi.new(
          '',
          '*WARN* file not found: ' + fns_pod
        ).warn unless @md.opt.act[:quiet][:set]==:on
      end
      sisupod_processing_path
    end
    def sisupod_gen_v2(fns_pod)
      sisupod_processing_path=
        processing_path.processing + '/' + Gt[:sisupod]
      if FileTest.directory?(sisupod_processing_path) \
      or FileTest.file?(sisupod_processing_path)
        FileUtils::rm_rf(sisupod_processing_path)
      end
      unless FileTest.directory?(sisupod_processing_path)
        FileUtils::mkdir_p(sisupod_processing_path)
      end
      (FileTest.file?(fns_pod)) \
      ? system("unzip -q #{fns_pod} -d #{processing_path.processing}")
      : (SiSU_Screen::Ansi.new(
          '',
          "*WARN* file not found: #{fns_pod}"
        ).warn unless @md.opt.act[:quiet][:set]==:on)
      sisupod_processing_path
    end
  end
end
__END__
