#!/usr/bin/env ruby
raise "Please, use ruby1.8.0 or later." if RUBY_VERSION < "1.8.0"
=begin
 * Name: SiSU - Simple information Structuring Universe - Structured information, Serialized Units
 * Author: Ralph Amissah
   * http://www.jus.uio.no/sisu
   * http://www.jus.uio.no/sisu/SiSU/download

 * Description: SiSU information Structuring Universe, processing
   * $Id$
 * Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 Ralph Amissah

 * License: GPL 2 or later

  Summary of GPL 2

  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 2 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, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA

  If you have Internet connection, the latest version of the GPL should be
  available at these locations:
    http://www.fsf.org/licenses/gpl.html
    http://www.gnu.org/copyleft/gpl.html
    http://www.jus.uio.no/sisu/gpl2.fsf

  SiSU was first released to the public on January 4th 2005

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

  © Ralph Amissah 1997, current 2005.
  All Rights Reserved.

 * Ralph Amissah: ralph@amissah.com
                  ralph.amissah@gmail.com

=end
Version='0.37'
SiSU_lib='sisu/' + Version
$VERBOSE=nil
PWD=Dir.pwd
module SiSU
  require "#{SiSU_lib}/sysenv"
  include SiSU_Screen
  class Op
    def initialize(cf,argv,x,tell)
      @cf,@argv,@x,@tell=cf,argv,x,tell
      @n_do=0
    end
    def select
      require "#{SiSU_lib}/#@x"
      @argv.each do |fns|
        if FileTest.file?(fns)
      	  case fns
      	  when /\.(?:[_-]?sst|ssm)$/
            case @x
            #when /^metaverse$/:  SiSU_Metaverse::Source.new(fns,@cf).read      # -m
            when /^wmap$/:       SiSU_Wordmap::Source.new(fns,@cf).read        # -w
            when /^source$/:     SiSU_Markup::Source.new(fns,@cf).read         # -s
            when /^sisudoc$/:    SiSU_Doc::Source.new(fns,@cf).read            # -S
            when /^digests$/:    SiSU_Digest_view::Source.new(fns,@cf).read    # -N
            when /^plaintext$/:  SiSU_Plaintext::Source.new(fns,@cf).read      # -a -e -f
            when /^odf$/:        SiSU_ODF::Source.new(fns,@cf).read            # -o
            when /^texpdf$/:     SiSU_Tex::Source.new(fns,@cf).read            # -p
            when /^texinfo$/:    SiSU_TexInfo::Source.new(fns,@cf).read        # -I
            when /^docbook$/:    SiSU_Docbook::Source.new(fns,@cf).read        # -B
            when /^xml$/:        SiSU_XML_SAX::Source.new(fns,@cf).read        # -x
            when /^xml_dom$/:    SiSU_XML_DOM::Source.new(fns,@cf).read        # -X
            when /^xhtml$/:      SiSU_XHTML::Source.new(fns,@cf).read          # -b
            when /^manifest$/:   SiSU_Manifest::Source.new(fns,@cf).read       # -y
            when /^urls$/:       SiSU_urls::Source.new(fns,@cf).read           # -u -v -V -M
            when /^zap$/:        SiSU_Zap::Source.new(fns,@cf).read            # -Z
            when /^dbi$/:        SiSU_DBI::SiSU_SQL.new(@cf,@tell,fns).connect #-D
            when /^remote_put$/ 
              case @tell
              when /scp/:       SiSU_Remote::Put.new(fns,@cf).scp             # -r
              when /rsync/:     SiSU_Remote::Put.new(fns,@cf).rsync           # -R
              else              #SiSU_Remote::Put.new(fns,@cf).scp
              end
            end
    	      @n_do=@n_do+1
            tell=SiSU_Screen::Ansi.new(@cf,@n_do,"#{@x.upcase} processed")
            tell.files_processed unless @cf =~/q/
            ObjectSpace.garbage_collect
      	  else                                 #print "not processed --> ", fns, "\n"
      	  end
        else                                   Operations.new(fns,@tell).not_found
        end
      end
      Operations.new.counter
    end
  end
  class Operations_database
    @@n_do=0
    def initialize(cf,operation='',fns='')
      @cf,@operation,@fns=cf,operation,fns
      @cX=SiSU_Screen::Ansi.new(@cf).cX
    end
    def counter
      @@n_do=0
    end
    def dbi                                                                      # -D -d
      require "#{SiSU_lib}/dbi"
      SiSU_DBI::SiSU_SQL.new(@cf,@operation,@fns).connect
    	@@n_do=@@n_do+1
      if @cf =~/D/:    tell=SiSU_Screen::Ansi.new(@cf,@@n_do,'Postgres entries processed')
      elsif @cf =~/d/: tell=SiSU_Screen::Ansi.new(@cf,@@n_do,'Sqlite entries processed')
      end
      tell.files_processed unless @cf =~/q/
      ObjectSpace.garbage_collect
    end
  end
  class Operations
    @@n_do=@@n_files_scroll=@@n_files_seg=@@n_files_scrollseg=@@n_files_nav=@@n_files_nav=0
    def initialize(fns='',cf='')
      @fns,@cf=fns,cf
      @cX=SiSU_Screen::Ansi.new(@cf).cX
    end
    def counter
      @@n_do=0
    end
    def homepage                                                                 # -C
      require "#{SiSU_lib}/conf"
      SiSU_initialize::SiSU_Config.new('',@cf).make_homepage
    end
    def conf                                                                     # -c -C
      require "#{SiSU_lib}/conf"
      SiSU_initialize::SiSU_Config.new('',@cf).css
      SiSU_initialize::SiSU_Config.new('',@cf).dtd
    end
    def cp_webserver_images                                                      # -CC
      require "#{SiSU_lib}/conf"
      SiSU_initialize::SiSU_Config.new('',@cf).cp_webserver_images
    end
    def cp_local_image_set                                                       # -C
      require "#{SiSU_lib}/conf"
      SiSU_initialize::SiSU_Config.new('',@cf).cp_local_images
      SiSU_initialize::SiSU_Config.new('',@cf).cp_external_images
    end
    def remote_put_base_site_rsync                                               # -CR
      require "#{SiSU_lib}/remote_put"
      SiSU_Remote::Put_base.new(@cf).rsync_base
    end
    def remote_put_base_site_rsync_match                                         # -CCRZ
      require "#{SiSU_lib}/remote_put"
      SiSU_Remote::Put_base.new(@cf).rsync_base_sync
    end
    def remote_put_base_site                                                     # -Cr
      require "#{SiSU_lib}/remote_put"
      SiSU_Remote::Put_base.new(@cf).scp_base
    end
    def remote_put_base_site_all                                                 # -CCr
      require "#{SiSU_lib}/remote_put"
      SiSU_Remote::Put_base.new(@cf).scp_base_all
    end
    def cgi                                                                      # -F
      require "#{SiSU_lib}/cgi"
      SiSU_CGI::SiSU_search.new(@fns,@cf).read
    end
    def encoding                                                                 # -K build character encoding db (uses KirbyBase)
      require "#{SiSU_lib}/character_encoding"
      SiSU_character_encode::Create.new.db
      #x=SiSU_character_encode::Query.new
      #x.report
      #x.table
      #y=x.hex('55','dec')
      #y=x.name(' A','name')
      #puts y
    end
    def build                                                                    # -m where file =~/\.r[1-3]$/ #composte (build) document
      require "#{SiSU_lib}/composite"
      if @fns =~/\.ssm$/
        SiSU_Assemble::Composite.new(@fns,@cf).read 
        # build document from requested parts, which may themselves be complete documents
        ObjectSpace.garbage_collect
      end
    end
    def metaverse                                                                # -m 
      require "#{SiSU_lib}/metaverse"
      SiSU_Metaverse::Source.new(@fns,@cf).read                                  # metaverse created here
    	@@n_do=@@n_do+1
      tell=SiSU_Screen::Ansi.new(@cf,@@n_do,'files processed')
      tell.files_processed unless @cf =~/q/
      ObjectSpace.garbage_collect
    end
    def html                                                                     # -h -H
      require "#{SiSU_lib}/html"
      SiSU_HTML::Source.new(@fns,@cf).read
      ObjectSpace.garbage_collect
      case @fns
      when /\.[_-]?sst$/                                                    #3
    	  @@n_do=@@n_do+1
    	  @@n_files_scrollseg=@@n_files_scrollseg+1
        tell=SiSU_Screen::Ansi.new(@cf,@@n_do,@@n_files_scroll,@@n_files_seg,@@n_files_scrollseg,@@n_files_nav)
        tell.html3numbers unless @cf =~/q/
      end
    end
    def termsheet                                                                # -t
      system("sisu_termsheet #@cf #@fns\n")
    	@@n_do=@@n_do+1
      tell=SiSU_Screen::Ansi.new(@cf,@@n_do,'Termsheet(s) processed')
      tell.termSheetTitle unless @cf =~/q/
    end
    def webrick                                                                  # -W
      port=prt=@fns
      dir=SiSU_Env::Info_dir.new #(@fns)
      prt=if prt !~/\d+/: 'webrick default (sysenv)' 
      else                "webrick port set to #{prt}"
      end
    	puts 	%{#{@cX.blue}<<#{@cX.off}#{@cX.green}Start Webrick web server on port: #{prt}#{@cX.off}#{@cX.blue}>> #{@cX.off*2} }
      system(%{sisu_webrick #{port}&\n} )
    end
    def php                                                                      # -z
      require "#{SiSU_lib}/html"
      SiSU_HTML::Source.new(@fns,@cf).read
      ObjectSpace.garbage_collect
      case @fns
      when /\.ph1$/ #1
    	  @@n_do=@@n_do+1
    	  @@n_files_scroll=@@n_files_scroll+1
        tell=SiSU_Screen::Ansi.new(@cf,@@n_do,@@n_files_scroll,@@n_files_seg,@@n_files_scrollseg,@@n_files_nav)
        tell.html1numbers unless @cf =~/q/
      when /\.ph2$/ #2
    	  @@n_do=@@n_do+1
    	  @@n_files_seg=@@n_files_seg+1
        tell=SiSU_Screen::Ansi.new(@cf,@@n_do,@@n_files_scroll,@@n_files_seg,@@n_files_scrollseg,@@n_files_nav)
        tell.html2numbers unless @cf =~/q/
      when /\.ph3$/ #3
    	  @@n_do=@@n_do+1
    	  @@n_files_scrollseg=@@n_files_scrollseg+1
        tell=SiSU_Screen::Ansi.new(@cf,@@n_do,@@n_files_scroll,@@n_files_seg,@@n_files_scrollseg,@@n_files_nav)
        tell.html3numbers unless @cf =~/q/
      when /\.ph0$/ #1
    	  @@n_do=@@n_do+1
    	  @@n_files_nav=@@n_files_nav+1
        tell=SiSU_Screen::Ansi.new(@cf,@@n_do,@@n_files_scroll,@@n_files_seg,@@n_files_scrollseg,@@n_files_nav)
        tell.html0numbers unless @cf =~/q/
      end
    end
    def semantics                                                                # not used
    #  @inst=@fns
    #  system(%{semantics.rb #@inst\n})
    #  tell=SiSU_Screen::Ansi.new(@cf,@@n_ym,'files processed for YAML semantic Info')
    #  tell.files_processed unless @cf =~/q/
    end
    def not_found
      puts "\n#{@cX.fuschia}FILE NOT FOUND:#{@cX.off} << #@fns >> - requested #@cf processing skipped\n"
    end
    def not_recognised
      case @fns
      when /\.s[123]$/
        puts %{\nIn filename: "#{@cX.fuschia}#@fns#{@cX.off}" << #{@fns.gsub(/\S+?(\.s[123])/,"\\1")} >> #{@cX.fuschia}is not a recognized filetype.#{@cX.off} #{@cX.brown}Please rename your file.#{@cX.off}\n\tAs of sisu-0.37, SiSU markup files with #{@cX.brown}the extensions .s1 .s2 and .s3 should be re-named .sst#{@cX.off}\n\tif you have the program called 'rename' installed, the following rune should do the trick:\n\t\trename 's/\.s[123]$/\.sst/' *.s{1,2,3}\n\trequested #@cf processing skipped\n}
      when /\.r[123]$/
        puts %{\nIn filename: "#{@cX.fuschia}#@fns#{@cX.off}" << #{@fns.gsub(/\S+?(\.r[123])/,"\\1")} >> #{@cX.fuschia}is not a recognized filetype.#{@cX.off} #{@cX.brown}Please rename your file.#{@cX.off}\n\tAs of sisu-0.37, SiSU (master or composite) markup files with #{@cX.brown}the extensions .r1 .r2 and .r3 should be re-named .ssm or .ssc#{@cX.off}\n\tif you have the program called 'rename' installed, the following rune should do the trick:\n\t\trename 's/\.r[123]$/\.ssm/' *.r{1,2,3}\n\tNote also that you will need to change the names of the files called/required\n\twithin the document text to build the composite document\n\t\t.s1 .s2 .s3 should be .sst \n\t\t.si should be .ssi\n\trequested #@cf processing skipped\n}
      else
        puts "\n#{@cX.fuschia}FILETYPE NOT RECOGNISED:#{@cX.off} << #@fns >> - is not a recognized filetype,\n\trequested #@cf processing skipped\n"
      end
    end
  end
  class Processing
    def initialize(cf,argv)
      @cf,@argv=cf,argv
    end
    def actions
      if @cf =~/([AabCcDdEeFfGHhiLMmNnoprRSsTtQqUuVvwWXxyZz0-9]|-(all|sisu))/ and @cf =~/^-/ and @cf !~/help/ #% FLAGS, all flag letters !
        @@tell=SiSU_Screen::Ansi.new(@cf)
        @cX=SiSU_Screen::Ansi.new(@cf).cX
        flag=SiSU_Env::Info_processing_flag.new
        if @cf =~/(all|sisu)/: system(%{nohup nice sisu -hwp *&\n})
        end
        extra=''
        if @cf !~/[mn]/
          extra+=if @cf =~/[abBehHhINoptwXxz]/ and @cf !~/[mn]/: 'm'                 #% add metaverse
          elsif @cf =~/[Dd]/ and @argv[0] !~/^remove$/ and @cf !~/[mn]/: 'm'       #% add metaverse
          else ''
          end
        end
        if @cf !~/y/
          extra+=if @cf =~/[abehHhINopsSstwXxz]/ and @cf !~/y/: 'y'                 #% add manifest
          elsif @cf =~/[Dd]/ and @argv[0] !~/^remove$/ and @cf !~/y/: 'y'          #% add manifest
          else ''
          end
        end
        @cf=@cf + extra
        if @cf =~/[vVM]/                                                           #% version information
          version=Hash.new
          version=SiSU_Env::Info_version.new.get_version
          rb_ver=SiSU_Env::Info_version.new.rbversion
          if version[:version]
            tell=SiSU_Screen::Ansi.new(@cf,version[:project],version[:version],version[:date_stamp],version[:date],rb_ver)
          tell.version
          else puts 'SiSU version information not available'
          end
        end
        if @cf =~/^-L$/: SiSU_Help::Help.new('license').help_request               #% version information
        end
        if @cf =~/[1-9][cMRrUuVv]?/                                                #% numeric shortcuts ...
          extra=''
          extra+=case @cf                                                          #% optional command flags
          when /([cMRrsSUuVv]+)/: $1
          else                    ''
          end
          @cf=case @cf
          when /1/: flag.cf_1            #'-mNhwpy'       
          when /2/: flag.cf_2            #'-mNhwpoay'     
          when /3/: flag.cf_3            #'-mNhwpoabxXy'  
          when /4/: flag.cf_4            #'-mNhwpoabxXDiy'
          when /5/: flag.cf_5            #'-mNhwpoabxXDuy'
          end
          @cf=@cf + extra
          tell=SiSU_Screen::Ansi.new(@cf,"\tsisu " + @cf + "\n")
          tell.printBrown unless @cf =~/q/
        end
        if @cf =~/m/i                                                              #% -m for -C
          dir=SiSU_Env::Info_dir.new
          path_css="#{dir.data_o}/_sisu/css"
          path_dtd="#{dir.data_o}/_sisu/dtd"
          unless FileTest.directory?(path_css) and FileTest.directory?(path_dtd): @cf=@cf+'CC'
          end
          if @cf =~/M/: $VERBOSE=false                                                         #debug $VERBOSE=true
            # -M test other expected directories including images
          end
        end
        if @cf =~/C/                                                               #% -C -CC initialize/configure
          Operations.new('',@cf).homepage
          Operations.new('',@cf).conf
          Operations.new('',@cf).cp_local_image_set
          Operations.new('',@cf).cp_webserver_images if @cf =~/CC/
          if @cf =~/R/
            if @cf =~/CCRZ/: Operations.new('',@cf).remote_put_base_site_rsync_match
            else             Operations.new('',@cf).remote_put_base_site_rsync
            end
          elsif @cf =~/r/
            if @cf =~/CCr/:  Operations.new('',@cf).remote_put_base_site_all
            else             Operations.new('',@cf).remote_put_base_site
            end
          end
        end
        if @cf =~/F/                                                               #% -F cgi sample search form
          webserver=@argv[0].to_s.strip
          if webserver =~/webrick|pwd/: Operations.new(webserver,@cf).cgi
          else                          Operations.new('',@cf).cgi
          end
        end
        if @cf =~/W/: Operations.new(@argv).webrick                                #% -W webrick #@argv==port
        end
        if @cf =~/k/                                                               #% -k dummy, build character encoding table
          #Operations.new(@cf).encoding
        end
        if @cf =~/Z/: Op.new(@cf,@argv,'zap','Zap, deletions').select              #% -Z wipe previous output clean
        end
        if @cf =~/s/: Op.new(@cf,@argv,'source','SiSU markup source').select       #% -s sisu source
        end
        if @cf =~/m/                                                               #% -m remote url requested? check whether (and download if) remote files requested for processing
          @retry_count= -1
          begin
            path_image='./_sisu/processing/external_document/image'
            path_skin='./_sisu/processing/external_document/skin/doc'
            #File.mkpath(path_image) unless FileTest.directory?(path_image)
            #File.mkpath(path_skin) unless FileTest.directory?(path_skin)
            @get=Array.new
            re=/(http:\/\/\S+?\.sst)/
        	  @argv.each do |fns|
              if fns =~re
                #fnu=URI.parse(fns)
                @get << re.match(fns)[1] if re 
              end
            end
            if @get.length > 0
              require 'open-uri'
              require 'pp'
              require "#{SiSU_lib}/composite"
              @rgx_image=/\{\s*(\S+?\.(?:png|jpg))/
              #@rgx_image=/\{?(\S+?\.(?:png|jpg))/
              @rgx_skin=/0~skin\s+(\S+)/
              #ext_doc="#{Dir.pwd}/_sisu/processing/external_document/"
              #File.mkpath("#{ext_doc}/skin/doc") unless FileTest.directory?("#{ext_doc}/skin/doc")
              #File.mkpath("#{ext_doc}/image") unless FileTest.directory?("#{ext_doc}/image")
              threads = []
              for requested_page in @get
                threads << Thread.new(requested_page) do |url|
                  open(url) do |f|
                    raise "#{url} not found" unless f
                    re_fnb=/(http:\/\/[^\/ ]+?\/[^\/ ]+?)\/\S+?\/([^\/]+?)\.ss(t)/ #revisit and remove DO
                    #re_fnb=/(http:\/\/[^\/ ]+?\/[^\/ ]+?)\/\S+?\/([^\/]+?)\.s([1-3])/
                    base_uri,fnb,instr=re_fnb.match(url)[1..3] if re_fnb
                    imagedir = base_uri + '/_sisu/image_local' #check on
                    doc_skin_dir = /(http:\/\/\S+?)\/[^\/]+?\.sst$/i.match(url).captures.join + '/_sisu/skin/doc'
                    #"Got file, and ready to process: #{fnb}.t#{instr}"
                    downloaded_file=File.new("#{fnb}.-sst",'w+')
                    images=SiSU_Assemble::Remote_image.new.image(imagedir)
                    skin=SiSU_Assemble::Remote_image.new.image(doc_skin_dir)
                    f.collect.each do |r|                                          #% work area
                      skin << r.scan(@rgx_skin).uniq if r =~@rgx_skin     
                      images << r.scan(@rgx_image).uniq if r =~@rgx_image     
                      downloaded_file << r
                    end
                    if skin and skin.length > 0
                      SiSU_Assemble::Remote_image.new.download_doc_skin(skin)
                    end
                    if images and images.length > 1
                      images.flatten!.uniq! 
                      tell=SiSU_Screen::Ansi.new('','downloading images:',images.join(','))
                      tell.warn unless @cf =~/q/
                      SiSU_Assemble::Remote_image.new.download_images(images)
                      tell=SiSU_Screen::Ansi.new('','downloading done')
                      tell.warn unless @cf =~/q/
                    end
                    downloaded_file.close
                  end
                end
              end
              Operations.new.counter
            end
            threads.each {|thr| thr.join} if threads #and threads.length > 0
          rescue: SiSU_Errors::Info_error.new($!,$@,@cf,@fns).error #ok
            @retry_count +=1
            retry unless @retry_count > 1
          ensure
          end
          @argv=@argv.collect {|x| x=x.gsub(/http:\/\/\S+\/(\S+)\.sst/,"\\1.-sst") }
          #@argv=@argv.collect {|x| x=x.gsub(/http:\/\/\S+\/(\S+)\.s([1-3])/,"\\1.u\\2") }
        end
        if @cf=~/m/ #and @cf !~/n/                                                 #% -m metaverse
          #Op.new(@cf,@argv,'metaverse','metaverse').select
        	@argv.each do |fns|
            if FileTest.file?(fns) or FileTest.symlink?(fns)
        		  case fns
              when /\.[_-]?sst|ssm$/                                  #% composite document remote url?
                Operations.new(fns,@cf).build if fns =~ /\.ssm$/
                fns=fns.gsub(/\.ssm$/,'._sst')                               #pre-processing
                Operations.new(fns,@cf).metaverse
              else #not_recognised
        		  end
            else 
              if @cf !~/[dD]/ and fns !~/^(?:drop(?:table(?:s)?|index|all)|index|(?:re)?create(?:all)?|available|help)$/
                Operations.new(fns,'metaverse').not_found
              else
              end
            end
        	end
          Operations.new.counter
        end
        @argv=@argv.collect {|x| x=x.gsub(/\.ssm$/,'._sst') }
        if @cf =~/S/: Op.new(@cf,@argv,'sisudoc','sisudoc (tgz)').select           #% -S make sisudoc
        end
        if @cf =~/N/: Op.new(@cf,@argv,'digests','digests').select                 #% -N digest tree
        end
        if @cf =~/[hHz]/                                                           #% -h -H -z html css
        	@argv.each do |fns|
            if FileTest.file?(fns)
              prc=@cf 
              if fns =~/\.[_-]?sst$/: $program='css'
              end
        		  case fns
        		  when /\.[_-]?sst$/: Operations.new(fns,prc).html
        		  else #not_recognised
        		  end
            else                  Operations.new(fns,'html').not_found
            end
        	end
          Operations.new.counter
        end
        if @cf =~/[aAfeE]/: Op.new(@cf,@argv,'plaintext','plaintext').select       #% -a -A -f -e -E plaintext -a creates ms-dos type; -A creates unix type, plaintext file
        end
        if @cf =~/o/: Op.new(@cf,@argv,'odf','OpenDocument').select                #% -o opendocument
        end
        if @cf =~/x/: Op.new(@cf,@argv,'xml','xml sax').select                     #% -x xml sax type
        end
        if @cf =~/X/: Op.new(@cf,@argv,'xml_dom','xml dom').select                 #% -X xml dom type
        end
        if @cf =~/b/: Op.new(@cf,@argv,'xhtml','xhtml sax').select                 #% -b xhtml sax type
        end
        if @cf =~/B/: Op.new(@cf,@argv,'docbook','docbook xml').select                 #% -B docbook xml
        end
        if @cf =~/w/: Op.new(@cf,@argv,'wmap','WordMap').select                    #% -w wordmap
        end
        if @cf =~/t/                                                               #% -t termsheet/standard form
          #puts "sisu -t [termsheetname].termsheet.rb" if @argv.length==0
          @help.termsheet if @argv.length==0
        	@argv.each do |fns|
            if FileTest.file?(fns)
        		  case fns
        		  when /\.(termsheet.rb)$/:            Operations.new(fns,@cf).termsheet
        		  else              		  	           #print "not processed --> ", fns, "\n"
        		  end
            else                                   Operations.new(fns,'termsheet').not_found
            end
            #puts "sisu -t [termsheetname].termsheet.rb"
        	end
          Operations.new.counter
        end
        if @cf =~/p/: Op.new(@cf,@argv,'texpdf','LaTeX pdf').select                #% -p latex/ texpdf
        end
        if @cf =~/I/: Op.new(@cf,@argv,'texinfo','TeX Info').select                #% -I texinfo (i taken by db import)
        end
        if @cf =~/[Dd]/                                                            #% -D -d DB
          if @cf =~/[iu]/
            dbinst=case @cf
            when /i/: 'import'
            when /u/: 'update'
            end
          else
            dbinst=@argv[0].to_s
            @argv.shift
          end
          if @cf =~/[Dd]/                                                          #% dbi sql postgresql & sqlite
            unless dbinst =~/drop(?:table(?:s)?|index|all)|index|(?:re)?create(?:all)?|available|help/ or dbinst.nil?
              if @argv.length > 0: Op.new(@cf,@argv,'dbi',dbinst).select
              else
                tell=SiSU_Screen::Ansi.new('',"#@cf #{dbinst}",'N/A in requested sql module')
                tell.warn unless @cf =~/q/
              end
            else                   Operations_database.new(@cf,dbinst).dbi
            end
          end
        end
        if @cf =~/G/: Operations.new(@argv).cgi                                    #% -G cgi - used to make dbi intecface
        end
        if @cf =~/y/: Op.new(@cf,@argv,'manifest','Manifest').select                 #% -y manifest
        end
        if @cf =~/r/: Op.new(@cf,@argv,'remote_put','scp').select                  #% -r copy to remote server
        end
        if @cf =~/R/: Op.new(@cf,@argv,'remote_put','rsync').select                #% -R copy to remote server
        end
        if @cf =~/[QuUvVM]/: Op.new(@cf,@argv,'urls','urls').select                 #% -Q -u -v -V -M urls
        end
        tell=SiSU_Screen::Ansi.new(@cf,"\tsisu -W [to start ruby web-server on output directory]\n")
        tell.printBrown if @cf =~/[uUvVM]/ unless @argv.join.empty?
      else                                                                         #% help instructions
        if @cf =~/-{0,2}help/ and @argv[0] =~/\S/: SiSU_Help::Help.new(@argv[0]).help_request 
        else SiSU_Help::Help.new('list').help_request 
        end
      end
      @argv.each do |fns|
        if FileTest.file?(fns)
          unless fns =~/\.[_-]?sst$/: Operations.new(fns,'').not_recognised
          end
        else                          #Operations.new(fns,'html').not_found
        end
      end
    end
  end
  begin                                                                            #% select what to do
    include SiSU
    @argv=$*
    @cf=@argv[0].to_s
    $program='css' if @argv =~/h/
    #$program='tbl' if @argv =~/o/
    $program='php' if @argv =~/z/ #or filesuffix =~/ph[0-3]/
    @argv.shift
    @argv.uniq!
    home=ENV['HOME']
    require 'jcode'
    $KCODE='UTF8'
    require "#{SiSU_lib}/sysenv"
    include SiSU_Env
    include SiSU_Screen
    require "#{SiSU_lib}/param"
    include SiSU_Param
    require "#{SiSU_lib}/defaults"
    include SiSU_Viz
    #require "#{SiSU_lib}/spell"
    #include Utility
    require "#{SiSU_lib}/help"
    include SiSU_Help
    #require 'pathname'
    require 'uri'
    @@ln=Array.new
    @op=Operations.new
    @update=false
    if @cf =~ /^--update$/: @update=true
    end
    if @update
      require "#{SiSU_lib}/update"
      @argv.each do |fns|
        if FileTest.file?(fns)
          case fns
          when /\.(?:[_-]?sst|ssm)$/:
            cf=SiSU_Update_control_flag::Check.new(fns,@cf).read
            Processing.new(cf,fns).actions
          else                                 #print "not processed --> ", fns, "\n"
          end
        else                                   Operations.new(fns,'file output to update').not_found
        end
      end
    else Processing.new(@cf,@argv).actions
    end
  rescue: STDERR.puts SiSU_Screen::Ansi.new(@cf,$!,$@,nil).rescue #fix
  ensure
    Dir.chdir(PWD)
  end
end
__END__
