#/!bin/bash
if test $1 = '-h'
then
echo "**********************************"
echo "***      Best aproximation     ***"
echo "***       of N to a serie      ***"
echo "*** of M1, M2, ..., Mn numbers ***"
echo "**********************************"
echo "best_aprox.bash 'N'(number) 'M1 M2 M3 ...Mn'"
else
foresthome=`(pwd)`
foresthome=${foresthome}/..
echo $* > arguments.inf
numarg=`(wc -w arguments.inf | awk '{print $1}')`
iarg=2
iclosest=1000000.
while test $iarg -le $numarg
do
argument=`(awk -f ${foresthome}/AWK/column.awk row=1 col=$iarg arguments.inf)`
echo $1" "$argument > numbers.inf
less=`(awk -f ${foresthome}/AWK/operations.awk operation=less numbers.inf)`

if test $less -eq 1
then
dif=`(cat numbers.inf | awk '{print $1 - $2}')`
else
dif=`(cat numbers.inf | awk '{print $2 - $1}')`
fi

echo $iclosest" "$dif > numbers.inf
less=`(awk -f ${foresthome}/AWK/operations.awk operation=less numbers.inf)`

if test $less -eq 1
then
iclosest=$dif
closestargument=$argument
fi

iarg=`(expr $iarg + 1)`
### End of arguments
done

rm numbers.inf arguments.inf
echo $closestargument
fi
