#include "cs.h"
#include "midiinterop.h"

#define dv127   (FL(1.0)/FL(127.0))

void midinoteoff(MIDINOTEON *p)
{
    if (!p->h.insdshead->m_chnbp) {
      return;
    }
    *p->xkey = p->h.insdshead->m_pitch;
    *p->xvelocity = p->h.insdshead->m_veloc;
}

void midinoteonkey(MIDINOTEON *p)
{
    if (!p->h.insdshead->m_chnbp) {
      return;
    }
    *p->xkey = p->h.insdshead->m_pitch;
    *p->xvelocity = p->h.insdshead->m_veloc;
}

void midinoteoncps(MIDINOTEON *p)
{
    MYFLT octave;
    long longOctave;
    if (!p->h.insdshead->m_chnbp) {
      return;
    }
    octave = (MYFLT) (p->h.insdshead->m_pitch / FL(12.0) + FL(3.0));
    longOctave = (long)(octave * OCTRES);
    *p->xkey = (MYFLT) CPSOCTL(longOctave);
    *p->xvelocity = p->h.insdshead->m_veloc;
}

void midinoteonoct(MIDINOTEON *p)
{
    MYFLT octave;
    if (!p->h.insdshead->m_chnbp) {
      return;
    }
    octave = (MYFLT) (p->h.insdshead->m_pitch / FL(12.0) + FL(3.0));
    *p->xkey = octave;
    *p->xvelocity = p->h.insdshead->m_veloc;
}

void midinoteonpch(MIDINOTEON *p)
{
    double pitch;
    double octave;
    double integer;
    double fraction;
    if (!p->h.insdshead->m_chnbp) {
      return;
    }
    pitch = (double)p->h.insdshead->m_pitch;
    octave = pitch / 12.0 + 3.0;
    fraction = modf(octave, &integer);
    fraction *= 0.12;
    *p->xkey = (MYFLT)(integer + fraction);
    *p->xvelocity = p->h.insdshead->m_veloc;
}

void midipolyaftertouch(MIDIPOLYAFTERTOUCH *p)
{
    MYFLT scale;
    if (!p->h.insdshead->m_chnbp) {
      return;
    }
    scale = (*p->hhigh - *p->olow) * dv127;
    *p->xpolyaftertouch = *p->olow +
      p->h.insdshead->m_chnbp->polyaft[(int)*p->xcontroller] * scale;
}

void midicontrolchange(MIDICONTROLCHANGE *p)
{
    MYFLT scale;
    if (!p->h.insdshead->m_chnbp) {
      return;
    }
    scale = (*p->hhigh - *p->olow) * dv127;
    *p->xcontrollervalue =
      *p->olow + p->h.insdshead->m_chnbp->ctl_val[(int)*p->xcontroller] * scale;
}

void midiprogramchange(MIDIPROGRAMCHANGE *p)
{
    if (!p->h.insdshead->m_chnbp) {
      return;
    }
    *p->xprogram = p->h.insdshead->m_chnbp->pgmno;
}

void midichannelaftertouch(MIDICHANNELAFTERTOUCH *p)
{
    MYFLT scale;
    if (!p->h.insdshead->m_chnbp) {
      return;
    }
    scale = (*p->hhigh - *p->olow) * dv127;
    *p->xchannelaftertouch = *p->olow + p->h.insdshead->m_chnbp->aftouch * scale;
}

void midipitchbend(MIDIPITCHBEND *p)
{
    MYFLT scale;
    if (!p->h.insdshead->m_chnbp) {
      return;
    }
    scale = (*p->hhigh - *p->olow) * dv127;
    *p->xpitchbend = *p->olow + p->h.insdshead->m_chnbp->pchbend * scale;
}

void mididefault(MIDIDEFAULT *p)
{
    if (!p->h.insdshead->m_chnbp) {
      return;
    }
    *p->xvalue = *p->xdefault;
}
