/* save_x_bitmap.c -- Write out the face as an X11 bitmap file. */

/* Copyright (C) 1988, 1990, 1992  Free Software Foundation, Inc.

   This file is part of GNU Finger.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */


#include <config.h>
#include <stdio.h>
#include <bitmap.h>
#include <sys/errno.h>

#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif

extern int errno;


/* Save the bitmap in FACE to the mugshot file for USER.
   Return zero if successful, file system error code if not. */
int 
save_x_bitmap (user, face)
     char *user;
     BITMAP *face;
{
  char *name, *filename, *our_name;
  FILE *file;
  int x, y, fcol;

  filename = mugshot_filename (user);
  name = (char *)rindex (filename, '/');

  if (name)
    name++;
  else
    name = filename;

  our_name = (char *)xmalloc (1 + strlen (name));
  strcpy (our_name, name);

  while ((name = (char *)rindex (our_name, '.')) != (char *)NULL)
    *name = '\0';

  file = fopen (filename, "w");

  if (!file)
    return (errno);

  /* Write out standard header */
  fprintf (file, "/* %s bitmap, written by GNU Finger. */\n", our_name);
  fprintf (file, "#define %s_width %d\n", our_name, face->width);
  fprintf (file, "#define %s_height %d\n", our_name, face->height);
  fprintf (file, "static char %s_bits[] = {", our_name);

  /* Print out the data itself. */
  fcol = 12;
  for (y = 0; y < face->height; y++)
    {
      byte *row = face->bits + (face->rowlen * y);

      for (x = 0; x < face->rowlen; x++)
	{
	  if (x || y)
	    fprintf (file, ",");

	  if (fcol == 12)
	    {
	      fprintf (file, "\n   ");
	      fcol = 0;
	    }

	  fprintf (file, "0x%02x", row[x]);
	  fcol++;
	}
    }
  fprintf (file, "};\n");
  fclose (file);
  return (0);
}
