hist3d <-
    function (x, y, xbreaks, ybreaks, freq= NULL, probability = !freq, include.lowest= TRUE,
              right= TRUE, 
              xlim = range(xbreaks), ylim = range(ybreaks), zlim = NULL,
              xlab = xname, ylab = yname, zlab,
              plot = TRUE, top = TRUE, nclass = NULL, ...)
{
    if (!is.numeric(x) | !is.numeric(y))
        stop("`x' and `y' must be numeric")
    xname <- deparse(substitute(x))
    yname <- deparse(substitute(y))
    n <- length(x <- x[!is.na(x)])
    use.xbr <- !missing(xbreaks)
    if(use.xbr) {
        if(!missing(nclass))
            warning("`nclass' not used when `xbreaks' specified")
    }
    else if(!is.null(nclass) && length(nclass) == 1)
        xbreaks <- nclass
    use.xbr <- use.xbr && (nB <- length(xbreaks)) > 1
    if(use.xbr)
        xbreaks <- sort(xbreaks)
    else {                              # construct vector of breaks
        rx <- range(x)
        nnb <-
            if(missing(xbreaks)) 1 + log2(n)
            else {                      # breaks = `nclass'
                if (is.na(xbreaks) | xbreaks < 2)
                    stop("invalid number of xbreaks")
                xbreaks
            }
        xbreaks <- pretty (rx, n = nnb, min.n=1, eps.corr = 2)
  	}
    nxB <- length(xbreaks)
    if(nxB <= 1) ##-- Impossible !
    stop(paste("hist3d: error, xbreaks=",format(xbreaks)))
    
    storage.mode(x) <- "double"
    storage.mode(xbreaks) <- "double"
        use.ybr <- !missing(ybreaks)
        if(use.ybr) {
            if(!missing(nclass))
                warning("`nclass' not used when `ybreaks' specified")
        }
        else if(!is.null(nclass) && length(nclass) == 1)
            ybreaks <- nclass
        use.ybr <- use.ybr && (nB <- length(ybreaks)) > 1
        if(use.ybr)
            ybreaks <- sort(ybreaks)
        else {                              # construct vector of breaks
            ry <- range(y)
            nnb <-
                if(missing(ybreaks)) 1 + log2(n)
                else {                      # breaks = `nclass'
                    if (is.na(ybreaks) | ybreaks < 2)
                        stop("invalid number of ybreaks")
                    ybreaks
                }
            ybreaks <- pretty (ry, n = nnb, min.n=1, eps.corr = 2)
	  	}
        nyB <- length(ybreaks)
        if(nyB <= 1) ##-- Impossible !
        stop(paste("hist3d: error, ybreaks=",format(ybreaks)))
        
        storage.mode(y) <- "double"
    storage.mode(ybreaks) <- "double"
    counts <- table(cut(x,xbreaks),cut(y,ybreaks))
    if (sum(counts) < n)
        stop("some data not counted; maybe breaks do not span range of data")
    xh <- diff(xbreaks)
    if (!use.xbr && any(xh <= 0))
        stop("not strictly increasing `xbreaks'.")
    yh <- diff(ybreaks)
    if (!use.ybr && any(yh <= 0))
        stop("not strictly increasing `ybreaks'.")
    if (is.null(freq)) {
        freq <- if(!missing(probability))
            !as.logical(probability)
        else if(use.xbr | use.ybr) {
            ##-- Do frequencies if breaks are evenly spaced
            (max(xh)-min(xh) < 1e-7 * mean(xh)) &  (max(yh)-min(yh) < 1e-7 * mean(yh))
        } else TRUE
    } else if(!missing(probability) && any(probability == freq))
        stop("`probability' is an alias for `!freq', however they differ.")
    density <- counts/(n*outer(xh,yh))
    xmids <- 0.5 * (xbreaks[-1] + xbreaks[-nxB])
    ymids <- 0.5 * (ybreaks[-1] + ybreaks[-nyB])
    equidist <- (!use.xbr & !use.ybr) || (diff(range(xh)) < 1e-7 * mean(yh)) & (diff(range(yh)) < 1e-7 * mean(yh))
    r <- structure(list(xbreaks = xbreaks, ybreaks = ybreaks, counts = counts,
                        intensities = density, 
            density = density, xmids = xmids, ymids = ymids,
                        xname = xname, yname = yname, equidist = equidist),
                   class="histogram3d")
    if (plot) {
        plot(r, freq = freq, 
             xlim = xlim, ylim = ylim, zlim = zlim, xlab = xlab, ylab = ylab, zlab = zlab,
			 top = top, ...)
        invisible(r)
    }
    else r
}

plot.histogram3d <-
    function (x, freq = equidist, col = 'gray', rgb = col,
              main = paste("Histogram of", x$xname, "and", x$yname),
              xlim = range(x$xbreaks), ylim = range(x$ybreaks), zlim = NULL,
              xlab = x$xname, ylab = x$yname, zlab,
              axes = TRUE, box = TRUE, add = FALSE, 
			  top = TRUE, ...)
{
    if (!add) clear3d()
    save <- par3d(skipRedraw = TRUE, ...)
    on.exit(par3d(save))

    equidist <- x$equidist
    if(freq && !equidist)
        warning("the AREAS in the plot are wrong -- rather use `freq=FALSE'!")

    z <- if (freq) x$counts else x$density
    nxB <- length(x$xbreaks)
    nyB <- length(x$ybreaks)

    if(is.null(z) || 0 == nxB || 0 == nyB) stop("`x' is wrongly structured")

	rgb <- matrix(rgb,nxB-1,nyB-1)
    for (i in 1:(nyB-1)) {
        keep <- z[,i] > 0
        quads3d(as.double(t(cbind(x$xbreaks[-nxB], x$xbreaks[-1], x$xbreaks[-1], x$xbreaks[-nxB])[keep,])),
                as.double(t(cbind(rep(x$ybreaks[i],nxB-1),rep(x$ybreaks[i],nxB-1),rep(x$ybreaks[i+1],nxB-1),rep(x$ybreaks[i+1],nxB-1))[keep,])),
                as.double(t(cbind(z[,i],z[,i],z[,i],z[,i])[keep,])),
                col = t(cbind(rgb[,i],rgb[,i],rgb[,i],rgb[,i])[keep,]))
        quads3d(as.double(t(cbind(x$xbreaks[-nxB], x$xbreaks[-1], x$xbreaks[-1], x$xbreaks[-nxB])[keep,])),
                as.double(rep(rep(x$ybreaks[i],(nxB-1))[keep],4)),
                as.double(t(cbind(rep(0,nxB-1),    rep(0,nxB-1),  z[,i],       z[,i])[keep,])),
				col = t(cbind(rgb[,i],rgb[,i],rgb[,i],rgb[,i])[keep,]))
        quads3d(as.double(t(cbind(x$xbreaks[-nxB], x$xbreaks[-1], x$xbreaks[-1], x$xbreaks[-nxB])[keep,])),
                as.double(rep(rep(x$ybreaks[i+1],(nxB-1))[keep],4)),
                as.double(t(cbind(rep(0,nxB-1),    rep(0,nxB-1),  z[,i],       z[,i])[keep,])),
				col = t(cbind(rgb[,i],rgb[,i],rgb[,i],rgb[,i])[keep,]))
        quads3d(as.double(t(cbind(x$xbreaks[-nxB], x$xbreaks[-nxB], x$xbreaks[-nxB], x$xbreaks[-nxB])[keep,])),
                as.double(t(cbind(rep(x$ybreaks[i],nxB-1),rep(x$ybreaks[i+1],nxB-1),rep(x$ybreaks[i+1],nxB-1),rep(x$ybreaks[i],nxB-1))[keep,])),
                as.double(t(cbind(rep(0,nxB-1),    rep(0,nxB-1),  z[,i],       z[,i])[keep,])),
                col = t(cbind(rgb[,i],rgb[,i],rgb[,i],rgb[,i])[keep,]))
        quads3d(as.double(t(cbind(x$xbreaks[-1], x$xbreaks[-1], x$xbreaks[-1], x$xbreaks[-1])[keep,])),
                as.double(t(cbind(rep(x$ybreaks[i],nxB-1),rep(x$ybreaks[i+1],nxB-1),rep(x$ybreaks[i+1],nxB-1),rep(x$ybreaks[i],nxB-1))[keep,])),
                as.double(t(cbind(rep(0,nxB-1),    rep(0,nxB-1),  z[,i],       z[,i])[keep,])),
				col = t(cbind(rgb[,i],rgb[,i],rgb[,i],rgb[,i])[keep,]))
    }
    if(!add) {
        if(is.null(zlim))
            zlim <- range(z, 0)
        if (missing(zlab))
            zlab <- if (!freq) "Density" else "Frequency"
        title3d(main = main, xlab = xlab, ylab = ylab, zlab = zlab)
        if(axes) {
           axes3d()
        }
        if(box) {
           box3d()
        }
    }
	if (top) rgl.bringtotop()
	invisible()
}