#!/bin/bash
filelist=""
modulelist=""
build_file(){
  echo "Building $1"
  for file in `grep -iE "^\s*use " $1`; do
    if [ ${#file} -gt 3 ]
    then
      filename=${file/use}
      if [ -e ${filename}.f90 ]; then
        modulelist="${filename} ${modulelist}"
        filelist="${filelist}\n${filename}.o"
        build_file ${filename}.f90
      fi
    fi
  done
}
progname=$1
if [[ $progname =~ .*\.f90 ]]; then
  build_file_name=$progname
else
  echo "Modifying progname"
  build_file_name=${progname}.f90
  progname=${progname}.f90
fi
build_file $build_file_name
echo "${modulelist}"
for filename in ${modulelist}; do
  echo "gfortran $2 -c -o ${filename}.o ${filename}.f90"
  gfortran $2 -c -o ${filename}.o ${filename}.f90
done
#echo "${filelist} --- $(echo ${filelist} | ruby -e 'puts Kernel.gets.split(" ").uniq.join(" ")') ---"
echo ${filelist}
filelist=`echo -e ${filelist} | sort | uniq | awk '{ printf "%s ", $1}' `
echo "gfortran $2 -o ${progname%.f90} $progname ${filelist}"
gfortran $2 -o ${progname%.f90} $progname ${filelist}
mkdir -p lib
mv *.o lib/
mv *.mod lib/
