#!/bin/sh
# Brute Force Hack Conversion from ECSL to MoML
# Author:  Christopher Brooks
# Version: $Id: ecsl2moml 46656 2007-08-08 20:07:43Z cxh $
#
# Copyright (c) 2004-2005 The Regents of the University of California.
# 	All Rights Reserved.
#
# Permission is hereby granted, without written agreement and without
# license or royalty fees, to use, copy, modify, and distribute this
# software and its documentation for any purpose, provided that the
# above copyright notice and the following two paragraphs appear in all
# copies of this software.
#
# IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
# FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
# ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
# THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
# THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
# PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
# CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
# ENHANCEMENTS, OR MODIFICATIONS.
#
# 						PT_COPYRIGHT_VERSION_2
# 						COPYRIGHTENDKEY


# Usage: ecsl2moml ecslfile

# Limitations:
#     Looks like the conversion tool loses the connection between
#     ports of a hierarchical actor and the inside relation...
#    
#     The Switch block is not properly translated because the
#     corresponding actor has a multiport, and it appears that
#     the order of connections is different. But for the Switch
#     block, the order matters.
#    
#     Also, forked connections are not properly translated.
#     They seem to translate into multiple connections to the
#     originating port.
#    
#     Also, for many blocks like Sum, Product, it would be better
#     to translate these into native PtII actors like AddSubtract,
#     MultiplyDivide.  This requires being smarter about which
#     ports to connect to, however, so it could be a good bit
#     of work to do this.

if [ $# -ne 1 ]; then
    echo "$0: Usage: $0 ecslfile"
    echo "   Read in ecslfile, generate a MoML file with the same base name"
    echo "   ecslfile should end in .xml"
    exit 2
fi

input=$1
if [ ! -r $input ]; then
    echo "$0: $input is not readable. Exiting."
    exit 3
fi

modelname=`basename $input .xml`
output="$modelname.moml"

tmpfile1=/tmp/ecsl2moml.$$.1
tmpfile2=/tmp/ecsl2moml.$$.2

STEPS=10
echo "1 of $STEPS: Add the MoML Header and get rid of RootFolder"
awk '{
    if ($0 ~ /<RootFolder/) {
        print "<?xml version=\"1.0\" standalone=\"no\"?>"
        print "<!DOCTYPE entity PUBLIC \"-//UC Berkeley//DTD MoML 1//EN\""
        print "    \"http://ptolemy.eecs.berkeley.edu/xml/dtd/MoML_1.dtd\">"
    } else if ($0 ~ /<\/RootFolder>/) {
        # Print nothing
    } else {
        print $0
    }
}' modelname=${modelname} $input > $tmpfile1

echo "2 of $STEPS: Get rid of the StateFlow section.  FIXME: eventually, deal with this"
awk '
    $0 ~ /<Stateflow/ { sawStateFlow = 1 }
    sawStateFlow == 0 { print $0}
    $0 ~ /<\/Stateflow/ { sawStateFlow = 0 }
' < $tmpfile1 > $tmpfile2

echo "3 of $STEPS: Get rid of the HardwareModels section.  FIXME: eventually, deal with this"
awk '
    $0 ~ /<HardwareModels/ { sawHardwareModels = 1 }
    sawHardwareModels == 0 { print $0}
    $0 ~ /<\/HardwareModels/ { sawHardwareModels = 0 }
' < $tmpfile2 > $tmpfile1

# Get rid of the enclosing <ComponentModels..> </ComponentModels>
grep -v "<ComponentModels" $tmpfile1 | grep -v "</ComponentModels" > $tmpfile2

sed 's/\r//g' <$tmpfile2 >$tmpfile1

# Join split lines
awk '{ if ( $0 ~ /[^>]$/) {
           printf("%s", $0);

       } else {
           print $0
       }

}' <$tmpfile1 >$tmpfile2

# Get rid of the enclosing <Dataflow..> </Dataflow>
grep -v "<Dataflow" $tmpfile2 | grep -v "</Dataflow" > $tmpfile1

echo "4 of $STEPS: Convert <System ... or <ComponentSheet to <entity"
awk ' {
    if ($0 ~ /<System/ || $0 ~ /<ComponentSheet/ || $0 ~ /<Component/ ) {
       # Get the value of the name field
       nf = split($0, f, "\"")   
       for (i = 1; i <= nf; i++) {
           if ( f[i] ~ /name=$/) {
               name = f[i+1]
               break;
           }
       }
       lastNameField = f[nf]

       # Get the value of the position field
       position=""
       nf = split($0, f, "\"")   
       for (i = 1; i <= nf; i++) {
           if ( f[i] ~ /osition=$/) {
               position = f[i+1]
               break;
           }
       }
       split(position, p, ",")
       #scale = 4
       scale = 1.0
       x = substr(p[1], 2, length(p[1])) / scale
       y = substr(p[2], 1, length(p[2]) - 1) / scale

       indent = substr($0, 0, index($0,"<") - 1)  
       # Sometimes we have <System ... />
       print indent "<entity name=\"" name "\" class=\"ptolemy.actor.TypedCompositeActor\"" lastNameField
       
       print indent "    <property name=\"_location\" class=\"ptolemy.kernel.util.Location\" value=\"[" x ", " y "]\">"
       print indent "    </property>"

       # Get the value of the Worst Case Execution Time field, if any
       if ($0 ~ /WCET=/) {
           wcet=0 
           nf = split($0, f, "\"")   
           for (i = 1; i <= nf; i++) {
               if ( f[i] ~ /WCET=$/) {
                   wcet = f[i+1]
                   break;
               }
           } # wcet for
           if (wcet != 0) {
               print indent "    <property name=\"frequency\" class=\"ptolemy.data.expr.Parameter\" value=\"" wcet "\">"
               print indent "    </property>"

           } # wcet if
       } # contains wcet

       useCTDirector = 1
       if (sawFirstEntity == 0 && useCTDirector == 1) {
           sawFirstEntity = 1
           # Add the director
           print "    <property name=\"CT Director\" class=\"ptolemy.domains.ct.kernel.CTMixedSignalDirector\">"
           print "        <property name=\"stopTime\" class=\"ptolemy.data.expr.Parameter\" value=\"10.0\">"
           print "        </property>"
           print "        <property name=\"ODESolver\" class=\"ptolemy.data.expr.Parameter\" value=\"&quot;ptolemy.domains.ct.kernel.solver.ExplicitRK23Solver&quot;\">"
           print "            <property name=\"style\" class=\"ptolemy.actor.gui.style.EditableChoiceStyle\">"
           print "                <property name=\"choice0\" class=\"ptolemy.data.expr.Parameter\" value=\"&quot;ptolemy.domains.ct.kernel.solver.ExplicitRK23Solver&quot;\">"
           print "                </property>"
           print "                <property name=\"choice1\" class=\"ptolemy.data.expr.Parameter\" value=\"&quot;ptolemy.domains.ct.kernel.solver.BackwardEulerSolver&quot;\">"
           print "                </property>"
           print "                <property name=\"choice2\" class=\"ptolemy.data.expr.Parameter\" value=\"&quot;ptolemy.domains.ct.kernel.solver.ForwardEulerSolver&quot;\">"
           print "                </property>"
           print "            </property>"
           print "        </property>"
           print "        <property name=\"breakpointODESolver\" class=\"ptolemy.data.expr.Parameter\" value=\"&quot;ptolemy.domains.ct.kernel.solver.DerivativeResolver&quot;\">"
           print "            <property name=\"style\" class=\"ptolemy.actor.gui.style.EditableChoiceStyle\">"
           print "                <property name=\"choice0\" class=\"ptolemy.data.expr.Parameter\" value=\"&quot;ptolemy.domains.ct.kernel.solver.DerivativeResolver&quot;\">"
           print "                </property>"
           print "                <property name=\"choice1\" class=\"ptolemy.data.expr.Parameter\" value=\"&quot;ptolemy.domains.ct.kernel.solver.BackwardEulerSolver&quot;\">"
           print "                </property>"
           print "                <property name=\"choice2\" class=\"ptolemy.data.expr.Parameter\" value=\"&quot;ptolemy.domains.ct.kernel.solver.ImpulseBESolver&quot;\">"
           print "                </property>"
           print "            </property>"
           print "        </property>"
           print "        <property name=\"_location\" class=\"ptolemy.kernel.util.Location\" value=\"{75.0, 40.0}\">"
           print "        </property>"
           print "    </property>"
        }  

       useSDFDirector = 0
       if (sawFirstEntity == 0 && useSDFDirector == 1) {
           sawFirstEntity = 1
           # Add the director
           print "    <property name=\"SDF Director\" class=\"ptolemy.domains.sdf.kernel.SDFDirector\">"
           print "        <property name=\"iterations\" class=\"ptolemy.data.expr.Parameter\" value=\"10\">"
           print "        </property>"
           print "        <property name=\"_location\" class=\"ptolemy.kernel.util.Location\" value=\"{75.0, 40.0}\">"
           print "        </property>"
           print "    </property>"
       }  

       useGiottoCodeGenerator = 0
       if (sawFirstEntity == 0 && useGiottoCodeGenerator == 1) {
           sawFirstEntity = 1
           print indent "    <property name=\"Giotto Director\" class=\"ptolemy.domains.giotto.kernel.GiottoDirector\">"
           print indent "        <property name=\"_location\" class=\"ptolemy.kernel.util.Location\" value=\"{245, 40}\">"
           print indent "        </property>"
           print indent "    </property>"
           print indent "    <property name=\"CodeGenerator\" class=\"ptolemy.domains.giotto.kernel.GiottoCodeGenerator\">"
           print indent "        <property name=\"_location\" class=\"ptolemy.kernel.util.Location\" value=\"{400, 35}\">"
           print indent "        </property>"
           print indent "    </property>"
        }

    } else if ($0 ~ /<\/System>/ || $0 ~ /<\/ComponentSheet>/ || $0 ~ /<\/Component>/ ) {
       # FIXME: If we have <System ... />, then the indent might be wrong?
       print indent "</entity>"
    } else {
       print $0
    }   
}' < $tmpfile1 > $tmpfile2


echo "5 of $STEPS: Convert <Annotation to MoML Annotation"
awk ' {
    if ($0 ~ /<Annotation/) {

       # Get the value of the Text field
       text=""
       nf = split($0, f, "\"")   
       for (i = 1; i <= nf; i++) {
           if ( f[i] ~ /Text=$/) {
               text = f[i+1]
               break;
           }
       }
       # Get the value of the position field
       position=""
       nf = split($0, f, "\"")   
       for (i = 1; i <= nf; i++) {
           if ( f[i] ~ /osition=$/) {
               position = f[i+1]
               break;
           }
       }
       split(position, p, ",")
       #scale = 4
       scale = 1.0
       x = substr(p[1], 2, length(p[1])) / scale
       y = substr(p[2], 1, length(p[2]) - 1) / scale

       if (length(text) > 0) {
           indent = substr($0, 0, index($0,"<") - 1)  
           annotationCount++
           print indent "<property name=\"annotation" annotationCount "\" class=\"ptolemy.kernel.util.Attribute\">"
           print indent "    <property name=\"_hideName\" class=\"ptolemy.kernel.util.SingletonAttribute\">"
           print indent "    </property>"
           print indent "    <property name=\"_iconDescription\" class=\"ptolemy.kernel.util.SingletonConfigurableAttribute\">" 
           print indent "        <configure><svg><text x=\"20\" y=\"20\" style=\"font-size:14; font-family:SansSerif; fill:red\">" text "</text></svg></configure>"
           print indent "    </property>"
           print indent "    <property name=\"_smallIconDescription\" class=\"ptolemy.kernel.util.SingletonConfigurableAttribute\">"
           print indent "    <configure>"
           print indent "        <svg>"
           print indent "        <text x=\"20\" style=\"font-size:14; font-family:SansSerif; fill:blue\" y=\"20\">-A-</text>"
           print indent "        </svg>"
           print indent "    </configure>"
           print indent "    </property>"
           print indent "    <property name=\"_controllerFactory\" class=\"ptolemy.vergil.basic.NodeControllerFactory\">"
           print indent "    </property>"
           print indent "    <property name=\"_editorFactory\" class=\"ptolemy.vergil.toolbox.AnnotationEditorFactory\">"
           print indent "    </property>"
           print indent "    <property name=\"_location\" class=\"ptolemy.kernel.util.Location\" value=\"[" x ", " y "]\">"
           print indent "    </property>"
           print indent "    <property name=\"_icon\" class=\"ptolemy.vergil.icon.XMLIcon\">"
           print indent "    </property>"

           print indent "</property>"
        }
    } else { # foo
        print $0
    }
} ' < $tmpfile2 > $tmpfile1


echo "6 of $STEPS: Convert <Line or <Signal to <relation"
awk ' {
    if ( $1 ~ /<Line/ || $1 ~ /<Signal/ ) {
       # Get the value of the _id field
       id=""
       nf = split($0, f, "\"")   
       for (i = 1; i <= nf; i++) {
           if ( f[i] ~ /_id=$/) {
               id = f[i+1]
               break;
           }
       }
       # Get the value of the _id field
       position=""
       nf = split($0, f, "\"")   
       for (i = 1; i <= nf; i++) {
           if ( f[i] ~ /position=$/) {
               position = f[i+1]
               break;
           }
       }
       if (position != "") {
           position = "position=\"" position "\""
       }

       indent = substr($0, 0, index($0,"<") - 1)  

#        if ($0 ~ /dstSignal_end_/) {
#            # Get the value of the dstSignal_end_ field
#            dstSignal_end_=""
#            nf = split($0, f, "\"")   
#            for (i = 1; i <= nf; i++) {
#                if ( f[i] ~ /dstSignal_end_=$/) {
#                    dstSignal_end_ = f[i+1]
#                    break;
#                }
#            }
#            print indent "<!--dstSignal_end--><link port=\"" dstSignal_end_ "\" relation=\"" id "\"/>" 

#            # Get the value of the srcSignal_end_ field
#            srcSignal_end_=""
#            nf = split($0, f, "\"")   
#            for (i = 1; i <= nf; i++) {
#                if ( f[i] ~ /srcSignal_end_=$/) {
#                    srcSignal_end_ = f[i+1]
#                    break;
#                }
#            }
#           print indent "<link port=\"" srcSignal_end_ "\" relation=\"" id "\"/>" 
#        } else {
           # We include the position here, if any, and strip it out later
           # if the position is (-1,-1). Signals often have (-1,-1) position
           # FIXME: A real hack. we depend on position being at the end
           print indent "<relation name=\"" id "\" class=\"ptolemy.actor.TypedIORelation\" " position "/>"
#       }

    } else { # bar
        print $0
    }
}' < $tmpfile1 > $tmpfile2

echo "7 of $STEPS: Convert <Primitive to <entity"
awk 'BEGIN {
    map["Abs"] = "vendors.ecsl_dp.ptolemy.ECSLAbs"
    map["ActionPort"] = "vendors.ecsl_dp.ptolemy.ECSLActionPort"
    map["Clock"] = "vendors.ecsl_dp.ptolemy.ECSLClock"
    map["Constant"] = "vendors.ecsl_dp.ptolemy.ECSLConstant"
    map["DataStoreMemory"] = "vendors.ecsl_dp.ptolemy.ECSLDataStoreMemory"
    map["DataStoreRead"] = "vendors.ecsl_dp.ptolemy.ECSLDataStoreRead"
    map["DataStoreWrite"] = "vendors.ecsl_dp.ptolemy.ECSLDataStoreWrite"
    map["DeadZone"] = "vendors.ecsl_dp.ptolemy.ECSLDeadZone"
    map["Demux"] = "vendors.ecsl_dp.ptolemy.ECSLDemux"
    map["DiscreteFilter"] = "vendors.ecsl_dp.ptolemy.ECSLDiscreteFilter"
    map["DiscreteIntegrator"] = "vendors.ecsl_dp.ptolemy.ECSLDiscreteIntegrator"
    map["DiscretePulseGenerator"] = "vendors.ecsl_dp.ptolemy.ECSLDiscretePulseGenerator"
    map["Display"] = "vendors.ecsl_dp.ptolemy.ECSLDisplay"
    map["Fcn"] = "vendors.ecsl_dp.ptolemy.ECSLFcn"
    map["From"] = "vendors.ecsl_dp.ptolemy.ECSLFrom"
    map["FromWorkspace"] = "vendors.ecsl_dp.ptolemy.ECSLFromWorkspace"
    map["Gain"] = "vendors.ecsl_dp.ptolemy.ECSLGain"
    map["Goto"] = "vendors.ecsl_dp.ptolemy.ECSLGoto"
    map["Ground"] = "vendors.ecsl_dp.ptolemy.ECSLGround"
    map["If"] = "vendors.ecsl_dp.ptolemy.ECSLIf"
    map["Integrator"] = "vendors.ecsl_dp.ptolemy.ECSLIntegrator"
    map["Interpolator"] = "vendors.ecsl_dp.ptolemy.ECSLInterpolator"
    map["Logic"] = "vendors.ecsl_dp.ptolemy.ECSLLogic"
    map["Math"] = "vendors.ecsl_dp.ptolemy.ECSLMath"
    map["Memory"] = "vendors.ecsl_dp.ptolemy.ECSLMemory"
    map["Merge"] = "vendors.ecsl_dp.ptolemy.ECSLMerge"
    map["MinMax"] = "vendors.ecsl_dp.ptolemy.ECSLMinMax"
    map["MultiPortSwitch"] = "vendors.ecsl_dp.ptolemy.ECSLMultiPortSwitch"
    map["Mux"] = "vendors.ecsl_dp.ptolemy.ECSLMux"
    map["Product"] = "vendors.ecsl_dp.ptolemy.ECSLProduct"
    map["RandomNumber"] = "vendors.ecsl_dp.ptolemy.ECSLRandomNumber"
    map["Reference"] = "vendors.ecsl_dp.ptolemy.ECSLReference"
    map["RelationalOperator"] = "vendors.ecsl_dp.ptolemy.ECSLRelationalOperator"
    map["Rounding"] = "vendors.ecsl_dp.ptolemy.ECSLRounding"
    map["SFunction"] = "vendors.ecsl_dp.ptolemy.ECSLSFunction"
    map["Saturate"] = "vendors.ecsl_dp.ptolemy.ECSLSaturate"
    map["SignalSpecification"] = "vendors.ecsl_dp.ptolemy.ECSLSignalSpecification"
    map["Signum"] = "vendors.ecsl_dp.ptolemy.ECSLSignum"
    map["Sin"] = "vendors.ecsl_dp.ptolemy.ECSLSin"
    map["Step"] = "vendors.ecsl_dp.ptolemy.ECSLStep"
    map["Stop"] = "vendors.ecsl_dp.ptolemy.ECSLStop"
    map["Sum"] = "vendors.ecsl_dp.ptolemy.ECSLSum"
    map["Switch"] = "vendors.ecsl_dp.ptolemy.ECSLSwitch"
    map["Terminator"] = "vendors.ecsl_dp.ptolemy.ECSLTerminator"
    map["ToWorkspace"] = "vendors.ecsl_dp.ptolemy.ECSLToWorkspace"
    map["TransferFcn"] = "vendors.ecsl_dp.ptolemy.ECSLTransferFcn"
    map["TransportDelay"] = "vendors.ecsl_dp.ptolemy.ECSLTransportDelay"
    map["Trigonometry"] = "vendors.ecsl_dp.ptolemy.ECSLTrigonometry"
    map["UniformRandomNumber"] = "vendors.ecsl_dp.ptolemy.ECSLUniformRandomNumber"
    map["UnitDelay"] = "vendors.ecsl_dp.ptolemy.ECSLUnitDelay"
    map["VariableTransportDelay"] = "vendors.ecsl_dp.ptolemy.ECSLVariableTransportDelay"
    map["ZeroOrderHold"] = "vendors.ecsl_dp.ptolemy.ECSLZeroOrderHold"


    map["Abs"] = "vendors.ecsl_dp.ptolemy.ECSLAbs"
    map["Clock"] = "vendors.ecsl_dp.ptolemy.ECSLClock"
    map["Constant"] = "vendors.ecsl_dp.ptolemy.ECSLConstant"
    map["Demux"] = "vendors.ecsl_dp.ptolemy.ECSLDemux"
    # FIXME
    map["DiscreteFilter"] = "vendors.ecsl_dp.ptolemy.ECSLDiscreteFilter"
    map["DiscreteIntegrator"] = "vendors.ecsl_dp.ptolemy.ECSLDiscreteIntegrator"
    map["DiscretePulseGenerator"] = "vendors.ecsl_dp.ptolemy.ECSLDiscretePulseGenerator"
    map["Display"] = "vendors.ecsl_dp.ptolemy.ECSLDisplay"
    # FIXME
    map["From"] = "vendors.ecsl_dp.ptolemy.ECSLFrom"
    map["Gain"] = "vendors.ecsl_dp.ptolemy.ECSLGain"
    # FIXME
    map["Goto"] = "vendors.ecsl_dp.ptolemy.ECSLGoto"
    map["Ground"] = "vendors.ecsl_dp.ptolemy.ECSLGround"
    map["Integrator"] = "ptolemy.domains.ct.lib.Integrator"
    map["Logic"] = "vendors.ecsl_dp.ptolemy.ECSLLogic"
    map["Merge"] = "vendors.ecsl_dp.ptolemy.ECSLMerge"
    # FIXME: should be Minimum or Maximum 
    map["MinMax"] = "vendors.ecsl_dp.ptolemy.ECSLMinMax"
    # FIXME
    map["MultiPortSwitch"] = "vendors.ecsl_dp.ptolemy.ECSLMultiPortSwitch"
    map["Mux"] = "vendors.ecsl_dp.ptolemy.ECSLMux"
    map["Product"] = "vendors.ecsl_dp.ptolemy.ECSLProduct"
    # FIXME
    map["RelationalOperator"] = "vendors.ecsl_dp.ptolemy.ECSLRelationalOperator"
    map["S-Function"] = "vendors.ecsl_dp.ptolemy.ECSLSFunction"
    # FIXME
    map["Saturate"] = "vendors.ecsl_dp.ptolemy.ECSLSaturate"

    # Generate SDF
    #map["Scope"] = "vendors.ecsl_dp.ptolemy.ECSLTimedPlotter"
    map["Scope"] = "vendors.ecsl_dp.ptolemy.ECSLSequenceScope"

    map["Signum"] = "vendors.ecsl_dp.ptolemy.ECSLSignum"
    # FIXME: set to Sin
    map["Sin"] = "vendors.ecsl_dp.ptolemy.ECSLSin"
    # FIXME Leave off sampleTime, convert integers to doubles

    # Generate SDF
    #map["Step"] = "vendors.ecsl_dp.ptolemy.ECSLStep"
    map["Step"] = "vendors.ecsl_dp.ptolemy.ECSLInterpolator"

    map["Sum"] = "vendors.ecsl_dp.ptolemy.ECSLSum"
    map["Switch"] = "vendors.ecsl_dp.ptolemy.ECSLSwitch"
    map["Terminator"] = "vendors.ecsl_dp.ptolemy.ECSLTerminator"
    # FIXME
    map["ToWorkspace"] = "vendors.ecsl_dp.ptolemy.ECSLToWorkspace"
    #map["UnitDelay"] = "vendors.ecsl_dp.ptolemy.ECSLUnitDelay"
    map["UnitDelay"] = "ptolemy.domains.sdf.lib.SampleDelay"
    map["ZeroOrderHold"] = "vendors.ecsl_dp.ptolemy.ECSLZeroOrderHold"
}
{
    if ($1 ~ /<Primitive/) {
       # Get the value of the name field
       name=""
       nf = split($0, f, "\"")   
       for (i = 1; i <= nf; i++) {
           if ( f[i] ~ /name=$/) {
               name = f[i+1]
               break;
           }
       }

       # Get the value of the position field
       position=""
       nf = split($0, f, "\"")   
       for (i = 1; i <= nf; i++) {
           if ( f[i] ~ /osition=$/) {
               position = f[i+1]
               break;
           }
       }
       split(position, p, ",")
       #scale = 2.4 
       scale = 1.0
       x = substr(p[1], 2, length(p[1])) / scale
       y = substr(p[2], 1, length(p[2]) - 1) / scale

       # Get the value of the BlockType field
       blockType=""
       nf = split($0, f, "\"")   
       for (i = 1; i <= nf; i++) {
           if ( f[i] ~ /BlockType=$/) {
               blockType = f[i+1]
               break;
           }
       }
       indent = substr($0, 0, index($0,"<") - 1)  
       print indent "<entity name=\"" name "\" class=\"" map[blockType] "\">"
       print indent "    <property name=\"_location\" class=\"ptolemy.kernel.util.Location\" value=\"[" x ", " y "]\">"
       print indent "     </property>"
    } else if ($1 ~ /<\/Primitive>/) {
        print indent "</entity>"
    } else { # bif
        print $0
    }
} ' < $tmpfile2 > $tmpfile1


relationsFile=ecsl2moml.relations
rm -f $relationsFile

echo "8 of $STEPS: Convert OutputPort and InputPort"
awk '
$0 ~ /<entity/ {

       # Get the value of the name field
       name=""
       nf = split($0, f, "\"")   
       for (i = 1; i <= nf; i++) {
           if ( f[i] ~ /name=$/) {
               name = f[i+1]
               break;
           }
       }
       containerCount += 1
       containerStack[containerCount] = name

       # Get the value of the class field
       class=""
       nf = split($0, f, "\"")   
       for (i = 1; i <= nf; i++) {
           if ( f[i] ~ /class=$/) {
               class = f[i+1]
               break;
           }
       }
}
{
    if ($1 ~ /<OutputPort/ || $1 ~ /<InputPort/ || $1 ~ /<TriggerPort/ || $1 ~ /<CInPort/ || $1 ~ /<COutPort/ ) {
       # Get the value of the name field
       name=""
       nf = split($0, f, "\"")   
       for (i = 1; i <= nf; i++) {
           if ( f[i] ~ /name=$/) {

               name = f[i+1]
               break;
           }
       }

       # Composite actors and Mux do not get In1 mapped to input
       # Other classes do get mapped. 
       # Note that giotto cannot handle multiports
       if (class != "ptolemy.actor.TypedCompositeActor" && class != "vendors.ecsl_dp.ptolemy.ECSLMux") {
           # Remap names like In1 to input
           if (name ~ /^In[0-9]*$/) {
               oldName = name
               name = "input"
   
           }
       }

       #if (class != "ptolemy.actor.TypedCompositeActor") {
       if (name == "") {
           if (name ~ /^Out[0-9]*$/) {
               oldName = name
               name = "output"
           }
           if (name == "") {
               # Name is empty
               if ($1 ~ /<OutputPort/) {
                   name = "output"
               } else if ($1 ~ /<InputPort/) {
                   name = "input"
               }
           }
       }

       # Get the value of the dstLine field
       dstLine=""
       nf = split($0, f, "\"")   
       if ( $0 ~ /dstLine=/ ) {
           for (i = 1; i <= nf; i++) {
               if ( f[i] ~ /dstLine=$/) {
                   dstLine = f[i+1]
                   break;
               }
           }
       } else {
           # Components have signals  
           for (i = 1; i <= nf; i++) {
               if ( f[i] ~ /dstSignal=$/) {
                   dstLine = f[i+1]
                   break;
               }
           }
       }

       # Get the value of the srcLine field
       srcLine=""
       nf = split($0, f, "\"")   
       if ( $0 ~ /srcLine=/ ) {
           for (i = 1; i <= nf; i++) {
               if ( f[i] ~ /srcLine=$/) {
                   srcLine = f[i+1]
                   break;
               }
           }
       } else {
           # Components have signals  
           for (i = 1; i <= nf; i++) {
               if ( f[i] ~ /srcSignal=$/) {
                   srcLine = f[i+1]
                   break;
               }
           }

       }
 
       # First, we handle the usual case where OutputPort only
       # has a dstLine field
       if ($1 ~ /<OutputPort/ || $1 ~ /<COutPort/ ) {
           relation = dstLine
           relation2PortMap[srcLine] = name
       } else { # bof
           relation = srcLine
          relation2PortMap[dstLine] = name
       }


       # Get the value of the position field
       position=""
       nf = split($0, f, "\"")   
       for (i = 1; i <= nf; i++) {
           if ( f[i] ~ /osition=$/) {
               position = f[i+1]
               break;
           }
       }
       split(position, p, ",")
       #scale = 4
       scale = 1.0
       x = substr(p[1], 2, length(p[1])) / scale
       y = substr(p[2], 1, length(p[2]) - 1) / scale

       location="[" x "," y "]"
       #print "<!--", position , x, y, p[1], p[2], location, "relation =", relation, $0, "-->"
       relationLocationMap[relation] = location
       relationPortMap[relation] = name
       #print "<!-- ", relation, name, relationPortMap[name], relation2PortMap[name], srcLine, dstLine, $0  " 6 -->"

       indent = substr($0, 0, index($0,"<") - 1)  

       print indent "<port name=\"" name "\" class=\"ptolemy.actor.TypedIOPort\">"
       if ($1 ~ /<OutputPort/ || $1 ~ /<COutPort/ ) {
           if (name == "output") {
               # If we have 2 or more output ports, then declare it a multiport
               # we need this for composite actors in sbw.
               outputCount++  
               if (outputCount > 2) {
                   print indent "    <property name=\"multiport\"/>"
               }
          }
           print indent "    <property name=\"output\"/>"
       } else if ($1 ~ /<InputPort/ || $1 ~ /<CInPort/ ) {
           if (name == "input") {
               # If we have 2 or more input ports, then declare it a multiport
               # we need this for composite actors in sbw.
               inputCount++  
               if (inputCount > 2) {
                   print indent "    <property name=\"multiport\"/>"
               }
           }
           print indent "    <property name=\"input\"/>"
       }  

       longName = containerStack[containerCount] "." name

       if (index(relation, " ") != 0) {
           if (class == "ptolemy.domains.ct.lib.Integrator" || class == "ptolemy.domains.sdf.lib.SampleDelay") { 
               # The class cannot handle a multiport, so add a relation.
               addRelationsContainer[longName] = containerStack[containerCount]
               addRelations[longName] = name
               name = name "_multiPort"
               longName = containerStack[containerCount] "_" name

           } else { 
               # The relation name has spaces in it, so this is a multiport
               print indent "    <property name=\"multiport\"/>"
           }
       }


       #if (class == "vendors.ecsl_dp.ptolemy.ECSLSum" \
       #        && name == "input" ) {
       #    # FIXME: Connect the first Input to minus, the second to plus
       #    if (oldName == "In1") {
       #        longName = containerStack[containerCount] ".plus"
       #    } else if (oldName == "In2") {
       #        longName = containerStack[containerCount] ".minus"
       #    }
       #}

       # Get the value of the position field
       position=""
       nf = split($0, f, "\"")   
       for (i = 1; i <= nf; i++) {
           if ( f[i] ~ /osition=$/) {
               position = f[i+1]
               break;
           }
       }
       split(position, p, ",")
       #scale = 4
       scale = 1.0
       x = substr(p[1], 2, length(p[1])) / scale
       y = substr(p[2], 1, length(p[2]) - 1) / scale
       print indent "    <property name=\"_location\" class=\"ptolemy.kernel.util.Location\" value=\"[" x ", " y "]\">"
       print indent "     </property>"

       print indent "</port>"

       # Handle Composite ports connected to relations
       if (class == "ptolemy.actor.TypedCompositeActor") {
           if (srcLine != "" && dstLine != "") {
              print indent "<!-- " $1, name, srcLine, dstLine, toBeLinked[srcLine], toBeLinked[dstLine] " 7 -->"

              if ($1 ~ /<OutputPort/ || $1 ~ /<COutPort/ ) {
                  #toBeLinked[dstLine] = name;
                  #print indent "<!-- 10 --><link port=\"" name "\" relation=\"" dstLine "\"/>"
              } else if ($1 ~ /<InputPort/ || $1 ~ /<CInPort/ ) {
                  #toBeLinked[srcLine] = name;
                  #print indent "<!-- 11 --><link port=\"" name "\" relation=\"" srcLine "\"/>"

              }
           }
       }


       if (length(links[longName]) == 0) { 
           links[longName] = relation
       } else {
           # Already have a relation for this longName
           links[longName] = links[longName] " " relation
       }

       # Second, we handle the case where OutputPort 
       # has a dstLine field _and_ a srcLine field
       if ( ($1 ~ /<OutputPort/ || $1 ~ /<COutPort/) && length(srcLine) > 0) {
           longName = containerStack[containerCount] "." name
           # FIXME: this needs to be linked in the container???
           #links[longName] = srcLine
       } else if ( ($1 ~ /<InputPort/ || $1 ~ /<CInPort/) && length(dstLine) > 0) {
           longName = containerStack[containerCount] "." name
           # FIXME: this needs to be linked in the container???
           #links[longName] = dstLine
       }       
    } else { # biz
        if ($1 ~ /<relation/) {
            # Get the value of the name field
            name=""
            nf = split($0, f, "\"")   
            for (i = 1; i <= nf; i++) {
                if ( f[i] ~ /name=$/) {
                    name = f[i+1]
                    break;
                }
            }


            # Get the value of the position field
            position=""
            nf = split($0, f, "\"")   
            for (i = 1; i <= nf; i++) {
               if ( f[i] ~ /osition=$/) {
                   position = f[i+1]
                   break;
               }
            }

            indent = substr($0, 0, index($0,"<") - 1)  

            # Get the location, if any

            if (position ~/(-1,-1)/) {
                # FIXME: A real hack. we depend on position being at the end
                positionLength = length("position=\"" position "\"/>") 
                print substr($0, 0, length($0)-positionHack) "/>"
            } else if (relationLocationMap[name] == "") { 
                print $0
            } else {
                # Get rid of the />
                print substr($0, 0, length($0)-2) ">"
                print indent "    <vertex name=\"vertex1\" value=\"" relationLocationMap[name] "\"/>" 
               print indent "</relation>"
            }
            # Get the port, if any
            if (relationPortMap[name] != "") { 
                print indent "<!-- " NR, $0, " 1 --><!-- link port=\"" relationPortMap[name] "\" relation=\"" name "\"/ -->"
            }
            #if (class == "ptolemy.actor.TypedCompositeActor") {
                if (relation2PortMap[name] != "") { 
                    print indent "<!-- " NR, name, relationPortMap[name], relation2PortMap[name] " 5 --><link port=\"" relation2PortMap[name] "\" relation=\"" name "\"/>"
                }
            #}
            #print "<!-- 9 -" name "-" toBeLinked[name] "- -->"
            #if (toBeLinked[name] != "") {
            #    print indent "<!-- 8 --><link port=\"" toBeLinked[name] "\" relation=\"" name "\"/>"
            #    toBeLinked[name] = ""
            #}
        } else {
            print $0   
        }
    }
}
$1 ~ /<\/entity>/ {
    container = containerStack[containerCount] 
    containerCount -= 1         
    indent = substr($0, 0, index($0,"<") - 1)  
    inputCount = 0
    outputCount = 0

    # Handle places where we need to add a relation
    for (addRelation in addRelations) {
       if ( length(addRelations[addRelation]) > 0 ) {
           addRelationsFullName = addRelationsContainer[addRelation] "_" addRelations[addRelation] "_multiPort"
           print indent "<relation name=\"" addRelationsFullName "\" class=\"ptolemy.actor.TypedIORelation\"/>"
           print indent "<!-- 2 --><link port=\"" addRelation "\" relation=\"" addRelationsFullName "\"/>" 
       }
    }


    # We need to add the link statements outside the container.
    # Sometimes, containers are nested, getting the links right is tricky.
    for ( link in links) {
       if ( length(links[link]) > 0 \
          &&  substr(link, 0, length(container) + 1) == container "." ) {
          # We have not yet printed this link, and it is for
          # the container we just exited.

          # Sometimes a dstLine will have many relations listed
          # dstLine="id32b id32c id32d id32e"

          relation = links[link]
          if (index(relation, " ") == 0) {
              # No spaces is the relation name
              print indent "<!-- 3 --><link port=\"" link "\" relation=\"" relation "\"/>" 
          } else {
              nf = split(relation, relations, " ") 
              for(i = 1; i <= nf; i++) {
                  # If the port is an addRelations port, then
                  # we will substitute n the next awk run
                  addRelationsHack = 0
                  for (addRelation in addRelations) {
                      if ( length(addRelations[addRelation]) > 0 ) {
                           addRelationsFullName = addRelationsContainer[addRelation] "_" addRelations[addRelation] "_multiPort"
                           if (link == addRelationsFullName) {
                               addRelationsHack = 1
                               # Now we write sed commands to a file
                               # for processing in the next step.
 
                               # Delete the creation of the relation
                               #print "s/[ 	]*<relation name=\"" relations[i] "\".*$//" >"ecsl2moml.relations"
                               print "s/[ 	]*<relation name=\"" relations[i] "\".*$//" >"ecsl2moml.relations"

                               # Substitute our relation in 
                               #print "s/relation=\"" relations[i] "\"/relation=\"" addRelationsFullName "\"/" >"ecsl2moml.relations"
                               print "s/relation=\"" relations[i] "\"/relation=\"" addRelationsFullName "\"/" >"ecsl2moml.relations"

                           }
                       }
                  } 
                  if (addRelationsHack == 0) {
                      print indent "<!-- 4--><link port=\"" link "\" relation=\"" relations[i] "\"/>"
                  }
              }
          }
          links[link] = ""  
       }

    }
    for (addRelation in addRelations) {
       if ( length(addRelations[addRelation]) > 0 ) {
          addRelations[addRelation] = ""
       }
    }
}' < $tmpfile1 > $tmpfile2

if [ -f ecsl2moml.relations ]; then 
    echo "9 of $STEPS: Substitute relation names fo relations"
    seds=`wc -l < ecsl2moml.relations`
    echo "         Running $seds expressions `date`"
    sed -f ecsl2moml.relations < $tmpfile2 > $tmpfile1
    echo "         `date`"
else
    cp $tmpfile2 $tmpfile1
fi

echo "10 of $STEPS: Parameter"
awk '{
    if ($1 ~ /<entity/) {
       # Get the value of the class field
       class=""
       nf = split($0, f, "\"")   
       for (i = 1; i <= nf; i++) {
           if ( f[i] ~ /class=$/) {
               class = f[i+1]
               break;
           }
       }
    }
    if ($1 ~ /<Parameter/) {
       # Get the value of the name field
       name=""
       nf = split($0, f, "\"")   
       for (i = 1; i <= nf; i++) {
           if ( f[i] ~ /name=$/) {
               name = f[i+1]
               break;
           }
       }

       # Get the value of the value field
       value=""
       nf = split($0, f, "\"")   
       for (i = 1; i <= nf; i++) {
           if ( f[i] ~ /Value=$/) {
               value = f[i+1]
               break;
           }
       }
       indent = substr($0, 0, index($0,"<") - 1)  
       # FIXME: do more with types?
       propertyClass = "ptolemy.data.expr.Parameter"

       if (class == "vendors.ecsl_dp.ptolemy.ECSLGain") {
           if (name == "Gain") {
               # FIXME: Gain must be a double so that 1/1000 = 0.001
               # instead of 0
               if (index(value, ".") == 0 && match(value, "[0-9]") != 0) {
                   # FIXME: append a .0.  This is _so_ wrong
                   value = value ".0"
               }
           }
       }

       if (class == "vendors.ecsl_dp.ptolemy.ECSLStep") {
           if (name == "After") {
               # FIXME: After must be a double so that 1/1000 = 0.001
               # instead of 0
               if (index(value, ".") == 0 \
                      && match(value, "[0-9]") != 0) {
                   # FIXME: append a .0.  This is _so_ wrong
                   value = value ".0"
               }
           }
       }

       if (class == "vendors.ecsl_dp.ptolemy.ECSLSum") {
           if (name == "Inputs" || name == "IconShape") {
               propertyClass = "ptolemy.data.expr.StringParameter"
           }
       }


       print indent "<property name=\"" name "\" class=\"" propertyClass "\" value=\"" value "\"/>"
    } else {
       print $0
    } 
} ' < $tmpfile1 > $tmpfile2

# 
cp $tmpfile2 $output

rm -f $tmpfile1 $tmpfile2

