/*  Michael Lehon
    10/11/2022
    Section 005
    Lab #8
    Takes a width input and generates the irish flag.
*/

#include <stdio.h>

typedef struct {
	char type[3];
	int width;
	int height;
	int maxColor;
} header;

typedef struct {
	unsigned int r;
	unsigned int g;
	unsigned int b;
} pixel;

int getWidth() {
	int width;
	scanf("%i", &width);
	return width;
}

// write header to file
void writeHeader(header headerInfo) {
	fprintf(stdout,"%s\n%d %d %d\n", headerInfo.type, headerInfo.width, headerInfo.height, 255);
}

// fill flag array with pixels
void fillFlagArray(pixel *array, int width, int height) {
	int i, j, k = 0;
	for (i = 0; i < height; i++) {
		for (j = 0; j < width / 3; j++) {
			array[k] = (pixel) {000, 128, 000};
			k++;
		}
		for (; j < width * 2 / 3; j++) {
			array[k] = (pixel) {255, 255, 255};
			k++;
		}
		for (; j < width; j++) {
			array[k] = (pixel) {255, 165, 000};
			k++;
		}
	}
}

// write pixels to file
void writePixels(pixel array[], int width, int height) {
	int k = 0;
	for (k = 0; k < (width * height); k++) {
		fprintf(stdout, "%d %d %d\n", array[k].r, array[k].g, array[k].b);
	}
}

// main
int main (void) {

	// ask user what the width of the flag should be
	fprintf(stderr, "\n\nFlag of Ireland");
	fprintf(stderr, "\n\tWhat width do you want the flag to be? ");

	// init imageInfo
	header imageInfo = {"P3", 0, 0, 255};
	imageInfo.width = getWidth();
	imageInfo.height = imageInfo.width / 2;

	// display the width and height of the flag
	pixel image[imageInfo.width * imageInfo.height];
	fprintf(stderr, "\n\nMaking the flag with width %d & height %d ...", imageInfo.width, imageInfo.height);
	fprintf(stderr, "\n\n");

	// write the header to the file
	writeHeader(imageInfo);

	// fill the image with the correctly colored pixels
	fillFlagArray(image ,imageInfo.width, imageInfo.height);
	
	// write the pixels to the file
	writePixels(image, imageInfo.width, imageInfo.height);

	return 0;
}
