#!/bin/bash
MY_PATH="`dirname \"$0\"`"              # relative
MY_PATH="`( cd \"$MY_PATH\" && pwd )`"  # absolutized and normalized
if [ -z "$MY_PATH" ] ; then
  # error; for some reason, the path is not accessible
  # to the script (e.g. permissions re-evaled after suid)
  exit 1  # fail
fi

function usage {
 echo "Usage : `basename ${0}` -i geometry.geo -size X.YYY"
 echo " converts geometry.geo into geometryX.YYY.msh with specified characteristic length"
 exit 0
}

if [[ $# -eq 0 ]] ; then
usage
fi

while [[ $# -gt 0 ]] && [[ ."$1" = .-* ]] ;
do
    opt="$1";
    shift;              #expose next argument
    case "$opt" in
        "-i" )
           FILE=${1}; shift;;
        "-i="* )     # alternate format: -i=argdat
           FILE="${opt#*=}" ;;
        "-size" )
           SIZE="$1"; shift;;
        "-size="* )
           SIZE="${opt#*=}";;
        *) echo >&2 "Invalid option: $@"; exit 1;;
   esac
done

filename=$(basename "${FILE}")
direc=$(dirname "${FILE}")
extension="${filename##*.}"
filename="${filename%.*}"

if [ ! -f ${direc}/${filename}${SIZE}.msh ];
then
gmsh ${FILE} -clscale ${SIZE} -3 -o ${direc}/${filename}${SIZE}.msh
else
echo ${direc}/${filename}${SIZE}.msh exists !
fi
