#' Default plot function for `pm` objects.
#'
#' @author Eric Coissac
#' @author Christelle Gonindard-Melodelima
#' @export
plot.pm = function(m,
                   points.cex=0.6,
                   labels.cex=0.6,
                   arrow.length=0.05,
                   asp=1,
                   ...) {

  if (is.null(m$y))
    stop("Cannot plot procrust model without the y values")

  layout(matrix(c(1,1,1,1,2,3),nrow = 2))

  xlim = c(min(m$y[,1],m$fitted.values[,1]),
           max(m$y[,1],m$fitted.values[,1])
  )
  ylim = c(min(m$y[,2],m$fitted.values[,2]),
           max(m$y[,2],m$fitted.values[,2])
  )

  centers = (m$y + m$fitted.values)/2

  plot(m$y[,1:2],
       xlim=xlim,ylim=ylim,
       cex=points.cex,
       col="blue",
       asp=asp)

  points(m$fitted.values[,1:2],
         xlim=xlim,ylim=ylim,
         cex=points.cex,
         col="red")

  arrows(m$fitted.values[,1],m$fitted.values[,2],
         m$y[,1],m$y[,2],
         length = arrow.length,
         col="black")

  text(centers[,1],centers[,2],
       rownames(m$fitted.values),
       xlim=xlim,ylim=ylim,
       cex=labels.cex,
       col="black",
       pos=3)

  anova = anova(m)
  v=anova[,"Sum Sq"]
  names(v)=rownames(anova)
  barplot(v/sum(v),las=2)
}
