#include <stdio.h>

#define window_size 64000

main()
{
	FILE *f = fopen( "out_file.bin", "rb" );
	if( f )
	{
		int fp = 0;
		int w = 0;
		signed short l,r;
		int res_l = 0, res_r = 0, res = 0;;
		FILE *p = fopen( "points.bin", "wb" );
		for(;;)
		{
			fread( &l, 2, 1, f );
			fread( &r, 2, 1, f );
			res_l += l;
			res_r += r;
			if( feof( f ) != 0 ) break;
			fp++;
			w++;
			if( w >= window_size ) 
			{
				//save point:
				res_l /= w;
				res_r /= w;
				res = ( res_l + res_r ) >> 1;
				fwrite( &res, 4, 1, p );
				w = 0;
				res = 0;
				res_l = 0;
				res_r = 0;
			}
		}
		//last point ==================
		res_l /= w;
		res_r /= w;
		res = ( res_l + res_r ) >> 1;
		fwrite( &res, 4, 1, p );
		//=============================
		fclose( p );
		fclose( f );

		//compress input file:
		FILE *new_file = fopen( "out_file2.bin", "wb" );
		f = fopen( "out_file.bin", "rb" );
		p = fopen( "points.bin", "rb" );
		int p1, p2;
		fread( &p1, 4, 1, p );
		fread( &p2, 4, 1, p );
read_points:
		//interpolate window:
		for( w = 0; w < window_size; w++ )
		{
			float t = (float)w / (float)window_size; //0 ... 1
			float fres = ((float)p1 * (1-t)) + ((float)p2 * t);
			res = (int)fres;
			if( feof( f ) != 0 ) goto comp_end;
			//read channels:
			fread( &l, 2, 1, f );
			fread( &r, 2, 1, f );
			//compress:
			res_l = l - res;
			res_r = r - res;
			l = res_l;
			r = res_r;
			//write results:
			fwrite( &l, 2, 1, new_file );
			fwrite( &r, 2, 1, new_file );
		}
		p1 = p2;
		fread( &p2, 4, 1, p );
		goto read_points;
comp_end:
		fclose( p );
		fclose( f );
		fclose( new_file );
	}
	return 0;
}
