/******************************************************************************
Copyright (C) 2009 Matteo Lucarelli

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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
******************************************************************************/

// Widget to plot simple (but fast) bar graph
// Use notes are in header file

#include "Fl_BarPlot.h"

Fl_BarPlot::Fl_BarPlot(int X, int Y, int W, int H) : Fl_Box(X,Y,W,H) 
{
	m_bgColor=FL_WHITE;
	m_barColor=FL_BLACK;
	
	m_barCount=0;
	m_barMin=0;
	m_barMax=100;
	
	m_barVal=NULL;
	
	m_NotchDistance=0;
}

Fl_BarPlot::~Fl_BarPlot()
{
	if (m_barVal) delete [] m_barVal;
}

void Fl_BarPlot::setBgColor(Fl_Color val)
{
	m_bgColor=val;
}

void Fl_BarPlot::setBarColor(Fl_Color val)
{
	m_barColor=val;
}

void Fl_BarPlot::setBars(int count,float minVal,float maxVal)
{
	if (m_barVal) delete [] m_barVal;
	
	m_barVal=new float[count];
	
	m_barCount=count;
	m_barMin=minVal;
	m_barMax=maxVal;
}

void Fl_BarPlot::setBarVal(int index, float val)
{
	if (index>=m_barCount) return;
	m_barVal[index]=val;
	redraw();
}

float Fl_BarPlot::getBarVal(int index)
{
	if (index>=m_barCount) return 0;
	return m_barVal[index];
}

void Fl_BarPlot::setNotch(float distance,int thick)
{
	m_NotchDistance=distance;
	m_NotchThick=thick;
}

void Fl_BarPlot::draw() 
{
	int i,H;
	
	fl_push_clip(x(),y(),w(),h());
	
	// background
	fl_color(m_bgColor);
	fl_rectf(x(),y(),w(),h());
	
	// bars
	float S=(float)w()/m_barCount;
	for (i=0;i<m_barCount;i++){
		
		H=(int)((m_barVal[i]-m_barMin)/(m_barMax-m_barMin)*h()+0.5);
		
		fl_color(m_barColor);
		if (S>=1) fl_rectf((int)(S*i+x()),h()-H+y(),(int)S,H);
		else fl_line((int)(S*i+x()),h()-H+y(),(int)(S*i+x()),h()+y());
		
		if (S>=3){
			fl_color(m_bgColor);
			fl_rect((int)(S*i+x()),h()-H+y(),(int)S,H);
		}
	}
	
	// notch
	if (m_NotchDistance!=0){
	
		float p;
		float ndPix=(float)h()*m_NotchDistance/(m_barMax-m_barMin);
		
		fl_color(m_bgColor);
		for (p=h()+y()-ndPix;p>y();p-=ndPix){
			fl_rectf(x(),(int)p,w(),m_NotchThick);
		}
	}

	fl_pop_clip();
}