#include <iostream>
#include <sstream>
#include "fft.h"
#include "filtmat.h"
#include "Image.h"

using namespace fft;
using namespace std;

int main(int argc, char** argv)
{
	if (argc < 4 || argc > 4)
	{
		cout << argv[0] << " <in-image> <out-image> [<radius>]" << endl;
		cout << "<in-image> - path to image to be filtred" << endl;
		cout << "<out-image> - path to image where will be stored result of filtering" << endl;
		cout << "<radius> - radius of low-pass mask in percent of minimal dimension of image. Must be in interval <1; 100>" << endl;
		cout << "\t if not specified, radius is 50%" << endl;

		return 0;
	}


	double radius = 0.5;

	if (argc == 4)
	{
		istringstream iss(argv[3]);
		int r = -1;
		iss >> r;

		if (r <= 0 || r > 100)
		{
			cerr << "Radius must be integer in interval <0; 100>" << endl;

			return 0;
		}

		radius = r * 0.01;
	}

	try
	{

		Image img(argv[1]);
		Array arrImg = img.toGreyScaleArray();
		u32 w = img.getWidth();
		u32 h = img.getHeight();

		u32 minSide = (w < h) ? w : h;
		u32 r = static_cast<u32>(radius * minSide);
		Array lowPassMask = circle(w, h, r, 1, 0);

		fft2(arrImg, w, true);
		fftshift2(arrImg, w);

		arrImg *= lowPassMask;

		fftshift2(arrImg, w);
		fft2(arrImg, w, false);

		Image::storeArray(argv[2],arrImg, w);
	}
	catch(exception& e)
	{
		cerr << e.what() << endl;
	}

	return 0;
}
