pca.lda <- function (Xtrain, Ytrain, Xtest = NULL, ncomp, nruncv = 0, alpha = 2/3, 
    priors = NULL) 
{
    ntrain <- nrow(Xtrain)
    Ytrain <- as.factor(Ytrain)
    if (is.vector(Xtest)) {
        Xtest <- matrix(Xtest, 1, length(Xtest))
    }
    if (is.null(Xtest)) {
        Xtest <- Xtrain
    }
    if (nruncv == 0 & length(ncomp) > 1) 
        stop("Since length(ncomp)>1, nruncv must be >0")
    if (nruncv > 0) {
        ncomp <- pls.lda.cv(Xtrain, Ytrain, ncomp = ncomp, nruncv = nruncv, 
            alpha = alpha, priors = priors)
    }
    pca.out <- prcomp(x = Xtrain, scale=T)
    Ztrain <- as.data.frame(pca.out$x[,1:ncomp], nrow = ntrain, ncol = ncomp)
    names(Ztrain) <- paste("PC",seq(1:ncomp),sep="")
    Ztrain$y <- Ytrain    
    Ztest <- as.data.frame(scale(Xtest, center = pca.out$center, scale = pca.out$scale) %*% pca.out$rotation[,1:ncomp])
    names(Ztest) <- paste("PC",seq(1:ncomp),sep="")   
    
    if (is.null(priors)) {
        lda.out <- lda(formula = y ~ ., data = Ztrain)
    }
    else {
        lda.out <- lda(formula = y ~ ., data = Ztrain, prior = priors)
    }
    posterior <- predict(object = lda.out, newdata = Ztest)$posterior ## Ztest je nereducirana matrika
    return(list(posterior = posterior, ncomp = ncomp))
}
