SUBROUTINE btree_add_i8_sp2d (tree, key, value, exists, existing_value, replace)
TYPE(btree_i8_sp2d), INTENT(INOUT) :: tree
INTEGER(KIND=keyt), INTENT(IN) :: key
TYPE(btree_data_sp2d), INTENT(IN) :: value
LOGICAL, INTENT(OUT), OPTIONAL :: exists
TYPE(btree_data_sp2d), INTENT(OUT), OPTIONAL :: existing_value
LOGICAL, INTENT(IN), OPTIONAL :: replace
!
TYPE(btree_node_i8_sp2d), POINTER :: node
INTEGER :: ge_pos, position
!
IF (PRESENT(exists)) THEN
CALL btree_find_full_i8_sp2d (tree, key, node, position, ge_pos, short=.TRUE.)
IF (position .GT. 0) THEN
exists = .TRUE.
existing_value = node%values(position)
IF (PRESENT(replace)) THEN
IF (replace) THEN
node%values(position) = value
END IF
END IF
RETURN
ELSE
exists = .FALSE.
END IF
ELSE
CALL btree_find_leaf_i8_sp2d (tree, key, node, ge_pos)
END IF
CALL btree_add_into_i8_sp2d (tree, node, key, value, before=ge_pos)
IF (PRESENT(exists)) existing_value = value
tree%b%n = tree%b%n + 1
END SUBROUTINE btree_add_i8_sp2d