/* Selena Phan
	17 October 2022
	CPSC 1011, Section 4
	Fall 2022 Lab #8
   * intro to PPM with creating a flag of Ireland
			green|white|orange
	* reinforces functions

	PPM images have 2 parts:
		header information
		pixel information

	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
*/

#include <stdio.h>
#include <string.h>
typedef struct{
	char type[4];
	int width, height, maxColor;
} size;
typedef struct{
	unsigned int red, green, blue;
} values;

int getWidth();
void writeHeader(size header);
void fillFlagArray(values flagArray[], int width, int height);
void writePixels(values flagArray[], int width, int height);

int main (void){
	size flag;

	// 1. get the user's input for width
	flag.width = getWidth();

	// 2. calculate the height based on the proportion stated on Wikipedia
	flag.height = flag.width / 2;

	values pixelMap[flag.height*flag.width];
	
	fprintf(stderr, "\n\nMaking the flag with width %d & height %d ...",
		flag.width, flag.height);
	fprintf(stderr, "\n\n");

	// write to stdout the ppm header values 
	writeHeader(flag);

	fillFlagArray(pixelMap, flag.width, flag.height);
	writePixels(pixelMap, flag.width, flag.height);
	return 0;
}

int getWidth(){
	int wide;
	fprintf(stderr, "\n\nFlag of Ireland");
	fprintf(stderr, "\n\tWhat width do you want the flag to be? ");
	scanf(" %d", &wide);
	return wide;
}

void writeHeader(size header){
	strcpy(header.type, "P3");
	header.maxColor = 255;
	fprintf(stdout, "%s\n", header.type);
	fprintf(stdout, "%d %d %d\n", header.width, header.height, header.maxColor);
}

void fillFlagArray(values flagArray[], int width, int height){
	int i,j,k = 0;
	values color;

	for(i = 0; i < height; i++){
		for(j = 0; j < (width/3); j++){
			color.red = 0;
			color.green = 128;
			color.blue = 0;
			flagArray[k++] = color;
		}
		for(; j < (2*width/3); j++){
			color.red = 255;
			color.green = 255;
			color.blue = 255;
			flagArray[k++] = color;
		}
		for(; j < width; j++){
			color.red = 255;
			color.green = 165;
			color.blue = 0;
			flagArray[k++] = color;
		}
	}
}

void writePixels(values flagArray[], int width, int height){
	for(int i = 0; i < (height); i++){
		for(int k = 0; k < width; k++){
			fprintf(stdout, " %d %d %d\n", 
			flagArray[k].red, flagArray[k].green, flagArray[k].blue);
		}
	}
}
