#!/bin/bash
# transform the nodal components exported from ansys into on csv for each component
#
# in Ansys: list component "all defined" expand=yes
# save the output in a file, and manually remove element component (thus
# keeping only nodes component)
#
# TODO: first exclude all ELEMENT components
#
file=$1
base=${1/.txt/}
tmp=/tmp/$base.tmp

# extract line nr thas starts a nodal ansys component
grep -n "NODE" $file   | sort -u -k 2 -t ":" | sort -n > $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":"`
    lineEnd=`expr $lineEnd - 1`
    # extract name = everything after name=" up to the next "
    name=`sed -n $cmd $tmp | cut -f2 -d":" | cut -c3- | cut -f1 -d" "`
    if [ "$name" != "" ]; then
        out=tmp/$name.csv
    else
        out=tmp/nodes-$index.csv
    fi;
    if [ -a "$out" ]; then
        out=tmp/$name-$index.csv
    fi
    echo $lineStart:$lineEnd \"$name\" saved in \"$out\"
    cmdExtract=$lineStart","$lineEnd"p"
    sed -n $cmdExtract $file | sed 's/^[ \t]*//'| sed '/^$/d' | sed '/^[^[0-9]/d' |  sed "s/ [ ]*/ /g" |  sed "s/ /\n/g" | sed '/^$/d' > "$out"
    index=`expr $index + 1`
done

# save last one
cmd=$nl"p"
lineStart=`sed -n $cmd $tmp | cut -f1 -d":"`
lineStart=`expr $lineStart - 1`
name=`sed -n $cmd $tmp | cut -f2 -d":" | cut -c3- | cut -f1 -d" "`
if [ "$name" != "" ]; then
    out=tmp/$name.csv
else
    out=tmp/nodes-$index.csv
fi;
if [ -a "$out" ]; then
    out=tmp/$name-$index.csv
fi
echo $lineStart- \"$name\" saved in \"$out\"
cmdExtract=1","$lineStart"d"
sed $cmdExtract $file | sed 's/^[ \t]*//' | sed '/^$/d' | sed '/^[^[0-9]/d' | sed "s/ [ ]*/ /g" |  sed "s/ /\n/g" | sed '/^$/d'  > "$out"

#rm -rf $tmp
