/*
 * Copyright (C) 2013-2015, Gaetan Bisson <bisson@archlinux.org>.
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
 * Decox. Decreasing continuous exponentials; toy decompression planner.
 *
 * Decox merely aims to give its author a better understanding of the behavior
 * of decreasing exponentials in the context of Haldanian decompression models.
 * The original idea to eventually model tissue compartments by continuous
 * functions was never implemented, but the name stuck anyway. Early versions
 * (numbered 0 to 9) were written in PARI/GP; standard C is used from 1.0 on.
 * 
 * Units are bars, liters, meters and minutes.
 *
 * WARNING: Any fitness of this software for actual dive planning is entirely
 * coincidental. This has never been the author's goal and he has taken no care
 * in this respect. You must be fully aware that diving safely requires proper
 * training and a thorough understanding of the limitations of your gear and
 * tools, including this piece of code.
 *
 * Compile with:
 *
 *   cc -O2 -lm -o decox decox.c
 */


/* ****************************************************************************
 *
 * HEADERS
 *
 */


#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>


/* ****************************************************************************
 *
 * FANCY STRUCTURES
 *
 */


/* We use static arrays of predefined lengths; increase if needed. */
#define ZHL_N 16
#define MAX 99

/* We store gases as a closed circuit setpoint (zero for open circuit mixes)
 * and fractions of oxygen, nitrogen, and helium; though this is not enforced,
 * those fractions are expected to add up to 100%. Any gas with ox==0 is
 * considered invalid. */
typedef struct {
	double sp; /* closed circuit setpoint */
	double ox; /* fraction of oxygen */
	double ni; /* fraction of nitrogen */
	double he; /* fraction of helium */
} gas_t;

/* Tissue compartment are defined by their gas tension, half-time, and m-value.
 * Separate series of compartments are to be used for every inert gas. */
typedef struct {
	double tn; /* current tension */
        double ht; /* half-time */
        double m0; /* m-value */
        double md; /* m-value */
} comp_t;

/* We store a diver's current runtime through the dive, oxygen toxicy exposure
 * levels (CNS and OTU), inert gas compartments (nitrogen and helium), and open
 * circuit gas consumption. */
typedef struct {
	double run; /* dive runtime */
	double cns; /* CNS fraction */
	double otu; /* OTU level */
	comp_t ni[ZHL_N]; /* compartments for nitrogen */
	comp_t he[ZHL_N]; /* compartments for helium */
	gas_t gas[MAX]; /* open circuit gases used */
	double vol[MAX]; /* corresponding volumes */
} diver_t;

/* A dive segment exposes the diver to a gas at a depth for a time. */
typedef struct {
	double depth;
	double time;
	gas_t gas;
} segment_t;


/* ****************************************************************************
 *
 * GLOBAL PHYSICAL CONSTANTS
 *
 */


/* infinity for physicists */
static const double INFTY = 999999999;

/* time step for discretization */
static const double step = 0.01;

/* surface air consumption */
static const double sac = 15;

/* safe ascent rate */
static const double rate = 9;

/* atmosphere pressure */
static const double atm = 1.013;

/* saltwater density */
static const double density = 1.03;

/* ambient pressure at depth */
static double pressure (double depth) {
	return atm+density*depth/10;
}

/* inert gas compartments' half-time and m-value from ZH-L16B */
static const double zhl_ni_ht[] = {5, 8, 12.5, 18.5, 27, 38.3, 54.3, 77, 109, 146, 187, 239, 305, 390, 498, 635};
static const double zhl_ni_m0[] = {29.6, 25.4, 22.5, 20.3, 19.0, 17.5, 16.5, 15.7, 15.2, 14.6, 14.2, 13.9, 13.4, 13.2, 12.9, 12.7};
static const double zhl_ni_md[] = {1.7928, 1.5352, 1.3847, 1.2780, 1.2306, 1.1857, 1.1504, 1.1223, 1.0999, 1.0844, 1.0731, 1.0635, 1.0552, 1.0478, 1.0414, 1.0359};
static const double zhl_he_ht[] = {1.88, 3.02, 4.72, 6.99, 10.21, 14.48, 20.53, 29.11, 41.20, 55.19, 70.69, 90.34, 115.29, 147.42, 188.24, 240.03};
static const double zhl_he_m0[] = {37.2, 31.2, 27.2, 24.3, 22.4, 20.8, 19.4, 18.2, 17.4, 16.8, 16.4, 16.2, 16.1, 16.1, 16.0, 15.9};
static const double zhl_he_md[] = {2.0964, 1.7400, 1.5321, 1.3845, 1.3189, 1.2568, 1.2079, 1.1692, 1.1419, 1.1232, 1.1115, 1.1022, 1.0963, 1.0904, 1.0850, 1.0791};

/* gradient factor coefficients and pressure points */
static const double gf1c = 0.3;
static const double gf2c = 0.9;
static const double gf1p = 7;
static const double gf2p = 1;

/* rough maximum operating depth */
static double mod (gas_t gas) {
	if (gas.sp) return INFTY;
	return 16 / gas.ox - 10;
}

/* CNS toxicity exposure limit */
static double cns_limit (double ox) {
	if (ox<0.5) return INFTY;
	if (ox<0.6) return 1800 - 1800 * ox;
	if (ox<0.7) return 1620 - 1500 * ox;
	if (ox<0.8) return 1410 - 1200 * ox;
	if (ox<0.9) return 1170 - 900 * ox;
	if (ox<1.1) return 900 - 600 * ox;
	if (ox<1.5) return 570 - 300 * ox;
	if (ox<1.66) return 1245 - 750 * ox;
	return 1;
}

/* run-of-the-mill air */
static const gas_t air = {
	.sp = 0,
	.ox = 0.21,
	.ni = 0.79,
	.he = 0,
};


/* ****************************************************************************
 *
 * WORKING WITH GASES
 *
 */


/* test if two gases are the same */
static int gas_same (gas_t a, gas_t b) {
	return a.sp==b.sp && a.ox==b.ox && a.ni==b.ni && a.he==b.he;
}

/* convert from gas label to gas_t */
static gas_t gas_parse (char *str) {
	gas_t gas = {
		.sp = 0,
		.ox = 1,
		.ni = 1,
		.he = 1,
	};
	if (!strncasecmp(str,"SP=",3)) {
		char *t = str; while (*t!=',') t++; *t = '\0';
		gas.sp = atof(str + 3);
		str = t + 1;
	}
	if (!strncasecmp(str,"AIR",3)) {
		gas.ox = 0.21;
		gas.ni = 0.79;
		gas.he = 0;
	}
	if (!strncasecmp(str,"Nx",2)) {
		gas.ox = atof(str + 2) / 100;
		gas.ni = 1 - gas.ox;
		gas.he = 0;
	}
	if (!strncasecmp(str,"Tx",2)) {
		char *t = str; while (*t!='/') t++; *t = '\0';
		gas.ox = atof(str + 2) / 100;
		gas.he = atof(t + 1) / 100;
		gas.ni = 1 - gas.ox - gas.he;
	}
	return gas;
}

/* holder for current gas */
static gas_t cur;

/* holder for current gas label */
static char str[MAX];

/* set gas label from gas_t */
static void gas_str (gas_t gas) {
	if (gas_same(cur,gas)) {
		sprintf(str, "");
		return;
	}
	cur = gas;
	int cc = 0;
	if (gas.sp) {
		sprintf(str, "SP=%04.2f,", gas.sp);
		cc = 8;
	}
	if (gas.he) sprintf(str+cc, "Tx%02.0f/%02.0f", gas.ox * 100, gas.he * 100);
	else if (gas.ni==0.79) sprintf(str+cc, "AIR");
	else sprintf(str+cc, "Nx%02.0f", gas.ox * 100);
}

/* partial pressure of nitrogen in gas at given absolute pressure */
static double nitrogen (gas_t gas, double pressure) {
	if (gas.sp) return fmax(0, pressure - gas.sp) * (gas.ni / (gas.ni + gas.he));
	return gas.ni * pressure;
}

/* partial pressure of helium in gas at given absolute pressure */
static double helium (gas_t gas, double pressure) {
	if (gas.sp) return fmax(0, pressure - gas.sp) * (gas.he / (gas.ni + gas.he));
	return gas.he * pressure;
}

/* partial pressure of oxygen in gas at given absolute pressure */
static double oxygen (gas_t gas, double pressure) {
	if (gas.sp) return fmin(gas.sp, pressure);
	return gas.ox * pressure;
}


/* ****************************************************************************
 *
 * DECOMPRESSION FUNCTIONS AND CONSTANTS
 *
 */


/* gradient factor at ambiant ressure */
static double gf (double pressure) {
	double r = (gf1c * (gf2p - pressure) - gf2c * (gf1p - pressure)) / (gf2p - gf1p);
	return r<gf1c ? gf1c : r;
}

/* m-value for compartment at pressure */
static double mval (double pressure, comp_t comp) {
        return pressure + gf(pressure) * (comp.m0 / 10 + comp.md * (pressure - 1) - pressure);
}

/* freshly rested diver */
static void afresh (diver_t *diver) {
	int i;
	diver->run = 0;
	diver->cns = 0;
	diver->otu = 0;
	for (i=0;i<ZHL_N;i++) {
		diver->ni[i].tn = nitrogen(air, atm);
		diver->ni[i].ht = zhl_ni_ht[i];
		diver->ni[i].m0 = zhl_ni_m0[i];
		diver->ni[i].md = zhl_ni_md[i];
		diver->he[i].tn = helium(air, atm);
		diver->he[i].ht = zhl_he_ht[i];
		diver->he[i].m0 = zhl_he_m0[i];
		diver->he[i].md = zhl_he_md[i];
	}
	for (i=0;i<MAX;i++) {
		diver->gas[i].ox = 0;
		diver->vol[i] = 0;
	}
}

/* update compartments after time breathing gas at pressure */
static void tension (diver_t *diver, double time, gas_t gas, double pressure) {
	int i;
	double ni = nitrogen(gas, pressure);
	double he = helium(gas, pressure);
	for (i=0;i<ZHL_N;i++) {
		diver->ni[i].tn = ni + (diver->ni[i].tn - ni) * pow(0.5, time / diver->ni[i].ht);
		diver->he[i].tn = he + (diver->he[i].tn - he) * pow(0.5, time / diver->he[i].ht);
	}
}

/* expose diver to depth for time breahting gas */
static void expose (diver_t *diver, double depth, double time, gas_t gas) {
	int i;
	double p = pressure(depth);
	double ox = oxygen(gas, p);
	tension(diver, time, gas, p);
	diver->run += time;
	if (ox>0.5) {
		diver->cns += time / cns_limit(ox);
		diver->otu += time * pow(2 * ox - 1, 5 / 6);
	}
	if (!gas.sp) {
		for (i=0;i<MAX;i++) if (!diver->gas[i].ox || gas_same(gas,diver->gas[i])) break;
		diver->gas[i] = gas;
		diver->vol[i] += time * sac * p;
	}
}

/* time breathing pp until any compartment greater than lim */
static double time2any (comp_t *comp, double pp, comp_t *lim) {
	int i;
	double t = INFTY;
	for (i=0;i<ZHL_N;i++) {
		double q = (pp - comp[i].tn) / (pp - lim[i].tn);
		if (q>0) t = fmin(t, comp[i].ht * log(q) / log(2));
		else if (pp>lim[i].tn) return 0;
		else if (pp<lim[i].tn) continue;
	}
	return t;
}

/* time breathing pp until all compartments smaller than lim */
static double time2all (comp_t *comp, double pp, comp_t *lim) {
	int i;
	double t = 0;
	for (i=0;i<ZHL_N;i++) {
		double q = (pp - comp[i].tn) / (pp - lim[i].tn);
		if (q>0) t = fmax(t, comp[i].ht * log(q) / log(2));
		else if (pp>lim[i].tn) return INFTY;
		else if (pp<lim[i].tn) continue;
	}
	return t;
}

/* time at sea level before 0.7 atm allowable */
static double nofly (diver_t *diver) {
	int i;
	comp_t cabin_ni[ZHL_N];
	comp_t cabin_he[ZHL_N];
	for (i=0;i<ZHL_N;i++) cabin_ni[i].tn = mval(0.7 * atm, diver->ni[i]);
	for (i=0;i<ZHL_N;i++) cabin_he[i].tn = mval(0.7 * atm, diver->he[i]);
	double ni = time2all(diver->ni, nitrogen(air, atm), cabin_ni);
	double he = time2all(diver->he, helium(air, atm), cabin_he);
	return fmax(ni, he);
}

/* time at sea level before complete desaturation */
static double desat (diver_t *diver) {
	int i;
	comp_t fresh_ni[ZHL_N];
	comp_t fresh_he[ZHL_N];
	for (i=0;i<ZHL_N;i++) fresh_ni[i].tn = 0.01 + nitrogen(air, atm);
	for (i=0;i<ZHL_N;i++) fresh_he[i].tn = 0.01 + helium(air, atm);
	double ni = time2all(diver->ni, nitrogen(air, atm), fresh_ni);
	double he = time2all(diver->he, helium(air, atm), fresh_he);
	return fmax(ni, he);
}

/* time at depth "from" until direct ascent to "to" allowable */
static double time2asc (diver_t *diver, double from, double to, gas_t gas) {
	int i;
	diver_t worst;
	afresh(&worst);
	for (i=0;i<ZHL_N;i++) worst.ni[i].tn = INFTY;
	for (i=0;i<ZHL_N;i++) worst.he[i].tn = INFTY;
	double depth = to;
	double p;
	while (depth<from) {
		p = pressure(depth);
		for (i=0;i<ZHL_N;i++) worst.ni[i].tn = fmin(worst.ni[i].tn, mval(pressure(depth), diver->ni[i]));
		for (i=0;i<ZHL_N;i++) worst.he[i].tn = fmin(worst.he[i].tn, mval(pressure(depth), diver->he[i]));
		tension(&worst, -step, gas, p);
		depth += step * rate;
	}
	p = pressure(from);
	double stop_ni = time2all(diver->ni, nitrogen(gas, p), worst.ni);
	double stay_ni = time2any(diver->ni, nitrogen(gas, p), worst.ni);
	double stop_he = time2all(diver->he, helium(gas, p), worst.he);
	double stay_he = time2any(diver->he, helium(gas, p), worst.he);
	double stop = fmax(stop_ni, stop_he);
	double stay = fmin(stay_ni, stay_he);
	if (stop>0) return stop;
	if (stay>0) return -stay;
	return -INFTY;
}

/* decompression schedule segment from depth "from" to "to" */
static void segment (diver_t *diver, double from, double to, gas_t gas) {
	double depth = from;
	while (depth>to) {
		double next = fmax(floor((depth - 1) / 3) * 3, to);
		double time = ceil(time2asc(diver, depth, next, gas));
		if (time>0) {
			expose(diver, depth, time, gas);
			printf("Stop at %2.0fm for %2.0f' (%3.0f)\n",depth,time,diver->run);
		}
		while (depth>next) {
			expose(diver, depth, step, gas);
			depth -= step * rate;
		}
		depth = next;
	}
}

/* no decompression limit breathing gas at depth */
static double ndl (gas_t gas, double depth) {
	diver_t diver;
	afresh(&diver);
	return fmax(0, -time2asc(&diver, depth, 0, gas));
}

/* print global dive volumes and toxicity levels */
static void summary (diver_t *diver) {
	gas_t *g = diver->gas;
	double *v = diver->vol;
	printf("---------------------------------\n");
	cur.ox = 0;
	while (g->ox) {
		gas_str(*g);
		printf("Used %4.0fL == %3.0fb of 12L %s\n", ceil(*v), ceil(*v / 12), str);
		g++;
		v++;
	}
	printf("CNS: %4.0f/100\n", diver->cns * 100);
	printf("OTU: %4.0f/300\n", diver->otu);
}

/* full decompression schedule from depth using gases */
static void deco (diver_t *diver, double depth, gas_t *bailout) {
	while (bailout->ox) {
		gas_t gas = bailout[0];
		double next = bailout[1].ox ? floor(mod(bailout[1])/3)*3 : 0;
		if (next<depth) {
			if (mod(gas)<depth) printf("==> Unsuitable bailout.\n");
			gas_str(gas);
			printf("Up from %2.0fm         (%3.0f) %s\n", depth, diver->run, str);
			segment(diver, depth, next, gas);
			depth = next;
		}
		bailout++;
	}
	if (depth) printf("==> No bailout.\n");
	summary(diver);
}

/* full decompression plan for bottom using bailout */
static void plan (segment_t *bottom, gas_t *bailout) {
	diver_t diver;
	afresh(&diver);
	double last = 0;
	while (bottom->time) {
		double depth = bottom->depth;
		double time = bottom->time;
		gas_t gas = bottom->gas;
		if (last) segment(&diver, last, depth, gas);
		expose(&diver, depth, time, gas);
		gas_str(gas);
		printf("Stay at %2.0fm for %2.0f' (%3.0f) %s\n", depth, time, diver.run, str);
		last = depth;
		bottom++;
	}
	deco(&diver, last, bailout);
}


/* ****************************************************************************
 *
 * MAIN
 *
 * Parse arguments into bottom/gases arrays; compute deco plan.
 */


#define ABOUT "\
Decox. Decreasing continuous exponentials; toy decompression planner.\n\
Copyright (C) 2013-2015, Gaetan Bisson. All rights reserved.\n\
Version 1.2; compiled "__DATE__".\n\
\n\
Usage: %s [depth time gas] ... [bailout] ...\n\
"

int main (int argc, char *argv[]) {
	segment_t bottom[MAX];
	gas_t bailout[MAX];
	int i;

	if (argc<4) {
		printf(ABOUT, argv[0]);
		return 1;
	}
	argv++;

	i = 0;
	while (*argv && *argv[0]<64) {
		bottom[i].depth = atof(argv[0]);
		bottom[i].time = atof(argv[1]);
		bottom[i].gas = gas_parse(argv[2]);
		argv += 3;
		i++;
	}

	i = 0;
	while (*argv) {
		bailout[i] = gas_parse(*argv);
		argv++;
		i++;
	}

	plan(bottom, bailout);
}
