/*                                             *
 * Functions for ppm files by Elias Broms 1995 *
 *                                             */

#include <stdio.h>
#include "ppm.h"

/* Returns an integer color with components r, g, b */
intcolor makecol(intcolorcomp r, intcolorcomp g, intcolorcomp b)
{
  intcolor col;

  col.r=r;
  col.g=g;
  col.b=b;
  return col;
}

/* Clears the picture */
void zeromap(intcolor col, intcolor **map)
{
  int x, y;
  for (y=0;y<HEIGHT;y++)
    for (x=0;x<WIDTH;x++)
      map[x][y]=col;
}

/* Writes the picture to a ppm file */
int writeppm(char *filename, intcolor **map)
{
  int x, y;
  FILE *fh;

  if (fh=fopen(filename, "w"))
  {
      fprintf(fh, "P3\n%d %d\n%d\n", WIDTH, HEIGHT, COLORS-1);
      for (y=0;y<HEIGHT;y++)
	  for (x=0;x<WIDTH;x++)
	      fprintf(fh, "%d %d %d  \n",
		      map[x][y].r,map[x][y].g,map[x][y].b);
      fclose(fh);
  }
}

/* Converts a real color to an integer color and plots it at (x, y) */
void colorplot(color c, int x, int y, intcolor **map)
{
  intcolor ic;

  if (c.x > 0.9999) c.x=0.9999;
  if (c.y > 0.9999) c.y=0.9999;
  if (c.z > 0.9999) c.z=0.9999;

  ic.r=(intcolorcomp)(((scalar)COLORS)*c.x);
  ic.g=(intcolorcomp)(((scalar)COLORS)*c.y);
  ic.b=(intcolorcomp)(((scalar)COLORS)*c.z);

  map[x][y]=ic;
}

int allocpicture(pictureptr, width, height)
double ***pictureptr;
long width, height;
{
    int outofmem=0;
    int i;

    if (*pictureptr=(double **)malloc(sizeof(double *)*width))
    {
        for (i=0; i<width; i++)
            if (!((*pictureptr)[i]=(double *)malloc(sizeof(double)*height)))
                outofmem=1;
    }
    else
        outofmem=1;
    return !outofmem;
}

void freepicture(picture, width)
double **picture;
long width;
{
    int i;

    /* If the array of intcolor vectors exists then... */
    if (picture)
    {
      /* Free all intcolor vectors (if they exists) */
      for (i=0; i<width; i++)
	if (picture[i])
	  free(picture[i]);

      /* Free the array of intcolor vectors */
      free(picture);
    }
}

