#include "../H/ugens.h"
#include "../H/sfheader.h"
#include <stdio.h>
#include <math.h>

extern SFHEADER sfdesc[NFILES];
extern int sfd[NFILES];
extern int bufsize[NFILES];
extern char *sndbuf[NFILES];
int (*getsample)();
int getfsample();
int getisample();

getsetnote(start,dur,filenum)
float start,dur;
int filenum;
{
	int nsamples = setnote(start,dur,filenum);
	_backup(filenum);
	if(sfclass(&sfdesc[filenum]) == SF_FLOAT) getsample = getfsample;
	else          	                          getsample = getisample;
	return(nsamples);

}
getisample(sampleno,c,input)
float *c;
double sampleno;
{

	int RECSIZE = bufsize[input];
	int BPREC = RECSIZE * sizeof(short);
	int BPFRAME = sfchans(&sfdesc[input]) * sizeof(short);
	int FPREC = RECSIZE/sfchans(&sfdesc[input]);

	int sample,i,j;
	short *array = (short *)sndbuf[input];
	float fraction;
	static int oldsample = 0;
	static int endsample = 0;

	sample = (int)sampleno;
	fraction = sampleno - (double)sample;
	if(!((sample >= oldsample) && (sample < endsample))) {
		if(sflseek(sfd[input], sample * BPFRAME, 0) <=0) {
			fprintf(stderr,"badlseek on inputfile\n");
			closesf();
		}
		if(read(sfd[input],(char *)array,BPREC) <= 0) {
			fprintf(stderr,"reached eof on input file \n");
			return(-1);
		}
		oldsample = sample;
		endsample = oldsample + FPREC - 1;
		}
	for(i=(sample-oldsample)*sfchans(&sfdesc[input]),j=0; 
					j<sfchans(&sfdesc[input]); i++,j++)  
		*(c+j) = (float)*(array+i) + fraction * 
			((float) *(array+i+sfchans(&sfdesc[input])) - 
				 (float) *(array+i));
	return(0);
}
getfsample(sampleno,c,input)
float *c;
double sampleno;
{
	int RECSIZE = bufsize[input];
	int BPREC = RECSIZE * sizeof(float);
	int BPFRAME = sfchans(&sfdesc[input]) * sizeof(float);
	int FPREC = RECSIZE/(float)sfchans(&sfdesc[input]);

	int sample,i,j;
	float *array = (float *)sndbuf[input];
	float fraction;
	static int oldsample = 0;
	static int endsample = 0;

	sample = (int)sampleno;
	fraction = sampleno - (double)sample;
	if(!((sample >= oldsample) && (sample < endsample))) {
		if(sflseek(sfd[input], sample * BPFRAME, 0) <=0) {
			fprintf(stderr,"badlseek on inputfile\n");
			closesf();
		}
		if(read(sfd[input],(char *)array,BPREC) <= 0) {
			fprintf(stderr,"reached eof on input file \n");
			return(-1);
		}
		oldsample = sample;
		endsample = oldsample + FPREC - 1;
		}
	for(i = (sample-oldsample)*sfchans(&sfdesc[input]),j=0; 
					j<sfchans(&sfdesc[input]); i++,j++)  
		*(c+j) = *(array+i) + fraction * 
			(*(array+i+sfchans(&sfdesc[input])) - *(array+i));
	return(0);
}
