#include <errno.h>
#include <stdio.h>
#include <string.h>

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

int main(int argc, char *argv[])
{
	FILE *outfile;
	int w, h, bpp;
	unsigned char *pixels;

	if (argc < 3) {
		fprintf(stderr, "Usage: %s [input] [output].\n", argv[0]);
		return 1;
	}

	pixels = stbi_load(argv[1], &w, &h, &bpp, 4);
	if (pixels == NULL) {
		fprintf(stderr, "Inable to read image from '%s'.\n", argv[1]);
		return 1;
	}

	outfile = fopen(argv[2], "wb");
	if (outfile == NULL) {
		fprintf(stderr, "Unable to write to '%s': %s\n", argv[2], strerror(errno));
		stbi_image_free(pixels);
		return 1;
	}

	fwrite(&w, 2, 1, outfile);
	fwrite(&h, 2, 1, outfile);
	fwrite(pixels, 1, w*h*4, outfile);

	stbi_image_free(pixels);
	fclose(outfile);

	return 0;
}
