/** .SND to .MID Converter ***********************************/
/**                                                         **/
/**                      SND2MID.c                          **/
/**                                                         **/
/** This utility will convert files in .SND format to MIDI  **/
/** format.                                                 **/
/**                                                         **/
/** Copyright (C) Marat Fayzullin 1996                      **/
/**     You are not allowed to distribute this software     **/
/**     commercially. Please, notify me, if you make any    **/
/**     changes to this file.                               **/
/*************************************************************/

#include "MIDI.h"

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

/** main() ***************************************************/
/** The main function will read .SND input file, or stdin   **/
/** if none was given. It will write out an output file in  **/
/** .MID format, or write into stdout if none was given.    **/
/*************************************************************/
int main(int argc,char *argv[])
{
  int Channels,Ticks,J,I,K;
  unsigned char Buf[16];
  FILE *FI,*FO;

  if(argc>3)
  {
    fprintf(stderr,"SND2MID Converter v.1.0 by Marat Fayzullin\n");
    fprintf(stderr,"Usage: %s [file.SND [file.MID]]\n",argv[0]);
    return(1);
  }

  if(!(FI=argc<2? stdin:fopen(argv[1],"rb")))
  { fprintf(stderr,"%s: Can't open input file\n",argv[0]);return(1); }
  if(fread(Buf,1,16,FI)!=16)
  { fprintf(stderr,"%s: Can't read header\n",argv[0]);return(1); }
  if(strncmp(Buf,"SND\032",4))
  { fprintf(stderr,"%s: Input not in .SND format\n",argv[0]);return(1); }
  if(!(FO=argc<3? stdout:fopen(argv[2],"wb")))
  { fprintf(stderr,"%s: Can't open output file\n",argv[0]);return(1); }

  Channels=Buf[5];             /* Total number of channels */
  if(Channels>16) Channels=16; /* Up to 16 channels        */
  Ticks=Buf[6];                /* Tick frequency (Hz)      */

  if(!InitMIDI(FO,Channels,Ticks))
  { fprintf(stderr,"%s: Failed to initialize MIDI\n",argv[0]);return(1); }

  while((J=fgetc(FI))>=0)
    switch(J)
    {
      case 0xFF: MIDITicks(1);break;
      case 0xFD: MIDITicks(fgetc(FI));break;
      case 0xFE:
        J=fgetc(FI);I=fgetc(FI);
        if(J<Channels) SetSound(J,I);
        break;
      default:
        I=fgetc(FI);I+=fgetc(FI)*256;K=fgetc(FI);
        if(J<Channels) Sound(J,I,K);
        break;
    }

  TrashMIDI();
  fclose(FO);
  fclose(FI);
  return(0);
}
