/*
   Copyright (c) 2015 Techmeology

   Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software and associated documentation files (the "Software"), to deal
   in the Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
   SOFTWARE.
*/

/*
	DCT image scaling program
	Dependencies: fftw3 (http://www.fftw.org/)
	Compilation: g++ --std=c++11 -O3 -s -o dctscale dctscale.cpp -lfftw3
	Usage: dctscale input.ppm output.ppm width height
	Input and output should be a pixmap
		(http://en.wikipedia.org/wiki/Portable_anymap)
*/

#include <exception>
#include <string>
#include <fftw3.h>

template <typename T> class Dct
{
	public:
		Dct(unsigned int size, bool inverse) :
			m_size(size),
			m_inverse(inverse),
			m_src((double *)fftw_malloc(size * sizeof(double))),
			m_dst((double *)fftw_malloc(size * sizeof(double))),
			m_plan(fftw_plan_r2r_1d(size, m_src, m_dst, inverse ?
				FFTW_REDFT01 : FFTW_REDFT10, FFTW_ESTIMATE))
		{
		}
		
		virtual ~Dct()
		{
			fftw_destroy_plan(m_plan);
			fftw_free(m_src);
			fftw_free(m_dst);
		}
		
		void Execute(T *src, T *dst,
			unsigned int src_stride, unsigned int dst_stride,
			unsigned int src_offs, unsigned int dst_offs)
		{
			for (unsigned int i = 0; i < m_size; i++){
				m_src[i] = src[i * src_stride + src_offs];
			}
			
			fftw_execute(m_plan);
			
			for (unsigned int i = 0; i < m_size; i++){
				dst[i * dst_stride + dst_offs] =
					m_inverse ? m_dst[i] : m_dst[i]/(2 * m_size);
			}
		}
		
		void Execute(T *b, unsigned int stride, unsigned int offs)
		{
			Execute(b, b, stride, stride, offs, offs);
		}
		
	private:
		Dct(const Dct<T> &) = delete;
		Dct &operator=(const Dct<T> &) = delete;
		
		unsigned int m_size;
		bool m_inverse;
		double *m_src;
		double *m_dst;
		fftw_plan m_plan;
};


class Image
{
	public:
		Image() : m_data(0), m_width(0), m_height(0)
		{
		}
		
		Image(const Image &src, unsigned int width, unsigned int height) :
			m_width(width), m_height(height),
			m_data(new unsigned char[width * height * 3])
		{
			/* Check that we don't have anb empty image */
			if (!src.m_data){
				for (unsigned int i = 0; i < m_width * m_height * 3; i++){
					m_data[i] = 0;
				}
				return;
			}
			
			/* Some images in double form */
			double *src_image = new double[src.m_width * src.m_height * 3];
			double *dst_image = new double[m_width * m_height * 3];
			
			
			/* Form the image in double form */
			for (unsigned int i = 0; i < src.m_width * src.m_height * 3; i++){
				src_image[i] = (double)src.m_data[i];
			}
			
			/* Forward DCT */
			Dct<double> row_forward(src.m_width, false);
			Dct<double> col_forward(src.m_height, false);
			
			for (unsigned int y = 0; y < src.m_height; y++){
				for (unsigned int c = 0; c < 3; c++){
					row_forward.Execute(src_image, 3, y * src.m_width * 3 + c);
				}
			}
			
			for (unsigned int xc = 0; xc < src.m_width * 3; xc++){
				col_forward.Execute(src_image, src.m_width * 3, xc);
			}
			
			/* Copy transformed image to the destination with zero padding */
			for (unsigned int y = 0; y < m_height; y++){
				for (unsigned int x = 0; x < m_width; x++){
					for (unsigned int c = 0; c < 3; c++){
						dst_image[y * m_width * 3 + x * 3 + c] =
							((y < src.m_height) && (x < src.m_width)) ?
							src_image[y * src.m_width * 3 + x * 3 + c] : 0.0;
					}
				}
			}
			
			/* Backward DCT */
			Dct<double> row_backward(m_width, true);
			Dct<double> col_backward(m_height, true);
			
			for (unsigned int xc = 0; xc < m_width * 3; xc++){
				col_backward.Execute(dst_image, m_width * 3, xc);
			}
			
			for (unsigned int y = 0; y < m_height; y++){
				for (unsigned int c = 0; c < 3; c++){
					row_backward.Execute(dst_image, 3, y * m_width * 3 + c);
				}
			}
			
			/* Form the image in unsigned char form */
			for (unsigned int i = 0; i < m_width * m_height * 3; i++){
				m_data[i] = (dst_image[i] < 0.0) ? 0 :
					(dst_image[i] > 255.0) ? 255 : dst_image[i];
			}
			
			/* Delete the double image buffers we created */
			delete []src_image;
			delete []dst_image;
		}
		
		virtual ~Image()
		{
			if (m_data){
				delete []m_data;
			}
		}
		
		void Load(const char *filename)
		{
			FILE *f = fopen(filename, "rb");
			if (!f){
				fprintf(stderr, "Could not open \"%s\" for reading\n",
					filename);
				throw std::exception();
			}
			
			char c = 0;
			int i = 0;
			unsigned int state = 0;
			std::string width;
			std::string height;
			std::string max;
			/*
				state:
					0 = "P6"[0]
					1 = "P6"[1]
					2 = Not end of line
					3 = Beginning of line
					4 = Width
					5 = Height
					6 = Max
					7 = Data
					8 = End of data
			 */
			while (state != 8){
				if (fread(&c, 1, 1, f) != 1){
					fprintf(stderr, "Could not read character in state %u\n",
						state);
				}
				
				switch (state){
					case 0:
						if ('P' != c){
							fprintf(stderr, "\"%s\" is not a pixmap\n",
								filename);
							throw std::exception();
						}
						state = 1;
						break;
					case 1:
						if ('6' != c){
							fprintf(stderr, "\"%s\" is not an RGB pixmap\n",
								filename);
							throw std::exception();
						}
						state = 2;
						break;
					case 2:
						if ('\n' == c){
							state = 3;
						}
						break;
					case 3:
						if ('#' == c){
							state = 2;
							break;
						}
						else {
							state = 4;
						}
						//Continue onto the next state if we should
						//(this character is the beginning of width)
					case 4:
						if (' ' == c){
							i = atoi(width.c_str());
							if (i <= 0){
								fprintf(stderr, "\"%s\" has width <= 0\n",
									filename);
								throw std::exception();
							}
							m_width = i;
							state = 5;
						}
						else {
							width += c;
						}
						break;
					case 5:
						if ('\n' == c){
							i = atoi(height.c_str());
							if (i <= 0){
								fprintf(stderr, "\"%s\" has height <= 0\n",
									filename);
								throw std::exception();
							}
							m_height = i;
							m_data = new unsigned char[m_width * m_height * 3];
							
							state = 6;
						}
						else {
							height += c;
						}
						break;
					case 6:
						if ('\n' == c){
							if (max != "255"){
								fprintf(stderr, "\"%s\" is not 8 bit\n",
									filename);
								throw std::exception();
							}
							
							i = 0; //we use i in state 7
							state = 7;
						}
						else {
							max += c;
						}
						break;
					case 7:
						if (m_width * m_height * 3 - 1 == i){
							state = 8;
						}
						else {
							m_data[i] = c;
							i++;
						}
						break;
				}
			}
			
			fclose(f);
		}
		
		void Save(const char *filename) const
		{
			FILE *f = fopen(filename, "wb");
			if (!f){
				fprintf(stderr, "Could not open \"%s\" for writing\n",
					filename);
				throw std::exception();
			}
			
			if (fprintf(f, "P6\n#Scaled with dctscale\n%u %u\n255\n",
				m_width, m_height) < 0){
				fprintf(stderr, "Could not write header to \"%s\"\n",
					filename);
				throw std::exception();
			}
			
			for (unsigned int i = 0; i < m_width * m_height * 3; i++){
				if (fwrite(m_data + i, 1, 1, f) != 1){
					fprintf(stderr, "Could not write image to \"%s\"\n",
						filename);
					throw std::exception();
				}
			}
			
			fclose(f);
		}
		
	private:
		Image(const Image &) = delete;
		Image &operator=(const Image &) = delete;
		
		unsigned char *m_data;
		unsigned int m_width;
		unsigned int m_height;
};

int main (int argc, char **argv)
{
	try {
		if (argc != 5){
			fprintf(stderr, "Usage: %s input.ppm output.ppm width height\n",
				argv[0]);
			throw std::exception();
		}
		
		const char *input = argv[1];
		const char *output = argv[2];
		int width = atoi(argv[3]);
		int height = atoi(argv[4]);
		
		if ((width <= 0) || (height <= 0)){
			fprintf(stderr, "Dimension arguments must be positive integers\n");
			throw std::exception();
		}
		
		Image original;
		original.Load(input);
		Image scaled(original, width, height);
		scaled.Save(output);
	}
	catch (std::exception e) {
		return 1;
	}
	
	return 0;
}
