#!/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/>.
#

suppressPackageStartupMessages(library(ggplot2))

plot_start <- function (dive, xmax, ymax) {
#        guides(colour=guide_legend(override.aes=list(colour='black'))) +
    p = ggplot(NULL, aes(x=time / 60)) +
        xlim(0, xmax) +
        ylim(0, ymax) +
        scale_color_manual(
            name='Legend',
            values=c('blue', 'black', 'orange', 'red'),
            labels=c('absolute pressure', 'pressure', 'gf pressure limit', 'pressure limit')) +
        xlab('Time [min]') +
        ylab('Pressure [Bar]') +
        theme_bw()
    p
}

aes_now <- function(...) {
  structure(list(...),  class = "uneval")
}


plot_dive_panel <- function(dive, lty='solid', pch=20, alpha=1, lwd=1, ps=2, points=T) {
    if (points)
        pt = geom_point(data=dive, aes(y=pressure), col='blue', size=ps, alpha=alpha, shape=pch)
    else
        pt = NULL

    p = list(
        pt,
        geom_line(data=dive, aes(y=tissue_pressure), col='black', linetype=lty, size=lwd, alpha=alpha),
        geom_line(data=dive, aes(y=tissue_gf_limit), col='orange', linetype=lty, size=lwd, alpha=alpha),
        geom_line(data=dive, aes(y=tissue_limit), col='red', linetype=lty, size=lwd, alpha=alpha),
        geom_line(data=dive, aes(y=pressure), col='blue', linetype=lty, size=lwd, alpha=alpha)
    )
    p
}

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

plot_dive <- function(dive) {
    p = plot_dive_basic(dive, points=F) + facet_wrap(~tissue_no)
    print(p)

    md = aggregate_leading_tissue(dive)
    p = plot_dive_basic(md) + ggtitle('Leading Tissue')
    print(p)

    for (i in 1:16) {
        d = dive[dive$tissue_no == i,]
        p = plot_dive_basic(d) + ggtitle(sprintf('Tissue %02d', i))
        print(p)
    }
}

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, points=T) {
    p1 = plot_dive_panel(ref_dive, pch=18, alpha=0.3, lwd=4, ps=6, points=points)
    p2 = plot_dive_panel(ref_dive, lty='dashed', lwd=0.5, points=points)
    p3 = plot_dive_panel(dive, ps=3, points=points)

    xmax = max(ref_dive$time / 60, dive$time / 60)
    ymax = max(ref_dive$pressure, dive$pressure)
    p = plot_start(dive, xmax, ymax) + p1 + p2 + p3 +
        scale_linetype(
            name='',
            labels=c(lab1, lab2))

    p
}

plot_cmp_dives <- function(ref_dive, dive, lab1, lab2) {
    p = plot_cmp_dives_basic(ref_dive, dive, lab1, lab2, points=F) + facet_wrap(~tissue_no)
    print(p)

    ref_md = aggregate_leading_tissue(ref_dive)
    md = aggregate_leading_tissue(dive)
    p = plot_cmp_dives_basic(ref_md, md, lab1, lab2) + ggtitle('Leading Tissue')
    print(p)

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

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()
