#! /bin/sh

     ###################################### 
     ##### Model Transformation Tools #####
     ######################################

# Bourne shell script: ibg2abg_m
# Based on rbg2abg_m

while [ -n "`echo $1 | grep '^-'`" ]; do
    case $1 in
	-I )
	    info=info ;;
	-nounits )
	    units=no ;;
	*)
	    echo "$1 is an invalid argument - ignoring" ;;
    esac
    shift
done

# Set up some vars
sys=$1
lbl_file=${sys}_lbl.txt
abg_file=${sys}_abg.m
err=mtt_error.txt
log=ibg2abg_m_${sys}.log

# Remove the old log file
rm -f ibg2abg_m.log
rm -f ${abg_file}

# Inform user
echo Creating ${abg_file}

# Use matrix manipulation to accomplish the transformation
${MATRIX} > ${log} 2> ${err} <<EOF
  name = '$1'
  infofile = fopen('mtt_info.txt', 'w');
  errorfile = fopen('mtt_error.txt', 'w');
  
  ## Interpret data from the ibg representation
  ibonds = $1_ibg;
  bonds = ibonds.bonds;

  [bonds,components,n_vector_bonds] = ibg2abg(name,bonds, \
					      infofile,errorfile)

  ## Write the acausal bond graph m-file
  write_abg(name,bonds,components,n_vector_bonds);
EOF

# Set the units for the abg file
test_units()
{
      grep '^[\s]*[#|%]UNITS' < ${lbl_file} >/dev/null
  if [ $? = "0" ]; then 
    grep '^[\s]*[#|%]UNITS' < ${lbl_file} |\
    gawk '{
      printf("mtt_units.sh %s %s %s %s %s\n", sys, $2, $3, $4, $5)
    }' sys=${sys}  | sh | grep ERROR
    if [ $? = "0" ]; then
      echo "    " *MTT_ERRROR: domains and units are not OK - exiting
      exit 1  
    else
      echo "    " domains and units are OK 
    fi
  else
    echo "  no domains or units declared"
  fi
} 

check_ports_exist()
{
 declared_ports=`grep '^[\s]*[#|%]UNITS' < ${lbl_file} | gawk '{print $2}'`
  for declared_port in $declared_ports; do
    grep "${sys}\.ports\.${declared_port}\.type" ${abg_file} >/dev/null
    if [ $? = "1" ]; then
      echo "*MTT_ERROR: Units declared for non-existent port ${declared_port}"
      exit 1
    fi
  done
}

set_units()
{ 
  grep '^[\s]*[#|%]UNITS' < ${lbl_file} |\
  gawk '{
    printf("  %s.ports.%s.domain = \"%s\";\n", sys, $2, $3);
    printf("  %s.ports.%s.units.effort = \"%s\";\n", sys, $2, $4);
    printf("  %s.ports.%s.units.flow = \"%s\";\n", sys, $2, $5);
  }' sys=${sys}
} 

if [ -z "$units" ]; then
  echo Checking port domains and units
  check_ports_exist;
  test_units;
  echo "## Port domain and units" >> ${abg_file}
  set_units >> ${abg_file}
fi

# Append any VAR declarations
if [ -f "$1_lbl.txt" ]; then
  echo "## Explicit variable declarations" >> ${abg_file}
  grep '^[\s]*[%|#][V|P]AR' $1_lbl.txt | tr '%' '#' >> ${abg_file}    
  grep '^[\s]*[%|#]NOT[V|P]AR' $1_lbl.txt | tr '%' '#' >> ${abg_file}    
fi

# Close off the function
echo "endfunction" >> ${abg_file}

# Errors and info
if [ "$info" = "info" ]; then
    cat mtt_info.txt
fi

if mtt_error mtt_error.txt; then
    exit 0
else
    exit 1
fi
