module strain_soften

implicit none

contains

function ss_new (ss_cur,ss_type,ss_onset,ss_end,ss_final,straintot,e2d,e2dprev,&
                 error_flag)

!------------------------------------------------------------------------------|
!(((((((((((((((( Purpose of the function  )))))))))))))))))))))))))))))))))))))
!------------------------------------------------------------------------------|
! This function calculates strain softened values of either the angle of
! internal friction, cohesion/yield strength or viscosity as a function of
! total strain or strain rate
!
!------------------------------------------------------------------------------|
!((((((((((((((((  declaration of the subroutine arguments  ))))))))))))))))))))
!------------------------------------------------------------------------------|

implicit none
double precision   :: ss_new,ss_cur,ss_onset,ss_end,ss_final,straintot,e2d
double precision   :: e2dprev
character (len=16) :: ss_type
logical            :: error_flag

!------------------------------------------------------------------------------|
!(((((((((((((((( declaration of the subroutine internal variables )))))))))))))
!------------------------------------------------------------------------------|

double precision :: fact

! Apply strain softening/weakening if onset value is positive
if (ss_onset.gt.0.d0) then
  ! Set type of strain softening/weakening
  select case (trim(ss_type))
    case ('tot_strain')
      ! Soften if beyond onset value
      if (straintot.gt.ss_onset) then
        fact=(straintot-ss_onset)/(ss_end-ss_onset)
        fact=min(fact,1.d0)
        ss_new=ss_cur+(ss_final-ss_cur)*fact
      endif
    case ('strain_rate')
      ! Soften cohesion if beyond onset value
      if (e2d.gt.ss_onset) then
        fact=(e2d-ss_onset)/(ss_end-ss_onset)
        fact=min(fact,1.d0)
        ss_new=ss_cur+(ss_final-ss_cur)*fact
      endif
    case ('step_strain_rate')
      ! Soften cohesion if beyond onset value
      if (e2dprev.gt.ss_onset) then
        fact=(e2dprev-ss_onset)/(ss_end-ss_onset)
        fact=min(fact,1.d0)
        ss_new=ss_cur+(ss_final-ss_cur)*fact
      endif
    case ('log_step_s_rate')
      ! Soften cohesion if beyond onset value
      if (e2dprev.gt.ss_onset) then
        fact=(log10(e2dprev)-log10(ss_onset))/(log10(ss_final)-log10(ss_onset))
        fact=min(fact,1.d0)
        ss_new=ss_cur+(ss_final-ss_cur)*fact
      endif
    case default
      write (*,*) 'ss_type: ',ss_type
      call stop_run('error in strain_soften$')
      error_flag = .true.
  end select
endif

end function ss_new

end module strain_soften
