1.SP2owin <- function(SP) {
2    if (!is.na(sp::is.projected(SP)) && !sp::is.projected(SP))
3      stop("Only projected coordinates may be converted to spatstat class objects")
4    check_spatstat("spatstat.geom")
5    pls <- slot(SP, "polygons")
6    nParts <- sapply(pls, function(x) length(slot(x, "Polygons")))
7    nOwin <- sum(nParts)
8    if (nOwin == 1) {
9        pl <- slot(pls[[1]], "Polygons")
10        crds <- slot(pl[[1]], "coords")
11	colnames(crds) <- c("x", "y")
12	rD <- pl[[1]]@ringDir
13	if (rD == 1) crds <- crds[nrow(crds):1,]
14	crds <- crds[-nrow(crds),]
15	res <- spatstat.geom::owin(poly=list(x=crds[,1], y=crds[,2]))
16    } else if (nOwin > 1) {
17        opls <- vector(mode="list", length=nOwin)
18        io <- 1
19        for (i in seq(along=pls)) {
20            pl <- slot(pls[[i]], "Polygons")
21            for (j in 1:nParts[i]) {
22                crds <- slot(pl[[j]], "coords")
23	        colnames(crds) <- c("x", "y")
24	        rD <- slot(pl[[j]], "ringDir") # sp:::.spFindCG(crds)$rD
25		hole <- slot(pl[[j]], "hole")
26
27	        if (rD == -1 && hole) crds <- crds[nrow(crds):1,]
28                else if (rD == 1 && !hole) crds <- crds[nrow(crds):1,]
29
30	        crds <- crds[-nrow(crds),]
31
32                opls[[io]] <- list(x=crds[,1], y=crds[,2])
33                io <- io+1
34            }
35        }
36        if (!spatstat.geom::spatstat.options("checkpolygons"))
37        	res <- spatstat.geom::owin(bbox(SP)[1,], bbox(SP)[2,], poly = opls,
38			check=FALSE)
39# 070718 added check avoidance
40	else res <- spatstat.geom::owin(poly=opls)
41    } else stop("no valid polygons")
42    res
43}
44