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

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

#include "mod.h"
#include "Sequencer.h"

void removeNoprint(char *);

int
MOD_sample::load(Sequencer &seq, FILE * modFd, int sampleNo, int cutFactor,
		 void *header, void *pf)
{
  int bytesRead = 0;
  int rc = -EINVAL;
  unsigned char ntscflag = *((unsigned char *)pf);
  unsigned char *buf = (unsigned char *)header;

  sampleNum_ = sampleNo;
  length_ = REV_SHORT(buf + 22) * 2;
  loopStart = REV_SHORT(buf + 26) * 2;
  loopEnd = loopStart + (REV_SHORT(buf + 28) * 2);

#if 0
  if (loopStart > length_)
    loopStart = 0;

  if (loopEnd <= loopStart)
    loopEnd = loopStart + 2;
#endif
  ok_ = 0;

  if (loopEnd > 2)
    mode_ = WAVE_LOOPING;
  else
    mode_ = 0;

  strncpy(name_, buf, 22);
  name_[22] = '\0';
  removeNoprint(name_);
  
  baseNote_ = C2FREQ;	/* Middle C */
  baseFreq_ = ((ntscflag == 1) ? NTSC_RATE : PAL_RATE);
  volume_ = BYTE(buf + 25);

  if (volume_ > 0)
    volume_ = (volume_ * 4) - 1;
  else
    volume_ = 0;
  
  finetune_ = BYTE(buf + 24) & 0x0f;
  
  if (finetune_ <= 7)
    finetune_ *= 12.5;
  else
    finetune_ = (short)(12.5 * (finetune_ - 16));
  
  if (length_ > 0)
    rc = seq.patchLoad(modFd, sampleNo, *this, bytesRead, cutFactor);

  if (!rc)
    ok_ = 1;
    
  return rc;
}
