#!/bin/bash
set -eu

# sanity check: do we have the required argument ?
if (( $# < 1 )) || (( $# > 3 )); then
    echo "Wrong number of parameters in $0 !!!"
    echo " Usage:"
    echo "  $0 [im] [jm] lm"
    echo " where im, jm and lm are the dimensions"
    exit 1
fi

if ( (( $1 % 8 != 0 )) && (( $# == 3 )) || (( $1 == 1 )) ); then
    echo "The number of longitudes must be a multiple of 8."
    echo "See the files dyn3d/groupe.F and dyn3dmem/groupe_loc.F."
    exit 1
fi

# build "fichnom", the relevant 'dimensions.im.jm.lm' file name
list=""
for i in "$@"; do list=$list.$i; done
fichdim=dimensions${list}

if [[ ! -f $fichdim ]]; then
    # assign values of im, jm and lm
    if [ $# -ge 3 ]; then
        im=$1
        jm=$2
        lm=$3
        ndm=1
    elif [ $# -ge 2 ]; then
        im=1
        jm=$1
        lm=$2
        ndm=1
    elif [ $# -ge 1 ]; then
        im=1
        jm=1
        lm=$1
        ndm=1
    fi

# since the file doesn't exist, we create it
    cat << EOF > "$fichdim"
! This module was automatically generated during the installation of LMDZ
! It contains the spatial resolution of the model

MODULE dimensions_mod
  IMPLICIT NONE; PRIVATE
  PUBLIC iim, jjm, llm, ndm
  ! ndm is computed such that iim=2**ndm

  INTEGER, PARAMETER :: iim = $im, jjm = $jm, llm = $lm, ndm = $ndm
END MODULE dimensions_mod
EOF
fi

# remove 'old' dimensions_mod.f90 file (if any) and replace it with new one
if [[ -f ../dimensions_mod.f90 ]]; then
    rm ../dimensions_mod.f90
fi
tar cf - "$fichdim" | ( cd .. ; tar xf - ; mv "$fichdim" dimensions_mod.f90 )
# line above is a trick to preserve time of creation of dimensions_mod.f90 files
