Sort <- function(...) {
  params <- list(...)
  f <- "function(x) {
    dim_bk <- dim(x)
    x <- do.call(sort, c(list(x, index.return = TRUE),
                         PARAMS))
    dim(x$x) <- dim_bk
    dim(x$ix) <- dim_bk
    x
  }"
  f <- gsub("PARAMS", deparse(params), f)
  r <- eval(parse(text = f))
  attr(r, 'circular') <- FALSE
  r
}

CircularSort <- function(start, end, ...) {
  params <- list(...)
  f <- "function (x) {
    start <- START
    end <- END
    dim_bk <- dim(x)
    x <- do.call(sort, c(list((x - start) %% (end - start) + start, 
                              index.return = TRUE),
                         PARAMS))
    dim(x$x) <- dim_bk
    dim(x$ix) <- dim_bk
    x
  }"
  f <- gsub("START", deparse(start), f)
  f <- gsub("END", deparse(end), f)
  f <- gsub("PARAMS", deparse(params), f)
  r <- eval(parse(text = f))
  attr(r, 'circular') <- TRUE
  r
}
