/* 
   Compilation: gcc -o /tmp/animation_size -Wall -Werror -g3 -O0 `pkg-config --cflags --libs gdk-pixbuf-2.0` animation_size.c
   Running: /tmp/animation_size image_filename [max_width max_height]
*/

#include <stdlib.h>
#include <gdk-pixbuf/gdk-pixbuf.h>

int
main (int argc, char **argv)
{
  GdkPixbufLoader *loader;
  GdkPixbuf *pixbuf;
  GdkPixbufAnimation *animation;
  gchar *file_content = NULL;
  gsize file_size;
  gint animation_width, animation_height, pixbuf_width, pixbuf_height,
    max_width = -1, max_height = -1;

  g_type_init ();

  g_assert (argc >= 2);

  g_assert (g_file_get_contents (argv[1], &file_content, &file_size, NULL));

  loader = gdk_pixbuf_loader_new ();

  if (argc >= 4)
    {
      max_width = atoi (argv[2]);
      max_height = atoi (argv[3]);

      g_debug ("max size: %dx%d", max_width, max_height);

      gdk_pixbuf_loader_set_size (loader, max_width, max_height);
    }

  g_assert (gdk_pixbuf_loader_write (loader, (const guchar *) file_content,
                                     file_size, NULL));

  g_free (file_content);

  animation = gdk_pixbuf_loader_get_animation (loader);
  pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);
  g_assert (animation);
  g_assert (pixbuf);

  animation_width = gdk_pixbuf_animation_get_width (animation);
  animation_height = gdk_pixbuf_animation_get_height (animation);
  pixbuf_width = gdk_pixbuf_get_width (pixbuf);
  pixbuf_height = gdk_pixbuf_get_height (pixbuf);

  g_debug ("animation: %dx%d", animation_width, animation_height);
  g_debug ("pixbuf: %dx%d", pixbuf_width, pixbuf_height);

  if (max_width != -1)
    {
      g_assert (animation_width <= max_width && animation_height <= max_height);
    }

  if (animation_width != pixbuf_width || animation_height != pixbuf_height)
    {
      g_message ("animation size (%dx%d) != pixbuf_size (%dx%d)",
                 animation_width, animation_height, pixbuf_width,
                 pixbuf_height);
    }

  g_assert (gdk_pixbuf_loader_close (loader, NULL));
  g_object_unref (loader);

  return 0;
}
