/* $Id: ppm.c,v 1.7 2005/06/17 11:32:21 cegger Exp $
******************************************************************************

   Display-file: ppm writer

   Copyright (C) 1998 Andrew Apted    [andrew@ggi-project.org]

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
   THE AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
   IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

******************************************************************************
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

#include "config.h"
#include <ggi/internal/ggi-dl.h>
#include <ggi/display/file.h>
#include <ggi/internal/gg_replace.h>	/* for snprintf() */


#define PPM_INFO_STRING  "# Generated by display-file target of LibGGI\n"


int _ggi_file_ppm_detect(char *filename)
{
	int len = strlen(filename);

	if (len < 5) {
		return 0;
	}

	return (strcmp(filename + (len-4), ".ppm") == 0);
}

void _ggi_file_ppm_write(ggi_visual *vis)
{
	unsigned char buf[200];

	int x, y;

	ggi_pixel last;
	ggi_color col;


	/* write header info */

	_ggi_file_write_string(vis, (const unsigned char *)"P6\n");
	_ggi_file_write_string(vis, (const unsigned char *)PPM_INFO_STRING);

	snprintf((char *)buf, 200, "%d %d\n255\n", LIBGGI_VIRTX(vis), LIBGGI_VIRTY(vis));
	_ggi_file_write_string(vis, buf);


	/* write out the pixels */

	ggiGetPixel(vis, 0, 0, &last);
	last = ~last;	/* must be different from first pixel */

	for (y=0; y < LIBGGI_VIRTY(vis); y++)
	for (x=0; x < LIBGGI_VIRTX(vis); x++) {

		ggi_pixel pix;

		ggiGetPixel(vis, x, y, &pix);

		if (pix != last) {
			ggiUnmapPixel(vis, pix, &col);
		}

		_ggi_file_write_byte(vis, (unsigned)(col.r >> 8));
		_ggi_file_write_byte(vis, (unsigned)(col.g >> 8));
		_ggi_file_write_byte(vis, (unsigned)(col.b >> 8));

		last = pix;
	}

	_ggi_file_flush(vis);
}
