! SPDX-License-Identifier: AGPL-3.0-or-later
! Copyright 2024-2025 Max-Planck-Institut für Nachhaltige Materialien GmbH
! Copyright 2011-2024 Max-Planck-Institut für Eisenforschung GmbH
!
! DAMASK is free software: you can redistribute it and/or modify
! it under the terms of the GNU Affero General Public License as
! published by the Free Software Foundation, either version 3 of the
! License, or (at your option) any later version.
!
! This program is distributed in the hope that it will be useful,
! but WITHOUT ANY WARRANTY; without even the implied warranty of
! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
! GNU Affero General Public License for more details.
!
! You should have received a copy of the GNU Affero General Public License
! along with this program.  If not, see <https://www.gnu.org/licenses/>.
!--------------------------------------------------------------------------------------------------
!> @author Pratheek Shanthraj, Max-Planck-Institut für Eisenforschung GmbH
!> @author Martin Diehl, Max-Planck-Institut für Eisenforschung GmbH
!> @author Philip Eisenlohr, Max-Planck-Institut für Eisenforschung GmbH
!> @author Fotios Tsiolis, Max-Planck-Institut für Eisenforschung GmbH
!> @brief Driver controlling inner and outer load case looping of the various spectral solvers
!> @details doing cutbacking, forwarding in case of restart, reporting statistics, writing
!> results
!--------------------------------------------------------------------------------------------------
#include <petsc/finclude/petscsys.h>
program DAMASK_grid
  use PETScSys
#ifndef PETSC_EXPOSES_MPI
  use MPI_f08
#endif

  use prec
  use parallelization
  use signal
  use CLI
  use HDF5_utilities
  use IO
  use config
  use math
  use discretization_grid
  use materialpoint
  use material
  use spectral_utilities
  use grid_utilities
  use grid_mechanical_spectral_basic
  use grid_mech_spectral_polarization
  use grid_mechanical_spectral_Galerkin
  use grid_mechanical_FEM
  use grid_chemical_FDM
  use grid_damage_spectral
  use grid_thermal_spectral
  use result

#ifndef PETSC_EXPOSES_MPIF90
  implicit none(type,external)
#else
  implicit none
#endif

  type :: tLoadCase
    type(tRotation)          :: rot                                                                 !< rotation of BC
    type(tBCmech) :: stress, &                                                           !< stress BC
                                deformation                                                         !< deformation BC (dot_F, F, or L)
    type(tBCthermal) ::         temperature                                                         !< thermal BC; unallocated = free
    real(pREAL) ::              t, &                                                                !< length of increment
                                r                                                                   !< ratio of geometric progression
    integer ::                  N, &                                                                !< number of increments
                                f_out, &                                                            !< frequency of result writes
                                f_restart                                                           !< frequency of restart writes
    logical ::                  estimate_rate                                                       !< follow trajectory of former loadcase
  end type tLoadCase

!--------------------------------------------------------------------------------------------------
! field labels information
  enum, bind(c); enumerator :: &
    FIELD_UNDEFINED_ID, &
    FIELD_MECH_ID, &
    FIELD_THERMAL_ID, &
    FIELD_DAMAGE_ID, &
    FIELD_CHEMICAL_ID
  end enum

  integer(kind(FIELD_UNDEFINED_ID)), allocatable :: ID(:)

!--------------------------------------------------------------------------------------------------
! loop variables, convergence etc.
  integer, parameter :: &
    subStepFactor = 2                                                                               !< for each substep, divide the last time increment by 2.0
  real(pREAL) :: &
    t = 0.0_pREAL, &                                                                                !< elapsed time
    t_0 = 0.0_pREAL, &                                                                              !< begin of interval
    Delta_t = 1.0_pREAL, &                                                                          !< current time interval
    Delta_t_prev = 0.0_pREAL, &                                                                     !< previous time interval
    t_remaining = 0.0_pREAL                                                                         !< remaining time of current load case
  logical :: &
    guess, &                                                                                        !< guess along former trajectory
    stagIterate, &
    cutBack = .false.,&
    sig
  integer :: &
    field, &
    cutBackLevel = 0, &                                                                             !< cut back level \f$ t = \frac{t_{inc}}{2^l} \f$
    stepFraction = 0, &                                                                             !< fraction of current time interval
    l = 0, &                                                                                        !< current load case
    inc, &                                                                                          !< current increment in current load case
    totalIncsCounter = 0, &                                                                         !< total # of increments
    unit_stat = 0, &                                                                                !< file unit for statistics output
    stagIter, &
    nActiveFields = 0, &
    maxCutBack, &                                                                                   !< max number of cut backs
    stagItMax                                                                                       !< max number of field level staggered iterations
  logical :: active_Gamma = .false., active_G = .false., active_parabolic = .false., exists
  integer(MPI_INTEGER_KIND) :: err_MPI
  character(len=pSTRLEN) :: &
    incInfo

  type(tLoadCase), allocatable, dimension(:) :: loadCases                                           !< array of all load cases
  type(tSolutionState), allocatable, dimension(:) :: solres
  procedure(grid_mechanical_spectral_basic_init), pointer :: &
    grid_mechanical_init
  procedure(grid_mechanical_spectral_basic_forward), pointer :: &
    grid_mechanical_forward
  procedure(grid_mechanical_spectral_basic_solution), pointer :: &
    grid_mechanical_solution
  procedure(grid_mechanical_spectral_basic_updateCoords), pointer :: &
    grid_mechanical_updateCoords
  procedure(grid_mechanical_spectral_basic_restartWrite), pointer :: &
    grid_mechanical_restartWrite

  type(tDict), pointer :: &
    load, &
    num_solver, &
    num_grid, &
    solver
  character(len=:), allocatable :: &
    fileContent, fname
  integer(HID_T) :: fileHandle


!--------------------------------------------------------------------------------------------------
! init DAMASK (all modules)

  call materialpoint_initAll()
  print'(/,1x,a)', '<<<+-  DAMASK_grid init  -+>>>'; flush(IO_STDOUT)

  print'(/,1x,a)', 'P. Shanthraj et al., Handbook of Mechanics of Materials, 2019'
  print'(  1x,a)', 'https://doi.org/10.1007/978-981-10-6884-3_80'


!-------------------------------------------------------------------------------------------------
! read (and check) field parameters from numerics file

  num_solver => config_numerics%get_dict('solver',defaultVal=emptyDict)
  num_grid => num_solver%get_dict('grid',defaultVal=emptyDict)

  stagItMax  = num_grid%get_asInt('N_staggered_iter_max',defaultVal=10)
  maxCutBack = num_grid%get_asInt('N_cutback_max',defaultVal=3)

  if (stagItMax < 0)    call IO_error(301,ext_msg='N_staggered_iter_max')
  if (maxCutBack < 0)   call IO_error(301,ext_msg='N_cutback_max')


  if (worldrank == 0) then
    fileContent = IO_read(CLI_loadFile)
    fname = CLI_loadFile
    if (scan(fname,'/') /= 0) fname = fname(scan(fname,'/',.true.)+1:)
    call result_openJobFile(parallel=.false.)
    call result_addSetupFile(fileContent,fname,'load case definition (grid solver)')
    call result_closeJobFile()
  end if

  call parallelization_bcast_str(fileContent)
  load => YAML_str_asDict(fileContent)
  solver => load%get_dict('solver')

!--------------------------------------------------------------------------------------------------
! assign mechanics solver depending on selected type

  nActiveFields = 1
  select case (solver%get_asStr('mechanical'))
    case ('spectral_basic')
      grid_mechanical_init         => grid_mechanical_spectral_basic_init
      grid_mechanical_forward      => grid_mechanical_spectral_basic_forward
      grid_mechanical_solution     => grid_mechanical_spectral_basic_solution
      grid_mechanical_updateCoords => grid_mechanical_spectral_basic_updateCoords
      grid_mechanical_restartWrite => grid_mechanical_spectral_basic_restartWrite
      active_Gamma = .true.

    case ('spectral_polarization')
      grid_mechanical_init         => grid_mech_spectral_polarization_init
      grid_mechanical_forward      => grid_mech_spectral_polarization_forward
      grid_mechanical_solution     => grid_mech_spectral_polarization_solution
      grid_mechanical_updateCoords => grid_mech_spectral_polarization_updateCoords
      grid_mechanical_restartWrite => grid_mech_spectral_polarization_restartWrite
      active_Gamma = .true.

    case ('spectral_Galerkin')
      grid_mechanical_init         => grid_mechanical_spectral_Galerkin_init
      grid_mechanical_forward      => grid_mechanical_spectral_Galerkin_forward
      grid_mechanical_solution     => grid_mechanical_spectral_Galerkin_solution
      grid_mechanical_updateCoords => grid_mechanical_spectral_Galerkin_updateCoords
      grid_mechanical_restartWrite => grid_mechanical_spectral_Galerkin_restartWrite
      active_G = .true.

    case ('FEM')
      grid_mechanical_init         => grid_mechanical_FEM_init
      grid_mechanical_forward      => grid_mechanical_FEM_forward
      grid_mechanical_solution     => grid_mechanical_FEM_solution
      grid_mechanical_updateCoords => grid_mechanical_FEM_updateCoords
      grid_mechanical_restartWrite => grid_mechanical_FEM_restartWrite

    case default
      call IO_error(601_pI16,trim(solver%get_asStr('mechanical')), 'is not a valid grid solver type', emph=[1])

  end select

!--------------------------------------------------------------------------------------------------
! initialize field solver information
  if (solver%get_asStr('thermal',defaultVal = 'n/a') == 'spectral') nActiveFields = nActiveFields + 1
  if (solver%get_asStr('damage', defaultVal = 'n/a') == 'spectral') nActiveFields = nActiveFields + 1
  if (solver%get_asStr('chemical', defaultVal = 'n/a') == 'FDM')    nActiveFields = nActiveFields + 1

  allocate(solres(nActiveFields))
  allocate(    ID(nActiveFields))

  field = 1
  ID(field) = FIELD_MECH_ID                                                                         ! mechanical active by default
  thermalActive: if (solver%get_asStr('thermal',defaultVal = 'n/a') == 'spectral') then
    field = field + 1
    ID(field) = FIELD_THERMAL_ID
    active_parabolic = .true.
  end if thermalActive
  damageActive: if (solver%get_asStr('damage',defaultVal = 'n/a') == 'spectral') then
    field = field + 1
    ID(field) = FIELD_DAMAGE_ID
    active_parabolic = .true.
  end if damageActive
  chemicalActive: if (solver%get_asStr('chemical',defaultVal = 'n/a') == 'FDM') then
    field = field + 1
    ID(field) = FIELD_CHEMICAL_ID
    active_parabolic = .true.
  end if chemicalActive

!--------------------------------------------------------------------------------------------------
! doing initialization depending on active solvers
  call spectral_utilities_init(active_Gamma, active_G, active_parabolic)

  do field = 2, nActiveFields
    select case (ID(field))

      case (FIELD_THERMAL_ID)
        call grid_thermal_spectral_init(num_grid%get_dict('thermal',defaultVal=emptyDict))

      case (FIELD_DAMAGE_ID)
        call grid_damage_spectral_init(num_grid%get_dict('damage',defaultVal=emptyDict))

      case (FIELD_CHEMICAL_ID)
        call grid_chemical_FDM_init(num_grid%get_dict('chemical',defaultVal=emptyDict))

    end select
  end do

  call grid_mechanical_init(num_grid%get_dict('mechanical',defaultVal=emptyDict))
  call discretization_grid_finalize()
  call config_numerics_deallocate()

!--------------------------------------------------------------------------------------------------
! open/create statistics file
  if (worldrank == 0) then
    fname = trim(CLI_jobName)//'.sta'
    inquire(file=fname,exist=exists)
    writeHeader: if (CLI_restartInc == -1 .or. .not. exists) then
      open(newunit=unit_stat,file=fname,form='FORMATTED',status='REPLACE')
      write(unit_stat,'(a)') 'Increment Time CutbackLevel Converged IterationsNeeded StagIterationsNeeded'
    else writeHeader
      open(newunit=unit_stat,file=fname,form='FORMATTED', position='APPEND', status='OLD')
    end if writeHeader
  end if

  writeUndeformed: if (CLI_restartInc == -1) then
    print'(/,1x,a)', '... saving initial configuration ..........................................'
    flush(IO_STDOUT)
    call materialpoint_result(0,0.0_pREAL)
  end if writeUndeformed

  loadCases = parse_and_print_load_cases(load%get_list('loadstep'), solver)

  loadCaseLooping: do l = 1, size(loadCases)
    t_0 = t                                                                                         ! load case start time
    guess = loadCases(l)%estimate_rate                                                              ! change of load case? homogeneous guess for the first inc

    incLooping: do inc = 1, loadCases(l)%N
      totalIncsCounter = totalIncsCounter + 1

!--------------------------------------------------------------------------------------------------
! forwarding time
      Delta_t_prev = Delta_t                                                                        ! last time intervall that brought former inc to an end
      if (dEq(loadCases(l)%r,1.0_pREAL,1.e-9_pREAL)) then                                           ! linear scale
        Delta_t = loadCases(l)%t/real(loadCases(l)%N,pREAL)
      else
        Delta_t = loadCases(l)%t * (loadCases(l)%r**(inc-1)-loadCases(l)%r**inc) &
                                 / (1.0_pREAL-loadCases(l)%r**loadCases(l)%N)
      end if
      Delta_t = Delta_t * real(subStepFactor,pREAL)**real(-cutBackLevel,pREAL)                      ! depending on cut back level, decrease time step

      skipping: if (totalIncsCounter <= CLI_restartInc) then                                        ! not yet at restart inc?
        t = t + Delta_t                                                                             ! just advance time, skip already performed calculation
        guess = .true.                                                                              ! QUESTION:why forced guessing instead of inheriting loadcase preference
      else skipping
        stepFraction = 0                                                                            ! fraction scaled by stepFactor**cutLevel

        subStepLooping: do while (stepFraction < subStepFactor**cutBackLevel)
          t_remaining = loadCases(l)%t + t_0 - t
          t = t + Delta_t                                                                           ! forward target time
          stepFraction = stepFraction + 1                                                           ! count step

!--------------------------------------------------------------------------------------------------
! report beginning of new step
          print'(/,1x,a)', '###########################################################################'
          print'(1x,a,1x,es12.5,6(a,i0))', &
                  'Time', t, &
                  's: Increment ', inc,'/',loadCases(l)%N,&
                  '-', stepFraction,'/',subStepFactor**cutBackLevel,&
                  ' of load case ', l,'/',size(loadCases)
          write(incInfo,'(4(a,i0))') &
                  'Increment ',totalIncsCounter,'/',sum(loadCases%N),&
                  '-', stepFraction,'/',subStepFactor**cutBackLevel
          flush(IO_STDOUT)

!--------------------------------------------------------------------------------------------------
! forward fields
          do field = 1, nActiveFields
            select case(ID(field))
              case(FIELD_MECH_ID)
                call grid_mechanical_forward (&
                        cutBack,guess,Delta_t,Delta_t_prev,t_remaining, &
                        deformation_BC = loadCases(l)%deformation, &
                        stress_BC      = loadCases(l)%stress, &
                        rotation_BC    = loadCases(l)%rot)

              case(FIELD_THERMAL_ID)
                if (allocated(loadCases(l)%temperature%myType)) then
                  call grid_thermal_spectral_forward(cutBack, guess, Delta_t, Delta_t_prev, t_remaining, &
                                                     loadCases(l)%temperature)
                else
                  call grid_thermal_spectral_forward(cutBack, guess, Delta_t, Delta_t_prev, t_remaining)
                end if
              case(FIELD_DAMAGE_ID); call grid_damage_spectral_forward(cutBack)
              case(FIELD_CHEMICAL_ID); call grid_chemical_FDM_forward(cutBack)
            end select
          end do
          if (.not. cutBack) call materialpoint_forward

!--------------------------------------------------------------------------------------------------
! solve fields
          stagIter = 1
          stagIterate = .true.
          do while (stagIterate)

            if (nActiveFields > 1) print'(/,1x,a,i0)', 'Staggered Iteration ',stagIter
            do field = 1, nActiveFields
              select case(ID(field))
                case(FIELD_MECH_ID)
                  solres(field) = grid_mechanical_solution(incInfo)
                case(FIELD_THERMAL_ID)
                  solres(field) = grid_thermal_spectral_solution(Delta_t)
                case(FIELD_DAMAGE_ID)
                  solres(field) = grid_damage_spectral_solution(Delta_t)
                case(FIELD_CHEMICAL_ID)
                  solres(field) = grid_chemical_FDM_solution(Delta_t)
              end select

              if (.not. solres(field)%converged) exit                                               ! no solution found

            end do
            stagIter = stagIter + 1
            stagIterate =            stagIter <= stagItMax &
                         .and.       all(solres(:)%converged) &
                         .and. .not. all(solres(:)%stagConverged)                                   ! stationary with respect to staggered iteration
          end do

!--------------------------------------------------------------------------------------------------
! check solution and either advance or retry with smaller timestep

          if (all(solres(:)%converged .and. solres(:)%stagConverged)) then                          ! converged and acceptable solution found
            call grid_mechanical_updateCoords()
            Delta_t_prev = Delta_t
            cutBack = .false.
            guess = .true.                                                                          ! start guessing after first converged (sub)inc
            if (worldrank == 0) then
              write(unit_stat,*) totalIncsCounter, t, cutBackLevel, &
                                solres(1)%converged, solres(1)%iterationsNeeded, StagIter - 1
              flush(unit_stat)
            end if
          elseif (cutBackLevel < maxCutBack) then                                                   ! further cutbacking tolerated?
            cutBack = .true.
            stepFraction = (stepFraction - 1) * subStepFactor                                       ! adjust to new denominator
            cutBackLevel = cutBackLevel + 1
            t = t - Delta_t
            Delta_t = Delta_t/real(subStepFactor,pREAL)                                             ! cut timestep
            print'(/,1x,a)', 'cutting back '
          else                                                                                      ! no more options to continue
            if (worldrank == 0) close(unit_stat)
            call IO_error(950)
          end if

        end do subStepLooping

        cutBackLevel = max(0, cutBackLevel - 1)                                                     ! try half number of subincs next inc

        if (all(solres(:)%converged)) then
          print'(/,1x,a,1x,i0,1x,a)', 'increment', totalIncsCounter, 'converged'
        else
          print'(/,1x,a,1x,i0,1x,a)', 'increment', totalIncsCounter, 'NOT converged'
        end if; flush(IO_STDOUT)

        call MPI_Allreduce(logical(signal_SIGUSR1),sig,1_MPI_INTEGER_KIND,MPI_LOGICAL,MPI_LOR,MPI_COMM_WORLD,err_MPI)
        call parallelization_chkerr(err_MPI)
        if (mod(inc,loadCases(l)%f_out) == 0 .or. sig) then
          print'(/,1x,a)', '... saving results ........................................................'
          flush(IO_STDOUT)
          call materialpoint_result(totalIncsCounter,t)
        end if
        if (sig) call signal_setSIGUSR1(.false.)

        call MPI_Allreduce(logical(signal_SIGUSR2),sig,1_MPI_INTEGER_KIND,MPI_LOGICAL,MPI_LOR,MPI_COMM_WORLD,err_MPI)
        call parallelization_chkerr(err_MPI)
        if (mod(inc,loadCases(l)%f_restart) == 0 .or. sig) then
          fileHandle = HDF5_openFile(CLI_jobName//'_restart.hdf5','w')
          call HDF5_addAttribute(fileHandle,'increment',totalIncsCounter)
          call HDF5_closeFile(fileHandle)
          do field = 1, nActiveFields
            select case (ID(field))
              case(FIELD_MECH_ID)
                call grid_mechanical_restartWrite()
              case(FIELD_THERMAL_ID)
                call grid_thermal_spectral_restartWrite()
              case(FIELD_DAMAGE_ID)
                call grid_damage_spectral_restartWrite()
              case(FIELD_CHEMICAL_ID)
                call grid_chemical_FDM_restartWrite()
            end select
          end do
          call materialpoint_restartWrite()
        end if
        if (sig) call signal_setSIGUSR2(.false.)

        call MPI_Allreduce(logical(signal_SIGINT),sig,1_MPI_INTEGER_KIND,MPI_LOGICAL,MPI_LOR,MPI_COMM_WORLD,err_MPI)
        call parallelization_chkerr(err_MPI)
        if (sig) exit loadCaseLooping
      end if skipping

    end do incLooping

  end do loadCaseLooping

!--------------------------------------------------------------------------------------------------
! report summary of whole calculation
  print'(/,1x,a)', '###########################################################################'
  if (worldrank == 0) close(unit_stat)

  call quit(0)                                                                                      ! no complains ;)

contains


function parse_and_print_load_cases(load_steps, solver) result(load_cases)

#ifndef __GFORTRAN__
  use prec
  use types
  use IO
  use math
  use parallelization

  import, only: tLoadCase, get_masked_tensor
#endif

  type(tList), intent(in), target :: load_steps
  type(tDict), pointer, intent(in) :: solver
  type(tLoadCase), allocatable, dimension(:) :: load_cases                                          !< array of all load cases

  integer :: i,j, l,m
  type(tDict), pointer :: &
    load_step, &
    step_bc, &
    step_mech, &
    step_therm, &
    step_discretization


  allocate(load_cases(size(load_steps)))
  do l = 1, size(load_steps)
    load_step => load_steps%get_dict(l)
    if (load_step%contains('boundary_condition')) then
      step_bc => load_step%get_dict('boundary_condition')
    else
      step_bc => load_step%get_dict('boundary_conditions')
    end if
    step_mech => step_bc%get_dict('mechanical')
    load_cases(l)%stress%myType=''
    readMech: do m = 1, size(step_mech)
      select case (step_mech%key(m))
        case ('L','dot_F','F_dot','F')                                                              ! assign values for the deformation BC matrix
          if (allocated(load_cases(l)%deformation%myType)) &
            call IO_error(830_pI16, 'load case', l, 'only one of L, dot_F, or F allowed in mechanical BC', emph=[2])
          load_cases(l)%deformation%myType = step_mech%key(m)
          if (load_cases(l)%deformation%myType == 'F_dot') load_cases(l)%deformation%myType = 'dot_F'
          call get_masked_tensor(load_cases(l)%deformation%values,load_cases(l)%deformation%mask,step_mech%get_list(m))
        case ('dot_P','P','P_dot')
          if (load_cases(l)%stress%myType /= '') &
            call IO_error(830_pI16, 'load case', l, 'only one of P or dot_P allowed in mechanical BC', emph=[2])
          load_cases(l)%stress%myType = step_mech%key(m)
          if (load_cases(l)%stress%myType == 'P_dot') load_cases(l)%stress%myType = 'dot_P'
          call get_masked_tensor(load_cases(l)%stress%values,load_cases(l)%stress%mask,step_mech%get_list(m))
      end select
      call load_cases(l)%rot%fromAxisAngle(step_mech%get_as1dReal('R',defaultVal = real([0.0,0.0,1.0,0.0],pREAL)),degrees=.true.)
    end do readMech
    if (.not. allocated(load_cases(l)%deformation%myType)) &
      call IO_error(830_pI16, 'load case', l, 'is incomplete: L, F_dot/dot_F, or F missing', emph=[2])

    if (step_bc%contains('thermal')) then
      step_therm => step_bc%get_dict('thermal')
      readTherm: do m = 1, size(step_therm)
        select case (step_therm%key(m))
          case ('T','dot_T')
            if (allocated(load_cases(l)%temperature%myType)) &
              call IO_error(830_pI16, 'load case', l, 'only one of T or dot_T allowed in thermal BC', emph=[2])
            load_cases(l)%temperature%myType = step_therm%key(m)
            load_cases(l)%temperature%value  = step_therm%get_asReal(m)
          case ('thermostat')
            load_cases(l)%temperature%thermostat = step_therm%get_asStr(m)
            if (load_cases(l)%temperature%thermostat /= 'shift' .and. &
                load_cases(l)%temperature%thermostat /= 'scale') &
              call IO_error(830_pI16, 'load case', l, 'thermal BC thermostat must be shift or scale', emph=[2])
        end select
      end do readTherm
      if (allocated(load_cases(l)%temperature%myType) .and. .not. allocated(load_cases(l)%temperature%thermostat)) &
        call IO_error(830_pI16, 'load case', l, 'thermal BC requires thermostat: shift or scale', emph=[2])
    end if

    step_discretization => load_step%get_dict('discretization')
    load_cases(l)%t = step_discretization%get_asReal('t')
    load_cases(l)%N = step_discretization%get_asInt  ('N')
    load_cases(l)%r = step_discretization%get_asReal('r',defaultVal= 1.0_pREAL)

    load_cases(l)%f_restart = load_step%get_asInt('f_restart', defaultVal=huge(0))
    if (load_step%get_asStr('f_out',defaultVal='n/a') == 'none') then
      load_cases(l)%f_out = huge(0)
    else
      load_cases(l)%f_out = load_step%get_asInt('f_out', defaultVal=1)
    end if
    load_cases(l)%estimate_rate = load_step%get_asBool('estimate_rate',defaultVal=.true.)

    reportAndCheck: if (worldrank == 0) then
      print'(/,1x,a,1x,i0)', 'load case:', l
      print'(2x,a,1x,l1)', 'estimate_rate:', load_cases(l)%estimate_rate
      if (load_cases(l)%deformation%myType == 'F') then
        print'(2x,a)', 'F:'
      else
        print'(2x,a)', load_cases(l)%deformation%myType//' / 1/s:'
      end if
      do i = 1, 3; do j = 1, 3
        if (load_cases(l)%deformation%mask(i,j)) then
          write(IO_STDOUT,'(2x,12a)',advance='no') '     x      '
        else
          write(IO_STDOUT,'(2x,f12.7)',advance='no') load_cases(l)%deformation%values(i,j)
        end if
        end do; write(IO_STDOUT,'(/)',advance='no')
      end do
      if (any(load_cases(l)%stress%mask .eqv. load_cases(l)%deformation%mask)) &
        call IO_error(830_pI16, 'mask consistency violated in load case', l, emph=[2])
      if (any(.not.(load_cases(l)%stress%mask .or. transpose(load_cases(l)%stress%mask)) .and. (math_I3<1))) &
        call IO_error(830_pI16, 'mixed boundary conditions allow rotation in load case', l, emph=[2])

      if (load_cases(l)%stress%myType == 'P')     print'(2x,a)', 'P / MPa:'
      if (load_cases(l)%stress%myType == 'dot_P') print'(2x,a)', 'dot_P / MPa/s:'

      if (load_cases(l)%stress%myType /= '') then
        do i = 1, 3; do j = 1, 3
          if (load_cases(l)%stress%mask(i,j)) then
            write(IO_STDOUT,'(2x,12a)',advance='no') '     x      '
          else
            write(IO_STDOUT,'(2x,f12.4)',advance='no') load_cases(l)%stress%values(i,j)*1e-6_pREAL
          end if
          end do; write(IO_STDOUT,'(/)',advance='no')
        end do
      end if
      if (any(dNeq(load_cases(l)%rot%asMatrix(), math_I3))) &
        write(IO_STDOUT,'(2x,a,/,3(3(3x,f12.7,1x)/))',advance='no') 'R:',&
                 transpose(load_cases(l)%rot%asMatrix())

      if (allocated(load_cases(l)%temperature%myType)) then
        if (load_cases(l)%temperature%myType == 'T') then
          print'(2x,a,1x,f0.3)', 'T / K:', load_cases(l)%temperature%value
        else
          print'(2x,a,1x,f0.3)', 'dot_T / K/s:', load_cases(l)%temperature%value
        end if
        print'(2x,a,1x,a)', 'thermal BC thermostat:', load_cases(l)%temperature%thermostat
      end if

      if (solver%get_asStr('mechanical') == 'spectral_Galerkin' .and. step_mech%contains('R')) &
        call IO_error(830_pI16, 'load case', l, 'contains rotation', 'R', &
                      'which is not supported when using the Galerkin solver', emph=[2,4])
      if (load_cases(l)%r <= 0.0_pREAL) &
        call IO_error(830_pI16, 'non-positive ratio for geometric progression in load case', l, emph=[2])
      if (load_cases(l)%t <= 0.0_pREAL) &
        call IO_error(830_pI16, 'negative time increment in load case', l, emph=[2])
      if (load_cases(l)%N < 1) &
        call IO_error(830_pI16, 'non-positive number of increments in load case', l, emph=[2])
      if (load_cases(l)%f_out < 1) &
        call IO_error(830_pI16, 'non-positive result frequency in load case', l, emph=[2])
      if (load_cases(l)%f_restart < 1) &
        call IO_error(830_pI16, 'non-positive restart frequency in load case', l, emph=[2])

      if (dEq(load_cases(l)%r,1.0_pREAL,1.e-9_pREAL)) then
        print'(2x,a)', 'r: 1 (constant step width)'
      else
        print'(2x,a,1x,f0.3)', 'r:', load_cases(l)%r
      end if
      print'(2x,a,1x,f0.3)',   't:', load_cases(l)%t
      print'(2x,a,1x,i0)',     'N:', load_cases(l)%N
      if (load_cases(l)%f_out < huge(0)) &
        print'(2x,a,1x,i0)',   'f_out:', load_cases(l)%f_out
      if (load_cases(l)%f_restart < huge(0)) &
        print'(2x,a,1x,i0)',   'f_restart:', load_cases(l)%f_restart

    end if reportAndCheck
  end do
end function parse_and_print_load_cases


subroutine get_masked_tensor(values,mask,tensor)

#ifndef __GFORTRAN__
  use prec
  use types

  import, none
#endif

  real(pREAL), intent(out), dimension(3,3) :: values
  logical,     intent(out), dimension(3,3) :: mask
  type(tList), pointer, intent(in) :: tensor

  type(tList), pointer :: row
  integer :: i,j


  values = 0.0_pREAL
  do i = 1,3
    row => tensor%get_list(i)
    do j = 1,3
      mask(i,j) = row%get_asStr(j) == 'x'
      if (.not. mask(i,j)) values(i,j) = row%get_asReal(j)
    end do
  end do

end subroutine get_masked_tensor

end program DAMASK_grid
