cv::Mat FastKDEBackground::operator()(const cv::Mat& img){
	if(!isInit) init(img);
	cv::Mat probimg;
	cv::Mat mask;
	imagebuffer.push_back(img);

	probimg=get_probabilities(img);
	cv::imshow("Probabilities",probimg*100);
	cv::threshold(probimg,mask, threshold, 255, CV_THRESH_BINARY_INV);
	mask.convertTo(mask,CV_8UC1);

	if(count<=twin){count++;}
	else{imagebuffer.pop_front();}

	return mask;
}
int encode(FILE *input_file, unsigned long file_size, FILE *output_file, unsigned int length)
{
	unsigned long i, j, n_symbols, current_symbol, tmp;
	unsigned long *probs;
	unsigned char *buffer;
	code *codefinal;

	n_symbols = pow_int(2, 8 * length);

	buffer = malloc(length * READ_SIZE);
	probs = malloc(pow_int(2, 8 * length) * sizeof(unsigned long));

	get_probabilities(input_file, n_symbols, probs);

	unsigned long tree[(n_symbols - 1) * 2];

	create_tree(probs, n_symbols, tree);

	// Show packed tree
	for (i = 0; i < (n_symbols - 1); i++)
		printf("(%lu, %lu) ", tree[i * 2], tree[i * 2 + 1]);
	printf("\n");

	codefinal = malloc(n_symbols * 2 * sizeof(code));
	create_huff_code(tree, n_symbols, codefinal);

	fseek(input_file, 0L, SEEK_SET);
	unsigned char binarybuffer[n_symbols];
	unsigned long binarybuffersize = 0;

	unsigned char *outbuffer;
	outbuffer = malloc(length);

	//Headers of file
	//X will be the number of bits added to create the last byte
	char filetype[] = ".huf1.0X";
	for (i = 0; i < 8; i++)
		fwrite(&filetype[i], 1, 1, output_file);

	fwrite(&length, 1, 1, output_file);

	for (i = 0; i < (n_symbols - 1) * 2; i++)
		fwrite(&tree[i], sizeof(unsigned long), 1, output_file);


	for (i = 0; i < file_size/length; i++) {
		fread(buffer, length, 1, input_file);
		current_symbol = 0;
		for (j = 0; j < length; j++)
			current_symbol += buffer[j]*pow_int(2,8*(length - 1 - j));

		for (j = 0; j < codefinal[current_symbol].length; j++)
			binarybuffer[binarybuffersize+j] = codefinal[current_symbol].value[j];

		binarybuffersize += codefinal[current_symbol].length;

		while (binarybuffersize >= length*8){
			*outbuffer = 0;
			for (j = 0; j < length*8; j++)
				*outbuffer += binarybuffer[length*8 - 1 - j] * pow_int(2,j);

			fwrite(outbuffer ,length ,1 ,output_file);

			for (j = 0; j < binarybuffersize - length*8; j++)
				binarybuffer[j] = binarybuffer[j+length*8];

			binarybuffersize -= length*8;
		}
	}
	unsigned char filled = length*8 - binarybuffersize;
	*outbuffer = 0;
	for (j = 0; j < length*8; j++)
		*outbuffer += binarybuffer[length*8 - 1 - j] * pow_int(2,j);

	fwrite(outbuffer ,length ,1 ,output_file);

	fseek(output_file, 7 * length, SEEK_SET);
	fwrite(&filled, 1, 1, output_file);

	free(probs);
	free(outbuffer);

	return 0;
}