library(FNN) #for the function knn.

intpm<-function(ri,PM){
(t(ri)%*%PM%*%ri)}

norm2.Fnormfn <- function(m, PM) {


  return(sum(apply(m,2,intpm, PM=PM))) # 
}

norm2.Fnormfn2 <- function(m, PM) {

di=dim(m)
s1=sum(apply(m[1:(di[1]/2),],2,intpm, PM=PM))
s2=sum(apply(m[((di[1]/2 + 1): di[1]),],2,intpm, PM=PM))
  return(s1+s2) # para que sea como RSS de Cutler!!! 
}

FstepArchetypoidsB <- function(i,nearest,data,ArchObj,sequ,aux,PM){


#datao=data
  x11 <- t(data[,,1])
    x12 <- t(data[,,2])
    x1=rbind(x11,x12)
    data=t(x1)
  
  N = dim(data)[1]
  
  if(sequ){
   ai <- bestModel(ArchObj[[i]])
  }else{
   ai <- bestModel(ArchObj[[i-aux]])  
  }
  
  if(is.null(parameters(ai))){
    stop("No archetypes computed")  
  }
  
    
  if(nearest){
  
    	dime=dim(parameters(ai))
  	ar=parameters(ai)
  	R=matrix(0,nrow=dime[1], ncol=N)
  	for(di in 1:dime[1]){ #dime[1] is the number of archetypes
  
  		
  Raux=matrix(ar[di,],byrow=F,ncol=N,nrow=dime[2])-t(data)
  
  
   dii=dim(Raux)
  
  		
  R[di,]= apply(Raux[1:(dii[1]/2),],2,intpm, PM=PM)+apply(Raux[((dii[1]/2 + 1): dii[1]),],2,intpm, PM=PM)
  
  
  

    	}

  ini_arch <- apply(R, 1, which.min)

 
    
    if( any(duplicated(ini_arch)) == TRUE){ #for very rare ocasions, it can be improved
     # ini_arch=unique(ini_arch)      

	 k=1
       neig=apply(R, 1, rank)     
      indices1 <- neig[1,]
      ini_arch <- indices1[,k]
      
      while(any(duplicated(ini_arch))){
        k=k+1  
       
        indicesk <- neig[k,]
               
        dupl <- anyDuplicated(indices1)
        ini_arch <- c(indices1[-dupl],indicesk[dupl])
       
      }
    }
    
  }else{
    ini_arch <- apply(coef(ai, "alphas"), 2, which.max) 
  }
  
  res <- FrealArchetypesB(data, huge = 200, i, ini_arch,PM) #as.vector(ini_arch)
  cat("Done!") 
  return(list(res[[1]],res[[2]],ini_arch))
}





stepFArchetypoidsnB <- function (data, k, norep=3,PM){
  mycall <- match.call()
  as <- list()
  for (i in 1:length(k)) {
    as[[i]] <- list()
    class(as[[i]]) <- "repArchetypoids"
    lass <- FstepArchetypesModB(data,k[i],verbose=FALSE,nrep=norep,PM=PM,saveHistory=F) 
          as[[i]]<- FstepArchetypoidsB(k[i],TRUE,data,lass,FALSE,k[i]-1,PM)
     
      
    
  }
  return(structure(as, class = "stepArchetypoids", call = mycall))
}

screeplot.stepArchetypoids <- function(as,nar=NULL){
xx=c()
l=length(as)

for (i in 1:l){
xx[i]=as[[i]][[2]]
}
if (is.null(nar)){
plot(1:l,xx,type='b',xlab='Archetypoids', ylab='RSS')}
else{
plot(nar,xx,type='b',xlab='Archetypoids', ylab='RSS')}
}


stepFArchetypoidswB <- function (data, k, norep=3,PM){
  mycall <- match.call()
  as <- list()
  for (i in 1:length(k)) {
    as[[i]] <- list()
    class(as[[i]]) <- "repArchetypoids"
    lass <- FstepArchetypesModB(data,k[i],verbose=FALSE,nrep=norep,PM=PM,saveHistory=F) 
          as[[i]]<- FstepArchetypoidsB(k[i],FALSE,data,lass,FALSE,k[i]-1,PM)
     
      
    
  }
  return(structure(as, class = "stepArchetypoids", call = mycall))
}


stepFArchetypoidsbB <- function (data, k, norep=3,PM){
  mycall <- match.call()
  as <- list()
  for (i in 1:length(k)) {
    as[[i]] <- list()
    class(as[[i]]) <- "repArchetypoids"
    lass <- FstepArchetypesModB(data,k[i],verbose=FALSE,nrep=norep,PM=PM,saveHistory=F) 
    ai <- bestModel(lass[[1]]) #archetypes
    ini_arch=c()
 for (j in 1:k[i]){
 ini_arch[j]=which.max(ai$betas[j,])
 }
 
as[[i]] <- FrealArchetypesB(data,huge = 200, k[i], ini_arch,PM) #which beta archetypoid
      
  }
  return(structure(as, class = "stepArchetypoids", call = mycall))
}
