##' sequence length
##'
##'
##' @title seqlen
##' @param fasfile fasta file
##' @return numeric vector
##' @export
##' @author Guangchuang Yu
seqlen <- function(fasfile) {
  x <- fa_read(fasfile)
  yy <- toString(x)
  yy <- gsub("-", "", yy)
  yy <- gsub(" ", "", yy)
  xx <- strsplit(yy, ",")
  sapply(xx, nchar)
}


##' summarize sequences in a fasta file
##'
##'
##' Compute number of sequences, length distribution, GC content and
##' proportion of ambiguous characters (anything other than A/C/G/T/U,
##' including gaps).
##' @title fa_summary
##' @param x fasta file or XStringSet object
##' @return data.frame with one row: \code{n_seq}, \code{min_len},
##' \code{max_len}, \code{mean_len}, \code{GC_pct} and \code{ambiguous_pct}
##' @importFrom Biostrings width
##' @export
##' @author Guangchuang Yu
##' @examples
##' fa_file <- system.file("extdata/HA.fas", package="seqmagick")
##' fa_summary(fa_file)
fa_summary <- function(x) {
    if (is.character(x)) {
        x <- fa_read(x)
    }
    lens <- width(x)
    ch <- unlist(strsplit(toupper(as.character(x)), "", fixed=TRUE),
                 use.names=FALSE)
    clean <- ch %in% c("A", "C", "G", "T", "U")
    denom <- sum(clean)
    gc_pct <- if (denom == 0) NA_real_
              else round(100 * sum(ch %in% c("G", "C")) / denom, 2)

    data.frame(n_seq=length(x),
               min_len=min(lens),
               max_len=max(lens),
               mean_len=round(mean(lens), 2),
               GC_pct=gc_pct,
               ambiguous_pct=round(100 * mean(!clean), 2))
}

