gcount <- function(chain, states, iord, maxord)
{
#
# Generalization of the count function.
# Returns a transition matrix of counts which is the
# number or transitions from state (sub iord+1) at time t-iord to
# state (sub iord) at time t-iord+1 to ... to state (sub 1) at
# time t. Optionally, one can include maxord, the maximum order you
# intend to fit. In this case, only data that would be available
# for the maximum order is used in the computations.
#
#
# check the number of states
        if(max(chain[!is.na(chain)]) > states) stop(paste("you need", max(
                        chain), "states for your\ndata"))
# if maxord is missing, set it equal to iord
        if(missing(maxord)) maxord <- iord
# initialize the counts
        dims <- rep(states, iord + 1)
        if(length(dims) == 1)
                kount <- matrix(0, 1, states)
        else kount <- array(0, dims)
        for(i in (maxord + 1):length(chain)) {
                aind <- chain[(i - iord):i]
                if(sum(is.na(chain[(i - maxord):i])) == 0) {
                        vind <- mat.index(aind, dims)
                        kount[vind] <- kount[vind] + 1
                }
        }
        return(kount)
}