#!/usr/bin/tclsh
#!/usr/bin/expect
#
# (find-fline "~/TH/Generate")
# (find-fline "~/TH/Htmllib.tcl")
# (find-fline "~/TH/Files.tcl")
# 
# (find-node "(make)Remaking Makefiles")
# (find-node "(make)Include" "generate dependencies")
# (find-fline "$PAGE2/")
# (find-fline "~/TCL/Makefile.L")



source [file dirname [info script]]/Htmllib.tcl

proc my {fname} { return "$fname" }
proc myl {fname} { return $fname }
procj MYL1 {fname text} {
  if {[void $text]} {set text [my $fname]}
  HREF1 [relativepathto $fname] $text
}

procj PL1 {abslurl text} {
  if {[void $text]} {set text $abslurl}
  MYL1 $abslurl $text
}
procj AL1 {anggurl text} {
  if {[void $text]} {set text $anggurl}
  MYL1 a/$anggurl $text
}
procj IMAGE1 {anggurl text} {
  if {[void $text]} {set text $anggurl}
  MYL1 $anggurl $text
}
procj IMAGE1 {url text} {
  HREF1 $url "<img src=\"$url\" alt=\"$text\">\n"
}

procj ML1 {mailadr text} {
  if [void $text] {
    set text $mailadr
  }
  HREF1 mailto:$mailadr $text
}



proc section {str} { if {$str==""} {return ""} {return "#$str"} }
proc or {text alt} { expr {$text!=""?$text:$alt} }

procj ESURL {estem {name {}}} {
  relativepathto e/$estem.html[section $name]
}
procj ES1 {whereto text} {
  foreach {stem name} $whereto {}
  L1 [ESURL $stem.e $name] $text
}

procj AURL {astem {name {}}} {
  relativepathto [expr {$name==""?"a/$astem":"a/$astem.html#$name"}]
}
procj AL1 {anggurl text} {	# experimental version
  foreach {astem name} $anggurl {}
  L1 [AURL $astem $name] [or $text $astem]
}
 
# set url [expr {$name==""?"$stem":"$stem.html#$name"}]


proc RULE {} { return "\n\n<hr size=1>\n\n" }






proc1 SELECT1 {name size tag1 text1 otherargs} {
  set s "<select name=\"$name\" size=$size>\n"
  append s "<option value=\"$tag1\" selected>$text1\n"
  foreach {tag text} $otherargs {
    append s "<option value=\"$tag\">$text\n"
  }
  append s "</select>\n"
  return $s
}



proc replicate_one {ListOfKeysAndDests cluster} {
  foreach {key dests} $ListOfKeysAndDests {
    if [regexp $key $cluster] {
      set result {}
      foreach dest $dests {
	regsub -all $key $cluster $dest changedcluster
	append result $changedcluster
      }
      return $result
    }
  }
  error "Aaargh, no keys in $cluster"
}
proc replicate_all {ListOfKeysAndDests subject} {
  set result {}
  while {[regexp {^([^®]*)®([^¯]*)¯(.*)$} $subject {} beg mid end]} {
    append result $beg [replicate_one $ListOfKeysAndDests $mid]
    set subject $end
  }
  append result $subject
  return $result
}




# Remove a suffix from a string
proc removetail {tail s} {
  set len [string length $s]
  set cutpos [expr $len-[string length $tail]]
  if {[string range $s $cutpos end]!=$tail} {
    error "\{$s\} has tail different from \{$tail\}"
  }
  return [string range $s 0 [expr $cutpos-1]]
}

# Print a list of e-scripts with descriptions
proc edescrs {} {
  global env
  source [file dirname [info script]]/Files.tcl
  foreach {key list} $keys_and_dests {
    if {$key=="escript.e"} {
      foreach escripte $list {
        set stem [removetail .e $escripte]
	set lines [split [readfile $env(ES)/$escripte] "\n"]
	set s1 {}
	set s2 {}
	regexp "^# +(E-scripts )?(.*)" [lindex $lines 2] -> {} s1
	regexp "^#\[ \t\]+(.*)$" [lindex $lines 3] -> s2
	if {$s2!=""} {set s2 " $s2"}
	puts "    \[escr $stem {$s1$s2}\]"
      }
    }
  }
  exit
}




proc LocalHack {} {
  global outfile
    puts $outfile
  regsub {.html$} $outfile .th outfileth
  IFLR "P ([PL ../R/$outfile rmtv]/[AL s/$outfileth src])" \
       "P ([HREF http://angg.twu.net/ home])"
}



proc replicate_all {ListOfKeysAndDests subject} {
  set result {}
  while {[regexp {^([^®]*)®([^¯]*)¯(.*)$} $subject {} beg mid end]} {
    append result $beg [replicate_one $ListOfKeysAndDests $mid]
    set subject $end
  }
  append result $subject
  return $result
}



proc unlf {str} { join [split $str "\n"] }

# unlf1: keep the lfs only inside the ®¯s, and remove the ®¯s.
proc unlf1 {rest} {
  set result {}
  while {[regexp {^([^®]*)®([^¯]*)¯(.*)} $rest {} beg mid rest]} {
    append result [unlf $beg] $mid
  }
  append result [unlf $rest]
  return $result
}

proc htmlize {title body} {
  outputs [TITLEDHTML1 [Q1 $title] "\
[H31 [Q1 $title]]
[E1 [unlf1 $body]]
[LocalHack]"]
}




# Process "find-..." lines.
# There are three cases:
#
# flinkli {01(find-23 "45")67}
#   -> beg=01 type=23 fname=45 rest={)67} tail=67
#
# flinkli {01(find-23 "45" "67")89}
#   -> beg=01 type=23 fname=45 rest={ "67")89} tag=67 tail=89
#
# flinkli {01(find-23 "45" 67)89}
#   -> beg=01 type=23 fname=45 rest=??
#   this case is so deprecated that I don't make a link from it.
#

# Build the actual html lines (inside a <pre> block). The text of the
# link is the quote/closeparen pair, to reduce visual clutter.
#
proc flinkh2 {beg type fname tail {url {}}} {
  if {$url!=""} {
    return [Q1 "$beg\(find-$type \"$fname"][HREF $url \")][Q1 $tail]
  } else {
    return [Q1 "$beg\(find-$type \"$fname\")$tail"]
  }
}
proc flinkh3 {beg type fname tag tail {url {}}} {
  if {$url!=""} {
    return [Q1 "$beg\(find-$type \"$fname\" \"$tag"][HREF $url \")][Q1 $tail]
  } else {
    return [Q1 "$beg\(find-$type \"$fname\" \"$tag\")$tail"]
  }
}

# Intermediate.
#
proc flink2 {beg type fname tail} {
  if {$type=="fline"} {
    if {[regexp "^~/(.*)" $fname -> relfname]} {
      return [flinkh2 $beg $type $fname $tail [relativepathto a/$relfname]]
    }
  }
  flinkh2 $beg $type $fname $tail
}
proc flink3 {beg type fname tag tail} {
  if {$type=="angg"} {
    return [flinkh3 $beg $type $fname $tag $tail [AURL $fname $tag]]
  }
  if {$type=="es"} {
    return [flinkh3 $beg $type $fname $tag $tail [ESURL $fname.e $tag]]
  }
  if {$type=="fline"} {
    if {[regexp "^~/(.*)" $fname -> relfname]} {
      return [flinkh3 $beg $type $fname $tag $tail \
	  [relativepathto a/$relfname]]
    }
  }
  flinkh3 $beg $type $fname $tag $tail
}

# Top level: takes an escript line containing a "find-" and
# converts it (or not).
#
proc flinkli {li} {
  if {[regexp {^(.*)\(find-(angg|es|fline) (.*)} $li -> beg type rest]} {
    if {[regexp {^"([^\"]+)"(.*)} $rest -> fname rest]} {
      if {[regexp {^\)(.*)} $rest -> tail]} {
	return [flink2 $beg $type $fname $tail]
      } else {
	if {[regexp {^ "((\\.|[^\"])*)"\)(.*)} $rest -> str {} tail]} {
	  return [flink3 $beg $type $fname $str $tail]
	}
      }
    }
  }
  return [Q1 $li]
}



proc txt2html {bigstr} {
  set hs {}
  foreach li [split $bigstr "\n"] {
    if [regexp "®|find-" $li] {
      if [regexp "^(.*)®(.*)¯(.*)$" $li {} beg mid end] {
	lappend hs [NAME $mid $beg\
	    [COLOR green [IT &laquo\;]$mid[IT &raquo\;]]$end]
      } else {
	lappend hs [flinkli $li]
      }
    } else {
      lappend hs [Q1 $li]
    }
  }
  set bigstr [join $hs "\n"]
  regsub -all "" $bigstr [COLOR red [BF *]] bigstr
  return $bigstr
}




# <table>
# <tr>
# <td bgcolor="#CC0000">
# <font color="#FFCC00">
# Warning: this is a htmlized version!
# <br>
# The original is across
# <a href="../e/x.e">this link.</a>
# </font>
# </td>
# </tr>
# </table>

proc WARN_HTMLIZED {orig} {
  return \
"<table><tr><td bgcolor=\"#CC0000\"><font color=\"#FFCC00\" size=-1>
Warning: this is a htmlized version!
<br>The original is across [HREF $orig this link.]
</font></td></tr></table>\n\n"
}

proc a2html {sourcefile} {
  regexp "^a/(.*)" $sourcefile -> source
  outputs [TITLEDHTML "$source (htmlized)" \
      [WARN_HTMLIZED $source] \
      [PRE1 [txt2html [readfile $sourcefile]]]]
}

#proc e2html {sourcefile} {
#  set tail [file tail $sourcefile]
#  outputs [TITLEDHTML "$tail (htmlized)" \
#      [WARN_HTMLIZED ../a/e/$tail] \
#      [PRE1 [txt2html [readfile $sourcefile]]]]
#}

# (find-fline "~/TCL/fix-eheaders")
# (find-fline "~/EXPECT/eheaders")

proc EHREF {dest} { return "&lt;[HREF $dest $dest]&gt;" }
proc EHREFR {dest {html {}}} {
  regexp "http://angg.twu.net/(.*)" $dest -> fname
  if {$html==""} {
    return "&lt;[HREF ../$fname $dest]&gt;"
  } else {
    return "&lt;[HREF ../$fname $dest]\[[HREF ../$fname.html .html]\]&gt;"
  }
}

proc e2html {sourcefile} {
  set tail [file tail $sourcefile]
  set contents [readfile $sourcefile]
  set v "#\n"
  set nv "#\[^\n\]+\n"
  set com "#\[^\n\]*\n"
  set bigre "^$nv${v}(($nv)+)${v}(($com)+)(.*)\$"
  if {![regexp $bigre $contents -> descr {} hrest {} rest]} {
    error "Bad efile: $sourcefile"
  }
  set eev1 [AL {eev.el eev} eev.el]
  set zshrc1 [AL {.zshrc ee} .zshrc]
  set emacs1 [AL {.emacs code-c-ds} .emacs]
  outputs [TITLEDHTML "$tail (htmlized)" \
      [WARN_HTMLIZED ../a/e/$tail] \
      [PRE1 \
"#######
#
[Q1 $descr]#
# Note 1: use the eev command (defined in $eev1) and the
# ee alias (in my $zshrc1) to execute parts of this file.
# Executing this file as a whole makes no sense.
#
# Note 2: be VERY careful and make sure you understand what
# you're doing.
#
# Note 3: If you use a shell other than zsh things like |&
# and the for loops may not work.
#
# Note 4: I always run as root.
#
# Note 5: some parts are too old and don't work anymore. Some
# never worked.
#
# Note 6: the definitions for the find-xxxfile commands are on my
# $emacs1.
#
# Note 7: if you see a strange command check my .zshrc -- it may
# be defined there as a function or an alias.
#
# Note 8: the sections without dates are always older than the
# sections with dates.
#
# This file is at [EHREF http://angg.twu.net/a/e/$tail]
#           or at [EHREF http://angg.twu.net/e/$tail.html].
#        See also [EHREFR http://angg.twu.net/emacs.html],
#                 [EHREFR http://angg.twu.net/a/.emacs .html],
#                 [EHREFR http://angg.twu.net/a/.zshrc .html],
#                 [EHREFR http://angg.twu.net/escripts.html],
#             and [EHREF http://angg.twu.net/].
#
#######
[txt2html $rest]"]]
}






# Top level stuff.
# The first argument sets "outfile"; "-" means stdout.
# All other arguments are digested in order; those that don't have
#   spaces are interpreted as names of files to source, the ones with
#   spaces are evaluated.

set outfile [lindex $argv 0]
foreach s [lrange $argv 1 end] {
  if {[regexp " " $s]} {
    eval $s
  } else {
    source $s
  }
}

exit