#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

double frac(double x)
{
	return x - (int)x;
}

int main(int argc, char **argv)
{
	FILE *in, *skew, *out;

	// open input
	if (strcmp(argv[1], "-") == 0) {
		in = stdin;
	} else {
		in = fopen(argv[1], "rb");
		if (in == NULL) {
			perror(argv[1]);
			exit(1);
		}
	}

	// open skew
	if (strcmp(argv[2], "-") == 0) {
		skew = stdin;
	} else {
		skew = fopen(argv[2], "rb");
		if (skew == NULL) {
			perror(argv[2]);
			exit(1);
		}
	}

	// open output
	if (strcmp(argv[3], "-") == 0) {
		out = stderr;
	} else {
		out = fopen(argv[3], "wb");
		if (in == NULL) {
			perror(argv[3]);
			exit(1);
		}
	}

	short prev_sample, sample = 0;
	int in_pos = -1;
	double p = -1.0;

	while (!feof(in) && !feof(skew)) {
		double delta_p;
		if (fread(&delta_p, sizeof(double), 1, skew) != 1) {
			exit(0);
		}

		p += delta_p;

		// read samples until we're at the right position
		while ((int)(ceil(p)) > in_pos) {
			prev_sample = sample;
			if (fread(&sample, sizeof(short), 1, in) != 1) {
				exit(0);
			}
			++in_pos;
		}

		// linear interpolation (works well since delta_p varies so slowly)
		double t = frac(p);
		short intp_sample = prev_sample * (1.0 - t) + sample * t;

		fwrite(&intp_sample, sizeof(short), 1, out);
	}
}
