/***************************************************************************
                          NotesIO.cpp  -  description
                             -------------------
    begin                : Fr Feb 11 2003
    copyright            : (C) 2005 by klaus frieler
    email                : kgf@omniversum.de
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

#include "types.h"
#include "FileReader.h"
#include "Melody.h"
#include "NoteReader.h"

bool NotesIO::read(const string& inFile, Melody** ppMelody )
{
   if(!ppMelody || !m_pParam) {
      setErrorText("Internal error: Invalid pointer");
      return false;
   }
   *ppMelody = new Melody;
   if(!*ppMelody){
      setErrorText("Out of memory");
      return false;
   }
   NotesReader reader(inFile, *ppMelody);
   if(!reader.read()){
      setErrorText(reader.getErrText());
      return false;
   }
   if((*ppMelody)->size() == 0){
      setErrorText("File empty");
      return false;
   }
   (*ppMelody)->check();
   //(*ppMelody)->dump();
   (*ppMelody)->dumpStatistics();

   return true;
}

bool NotesIO::write(const string& outFile, const Melody* pMelody)
{
   char buf[1024] = "";
   bool bRet = false;
   if(!pMelody) return false;

   FILE * fp = fopen(outFile.c_str(), "w");
   if(!fp){
      setErrorText("Could not open file");
      return bRet;
   }
   double startOffset = pMelody->at(0).getTime();
   for(uint i = 0; !feof(fp) && i < pMelody->size(); ++i){
      Tone tone1 = pMelody->at(i);
      double onset = tone1.getTime();
      double offset = onset + tone1.getDuration();
      uint pitch =   tone1.getPitch();
      if(pitch == 0 || pitch>128) continue;
      uint iOnset = (uint)floor(onset-startOffset);
      uint iOffset = (uint)floor(offset-startOffset);
      sprintf(buf,"Note %d %d %d\n", iOnset, iOffset, pitch);
      fputs(buf, fp);
      if(ferror(fp)) goto out;
   }
   bRet = true;

out:
   if(!bRet)
      setErrorText("I/O error during write");
   fclose(fp);
   return bRet;

}
