/*
    yamm, Yet Another Micro Monitor
    graph.c
    Copyright (C) 1994, 1995  Riccardo Facchetti

    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 2 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, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#if !defined(NO_CURSES)

#include <memory.h>
#if !defined(NCURSES)
#include <curses.h>
#else
#include "ncurses.h"
#endif /* !NCURSES */
#include "yamm.h"

#define PF printw
#define START	4
#define END		1
#define POINTS	(LINES-START-END-1)
#define HIST	COLS
#define HISTARR	512
#define DECLINE "================================================================================"
#define ALFLINE "--------------------------------------------------------------------------------"

static float bar_hist[HISTARR];
static int last = 0;
static void PrintBar(void);
static void CleanDisp(void);

void ShowLoadGraph( struct pst_dynamic *dinfo ) {
	if (last == HIST) {
		ResetHist();
		CleanDisp();
	}
	bar_hist[last++] = dinfo->psd_avg_1_min;
	PrintBar();
}

void ResetHist (void) {
	last = 0;
	memset(bar_hist, 0, HISTARR * sizeof(float));
}

static void PrintBar(void) {
	int i, j;
	float max=0;
	int intmax=0, oldintmax=0;

	for (i=0; i<HIST; i++)
		if (max < bar_hist[i])
			max = bar_hist[i];

	oldintmax = intmax;

	if (max < 100)
		intmax = 100;
	if (max < 20)
		intmax = 20;
	if (max < 10)
		intmax = 10;
	if (max < 4)
		intmax = 4;
	if (max < 2)
		intmax = 2;
	if (max < 1)
		intmax = 1;

	if (max == 0)
		return;

/*
 * Display has scaled, reset (clean) it
 */
	if (oldintmax != intmax)
		CleanDisp();

	for (i=0; i<=intmax; i+=intmax/2) {
		if (intmax == 1) {
			move(START+POINTS-9, 0);
			PF(ALFLINE);
			move(START+POINTS-19, 0);
			PF(DECLINE);
			break;
		}
		if (i==0)
			continue;
		move(START+POINTS-(POINTS*i)/intmax, 0);
		if (i%intmax)
			PF(ALFLINE);
		else
			PF(DECLINE);
	}

	for (i=0; i<=last; i++)
		for (j=0; j<((int)((float)POINTS*bar_hist[i]/(float)intmax)); j++) {
			move (START+POINTS-j, i);
			PF("%c", '*');
		}

	curses_refresh();
}

static void CleanDisp(void) {
	int i, j;

	for (i=0; i<COLS; i++)
		for (j=0; j<POINTS; j++) {
			move(START+POINTS-j, i);
			PF("%c", ' ');
		}
}
#endif /* !NO_CURSES */
