// -*-C++-*-
// This file is part of the gmod package
// Copyright (C) 1997 by Andrew J. Robinson

#include "ult.h"
#include "Sequencer.h"

void removeNoprint(char *);

int
ULT_sample::load(Sequencer &seq, FILE * modFd, int sampleNo, int cutFactor,
		 void *header, void *version)
{
#define SAMP_16BIT      4
#define SAMP_LOOP       8
#define SAMP_REVERSE    16
  int bytesRead = 0;
  unsigned char *buf = (unsigned char *)header;
  int loop = 0;

  sampleNum_ = sampleNo;
  mode_ = 0;

  memcpy(name_, buf, 32);
  name_[32] = 0;
  removeNoprint(name_);

  loopStart = INTEL_LONG(buf + 44);
  loopEnd = INTEL_LONG(buf + 48);
  loop = BYTE(buf + 61);
  volume_ = BYTE(buf + 60);

  if (*((int *)version) >= 4)
    {
      baseFreq_ = (unsigned short) (INTEL_SHORT (buf + 62));
      //s.finetune = (signed short)(INTEL_SHORT(buf + 64));
    }
  else
    {
      baseFreq_ = NTSC_RATE;
      //s.finetune = (signed short)(INTEL_SHORT(buf + 62));
    }

  /* calculate length in "samples" and turn it into bytes */
  length_ = INTEL_LONG(buf + 56) - INTEL_LONG(buf + 52);

  if (loop & SAMP_16BIT)
    length_ *= 2;

  if (loop & SAMP_16BIT)
    mode_ |= WAVE_16_BITS;
  if (loop & SAMP_LOOP)
    mode_ |= WAVE_LOOPING;
  if (loop & SAMP_REVERSE)
    mode_ |= WAVE_BIDIR_LOOP;

  baseNote_ = C2FREQ;

 if (length_ > 0)
   ok_ = !seq.patchLoad(modFd, sampleNo, *this, bytesRead, cutFactor);
 else
   ok_ = 0;

  return bytesRead;
}
