# Produces a matrix with clusters as rows and regions as columns,
# indicating how many species of a region belong to the clusters
#
# x: prab object as generated by prabinit
# xc: prabclust object as produced by prabclust
crmatrix <- function(x,xc,percentages=FALSE){
  onoise <- 0 %in% xc$clustering
  ofac <- levels(as.factor(xc$clustering))
  ol <- length(ofac)
  snoise <- "N" %in% xc$symbols
  sfac <- levels(as.factor(xc$symbols))
  sl <- length(sfac)
  
  cln <- sl-as.integer(snoise)
  
  clu <- xc$clustering
  if (onoise){
    if (ol!=sl)
      clu[xc$clustering>cln] <- 0
  }
  if (!onoise){
    if (snoise)
      clu[xc$clustering>cln] <- 0
  }
  
  clu[clu==0] <- cln+1

  cin <- rep(1,sl)
  if (percentages)
    for (i in 1:sl)
      cin[i] <- sum(clu==i) 
  cmatrix <- matrix(0,nrow=sl,ncol=x$n.regions)
  for (i in 1:sl)
    for (j in 1:x$n.regions)
      cmatrix[i,j] <- sum(x$prab[j,clu==i])/cin[i]
  cmatrix
}

