## Ensure that our DLL is unloaded with the package, this allows
## for more convenient dev workflow in which you can reinstall
## the package and then "reload" it by detaching and calling
## library.
.onUnload <- function(libpath) library.dynam.unload("nidemo", libpath)

## A .Call function to compute the average of an integer vector
avg <- function(x) .Call(.nid_avg, as.integer(x))

## Tabulate occurance count of letters 'a'-'z' in a
## text file.
alpha_freq <- function(file)
{
    ans <- .Call(.nid_alpha_freq, file)
    names(ans) <- letters
    ans
}

## Tabulate occurance count of letters 'a'-'z' in a
## text file.  Same as alpha_freq, but in pure R.
alpha_freq_R <- function(file)
{
    ss <- paste(readLines(file), collapse="")
    t <- table(tolower(strsplit(ss, "")[[1]]))
    t <- t[letters]
    t[is.na(t)] <- 0L
    names(t) <- letters
    t
}

## Demo for a C implementation of which()
## x - a logical vector
## returns an integer vector giving the indices
## of the TRUEs in x.
demo_which <- function(x) .Call(.nid_which, x)

## Here's an example of using the .C interface
avg0 <- function(x)
{
    .C("nid_avg0", as.integer(x), length(x),
       ans = double(1),
       PACKAGE = "nidemo")
}

## This is a version of alpha_freq with some bugs intentionally added
## for the purpose of demonstrating how to use gdb.
buggy_freq <- function(file)
{
    ans <- .Call(.nid_buggy_freq, file)
    names(ans) <- letters
    ans
}

## The following three functions provide the API for an external pointer
## based alphabet frequency example.  The purpose is really only to
## demonstrate how to use R external pointers with registered
## finalizers.
##
## Example usage:
##
## x <- make_freq("alice")
## update_freq(x, "some/file.txt")
## update_freq(x, "some/another.txt")
## report_freq(x)
## rm(x)
## gc()
##
## The code is in src/extptrfreq.c

make_freq <- function(id) .Call(.nid_make_freq_data, as.character(id))

update_freq <- function(xp, fname) {
    invisible(.Call(.nid_update_freq, xp, as.character(fname)))
}

report_freq <- function(xp) .Call(.nid_report_freq, xp)
