!DEC$ FREEFORM

SUBROUTINE UEXTERNALDB(LOP,LRESTART,TIME,DTIME,KSTEP,KINC)
    !when timestep converged, write STRESS to file
    
    USE ABQinterface
    
    IMPLICIT NONE
    
    INTEGER(KIND=AbqIK),INTENT(IN)::LOP,LRESTART,KSTEP,KINC
    REAL(KIND=AbqRK),DIMENSION(2),INTENT(IN)::TIME
    REAL(KIND=AbqRK),INTENT(IN)::DTIME
    REAL(KIND=AbqRK),DIMENSION(6):: STRESS
    POINTER(pt_STRESS,STRESS)
    INTEGER:: i
    !Name of directory in which UMAT_Driver is stared
    CHARACTER(LEN=256)::  OUTDIR
    !lenght of name of this directory
    INTEGER:: LENOUTDIR
        
    IF (LOP==0) THEN !at beginning of analysis allocate memory
        pt_STRESS=SMAFloatArrayCreate(1,6,0.0_AbqRK)
    ELSE IF (LOP==2) THEN !write STRESS to a file
        pt_STRESS=SMAFloatArrayAccess(1)
        CALL GETOUTDIR(OUTDIR,LENOUTDIR)
        OPEN(unit=101,file=OUTDIR(1:LENOUTDIR)//'/STRESS_out.txt',action='WRITE',position='append',status='unknown')
        DO i=1,6
            WRITE (101,fmt='(E16.9)',advance='no') STRESS(i)
        END DO
        CLOSE(unit=101)
    ELSE IF ((LOP==3) .AND. (LRESTART>0)) THEN !at the end deallocate data
        CALL SMAFloatArrayDelete(1)
    END IF

END SUBROUTINE UEXTERNALDB
