/*-------------- Telecommunications & Signal Processing Lab ---------------
                             McGill University

Routine:
  int AFwrF8 (AFILE *AFp, const float Fbuff[], int Nval)

Purpose:
  Write 64-bit float data to an audio file (float input values)

Description:
  This routine writes a specified number of 64-bit float samples to an audio
  file.  The input to this routine is a buffer of float values.

Parameters:
  <-  int AFwrF8
      Number of samples written.  If this value is less than Nval, an error
      has occurred.
   -> AFILE *AFp
      Audio file pointer for an audio file opened by AFopenWrite
   -> const float Fbuff[]
      Array of floats with the samples to be written
   -> int Nval
      Number of samples to be written

Author / revision:
  P. Kabal  Copyright (C) 1997
  $Revision: 1.10 $  $Date: 1997/10/15 13:45:13 $

-------------------------------------------------------------------------*/

static char rcsid [] = "$Id: AFwrF8.c 1.10 1997/10/15 libtsp-v3r0 $";

#include <libtsp/AFdataio.h>
#include <libtsp/Xstdio.h>
#include <libtsp/AFpar.h>
#include <libtsp/UTtypes.h>

#define LW		FDL_FLOAT64
#define MINV(a, b)	(((a) < (b)) ? (a) : (b))
#define NBBUF		8192

#define FWRITE(buf,size,nv,fp)	(int) fwrite ((const char *) buf, \
					      (size_t) size, (size_t) nv, fp)


int
AFwrF8 (AFp, Fbuff, Nval)

     AFILE *AFp;
     const float Fbuff[];
     int Nval;

{
  int is, N, Nw, i;
  double8_t Buf[NBBUF/LW];
  double8_t *B;
  unsigned char *cp;
  unsigned char t;

/* Write data to the audio file */
  is = 0;
  while (is < Nval) {
    N = MINV (NBBUF / LW, Nval - is);
    B = Buf;
    for (i = 0; i < N; ++i) {
      *B = AFp->ScaleF * Fbuff[i+is];
      if (AFp->Swapb == DS_SWAP) {
	cp = (unsigned char *) B;
	t = cp[7]; cp[7] = cp[0]; cp[0] = t;
	t = cp[6]; cp[6] = cp[1]; cp[1] = t;
	t = cp[5]; cp[5] = cp[2]; cp[2] = t;
	t = cp[4]; cp[4] = cp[3]; cp[3] = t;
      }
      ++B;
    }
    Nw = FWRITE (Buf, LW, N, AFp->fp);
    is += Nw;
    if (Nw < N)
      break;
  }

  return is;
}
