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

#include <errno.h>
#include <string.h>

#include "s3m.h"
#include "Sequencer.h"

void removeNoprint(char *);

int
S3M_sample::load(Sequencer &seq, FILE * modFd, int sampleNo, int cutFactor,
		 void *lf, void *bf)
{
  unsigned char *buffer = (unsigned char *)bf;
  int bytesRead;
  int rc;

  sampleNum_ = sampleNo;
  ok_ = 0;
  mode_ = *((unsigned int *)lf);
  length_ = INTEL_LONG(&buffer[0x10]);

  if (length_ == 0)
      return 0;

  loopStart = INTEL_LONG(&buffer[0x14]);
  loopEnd = INTEL_LONG(&buffer[0x18]);
  volume_ = buffer[0x1c];

  if (buffer[0x1f] & 0x01)
    mode_ |= WAVE_LOOPING;

  if (buffer[0x1f] & 0x04)
    mode_ |= WAVE_16_BITS;

  baseFreq_ = INTEL_LONG(&buffer[0x20]);

  strncpy(name_, (char *)&buffer[0x30], 28);
  name_[28] = '\0';
  removeNoprint(name_);
  baseNote_ = C2FREQ;	/* Middle C */

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

  rc = seq.patchLoad(modFd, sampleNo, *this, bytesRead, cutFactor);

  if (!rc)
    ok_ = 1;
  else if (rc == -ENOSPC)
    bytesRead = -bytesRead;

  return bytesRead;
}
