#ifndef _EXTRACTLYRICS_CPP_
#define _EXTRACTLYRICS_CPP_

#include <string.h>
#include <iostream.h>
#include <stdio.h>
#include <fstream.h>
#include <stdlib.h>

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

#include "extractLyrics.h"

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

// #define EXTRACTLYRICS_CONTEXT Addon::TREAT_SELECTION + Addon::TREAT_TRACK + Addon::TREAT_PART + Addon::TREAT_SONG
#define EXTRACTLYRICS_CONTEXT Addon::TREAT_PART + Addon::TREAT_TRACK + Addon::TREAT_SONG

extern "C" {
  Addon * extractLyrics(Element * target) { return new ExtractLyrics(target); }
  const char  * extractLyrics_name()     { return "lyrics"; }
  const char  * extractLyrics_category() { return "output"; }
  int     extractLyrics_context() { return EXTRACTLYRICS_CONTEXT; }
}


ExtractLyrics::ExtractLyrics(Element * target) : Addon("lyrics", target, !TO_BE_UNDONE, EXTRACTLYRICS_CONTEXT) {
  const char * filename = mainEditor->filename();
  if ((filename!=0)&&(strlen(filename)>0)) {
    char * fname = (char*) strdup(filename);
    int flen = strlen(fname);
    sprintf(fname+flen-3, "lyr");
    ofstream out(fname);
    outptr = &out;
    run();
    outptr->close();
    free(fname);
  }
}

ExtractLyrics::~ExtractLyrics() {

}

void ExtractLyrics::extract(Event * ev) {
  if (ev->isA()==NOTE) {
    Lyrics * lyr = ((Note*) ev)->lyrics();
    if (lyr!=0) {
      const char * txt = lyr->get();
      (*outptr) << txt << endl;
      int len = strlen(txt);
      if (txt[len-1]=='.' || txt[len-1]==',') (*outptr) << endl;
    }
  }
}


void ExtractLyrics::selection(Table * selection) {
}

void ExtractLyrics::part(Part * part) {
  for (Event * ev = (Event*)part->first(); ev != 0; ev = (Event*) Element::next(ev)) {
    extract(ev);
  }
  (*outptr) << endl;
}

void ExtractLyrics::track(Track * track) {
  int sz = track->size();
  (*outptr) << track->name()->getValue() << ":\n" << endl;
  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)) {
      extract(ev);
    }
  }
  (*outptr) << endl;
}

void ExtractLyrics::song(Song * song) {
  Lyrics * lyr = 0;
  (*outptr) << song->title() << ":\n" << endl;
  int sz1 = song->size();
  for (int i1=0; i1<sz1; i1++) {
    Track * tr = (Track*) song->get(i1);
    (*outptr) << tr->name()->getValue() << ":\n" << endl;

    int sz = tr->size();
    for (int i=0; i<sz; i++) {
      Part * pt = (Part*) tr->get(i);
      for (Event * ev = (Event*) pt->first(); ev != 0; ev = (Event*) Element::next(ev)) {
	extract(ev);
      }
    }

  }
  (*outptr) << endl;
}

void ExtractLyrics::undo() {
}

void ExtractLyrics::redo() {
}






#endif
