#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>

int main( int argc, char *argv[] )
{
	if( argc!=9 ) {
		printf( "usage: command [infile] [outfile] [width] [height] [offstL] [offsetT] [offsetR] [offsetB]\n" );
		exit(-1);
	}
	// init
	int offsetL = 0, offsetR = 0, offsetT = 0, offsetB = 0;
	
	char* infile  = argv[1];
	char* outfile = argv[2];
	const int src_width = atoi(argv[3]);
	const int src_height= atoi(argv[4]);
	const int src_offsetL = atoi(argv[5]);
	const int src_offsetT = atoi(argv[6]);
	const int src_offsetR = atoi(argv[7]);
	const int src_offsetB = atoi(argv[8]);
	offsetT = src_offsetT;
	offsetB = src_offsetB;
	offsetL = src_offsetL;
	offsetR = src_offsetR;
	const int dst_width = src_width  - offsetL - offsetR;
	const int dst_height= src_height - offsetT - offsetB;
	const long src_size = src_width*src_height*3/2;
	const long dst_size = dst_width*dst_height*3/2;
	

	// malloc
	unsigned char* src_frame  = new unsigned char[src_size];
	unsigned char* dst_frame  = new unsigned char[dst_size];
	
	// get total file size
	FILE *fp = fopen(infile, "rb");
	fseek(fp, 0L, SEEK_END); 
	const long src_total_size = ftell(fp);
	fseek(fp, 0L, SEEK_SET);
	printf("src_total_size %ld\n", src_total_size);
	
	const long src_frame_num = src_total_size/src_size;
	printf("src_frame_num %ld\n", src_frame_num);
	printf("src_width %d, src_height %d\n", src_width, src_height);
	printf("dst_width %d, dst_height %d\n", dst_width, dst_height);

	FILE *fout = fopen(outfile, "wb");

	// main process( frame crop )
	for (int frameNo = 0; frameNo < src_frame_num; frameNo++){
		size_t size = 0;
		size = fread(src_frame, 1, src_size, fp);

		if( size!=src_size ){ goto END;}
		printf("frameNo %ld\r", frameNo);

		long offset0 = 0;
		long offset1 = 0;

	    // luma
		for ( int y = offsetT, j= 0; y<src_height-offsetB; y++, j++){
			int dst_y = j;
			memcpy(dst_frame+(dst_y)*dst_width, src_frame+(y)*src_width + offsetL, dst_width); 
		}

		// chroma cb
		offset0 = src_height*src_width;
		offset1 = dst_height*dst_width;
		for ( int y = offsetT/2, j=0; y<src_height/2 - offsetB/2; y++, j++){
			int dst_y = j;
			memcpy(dst_frame+offset1+(dst_y)*dst_width/2, src_frame+offset0+(y)*src_width/2 + offsetL/2, dst_width/2); 
		} // chroma  cr

		offset0 += (src_height/2)*(src_width/2);
		offset1 += (dst_height/2)*(dst_width/2);
		for ( int y = offsetT/2, j=0; y<src_height/2 - offsetB/2; y++,j++){
			int dst_y = j;
			memcpy(dst_frame+offset1+(dst_y)*dst_width/2, src_frame+offset0+(y)*src_width/2 + offsetL/2, dst_width/2); 
		}

		// write
		fwrite(dst_frame, 1, dst_size, fout); 
	}
	
	END:
	// destory
	delete src_frame; src_frame=NULL;
	delete dst_frame; dst_frame=NULL;
	fclose(fp);
	fclose(fout);
	return 0;
}
