#' Reflect the signs of the columns of the factor pattern matrix
#' so that the number of positive loadings is larger than the negative ones.
#'
#' @param A Factor Pattern matrix or an object with $loadings.
#' @param unclass = 1 to unclass the result
#' @param sortcols = 1 to sort factors (columns of A) according to
#' factor contributions.
#' @param print = 1 to print the result
#'
#' @details
#' First, if sortcols == 1, the columns of \code{A} are reordered
#' according to the magnitude of \code{diag(t(A)\%*\%A)}. \cr
#' Then, for each column of \code{A},
#' the sign will be reflected if the number of negative loadings is
#' greater than the positive ones.
#'
#' @examples
#' set.seed(1701)
#' n <- 20; ndim <- 4
#' A0 <- matrix(runif(n*ndim),n,ndim)
#' dimnames(A0)=list( paste("v",1:n,sep=""),paste("f",1:ndim,sep=""))
#' A0v <- varimax(A0)$loadings
#' A0v <- A0v*matrix(sample(c(-1,1,1),n*ndim,replace=TRUE),n,ndim)
#' A0v[,3:4] <- -A0v[,3:4]
#'
#' A0vs <- reflect_fa(A0v)$loadings
#' Print(A0v,A0vs, fmt="6.3")
#'
#' A0vsc <- reflect_fa(A0v, sortcol=1)$loadings
#' Print(A0v,A0vsc, fmt="6.3")
#'
#' # attributes
#' print(reflect_fa(A0v)$loadings)
#' print(reflect_fa(A0v, unclass=1)$loadings)
#'
#' @return A list of \cr
#' loadings = reordered loadings matrix \cr
#' col_order = sort order of the cols \cr
#' sign = a vector indicating if the signs were preserved or not
#'
#' @export
#'

reflect_fa <- function( A, sortcols=0, unclass=0 ){
 # reeflect the signs of the columns
 # Shin-ichi Mayekawwa
 # 20210416cot,17cot
 # lazy.tools: 20210421
 #

 # store attributes
 attrib=attributes(A)
 A=unclass(A)
 n=nrow(A)

  # names
 if( is.null(rownames(A)) ) rownames(A)=paste("r",1:nrow(A),sep="")
 if( is.null(colnames(A)) ) colnames(A)=paste("c",1:ncol(A),sep="")
 rname=rownames(A); cname=colnames(A)

 odc=1:ncol(A)
 names(odc)=cname
 if( sortcols == 1 ){
  # sort by diag(t(A)%*%A)
  fc=colSums(A*A)
  names(fc)=cname
  odc=order(-fc)
  A=A[,odc]
  cname=colnames(A)
 }

 # sig[j]=1 if the # of negative loadings is less than positive ones.
 sig=2*( (colSums(A>0)-nrow(A)/2) >= 0 )-1
 A=A%*%diag( sig )
 rownames(A)=rname
 colnames(A)=cname

 if( !unclass ){
  attributes(A)=attrib
  rownames(A)=rname
  colnames(A)=cname
 }


 return( list(loadings=A, sign=sig, col_order=odc ) )

} # end of reflect_fa



