#include <opencv2/opencv.hpp>
#include <iostream> 
#include <cstdint>
#include <boost/chrono.hpp>

using namespace std;

int main(int argc, char **argv) {
	if(argc<3)
	{
		cout << "Usage: ./as5 input.png output.png" << endl;
		return -1;
	}
	//cout << argv[0] << endl;
	//cout << argv[1] << endl;
	//cout << argv[2] << endl;
	cv::Mat image = cv::imread(argv[1],cv::IMREAD_COLOR);
	if (image.empty()) {
		cout << "Could not load image" << endl;
		return -2;

	}
	int rows=image.rows;
	int cols=image.cols;
	int channels=3;

	//Allocate ***ptr
	uint8_t ***arr= new uint8_t **[rows];
	for (int i=0;i<rows;i++)
	{
		arr[i]=new uint8_t *[cols];
		for (int j=0;j<cols;j++) {
			arr[i][j]=new uint8_t[channels];
		}
	}
	//EOF ALLOC
	//copy image to 3D tensor
	for (int i=0;i<rows;i++)
	{
		for (int j=0;j<cols;j++)
		{
			cv::Vec3b pixel=image.at<cv::Vec3b>(i,j);
			for (int k=0;k<3;k++){
				arr[i][j][k]=pixel[k];
			}

		}
	}
	//Transformation

	for (int i=0;i<rows;i++){

		for(int j=0;j<cols;j++){
			uint8_t B=arr[i][j][0];
			uint8_t G=arr[i][j][0];
			uint8_t R=arr[i][j][0];
			uint8_t gray=0.299*R+0.587*G+0.114*B;
			arr[i][j][0]=gray;
			arr[i][j][1]=gray;
			arr[i][j][2]=gray;

		}
	}
	//copy back
	for (int i=0;i<rows;i++){
		for(int j=0;j<cols;j++){
			image.at<cv::Vec3b>(i,j)[0]=arr[i][j][0];
			image.at<cv::Vec3b>(i,j)[1]=arr[i][j][1];
			image.at<cv::Vec3b>(i,j)[2]=arr[i][j][2];

		}
	}
	cv::imwrite(argv[2],image);
	return 0;
}

