#!/bin/bash
# extract a named structuralComponent or all structuralComponent from a pml
# Usage:
# extractSC.bash file.pml SCname
if [[ ($# -ne 1) && ($# -ne 2) ]] ; then
        echo "extractSC file.pml [SCname]"
        exit
fi

file=$1
base=${1/.pml/}
tmp=/tmp/$base.tmp

# extract line nr that match "structuralComponent" (odd line=start, even line=end)
grep -n structuralComponent $file > $tmp

index=1
nl="`wc -l $tmp | cut -f1 -d" "`"

while [ $index -lt $nl ]; do
    cmd=$index"p"
    lineStart=`sed -n $cmd $tmp | cut -f1 -d":"`
    indexEnd=`expr $index + 1`
    cmdEnd=$indexEnd"p"
    lineEnd=`sed -n $cmdEnd $tmp | cut -f1 -d":"`
    # extract name = everything after name=" up to the next "
    name=`sed -n $cmd $tmp | cut -f2 -d":" | grep "name" | cut -c2- | sed "s/.*name=\"\([^\"]*\).*/\1/g"`
    if [[ ((($# -eq 2) &&  ($name == $2)) || ($# -eq 1)) ]]; then
        if [ "$name" != "" ]; then
            out=$name.pml
        else
            out=sc-$index.pml
        fi;
        # test if file exists
        if [ -a "$out" ]; then
            out=$name-$index.pml
        fi
        out=`echo $out | sed "s/ /_/g" | sed "s/\//-/g"`
        echo $lineStart:$lineEnd \"$name\" saved in \"$out\"
        cmdExtract=$lineStart","$lineEnd"p"
        sed -n $cmdExtract $file > $out
    fi
    index=`expr $index + 2`
done

rm -rf $tmp
