1# 2005 (c) Virgilio Gomez Rubio, partly derived from
2# earlier code by Thomas Jagger
3
4# The code in this file exports and sp object into a S-Plus map
5# format to be import by WinBUGS.
6
7# file: file where output is written
8# map: sp object (SpatialPolygons object)
9# xScale/yScale: scales to be written in the output file
10
11sp2WB <- function(map, filename, Xscale=1, Yscale=Xscale, plotorder=FALSE) {
12
13# Write some tests here to ensure that all the objects passed
14# are of the appropriate type
15
16	f<-file(filename,"w")
17
18# Get the total number of areas and Rings
19	SRings<-slot(map, "polygons")
20	nareas<-length(SRings)
21	nRings<-sum(sapply(SRings, function(x) length(slot(x, "Polygons"))))
22	IDs<-sapply(SRings, function(i) slot(i, "ID"))
23
24# Plot header of the f
25	cat(file=f, "map:",nareas, "\n", sep="")
26	cat(file=f, "Xscale:", Xscale, "\n", sep="")
27	cat(file=f, "Yscale:", Yscale, "\n", sep="")
28	cat(file=f, "\n")
29
30	if(plotorder)
31		porder <- slot(map, "plotOrder")
32	else
33		porder<-1:nareas
34
35# Different
36	for(area in (1:nareas)[porder])
37		cat(file=f, area, " area", IDs[area], "\n", sep="")
38
39	cat(file=f, "\n")
40
41	index<-1
42# Loop to print all the individual rings
43	for(area in (1:nareas)[porder]) {
44		label<-paste("area", IDs[area], sep="")
45		Rings<-slot(SRings[[area]], "Polygons")
46		lRings<-length(Rings)
47
48		if(plotorder)
49			porderrings<-slot(Rings, "plotOrder")
50		else
51			porderrings<-1:lRings
52
53		for(ring in (1:lRings)[porderrings]) {
54			coords<-slot(Rings[[ring]], "coords")
55			ncoords<-length(coords[,1])
56
57# Should we check that there are only x/y coordinates?
58                        xcrd <- formatC(coords[,1], format="f")
59                        ycrd <- formatC(coords[,2], format="f")
60			for(i in 1:ncoords)
61                                cat(file=f, label, xcrd[i], ycrd[i],
62                                        "\n")
63
64			if(index<nRings)
65				cat(file=f, "NA", "NA", "NA\n")
66			else
67				cat(file=f, "\n")
68
69			index<-index+1
70		}
71
72	}
73
74	cat(file=f, "END\n")
75	close(f)
76	invisible(NULL)
77}
78
79