#include <stdio.h>
#include <stdint.h>
#include <math.h>

#define RATE 16000.0

float sinetab[2048];

typedef struct oscillator {
	uint32_t phasor;
	uint32_t step;
	float value;
} osc_t;

void update_osc(osc_t* o) {
	o->phasor += o->step;
	o->value = sinetab[o->phasor >> (32-11)];
}

void set_osc_freq(osc_t* o, float f) {
	o->step = (uint32_t) ((f / RATE) * UINT32_MAX);
}
int main(int argc, char *argv[]) {
	FILE *full_speed, *half_speed;
	int16_t x, y, a, b, out;
	int8_t step;
	osc_t lfo_fade, lfo_pan;

	for(int i=0; i<2048; i++) {
		sinetab[i] = (float) (0.5 + 0.5*sin(i*2*M_PI/2048));
	}

	lfo_fade.phasor = 0.25*UINT32_MAX;
	lfo_pan.phasor = 0.25*UINT32_MAX;
	set_osc_freq(&lfo_fade, 0.05);
	set_osc_freq(&lfo_pan, 0.025);

	full_speed = popen(argv[1], "r");
	half_speed = popen(argv[1], "r");

	fread(&a, 2, 1, half_speed);
	fread(&b, 2, 1, half_speed);
	step = 0;
	while(1) {
		update_osc(&lfo_fade);
		update_osc(&lfo_pan);
		fread(&x, 2, 1, full_speed);
		switch(step) {
			case 0:
				y = a;
				step++;
				break;
			case 1:
				y = (a+b)/2;
				a = b;
				fread(&b, 2, 1, half_speed);
				step = 0;
				break;
		}
		/* Left */
		out = (int16_t) (lfo_fade.value*x*(0.25 + 0.5*lfo_pan.value) + (1-lfo_fade.value)*y);
		fwrite(&out, 2, 1, stdout);
		/* Right */
		out = (int16_t) (lfo_fade.value*x*(0.75 - 0.5*lfo_pan.value) + (1-lfo_fade.value)*y);
		fwrite(&out, 2, 1, stdout);
	}
	return 1;
}
