
/*
**  jazz - a midi sequencer for Linux
**
**  Copyright (C) 1994-1996 Andreas Voss (andreas@avix.rhein-neckar.de)
**
**  Copyright (C) 1995-1996 Per Sigmond (Per.Sigmond@hia.no)
**
**  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.
**
**  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, write to the Free Software
**  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "wx.h"
#pragma hdrstop

#include "events.h"
#include "wx.h"

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdarg.h>



void Error(char *fmt, ...)
{
  char buf[200];
  va_list argptr;
  va_start(argptr, fmt);
  vsprintf(buf, fmt, argptr);
  va_end(argptr);
  wxMessageBox(buf, "fatal error");
  exit(1);
}



int tReadBase::Open(char *fname)
{
  if (fname == NULL)
    fd = stdin;
  else
  {
    fd = fopen(fname, "rb");
    if (fd == NULL)
      Error("Fehler beim oeffnen von %s", fname);
  }
  return 1;
}


void tReadBase::Close()
{
  if (fd != stdin)
    fclose(fd);
}




int tWriteBase::Open(char *fname, int nTracks, int TicksPerQuarter)
{
  if (fname == NULL)
    fd = stdout;
  else
  {
#ifndef VMS
#ifndef wx_msw
    FILE *testfd = fopen(fname, "r");
    if (testfd) {
	fclose( testfd );
    	char *syscmd;
    	syscmd = new char[ strlen( "cp" ) + 2*strlen( fname ) + strlen( ".backup" ) + 3 ];
    	sprintf( syscmd, "cp %s %s.backup", fname, fname );
    	if (system( syscmd ) != 0) {
		fprintf(stderr, "Could not make backup file %s.backup\n", fname );
    	}
    	delete syscmd;
    }
#endif
#endif
    fd = fopen(fname, "wb");
    if (fd == NULL)
    {
      Error("Fehler beim oeffnen von %s", fname);
      return 0;
    }
  }
  return nTracks;
}


void tWriteBase::Close()
{
  if (fd != stdout)
    fclose(fd);
}


// -------------------------------------------------------
// tGetMidiBytes
// -------------------------------------------------------

int tGetMidiBytes::Write(tEvent *e, uchar *s, int len)
{
  int Stat = e->Stat;

  switch (Stat)
  {
    case StatKeyOff:
      Stat = StatKeyOn;  // better RunningStatus
    case StatKeyOn:
    case StatAftertouch:
    case StatControl:
    case StatProgram:
    case StatMono:
    case StatPitch:
      nBytes = 0;

      Buffer[nBytes++] = Stat | ((tChannelEvent *)e)->Channel;
      while(len--)
        Buffer[nBytes++] = *s++;
      return 0;

    default:
      return 1;
  }
}

