## create a DNAStringSet covering the single range in roi but
## incorporating variants given by x, a GRanges object returned by
## callVariants

variantSequences <-
    function(x, roi, refSeq, ...)
{
    stopifnot(length(roi) == 1L)

    ## sequence in region of interest, replicated for each variant
    x <- subsetByOverlaps(x, roi)
    at <- split(start(x) - start(roi) + 1L, x$id)
    alt <- split(x$alt, x$id)
    alts <- Map(replaceLetterAt, at=at, letter=alt, refSeq)
    DNAStringSet(alts)
}

matchPWMs <-
    function(pwms, subject, min.score="80%", ...)
{
    subject <- as(subject, "DNAString")
    hits <- lapply(pwms, matchPWM, subject, min.score=min.score, ...)
    good <- sapply(hits, function(hit) isTRUE(width(hit) > 0))
    hits <- hits[good]

    ## Post-calculate the scores of the hits:
    scores <- Map(function(pwm, hit) {
        PWMscoreStartingAt(pwm, subject(hit), start(hit))
    }, pwms[names(hits)], hits)

    DataFrame(PWM=rep(names(hits), elementLengths(hits)),
              score=unlist(scores, use.names=FALSE),
              start=unlist(lapply(hits, start)),
              end=unlist(lapply(hits, end)),
              seq=do.call(c, lapply(unname(hits), as, "DNAStringSet")))
}
