#ifndef _QUANTIZELENGTH_CPP_
#define _QUANTIZELENGTH_CPP_

#include <iostream.h>

#include <reference.h>
#include <table.h>
#include <event.h>
#include <part.h>
#include <track.h>
#include <song.h>
#include <str.h>
#include <prMainEditor.h>

#include "quantizeLength.h"

extern Table * selectioN;
extern Table * selectionMemory;
extern PrMainEditor * mainEditor;

#define QUANTIZELENGTH_CONTEXT Addon::TREAT_SELECTION + Addon::TREAT_TRACK + Addon::TREAT_PART + Addon::TREAT_SONG

extern "C" {
  Addon * quantizeLength(Element * target) { return new QuantizeLength(target); }
  const char  * quantizeLength_name() { return "quantize length"; }
  const char  * quantizeLength_category() { return "quantize"; }
  int     quantizeLength_context() { return QUANTIZELENGTH_CONTEXT; }
}


QuantizeLength::QuantizeLength(Element * target) : Addon("quantize", target, !TO_BE_UNDONE, QUANTIZELENGTH_CONTEXT) { run(); }

QuantizeLength::~QuantizeLength() {

}

void setLength(Event * ev, int grid) {
  long foo = ev->duration();
  foo += int(0.5*grid);
  foo -= foo%grid;
  if (foo==0) foo = grid;
  ev->setDuration(foo);
}

void QuantizeLength::selection(Table * selection) {
  int grid = mainEditor->grid();
  for (Reference * r = (Reference*)selection->first(); r != 0; r = (Reference*) Element::next(r)) {
    Event * ev = (Event*) r->getValue();
    //ev->snapStart(grid);
    setLength(ev,grid);
  }
}

void QuantizeLength::part(Part * part) {
  int grid = mainEditor->grid();
  for (Event * ev = (Event*)part->first(); ev != 0; ev = (Event*) Element::next(ev)) {
    //ev->snapStart(grid);
    setLength(ev,grid);
  }
}

void QuantizeLength::track(Track * track) {
  int grid = mainEditor->grid();
  int sz = track->size();
  for (int i=0; i<sz; i++) {
    Part * pt = (Part*) track->get(i);
    for (Event * ev = (Event*) pt->first(); ev != 0; ev = (Event*) Element::next(ev)) {
      //ev->snapStart(grid);
      setLength(ev,grid);
    }
  }
}

void QuantizeLength::song(Song * song) {
  int grid = mainEditor->grid();
  int szs = song->size();
  for (int i=0; i<szs; i++) {
    Track * track = (Track*) song->get(i);
    int sz = track->size();
    for (int i=0; i<sz; i++) {
      Part * pt = (Part*) track->get(i);
      for (Event * ev = (Event*) pt->first(); ev != 0; ev = (Event*) Element::next(ev)) {
	//ev->snapStart(grid);
	setLength(ev,grid);
      }
    }
  }
}

void QuantizeLength::undo() {
}

void QuantizeLength::redo() {
}






#endif
