
/* This file is part of the GMOD package */

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/soundcard.h>

#include "defines.h"
#include "structs.h"
#include "globals.h"
#include "protos.h"

void
patch_load (FILE * mod_fd, struct patch_info *patch, int sample_num)
{
  int bytes_read;
  int len = patch->len;
  unsigned short loop_flags = patch->mode;
  int loop_start = patch->loop_start;
  int loop_end = patch->loop_end;
  int mem_avail;

  if ((bytes_read = fread (patch->data, 1, len, mod_fd)) != len)
    {
      if (((loop_flags & WAVE_16_BITS) && (bytes_read > 1)) ||
	  (!(loop_flags & WAVE_16_BITS) && (bytes_read > 0)))
	{
	  fprintf (stderr, "Warning: Short sample\n");

	  if ((loop_flags & WAVE_16_BITS) && ((bytes_read % 2) != 0))
	    bytes_read--;

	  while (bytes_read < len)
	    {
	      if (loop_flags & WAVE_16_BITS)
		{
		  patch->data[bytes_read] = patch->data[bytes_read - 2];
		  bytes_read++;
		  patch->data[bytes_read] = patch->data[bytes_read - 2];
		}
	      else
		patch->data[bytes_read] = patch->data[bytes_read - 1];
	      bytes_read++;
	    }
	}
      else
	{
	  fprintf (stderr, "Warning:  Could not load sample\n");
	  sample_ok[sample_num] = 0;
	  return;
	}
    }

  /* try to remove loop clicking */

  if ((loop_flags & WAVE_LOOPING) && (loop_end >= 2) &&
      !(loop_flags & WAVE_16_BITS))
    {
      patch->data[loop_end] = patch->data[loop_start];

      if (loop_flags & WAVE_UNSIGNED)
	patch->data[loop_end - 1] =
	  ((unsigned char) (patch->data[loop_end - 2]) +
	   (unsigned char) (patch->data[loop_end])) / 2;
      else
	patch->data[loop_end - 1] =
	  ((signed char) (patch->data[loop_end - 2]) +
	   (signed char) (patch->data[loop_end])) / 2;
    }

  mem_avail = gus_mem_free (gus_dev);	/* XXX */

  if (mem_avail < len)
    {
      printf ("*** Skipping patch - %d needed, %d available ***\n",
	      len, mem_avail);
      sample_ok[sample_num] = 0;
    }
  else
    {
      SEQ_WRPATCH (patch, sizeof (*patch) + len);

      sample_ok[sample_num] = 1;
    }
}
