
#include "mmxnow.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

mmxnow_image_t* read_pgm(const char* filename)
{
    mmxnow_image_t* img = malloc(sizeof(mmxnow_image_t));
    FILE* f;
    char b[1000];
    size_t size;

    if (!img)
	return 0;

    memset(img, 0, sizeof(img));
    f = fopen(filename, "r");
    if (!f)
    {
	perror("file open");
        goto fail;
    }

    if (!fgets(b, sizeof(b), f))
	goto fail;

    if (strncmp(b, "P6", 2))
    {
	printf("unsupported format %s\n", b);
	goto fail;
    }

    // skip comment lines
    for (;;)
    {
	fgets(b, sizeof(b), f);
	if (b[0] != '#')
            break;
    }
    sscanf(b, "%d %d", &img->width, &img->height);
    fgets(b, sizeof(b), f);
    if (!strcmp(b, "255"))
    {
	printf("unsupported img format %s\n", b);
        goto fail;
    }
    size = img->width * img->height * 3;
    img->plane[0] = (uint8_t*) malloc(size);
    if (!img->plane[0])
        goto fail;
    if (!feof(f))
	fread(img->plane[0], size, 1, f);
    //printf("Found image %dx%d\n", img->width, img->height);
    return img;

fail:
    free(img);
    return 0;
}

void write_pgm(const char* filename, mmxnow_image_t* img)
{
    FILE* f = fopen(filename, "w");
    if (f)
    {
	fprintf(f, "P6\n# mmxnow test image\n%d %d\n255\n",
		img->width, img->height);
	fwrite(img->plane[0], 1, (unsigned) (3 * img->width * img->height), f);
	printf("Written image: %s  %dx%d\n", filename,
	       img->width, img->height);
    }
}

int main(int argc, char* argv[])
{
    mmxnow_image_t* img;

    img = read_pgm("test.pgm");

    if (img)
    {
	mmxnow_context_t* rgb24_yv12, *yv12_rgb16, *rgb16_rgb24;
	unsigned int flags = MMXNOW_MMX;

	rgb24_yv12 = mmxnow_create(MMXNOW_BGR24_TO_YV12, flags);
	yv12_rgb16 = mmxnow_create(MMXNOW_YV12_TO_BGR16, flags);
	rgb16_rgb24 = mmxnow_create(MMXNOW_BGR16_TO_BGR24, flags);

	if (rgb24_yv12 && yv12_rgb16 && rgb16_rgb24)
	{
	    printf("converting image\n");
	}
	else
	    printf("context %p  %p  %p\n", rgb24_yv12, yv12_rgb16, rgb16_rgb24);

	write_pgm("testX.pgm", img);
    }

    return 0;
}
