/*
 * vi:set ts=4 nowrap:
 * PD is Copyright (c) 1997-2002 Miller Puckette.
 *
 * $Id: roller_plot.c,v 0.2 2002/09/24 15:01:10 rath Exp $
 *
 * Copyright 2002 Nicola Bernardini (nicb@centrotemporeale.it)
 *
 * The  pd  modules  contained herein are the result of a joint effort from
 * several authors in the context of the IST-FET Disappearing Computer pro-
 * active    project    called    SOb   (Sound   Object)   (IST-2000-25287,
 * http://www.soundobject.org)  at  the   University   of   Verona,   Italy
 * (http://www.univr.it).
 *
 * The main author of the modules is Matthias Rath (rath@sci.univr.it).
 *
 * Other authors (either writers or designers) are:
 *
 * Davide Rocchesso (rocchesso@sci.univr.it)
 * Federico Fontana (fontana@sci.univr.it)
 * Laura Ottaviani (ottavian@sci.univr.it)
 * Gianpaolo Borin (gianpaolo.borin@tin.it)
 * Federico Avanzini (avanzini@dei.unipd.it)
 * Nicola Bernardini (nicb@centrotemporeale.it)
 *
 * This file is part of the SOb PD modules.
 *
 * The  SOb  PD modules are free software; you can redistribute them and/or
 * modify them under the  terms  of  the  GNU  General  Public  License  as
 * published   by   the  Free Software  Foundation;  either  version  2  of
 * the  License, or (at your option) any later version.
 *
 * The SOb PD modules are 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 the SOb PD modules; if not, write to the Free  Software  Foundation,
 * Inc.,  59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 */

#include <stdio.h>
#include <errno.h>
#include <string.h>

#if defined(unix)
#include <unistd.h>
#endif /* defined(unix) */

#include "roller.h"

static void
_plot(FILE *plot, const t_float array[], const t_int size, const char label[])
{
	t_int i = 0;

	fprintf(plot, "plot '-' title '%s' w lines\n", label);

	for (i = 0; i < size; ++i)
		fprintf(plot, "%03d %08.6f\n", i, array[i]);

	fputs("e\n", plot);
}

static void
do_the_plots(const t_roller *r, FILE *plot)
{
	fputs("set term x11 1;\n", plot);
	_plot(plot, r->tables.sigma, r->tables.size, "sigma=f(p)");
	fputs("set term x11 2;\n", plot);
	_plot(plot, r->tables.ptilde, r->tables.size, "ptilde(t)");
}

void
roller_plot(t_roller *x)
{
#if defined(HAS_POPEN)
#	define	ERROR_STRING_SIZE	(1024)
	FILE *gnuplot = (FILE *) NULL;
	
	if ((gnuplot = popen("gnuplot -persist", "w")) != (FILE *) NULL)
	{
		do_the_plots(x, gnuplot);
		pclose(gnuplot);
	}
	else
	{
		char string[ERROR_STRING_SIZE] = "";
		strerror_r(errno, string, ERROR_STRING_SIZE);
		pd_error(x, "roller system error: %s", string);
	}
#endif /* defined(HAS_POPEN) */
}
