#include <Foundation/Foundation.h>

#include "GSSoundSink.h"
#include "GSSoundSource.h"

/* for the test */
#include "AudioOutputSink.m"
#include "SndfileSource.m"

#define BUFFER_SIZE 4096

int main (int argc, char *argv[])
{
  SndfileSource *source;
  AudioOutputSink *sink;
  NSString *file;
  NSData *audioData;
  void *buffer;
  NSUInteger bytesRead;
  BOOL success = YES;
  
  if (argc > 2)
    {
      NSLog (@"Too many arguments");
      return 1;
    }
  else if (argc < 2)
    {
      NSLog (@"Too few arguments");
      return 1;
    }
  
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  
  file = [NSString stringWithCString: argv[1]];
  audioData = [[NSData alloc] initWithContentsOfMappedFile: file];
  if (!audioData)
    {
      NSLog (@"Could not open file %@", file);
      return 1;
    }
  
  source = [[SndfileSource alloc] initWithData: audioData];
  if (source == nil)
    {
      NSLog (@"Could not initialize %@", [SndfileSource class]);
      return 1;
    }
  NSLog (@"Duration: %d", [source duration]);
  sink = [[AudioOutputSink alloc] initWithEncoding: [source encoding]
                                          channels: [source channelCount]
                                        sampleRate: [source sampleRate]
                                         byteOrder: [source byteOrder]];
  if (!sink)
    {
      NSLog (@"Could not initialize %@", [AudioOutputSink class]);
      return 1;
    }
  [sink open];
  
  buffer = NSZoneMalloc (NSDefaultMallocZone(), BUFFER_SIZE);
  bytesRead = [source readBytes: buffer length: BUFFER_SIZE];
  while (bytesRead > 0 && success)
    {
      success = [sink writeBytes: buffer length: bytesRead];
      bytesRead = [source readBytes: buffer length: BUFFER_SIZE];
    }
  
  RELEASE(source);
  RELEASE(sink);
  RELEASE(audioData);
  RELEASE(file);
  RELEASE(pool);
  return 0;
}
