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

#include <string.h>

#include "mtm.h"
#include "Sequencer.h"

void removeNoprint(char *);

int
MTM_sample::load (Sequencer &seq, FILE * modFd, int sampleNo, int cutFactor,
		  void *header, void *)
{
#define MTM_ATTRIBUTE_16BIT 1
  int bytesRead;
  unsigned char *buf = (unsigned char *)header;

  sampleNum_ = sampleNo;
  mode_ = WAVE_UNSIGNED;
  ok_ = 0;
  memcpy(name_, buf, 22);
  name_[22] = '\0';
  removeNoprint(name_);

  length_ = INTEL_LONG(buf + 22);
  loopStart = INTEL_LONG(buf + 26);
  loopEnd = INTEL_LONG(buf + 30);
  finetune_ = *(buf + 34) & 0x0f;

  if (finetune_ <= 7)
    finetune_ *= 12.5;
  else
    finetune_ = (short)(12.5 * (finetune_ - 16));

  volume_ = *(buf + 35);

  if (volume_ > 0)
    volume_ = volume_ * 4 - 1;

  if (*(buf + 36) & MTM_ATTRIBUTE_16BIT)
    mode_ |= WAVE_16_BITS;

  /* found a mod with lots of samples with loopEnds of 2.  played fine
       * without them.  should I check that here?
       */
  if (loopEnd > 2)
    mode_ |= WAVE_LOOPING;
#if 0
  else
    loopEnd = loopStart = 0;
#endif

  baseNote_ = C2FREQ;	/* was 261630 - Middle C */
  baseFreq_ = NTSC_RATE;

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

  return bytesRead;
}
