#!/bin/csh

#############################################################
# Script to compile the MAS code for use with CISM project.
#
# Usage: ./compile <program name>
# where <program name> is the Fortran source file for MAS
# with trailing '.F' omitted.
#############################################################

set na=$#argv

if ($na == 1) then
  set root=$1
else
  echo ''
  echo 'Usage: ./compile <program name>'
  echo 'where <program name> is the Fortran source filename for MAS'
  echo 'with trailing ".F" ommited.'
  echo ''
  echo 'Example:'
  echo './compile mas47d_cism_v01'
  echo ''
  exit 1
endif

echo ''
echo "MAS source file: $root"


# Check MAS source file 
set source=${root}.F

if (!(-f $source)) then
  echo ''
  echo "### ERROR while compiling $root"
  echo "MAS source file $source does not exist."
  exit 1
endif


# Set some identification parameters.
set MACHNAME=`hostname`
set MACHTYPE=`uname`

echo ''
echo "Machine name: $MACHNAME"
echo "Machine type: $MACHTYPE"


# Compile a "low" resolution version.
echo ''
echo 'Compiling the "low" resolution version ...'

set NR=61
set NT=71
set MP=6

# Substitute the parameters to produce the source file from the template file.
sed "s/<MACHNAME>/${MACHNAME}/g \
     s/<MACHTYPE>/${MACHTYPE}/g \
     s/<NR>/${NR}/g \
     s/<NT>/${NT}/g \
     s/<MP>/${MP}/g" ${source} > mas.F

# Calculate the number of phi mesh points, NP.
set i=0
set NP=1
while ($i < $MP)
  @ i = $i + 1
  @ NP = $NP * 2
end

set tail="${NR}x${NT}x${NP}"

# Compile the MAS code.
../../bin/${SYSTEM}/precomp mas.F pmas.f
../../bin/${SYSTEM}/expmac pmas.f ppmas.f
make mas

# Check that the executable has been produced.
if (!(-f mas)) then
  echo ''
  echo "### ERROR while compiling $root"
  exit 1
endif

# Rename the executable to show the mesh size.
mv mas mas_${tail}

echo ''
echo "MAS low resolution mas_${tail} has been compiled successfully."


# Compile a "medium" resolution version.
echo ''
echo 'Compiling the "medium" resolution version ...'

set NR=101
set NT=101
set MP=7

# Substitute the parameters to produce the source file from the template file.
sed "s/<MACHNAME>/${MACHNAME}/g \
     s/<MACHTYPE>/${MACHTYPE}/g \
     s/<NR>/${NR}/g \
     s/<NT>/${NT}/g \
     s/<MP>/${MP}/g" ${source} > mas.F

# Calculate the number of phi mesh points, NP.
set i=0
set NP=1
while ($i < $MP)
  @ i = $i + 1
  @ NP = $NP * 2
end

set tail="${NR}x${NT}x${NP}"

# Compile the MAS code.
../../bin/${SYSTEM}/precomp mas.F pmas.f
../../bin/${SYSTEM}/expmac pmas.f ppmas.f
make mas

# Check that the executable has been produced.
if (!(-f mas)) then
  echo ''
  echo "### ERROR while compiling $root"
  exit 1
endif

# Rename the executable to show the mesh size.
mv mas mas_${tail}

echo ''
echo "MAS medium resolution mas_${tail} has been compiled successfully."


/bin/rm -f mas.F

echo ''
echo 'The MAS code has been compiled successfully.'

exit 0
