#!/bin/sh
# This script reads in applets and updates the html to
# handle the latest version of the plugin
#
# $Id: fixapplets 26703 2003-03-31 17:33:32Z cxh $
# Usage: fixapplets [-n] file.htm [...]

printOnly=no
if [ $# -lt 1 ]; then
    echo "$0: Usage: $0 file . . ."
    exit 4
fi

if [ "$1" = "-n" ]; then
    echo "$0: -n: Not updating files"
    printOnly=yes
    shift
fi

for file in $@
do
        # 1)Get the current parameters, create a new .htm file with
        # those parameters.
    sed -e 's/CODEBASE/codebase/' \
	-e 's/CODE/code/' \
	-e 's/ARCHIVE/archive/' \
	-e 's/WIDTH/width/' \
	-e 's/HEIGHT/height/' \
	-e 's/<!-- CONVERTER VERSION 1.0 -->//' \
	-e 's/<!--"CONVERTED_APPLET"-->//' \
        -e 's/^\([	 ]*\)width=\([0-9]*\) height=\([0-9]*\)/\1width = "\2" \
\1height = "\3"/' \
	$file |
    awk '
 BEGIN {
	    # applet parameters that go inside <applet ... >
	    appletParamNames["codebase"] = 1
	    appletParamNames["code"] = 1
	    appletParamNames["archive"] = 1
	    appletParamNames["width"] = 1
	    appletParamNames["height"] = 1
            singlequote = sprintf("%c", 39)

	}
 $0 ~ /<!-- HTML CONVERTER -->/ { sawHTMLConverter = 1
                  stopPrinting = 1
                }
 $1 ~ /<OBJECT/ { stopPrinting = 1
                }
 $0 ~ /<SCRIPT LANGUAGE="JavaScript"><!--/ {stopPrinting = 1}
 stopPrinting == 0 { print $0 }
 $1 ~ /<EMBED/  { sawEmbed = 1
		  paramCount = 0
		  appletParamCount = 0
	        }
 $1 ~ /<NOEMBED/    {
			sawNoEmbed = 1
			alternateHTML = ""    
		    }
 sawEmbed == 1 && sawNoEmbed == 0 && $1 !~ /<EMBED/ { 
                    # We search the contents of the EMBED tag to
                    # get the various applet parameters.
		    if ( $0 ~ /=/) {
                        # Unfortunately, if we run this script over and
                        # over again, then the htmlconverter tends to
                        # combine all the application applet parameters
                        # like pxgraphargs on to one line, which makes
                        # it much more difficult to parse.

                        q = split($0, quotes, "\"")
                        # If q == 3, then we have a standard line like
                        # type = "foo"
                        # If q == 5, then we have a standard line like
                        # background = "bar" pxgraphargs = "bif"

                        if (q == 1 || q == 2 ) {
                            fewquotes = 1
                        }
                        for (qnf = 1; fewquotes == 1 || qnf < q; qnf += 2) {
                           if (fewquotes == 1) {
                                # Go through the for loop only once.
                                fewquotes = 0
                                if (q ==1) {
                                    # There were no double quotes in the line
                                    # we might have codebase=../../..
                                    #qf = $0
                                    # Add double quotes around the =
			            neq=split($0, eq, "=")
                                    t2 = eq[2]
                                    if (index(eq[2], " ") == 1) {
                                        # remove leading space
                                        t2 = substr(eq[2], 2, length(eq[2]) -1)
                                    }
                                    qf = eq[1] "= \"" t2
                                    # If the line has more than one =,
                                    # collect them
                                    for(i=3;i<=neq;i++) {
                                        qf = qf "=" eq[i]
                                    }
                                    qf = qf "\""
                                 } 
                                if (q ==2) {
                                    # We might have archive = "
                                    qf = $0  
                                    # Go through the loop only once
                                    qnf = q
                                }
                            } else {
                                # Reassemble the tag = value into qf
                                qf = quotes[qnf] "\"" quotes[qnf + 1] "\" "
                            }
                            #print "q: ", q, "qnf: ", qnf,  "noquotes: ", noquotes, "-->", qf

			    # Line like   background="#faf0e6"
		            # We call split twice so that we get the
		            # name that is in $1 without leading spaces
			    #split($1, n, "=")
			    #nf=split($0, f, "=")
                            split(qf, words, " ")
			    split(words[1], n, "=")
			    nf=split(qf, f, "=")
                            #print "qf: ", qf, "f[2]:", f[2]
                            # Deal with lines that have other = in them, like 
                            # plot/demo/Binary.htm
                            if (nf > 2) {
                                for(i=3;i<=nf;i++) {
                                   f[2] = f[2] "=" f[i]
                                }
                            }

			    # Look for applet parameters
			    sawAppletParam = 0
                            if (substr(f[2], length(f[2]), 1) == "\\") {
                                # Strip off any trailing back slashes
                                f[2] = substr(f[2], 1, length(f[2]) - 1)
                            }

			    for (appletParamName in appletParamNames) {
			        if (n[1] == appletParamName) {
			            if (n[1] == "code" \
				        && f[2] ~ /.class"/ ) {
                                        # Replace .class" with "
				        f[2] = substr(f[2], 0, length(f[2])- 7) "\""
				    }				
				    sawAppletParam = 1
		                    appletParams[appletParamName] = f[2]
                                    #print "appletParam:",  appletParamName, f[2]
				    lastAppletParam = appletParamName
			        }
			    }
			    if (sawAppletParam == 0 \
				    && n[1] != "type" \
				    && n[1] != "scriptable" \
				    && n[1] != "pluginspage") {
			        paramName[paramCount] = n[1]
                                tf = f[2]
                                if (index(f[2], " ") == 1) {
                                    tf = substr(f[2], 2, length(f[2]) - 1)
                                }

                                if ( match(tf, singlequote) == 0) { 
			            paramValue[paramCount++] = tf
                                    #print "No singlequote: " paramValue[paramCount -1]
                                } else {
                                    nff = split(tf, ff, singlequote)
                                    param = ""
                                    for(i=1; i<nff; i++) {
                                        #print "--->" ff[i] "<---"
                                        param=sprintf("%s%s\\%c", param, ff[i], 39)
                                    }                                    
		                    paramValue[paramCount++] = param ff[nff]
                                    #print "saw singlequote: " paramValue[paramCount -1]
                                }
			   }
                        }
		    } else {
			if ($1 !~ /</ && lastAppletParam == "archive") {
			    # continuation lines like: 
			    # archive="
			    #    ptolemy/ptsupport.jar,
			    #    ptolemy/domains/sdf/sdf.jar"
                            t1 = $1
                            if (substr($1, length($1),1) == ">") {
                                # Strip off trailing >
			        t1 = substr($1, 1, length($1) - 1)
                            } 
                            appletParams["archive"]= appletParams["archive"] t1

			}
		    }
		}
 sawNoEmbed == 1 && $1 !~ /NOEMBED>/   {
		    alternateHTML = alternateHTML "\n" $0
		    }
 $1 ~ /<\/NOEMBED/  { sawNoEmbed = 0 }
 $1 ~ /<\/EMBED/    { sawEmbed = 0}
 $1 ~ /<\/OBJECT>/  { if (sawHTMLConverter == 0) {
                         generateApplet = 1 
                         stopPrinting = 0
                      }
                    }

 $0 ~ /<!-- \/HTML CONVERTER -->/  {
                      sawHTMLConverter = 0
                      stopPrinting = 0
                      generateApplet = 1 
                    }

 generateApplet == 1 {
                    generateApplet = 0
		    print "<applet"

		    for (appletParam in appletParams) {
			if (appletParams[appletParam] != "") {
			    printf("\t%s = %s\n", appletParam, appletParams[appletParam])
			}
		    } 

		    print ">"
		    for (i = 0; i < paramCount; i++) {
			printf("        <param name = \"%s\" value =%s>\n", paramName[i], paramValue[i])
		    }
		    if (alternateHTML ~ /No JDK 1.3 support for applet!/) {_
			print "No Java Plug-in support for applet, see <a href=\"http://java.sun.com/products/plugin/\"><code>http://java.sun.com/products/plugin/</code></a>"
		    } else {
                        if (substr(alternateHTML,length(alternateHTML), 1) == "\\") {

                            print substr(alternateHTML, 1, length(alternateHTML)- 1)
                        } else {
			    print alternateHTML
                        }
		    }
		    print "</applet>"
               }		

 '  > fixapplets.htm
        # For debugging purposes, uncomment the next line
        # and view fixapplets.htm
        #exit

        # At this point, fixapplets.htm contains just the applet tag 
	
	# 2) Run the HTMLConverter that is part of the jdk on
	# the html file.

	# The HTMLConverter writes files to a temporary directory,
	# so we delete it and create it
	CURRENT_DIRECTORY=`pwd | sed 's@/cygdrive/\([a-z]\)@\1:@'`
	rm -rf htmlconverter_bak
	mkdir htmlconverter_bak

	# Avoid a basename message here
	"$PTII/bin/htmlconverter" -q \
	    -backup $CURRENT_DIRECTORY/htmlconverter_bak \
	    fixapplets.htm

	# 3) Add trailing back slashes

awk '$NF ~ /document.writeln/ {
      sawWriteln = 1
     }
$NF ~ /);$/ {
      sawWriteln = 0
     }

     {
      if (sawWriteln == 1) {
           if (substr($NF,length($NF), 1) == "\\") {
               print $0
           } else {
               if ( $0 ~ /^<PARAM/) {
                    print "	    " $0 " \\"
               } else {
                    print $0 " \\"
               }
           }
      } else {
           print $0
      }
    }
    ' fixapplets.htm |
    sed -e 's/CODEBASE/codebase/' \
	-e 's/CODE/code/' \
	-e 's/ARCHIVE/archive/' \
	-e 's/WIDTH/width/' \
	-e 's/HEIGHT/height/' \
	-e 's/VALUE  = /VALUE = /' \
	-e 's/VALUE=[^ ]/VALUE = /' \
	-e 's/VALUE = *\("[^"]*"\) *>/VALUE = \1 >/' \
	-e 's/VALUE  ="/VALUE = "/' \
	-e 's/<!--"CONVERTED_APPLET"-->//' \
	-e 's/<!--"END_CONVERTED_APPLET"-->//' \
	-e '# Split up lines that contain code ... codebase ...
            s/ code = \("[^"]*"\) codebase = \("[^"]*"\) archive = \("[^"]*"\) width = \("[^"]*"\) height = \("[^"]*"\)/code = \1 \\\
            codebase = \2 \\\
            archive = \3 \\\
            width = \4 \\\
            height = \5/' \
 	-e 's/width = \("[^"]*"\) height = \("[^"]*"\)/width = \1 \\\
            height = \2/' \
	-e 's/<PARAM NAME = code /<PARAM NAME = "code" \\\
                   /' \
	-e 's/<PARAM NAME = codebase /<PARAM NAME = "codebase"   /' \
	-e 's/<PARAM NAME = archive /<PARAM NAME = "archive" \\\
                   /' \
	-e 's/<PARAM NAME = background /<PARAM NAME = "background" /' \
	-e 's/background = */background = /' \
	-e 's/\\\\/\\/g' \
	 |
     grep -v '^ \\$' |
awk ' $0 == "<!--" { sawCommentStart = NF; sawAppletStart = 0} 
      { if (sawCommentStart == 0)  {
           print $0
        } else {
           if ($1 == "<APPLET" && NF == sawCommentStart + 1) {
              sawAppletStart = 1
           } 
           if (sawAppletStart != 0) {
              print $0
           }
        }
      }
      $0 == "-->" { sawCommentStart = 0; sawAppletStart = 0}
    ' | 
awk '
      { if ($0 !~ /<!-- HTML CONVERTER -->/ && $0 !~ /<!-- \/HTML CONVERTER -->/){
          if (skipNextLine > 0) {
	      skipNextLine--
          } else {
              if (NR > 1) {
	          print lastline
              }
          }
	  lastline = $0
       } else {
	  if ($0 ~ /<!-- HTML CONVERTER -->/) {
	      lastline = $0
          } else {
	      if ($0 ~ /<!-- \/HTML CONVERTER -->/) {
		 skipNextLine = 2      
		 print lastline
                 print $0
		 lastline = $0
	      }
          }
       }
     }
     END {print lastline}     
     '  |
     sed -e 's/\\\\/\\/g' \
     > fixapplets2.htm
     diff $file fixapplets2.htm
     if [ "$printOnly" = "no" ]; then
	 mv fixapplets2.htm $file
     else 
	 tmpFile="`basename $file .htm`.htm"
	 if [ ! -f $tmpFile ]; then
	     mv fixapplets2.htm $tmpFile
	     echo "Your results are in $tmpFile"
	 else 
	     echo "Your results are in fixapplets2.htm"
	 fi    
     fi
     #rm -rf htmlconverter_bak fixapplets.htm	 

done


