// ----------------------------------------------------------------------------
//
//  Copyright (C) 2010-2017 Fons Adriaensen <fons@linuxaudio.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/>.
//
// ----------------------------------------------------------------------------


#include <math.h>
#include "gmeter.h"


XImage  *Gmeter::_scale = 0;
XImage  *Gmeter::_imag0 = 0;
XImage  *Gmeter::_imag1 = 0;


Gmeter::Gmeter (X_window *parent, int xpos, int ypos) :
    X_window (parent, xpos, ypos, XS, YS, 0),
    _k0 (86),
    _k1 (86)
{
    if (!_imag0 || !_imag1 || !_scale) return;
    x_add_events (ExposureMask);
    XPutImage (dpy (), win (), dgc (), _imag0, 0, 0, 0, YM, XS, DY); 
}


Gmeter::~Gmeter (void)
{
}


void Gmeter::handle_event (XEvent *E)
{
    switch (E->type)
    {
    case Expose:
	expose ((XExposeEvent *) E);
	break;  
    }
}


void Gmeter::expose (XExposeEvent *E)
{
    if (E->count) return;
    XSetFunction (dpy (), dgc (), GXcopy);
    XPutImage (dpy (), win (), dgc (), _scale,  0, 0,  0,  0, XS, YM); 
    XPutImage (dpy (), win (), dgc (), _imag0,  0, 0,  0, YM, XS, DY); 
    XPutImage (dpy (), win (), dgc (), _imag1,  _k0 - 1, 0, _k0 - 1, YM, 3 + _k1 - _k0, DY); 
}

#include <stdio.h>
void Gmeter::update (float v0, float v1)
{
    int k0, k1;

     k0 = (int)(floorf (86.5f + 4.0f * v0));
     k1 = (int)(floorf (86.5f + 4.0f * v1));
     if (k0 < 6) k0 = 6;
     if (k0 > 246) k0 = 246;
     if (k1 < 6) k1 = 6;
     if (k1 > 246) k1 = 246;
     XSetFunction (dpy (), dgc (), GXcopy);
     XPutImage (dpy (), win (), dgc (), _imag0,  _k0 - 1, 0, _k0 - 1, YM, 3 + _k1 - _k0, DY); 
     _k0 = k0;
     _k1 = k1;
     XPutImage (dpy (), win (), dgc (), _imag1,  _k0 - 1, 0, _k0 - 1, YM, 3 + _k1 - _k0, DY); 
}


