#!/bin/sh
# Brute Force Hack Conversion from ECSL to MoML
# Author:  Christopher Brooks
# Version: $Id: ecsl2moml 35142 2004-10-22 05:05:10Z cxh $
#
# Copyright (c) 2004 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

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

# 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\">"
        print "<entity name=\"" modelname "\" class=\"ptolemy.actor.TypedCompositeActor\">"
    } else if ($0 ~ /<\/RootFolder>/) {
        print "</entity>"
    } else {
        print $0
    }
}' modelname=${modelname} $input > $tmpfile1

# 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

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

# Convert <System ... to <entity
awk ' {
    if ($0 ~ /<System/) {
       # 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;
           }
       }
       indent = substr($0, 0, index($0,"<") - 1)  
       # Sometimes we have <System ... />
       print indent "<entity name=\"" name "\" class=\"ptolemy.actor.TypedCompositeActor\"" f[nf]
    } else if ($0 ~ /<\/System>/) {
       # FIXME: If we have <System ... />, then the indent might be wrong?
       print indent "</entity>"
    } else {
       print $0
    }   
}' < $tmpfile1 > $tmpfile2


# 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;
           }
       }
       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=\"15.0, 275.0\">"
           print indent "    </property>"
           print indent "    <property name=\"_icon\" class=\"ptolemy.vergil.icon.XMLIcon\">"
           print indent "    </property>"

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


# Convert <Line to <relation
awk ' {
    if ( $1 ~ /<Line/) {
       # 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;
           }
       }
       indent = substr($0, 0, index($0,"<") - 1)  
       print indent "<relation name=\"" id "\" class=\"ptolemy.actor.TypedIORelation\"/>"

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

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

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


# Convert <Primitive to <entity
awk 'BEGIN {
    map["Abs"] = "ptolemy.actor.lib.AbsoluteValue"
    map["Clock"] = "ptolemy.actor.lib.Clock"
    map["Constant"] = "ptolemy.actor.lib.Const"
    map["Demux"] = "ptolemy.actor.lib.Select"
    # FIXME
    map["DiscreteFilter"] = "ptolemy.domains.de.lib.EventFilter"
    map["DiscretePulseGenerator"] = "ptolemy.actor.lib.Pulse"
    map["Display"] = "ptolemy.actor.lib.gui.Display"
    # FIXME
    map["From"] = "ptolemy.actor.lib.Stop"
    map["Gain"] = "ptolemy.actor.lib.Scale"
    # FIXME
    map["Goto"] = "ptolemy.actor.lib.Stop"
    map["Ground"] = "ptolemy.actor.lib.Discard"
    map["Integrator"] = "ptolemy.domains.ct.lib.Integrator"
    map["Logic"] = "ptolemy.actor.lib.logic.LogicFunction"
    map["Merge"] = "ptolemy.domains.de.lib.Merge"
    # FIXME: should be Minimum or Maximum 
    map["MinMax"] = "ptolemy.actor.lib.Maximum"
    # FIXME
    map["MultiPortSwitch"] = "ptolemy.actor.lib.Switch"
    map["Mux"] = "ptolemy.actor.lib.Multiplexor"
    map["Product"] = "ptolemy.actor.lib.MultiplyDivide"
    # FIXME
    map["RelationalOperator"] = "ptolemy.actor.lib.logic.Comparator"
    map["S-Function"] = "ptolemy.matlab.Expression"
    # FIXME
    map["Saturate"] = "ptolemy.actor.lib.Quantizer"
    map["Signum"] = "ptolemy.actor.lib.Quantizer"
    # FIXME: set to Sin
    map["Sin"] = "ptolemy.actor.lib.TrigFunction"
    # FIXME
    map["Step"] = "ptolemy.actor.lib.Stop"
    map["Sum"] = "ptolemy.actor.lib.Accumulator"
    map["Switch"] = "ptolemy.actor.lib.Switch"
    map["Terminator"] = "ptolemy.actor.lib.Stop"
    # FIXME
    map["ToWorkspace"] = "ptolemy.actor.lib.Stop"
    map["UnitDelay"] = "ptolemy.domains.de.lib.TimedDelay"
    map["ZeroOrderHold"] = "ptolemy.domains.ct.lib.ZeroOrderHold"
}
{
    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 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] "\">"
    } else if ($1 ~ /<\/Primitive>/) {
        print indent "</entity>"
    } else {
        print $0
    }
} ' < $tmpfile2 > $tmpfile1


# 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

}
{
    if ($1 ~ /<OutputPort/ || $1 ~ /<InputPort/ || $1 ~ /<TriggerPort/) {
       # 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;
           }
       }

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

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

       print indent "<port name=\"" name "\" class=\"ptolemy.actor.TypedIOPort\">"
       if ($1 ~ /<OutputPort/) {
           print "<property name=\"output\"/>"
       } else if ($1 ~ /<InputPort/) {
           print "<property name=\"input\"/>"
       }  
       if (index(relation, " ") != 0) {
           # The relation name has spaces in it, so this is a multiport
           print indent "    <property name=\"multiport\"/>"
       }

       print indent "</port>"

 
       containerName = containerStack[containerCount] "." name
       links[containerName] = relation
    } else {
        print $0
    }
}
$1 ~ /<\/entity>/ {
    container = containerStack[containerCount] 
    containerCount -= 1         

    # We need to add the link statements outside the container.
    # Sometimes, containers are nested, getting the links right is tricky.
    indent = substr($0, 0, index($0,"<") - 1)  
    for ( link in links) {
       if ( length(links[link]) > 0 \
          &&  substr(link, 0, length(container)) == 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 "<link port=\"" link "\" relation=\"" relation "\"/>" 
          } else {
              nf = split(relation, relations, " ") 
              for(i = 1; i < nf; i++) {
              print indent "<link port=\"" link "\" relation=\"" relations[i] "\"/>" 
              }
          }
          links[link] = ""  
       }

    }

}' < $tmpfile1 > $tmpfile2



# Parameter
awk '{
    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?
       print indent "<property name=\"" name "\" class=\"ptolemy.data.expr.Parameter\" value=\"" value "\"/>"
    } else {
       print $0
    } 
} ' < $tmpfile2 > $tmpfile1


cp $tmpfile1 $output

rm -f $tmpfile1 $tmpfile2