#!/usr/bin/env Rscript
#
# DecoTengu - dive decompression library.
#
# Copyright (C) 2013 by Artur Wroblewski <wrobell@pld-linux.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

LEGEND_WIDTH_STR = 'Inert gas pressure'

col2alpha <- function(name, alpha) {
    c3 = col2rgb(name) / 255
    rgb(c3[1,], c3[2,], c3[3,], alpha)
}

plot_start <- function(dive, xmax, ymax, labels=T) {
    xlab = NA
    ylab = NA

    if (labels) {
        xlab = 'Time [min]'
        ylab = 'Pressure [Bar]'
    }
    
    plot(NA, xlim=c(0, xmax), ylim=c(0, ymax), xlab=xlab, ylab=ylab)
    grid()
}

plot_dive_panel <- function(dive, lty='solid', pch=20, alpha=1, lwd=2, ps=0.75, pt=T) {
    time = dive$time / 60
    lines(time, dive$tissue_pressure, col=col2alpha('black', alpha), lty=lty, lwd=lwd)
    lines(time, dive$tissue_gf_limit, col=col2alpha('orange', alpha), lty=lty, lwd=lwd)
    lines(time, dive$tissue_limit, col=col2alpha('red', alpha), lty=lty, lwd=lwd)
    lines(time, dive$pressure, col=col2alpha('blue', alpha), lty=lty, lwd=lwd)

    if (pt)
        points(time, dive$pressure, col=col2alpha('blue', alpha), cex=ps, pch=pch)
}

plot_dive_basic <- function(dive, pt=T, labels=T) {
    plot_start(dive, max(dive$time / 60), max(dive$pressure), labels=labels)
    plot_dive_panel(dive, pt=pt)
}

add_legend <- function() {
    colors = c('blue', 'black', 'orange', 'red')
    legend(
        'topright',
        c(
            'Absolute pressure', 'Inert gas pressure',
            'GF ceiling limit', 'Ceiling limit'
        ),
        fill=colors,
        border=colors,
        bg='white',
        inset=c(0.015, 0.02),
        text.width=strwidth(LEGEND_WIDTH_STR)
    )
}

plot_dive <- function(dive) {
    layout(matrix(1:16, 4, 4, byrow=T))
    op = par(mar=c(2.5, 2.5, 2, 1) + 0.1, font.main=1)
    for (i in 1:16) {
        d = dive[dive$tissue_no == i,]
        plot_dive_basic(d, pt=F, labels=F)
        title(sprintf('Tissue %02d', i))
    }
    par(op)

    layout(matrix(1))
    md = aggregate_leading_tissue(dive)
    p = plot_dive_basic(md)
    title('Leading Tissue')
    add_legend()
 
    for (i in 1:16) {
        d = dive[dive$tissue_no == i,]
        p = plot_dive_basic(d)
        title(sprintf('Tissue %02d', i))
        add_legend()
    }
}

aggregate_leading_tissue <- function(dive) {
    md = aggregate(cbind(tissue_limit, tissue_gf_limit, tissue_pressure) ~ time + depth + pressure, dive, max)
    md[order(md$time),]
}

plot_cmp_dives_basic <- function(ref_dive, dive, lab1, lab2, pt=T, lwd=10, labels=T) {
    xmax = max(ref_dive$time,  dive$time) / 60
    ymax = max(ref_dive$pressure, dive$pressure)
    plot_start(dive, xmax, ymax, labels=labels)
    plot_dive_panel(ref_dive, pch=18, alpha=0.3, lwd=lwd, ps=1.2, pt=pt)
    plot_dive_panel(ref_dive, lty='dashed', lwd=1, pt=F)
    plot_dive_panel(dive, pt=pt)
}

add_legend_cmp <- function() {
    op = par(lend='butt')
    legend(
        'topright',
        c('Reference dive', 'Dive'),
        lwd=c(10, 2),
        pch=c(18, 20),
        col=c(col2alpha('blue', 0.3), 'blue'),
        bg='white',
        inset=c(0.015, 0.15),
        seg.len=1.5,
        text.width=strwidth(LEGEND_WIDTH_STR)
    )
    par(op)
}

plot_cmp_dives <- function(ref_dive, dive, lab1, lab2) {
    layout(matrix(1:16, 4, 4, byrow=T))
    op = par(mar=c(2.5, 2.5, 2, 1) + 0.1, font.main=1)
    for (i in 1:16) {
        d = dive[dive$tissue_no == i,]
        r = ref_dive[ref_dive$tissue_no == i,]
        plot_cmp_dives_basic(r, d, lab1, lab2, pt=F, lwd=5, labels=F)
        title(sprintf('Tissue %02d', i))
    }
    layout(matrix(1))
    par(op)

    ref_md = aggregate_leading_tissue(ref_dive)
    md = aggregate_leading_tissue(dive)
    plot_cmp_dives_basic(ref_md, md, lab1, lab2)
    title('Leading Tissue')
    add_legend()
    add_legend_cmp()

    for (i in 1:16) {
        d = dive[dive$tissue_no == i,]
        r = ref_dive[ref_dive$tissue_no == i,]
        plot_cmp_dives_basic(r, d, lab1, lab2)
        title(sprintf('Tissue %02d', i))
        add_legend()
        add_legend_cmp()
    }
}

args = commandArgs(trailingOnly=T)
k = length(args)

if (k == 3) {
    pdf(args[3], width=12, height=10)
    ref = read.csv(args[1])
    dive = read.csv(args[2])
    plot_cmp_dives(ref, dive, '', '')
} else if (k == 2) {
    pdf(args[2], width=12, height=10)
    dive = read.csv(args[1])
    plot_dive(dive)
} else {
    cat('usage: dt-plot [ref] dive output\n')
    quit('no', 1)
}

dev.off()
