/* 
Devin Evangelista
CPSC 101 Section 5 
Fall 2022 Lab 8

   * intro to PPM with creating a flag of Ireland
			green|white|orange
	* reinforces loops and arrays

	PPM images have 2 parts:
		header information
		pixel information

	An image is height (rows) X width (columns).
	So, a 300 X 600 image is 300 rows high and 600 columns wide.

	All of the image contents (header and pixel info) will be written
	to stdout so when we run the program with redirection, those items
	being sent to stdout will be redirected to a file

	For example, to run this program, you will type:
		./a.out > flag.ppm
	and everything that was sent to stdout will be written to the file
	called  flag.ppm

	All the other statements that you want to go to the screen and not 
	the image will be written to stderr.

*/

#include <stdio.h>
	typedef struct header{ // structures declared
		char type[4];
		int width;
		int height;
		int maxColor;
	}header;

	typedef struct pixel{
		unsigned int r;
		unsigned int g;
		unsigned int b;
	}pixel;
//Width Function
int getWidth(){
	int width;

	fprintf(stderr, "\n\nFlag of Ireland");
	fprintf(stderr, "\n\tWhat width do you want the flag to be? ");
	// 1. get the user's input for width
   fscanf(stdin, " %d", &width);

	return width;
}
//Header Function
void writeHeader(header input){
	
	fprintf(stdout, "P3\n");
	fprintf(stdout, "%d %d %d\n", input.width, input.height, input.maxColor);
}
//Fill the array function
void fillFlagArray(pixel P_array[], int P_width, int P_height){
	int i, j, k = 0;

	for (i = 0; i < P_height; i++ ) {
	   for (j = 0; j < P_width/3; j++ ) {
		   //fill in array with green 
			//which is r, g, b of:  0 128 0
			pixel pixelholder = (pixel) {0, 128, 0};
			
			P_array[k++] = pixelholder;
		
		}
		for (; j < P_width*2/3; j++) {
			//fill in array with white 
			//which is r, g, b of:  255 255 255
			pixel pixelholder = (pixel) {255, 255, 255};

			P_array[k++] = pixelholder;

		}
		for (; j < P_width; j++) {
			//fill in array with orange 
			//which is r, g, b of:  255 165 0
			pixel pixelholder = (pixel) {255, 165, 0};

			P_array[k++] = pixelholder;

		}
	}
}
//Write pixels to stdout function
void writePixels(pixel P_array2[], int P_width2, int P_height2){
	int i;
	for (i = 0; i < P_width2*P_height2; i++) {
	//	print each value from array to stdout
		fprintf(stdout, " %i %i %i\n",  P_array2[i].r, P_array2[i].g, P_array2[i].b);
	}


}

int main (void){
	int height;  

	int W = getWidth();
	
	header head = (header){"P3", W, W/2, 255}; 
	
	//Print statements to screen
	fprintf(stderr, "\n\nMaking the flag with width %d & height %d ...",
		head.width, head.height);
	fprintf(stderr, "\n\n");

  	writeHeader(head);	

	pixel array1[W*(W/2)];
	fillFlagArray(array1, W, W/2);
	
	writePixels(array1, W, W/2);
	


	return 0;
}
