/*
gcc -I/usr/include ptmedit.c -L/usr/lib -lgimp -lgtk -lgdk -lglib -lm -L/usr/X11/lib -lX11 -lXext
 */
gint mapID;

GPlugInInfo PLUG_IN_INFO =
{
 NULL,
 NULL,
 query,
 run,
};

static void query()
{
/* GParamDef is a special data structure from gimp.h */
static GParamDef args[] = {
        { PARAM_INT32, "run_mode", "Interactive, non-interactive" },
        { PARAM_IMAGE, "image", "Input image (unused)" },
        { PARAM_DRAWABLE, "drawable_id", "Input drawable (map)" },
        { PARAM_DRAWABLE, "tileset", "Tiles used"},
        { PARAM_INT32, "tilewidth", "" },
        { PARAM_INT32, "tileheight", "" },
    };

/* Number of params = all data in the GParamDef / One line 
   The next 3 lines are common to randnote and tileit  */
static int nargs = sizeof(args) / sizeof (args[0]);
static GParamDef *return_vals = NULL;
static int nreturn_vals = 0;

gimp_install_procedure (
        "plug-in-PTMeditor",
        "A Pingus Level Editor",
        "edit_help",
        "Craig Timpany",
        "copyrights",
        "copyright_date",
        "<Image>/Filters/Experidemented/PTMedit",
        (char *) "INDEXED",
        PROC_PLUG_IN,
        nargs, 
	nreturn_vals,
        args, 
	return_vals);
}


/*********/
/*  RUN  */
/*********/
static void run(char *name, int nparams, GParam *param, int *nreturn_vals,
    GParam **return_vals)
{
  gint state;
  GRunModeType run_mode;
  GStatusType status = STATUS_SUCCESS;
  static GParam values[1];

  run_mode = param[0].data.d_int32;

  *nreturn_vals = 1;
  *return_vals = values;

  values[0].type = PARAM_STATUS;
  
  printf("\nAnd a big hello to all our readers out there in std-out-land!"); 
  if (nparams != 3) printf("\nUhoh, nparams=%d!",nparams);

  mapID=param[2].data.d_drawable;

  state=reload();

  values[0].data.d_status = status;

  if (run_mode==RUN_INTERACTIVE) state=dogui();
  if (run_mode==RUN_NONINTERACTIVE && nparams != 7) status = STATUS_CALLING_ERROR;

  /* The drawables can't be altered after detaching I think */
  gimp_drawable_detach(mapdrw);
  gimp_drawable_detach(outdrw);
  gimp_displays_flush();
}


gint refresh()
/***********/
{
  guchar *mappoint;
  gint state;

  /* check image sizes haven't changed */

  mappoint=scanmap();
  state=expandall(mappoint, tilewidth);

 
  gimp_drawable_merge_shadow(outdrw->id, FALSE);
  gimp_drawable_update
    (outdrw->id, 0, 0, tilewidth*mapdrw->width, tileheight*mapdrw->height);
 gimp_drawable_flush(outdrw);
 gimp_displays_flush();

  return state;
}


gint reload()
/**********/
{

  guchar *mappoint;
  int tilesetwidth, tilesetheight, state, dispret;
  gint mapwidth, mapheight, outdrwID;
  char tilesetname[]="/home/Craig/pingutiles/glassytiles.gif";
  gint tilesetID, oldid;

/* Get pointer from Drawable ID */
 mapdrw = gimp_drawable_get(mapID);

 /* Get map image and return pointer to data */
 mappoint=scanmap();

 mapwidth = mapdrw->width;
 mapheight = mapdrw->height;

/* Load tileset, find it's total width and height */
 
 /* Kill Old if it exists*/
 printf("%d",(gimp_drawable_image_id(tilesetID)));
 oldid=gimp_drawable_image_id(tilesetID);
 if (oldid!=-1) 
   {
printf("\noldid is %d", oldid);
gimp_image_delete(oldid);
   }

 tilesetID = loadtiles (tilesetname, 0);
 tileset = gimp_drawable_get(tilesetID);

 tilesetwidth = tileset->width;
 tilesetheight = tileset->height;

 /* Print some debugging info */
 printf("\nTileset is %dx%d",tilesetwidth,tilesetheight);
 if (tilesetwidth%tilewidth==0 && tilesetheight%tileheight==0) 
   printf ("\nRejoice, the tileset is a multiple of the tilesize!");

 /* 1.1 Only???
 else gimp_message(&"Warning: The image you're using for the source tileset isn't an integer number of tiles wide and high");
 */

 gimp_tile_cache_size((mapwidth*mapheight+tilesetwidth*tilesetheight*4)/1024);

 /* Kill Old if it exists*/
 /* oldid=gimp_drawable_image_id(outdrwID);
    if (oldid!=-1) gimp_image_delete(oldid);*/

 outdrwID=makenewoutput(tilewidth*mapwidth, 
			tileheight*mapheight, tileset->bpp);
 outdrw = gimp_drawable_get(outdrwID);

 state=expandall(mappoint, tilewidth);
 /* TODO: Put out a more useful message to user */
 printf("state is %d", state);
 /* TODO: Somehow halt further stuff if state==-1 */

 /* Update the preview window */
 gimp_drawable_flush(outdrw);
 gimp_drawable_merge_shadow(outdrw->id, FALSE);
 gimp_drawable_update(outdrw->id, 0, 0, tilewidth*mapwidth, tileheight*mapheight);

 dispret=gimp_display_new(gimp_drawable_image_id(outdrw->id));
 printf("\nThere are %d skids in my undies!",dispret);

  return state;
}


/* Kill the requester *
 ********************/
void delete_event( GtkWidget *widget,
                   GdkEvent  *event,
                   gpointer   data )
{
    gtk_main_quit ();
}


/* Either does a GUI or makes a dog of a UI */
int dogui ()
/*********/
{
  GtkWidget *window;
  GtkWidget *button;
  GtkWidget *box1;
  GtkWidget *fileentry;
  gchar **argv;
  gint argc;
  char buf[256];

  argc = 1;
  argv = g_new (gchar *, 1);
  argv[0] = g_strdup ("PTM editor");

  gtk_init (&argc, &argv);
  gtk_rc_parse (gimp_gtkrc ());    

  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title (GTK_WINDOW (window), "Level Editor");

  /* Here we just set a handler for delete_event that immediately
   * exits GTK. */
  gtk_signal_connect (GTK_OBJECT (window), "delete_event",
		      GTK_SIGNAL_FUNC (delete_event), NULL);

  gtk_container_border_width (GTK_CONTAINER (window), 10);
  box1 = gtk_hbox_new(FALSE, 0);

  gtk_container_add (GTK_CONTAINER (window), box1);

  button = gtk_button_new_with_label ("Refresh");
  gtk_signal_connect (GTK_OBJECT (button), "clicked",
		      GTK_SIGNAL_FUNC (refresh), NULL);

  /* Instead of gtk_container_add, we pack this button into the invisible
   * box, which has been packed into the window. */
  gtk_box_pack_start(GTK_BOX(box1), button, TRUE, TRUE, 0);
  gtk_widget_show(button);

  /* Do these same steps again to create a second button */
  button = gtk_button_new_with_label ("Reload");

  /* Call the same callback function with a different argument,
   * passing a pointer to "button 2" instead. */
  gtk_signal_connect (GTK_OBJECT (button), "clicked",
		      GTK_SIGNAL_FUNC (reload), NULL);

  gtk_box_pack_start(GTK_BOX(box1), button, TRUE, TRUE, 0);

  gtk_widget_show(button);

  button = gtk_button_new_with_label ("Close");
  gtk_signal_connect (GTK_OBJECT (button), "clicked",
		      GTK_SIGNAL_FUNC (delete_event), NULL);

  /*
button = gtk_button_new_with_label ("Load Tiles");
  gtk_signal_connect (GTK_OBJECT (button), "clicked",
		      GTK_SIGNAL_FUNC (loadtilesdialog), NULL);
  */
  gtk_box_pack_start(GTK_BOX(box1), button, TRUE, TRUE, 0);

  /*  fileentry = gtk_entry_new();
  gtk_widget_set_usize(fileentry, 32, 0);
  gtk_entry_set_text(GTK_ENTRY(entry), buf);
  gtk_widget_show(fileentry);*/

  gtk_widget_show(button);
  gtk_widget_show(box1);
  gtk_widget_show (window);

  gtk_main ();
  return 0;
}

/*
loadtilesdialog()
{
  GtkWidget *filesel;
  filesel=gtk_file_selection_new ("Load image to use as tiles");
  gtk_window_position(GTK_WINDOW(filesel), GTK_WIN_POS_MOUSE);
** gtk_signal_connect (GTK_OBJECT (GTK_FILE_SELECTION (filesel)->ok_button)
   , "clicked", (GtkSignalFunc) CML_execute_load_from_file, filesel);
}
*/
int expandall
(guchar *mapdat, int tilewidth)
     /**************************************/
{
  gint x, y, tilespersetrow, tilespersetcol, state=0;
  gint mapwidth, mapheight;
  GPixelRgn tsrgn, outrgn;

  gimp_progress_init("Building Preview");

  mapwidth = mapdrw->width;
  mapheight = mapdrw->height;

  tilespersetrow=(tileset->width)/tilewidth;
  tilespersetcol=(tileset->height)/tileheight;

  /* Stuff for initing pixel rgns */
  gimp_pixel_rgn_init(&tsrgn, 
		      tileset, 
		      0, 0, 
		      tileset->width, tileset->height,
		      FALSE, FALSE);
  gimp_pixel_rgn_init(&outrgn, 
		      outdrw, 
		      0, 0, 
		      outdrw->width, outdrw->height,
		      TRUE, TRUE);

   for (y=0; y < mapheight; y++)
     {
       for (x=0; x < mapwidth && state==0; x++)
	 {    
	   state=expand(*(mapdat++), 
			tilespersetrow, tilespersetcol, x, y, tsrgn, outrgn);
	 };
       gimp_progress_update((double) y / (double) mapheight);
     };
   printf("Exited loop\n");
gimp_progress_update((double)1);
return state;
}


int expand(guchar colour, 
/**********/int tileswide, int tileshigh, int xpos, int ypos, 
	    GPixelRgn tsrgn, GPixelRgn outrgn)
{
int row, col;
guchar *tiletaken;

/* TODO: Find some way of carrying on in this situation */
if (colour>tileswide*tileshigh) { 
  printf("\nNo such tile for that colour");
  return -1; 
};

/* printf("%d@%d,%d ", colour, xpos, ypos); */ 

 row=colour/tileswide; /* FIXME: Force rounding down somehow */
 col=colour%tileswide; /* Finds remainder of colour/height */

 /* printf("row=%d col=%d", row, col);*/

 tiletaken = (guchar *) g_malloc(tilewidth*tileheight*4);

 gimp_pixel_rgn_get_rect(&tsrgn, tiletaken, 
			 col*tilewidth, row*tileheight, tilewidth, tileheight);

 gimp_pixel_rgn_set_rect(&outrgn, tiletaken,
		       xpos*tilewidth, ypos*tileheight, tilewidth, tileheight);
return 0;
}


gint32 loadtiles(char *filename, gint32 run_mode)
/***************************************************/
{
  GParam* params;
  gint retvals;
  gint32 imageID, drwID, tilesetdisp;

  printf("\nfile load run mode is %d",run_mode);

  params = gimp_run_procedure ("gimp_file_load",
			       &retvals,
			       PARAM_INT32, run_mode,
			       PARAM_STRING, filename,
			       PARAM_STRING, filename,
			       PARAM_END);

  imageID = params[1].data.d_image;
 
  tilesetdisp = gimp_display_new(imageID);

  params = gimp_run_procedure ("gimp_image_active_drawable",
			       &retvals,
			       PARAM_IMAGE, imageID,
			       PARAM_END);
  drwID= params[1].data.d_image;

 if (gimp_drawable_type(drwID) != ( RGB_IMAGE || RGBA_IMAGE )) 
   params = gimp_run_procedure("gimp_convert_rgb", 
			       &retvals, PARAM_IMAGE, imageID, PARAM_END);
  return drwID;
}


guchar *scanmap()
/****************/ 
{
 GPixelRgn wholemap;
 guchar *mapdat;
gint mapwidth, mapheight;

/* get width and height of the map drawable */
 mapwidth = mapdrw->width;
 mapheight = mapdrw->height;
 printf("Map width is %d, Map height is %d", mapwidth, mapheight);

gimp_pixel_rgn_init(&wholemap, mapdrw, 0, 0, mapwidth, mapheight, FALSE, FALSE);
 mapdat = (guchar *) g_malloc(mapwidth*mapheight);
 gimp_pixel_rgn_get_rect(&wholemap, mapdat, 0, 0, mapwidth, mapheight);
 
/* mapdat contains nice index colour info for the map, inc the pointer to get the next pixel, eg *(mapdat++) */

return mapdat;
}


gint32 makenewoutput(width, height, alpha)
/***************************/
{
gint imageID, layerID;
gint32 outdrw;
gint retvals;
GParam* params;

imageID=gimp_image_new(width, height, RGB);
gimp_image_set_filename(imageID, "Level Preview");
printf("alpha is %d", alpha); 
switch (alpha)
  {
  case 3:
 layerID = gimp_layer_new (imageID, 
			   "Tile Map", 
			   width, height, 
			   RGB_IMAGE, 100, NORMAL_MODE);
 break;

  case 4:
 layerID = gimp_layer_new (imageID, 
			   "Tile Map", 
			   width, height, 
			   RGBA_IMAGE, 100, NORMAL_MODE);
 break;

  default:
    printf("\nSomething has gone very wrong");
  };

gimp_image_add_layer (imageID, layerID, 0);

params = gimp_run_procedure ("gimp_image_active_drawable",
			       &retvals,
			       PARAM_IMAGE, imageID,
			       PARAM_END);
outdrw=params[1].data.d_image;

return outdrw;
};

/* To run procedure from pdb: */
/* GParam* gimp_run_procedure(char *name, int *nreturnvals,..); */
/* Return vals get spewed into GParam* array */
/* See loadtiles() */
