#
# plot dive profiles
#

library(Hmisc)
library(grid)

if (length(kz.args) != 3) {
    stop('Arguments required: output file, signature flag, output file format')
}

kz.args.fout = kz.args[1]
kz.args.sig = kz.args[2] == 'True'
kz.args.fmt = kz.args[3]

kz.args.width = 10
kz.args.height = 5

if (kz.args.fmt == 'pdf') {
    cairo_pdf(kz.args.fout, width=kz.args.width, height=kz.args.height, onefile=TRUE)
} else if (kz.args.fmt == 'png') {
    fimg = png
    kz.args.width = 800
    kz.args.height = 400
    png(kz.args.fout, width=kz.args.width, height=kz.args.height)
} else if (kz.args.fmt == 'svg') {
    svg(kz.args.fout, width=kz.args.width, height=kz.args.height)
}

if (is.null(kz.dives.ui$title))
    par(mar=c(5, 4, 1, 2) + 0.1)

for (i in 1:nrow(kz.dives)) {
    dive = kz.dives[i,]
    dive.title = if (is.null(kz.dives.ui$title)) NA else kz.dives.ui[i, 'title']
    dive.info = if (is.null(kz.dives.ui$info)) NA else kz.dives.ui[i, 'info']

    dp = kz.profiles[kz.profiles$dive == i, ]

    dive_time = dp$time / 60.0
    xlim = range(dive_time)
    ylim = rev(range(dp$depth))
    plot(NA, xlim=xlim, ylim=ylim,
        xlab='Time [min]', ylab='Depth [m]')

    # deco info
    if (any(!is.na(dp$deco_time))) {
        deco_depth = approxfun(dp$time, dp$deco_depth,
            method='constant', f=1)(dp$time)

        n = length(dp$time)
        dc = rep(rgb(0.90, 0.90, 1.0), n - 1)
        dc[which(dp$deco_alarm)] = rgb(1.0, 0.50, 0.50)
        rect(dive_time[1:n - 1], deco_depth[1:n - 1], dive_time[2:n], rep(0, n - 1),
            col=dc, border=dc)
    }

    # then the grid
    minor.tick(nx=5, ny=2)
    grid()

    # and finally plot the dive profile
    lines(dive_time, dp$depth, col='blue')

    # gas switch
    i_gas = which(!is.na(dp$gas_name))
    if (length(i_gas) > 0) {
        p_gas = c(4, rep(c(3, 1), 5)) # right, bottom, top, bottom, top...
        points(dive_time[i_gas], dp$depth[i_gas], pch=21, cex=0.5,
            col='blue', bg='blue')
        text(dive_time[i_gas], dp$depth[i_gas], dp$gas_name[i_gas],
            pos=p_gas, cex=0.7, offset=0.3)
    }

    if (!is.na(dive.title))
        title(sprintf('Dive %s', dive.title))

    if (!is.na(dive.info))
        grid.text(dive.info, x=0.85, y=0.25, just=c('left', 'bottom'),
            gp=gpar(cex=0.8, fontfamily='monospace'))

    if (kz.args.sig)
        grid.text(sprintf('generated by kenozooid ver. %s', kz.version),
            x=0.99, y=0.01, just=c('right', 'bottom'),
            gp=gpar(cex=0.6, fontface='italic'))
}

dev.off()

# vim: sw=4:et:ai
