#!/bin/csh -f

# For now we assume that any matching <A and > are on the same line
# and that there is at most one anchor per line.  Also assumes input
# files do not contain  (nonprinting bell character).  Also assumes
# no anchor or filename contains the bizarre string "/><".

set anchors = phtml2html.anchors.$user.$$

echo '/><' > $anchors # a dummy string for matching lines originally in input

foreach file ($*)
  set fileroot = $file:r
  set filebase = $fileroot:t
  sed -n 's+.*<A NAME="\([^"]*\)">.*+'"$filebase.html#\1+p" $file >> $anchors
  sed 's+^\(.*\)\(<A NAME="[^"]*">\)\(.*\)$+\1\\
\2\\
\3+' $file | grep -v '^ *$' | tr -d '' | sed 's+^+/>< +' > $fileroot.work
end
foreach file ($*)
  set fileroot = $file:r
  set filebase = $fileroot:t
  foreach f2 ($*)
    if ("$f2" != "$file") then
      cp $fileroot.work $fileroot.html
      set fr2 = $f2:r
      set fb2 = $fr2:t
      sed 's+^\(.*<A NAME="\)\([^"]*\)\(">.*\)$+\1\2\3\\
<A HREF="'"$fb2.html"'#\2">['"$fb2"']</A>+' $fileroot.html > $fileroot.work
    endif
  end
  fgrep -f $anchors $fileroot.work | sed 's+^/>< ++' | tr -d '' > $fileroot.html
  rm $fileroot.work
end

rm -f $anchors
