#include <gtk/gtk.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>


gboolean handler (GIOChannel * channel,
		  GIOCondition condition,
		  gpointer data);

void
clicked (void)
{
	g_printerr ("click!\n");
}

int
main (int argc,
      char * argv[])
{
	GtkWidget * window;
	GtkWidget * button;

	gtk_init (&argc, &argv);

	window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
	button = gtk_button_new_with_label ("Click me");
	g_signal_connect (button, "clicked", G_CALLBACK (clicked), NULL);
	gtk_container_add (GTK_CONTAINER (window), button);
	gtk_widget_show_all (window);
	g_signal_connect (window, "destroy", G_CALLBACK (gtk_main_quit), NULL);

	//my $FIFOFile='fifo';
	//my $fifofh;
	//if (!-e $FIFOFile)
	if (! g_file_test ("fifo", G_FILE_TEST_EXISTS))
	{
    		//system 'mkfifo',$FIFOFile;
		system ("mkfifo fifo");
	//	warn "Created fifo $FIFOFile\n";
		g_printerr ("Created fifo\n");
	}
	//if (-p $FIFOFile)
//	if (g_file_test ("fifo", G_FILE_TEST_IS_PIPE))
	{
		GIOChannel * channel;
		int fifofd;
		//sysopen $fifofh,$FIFOFile,O_NONBLOCK;
		fifofd = open ("fifo", O_NONBLOCK);
		if (0 > fifofd) {
			perror ("fifo");
			return -1;
		}
		channel = g_io_channel_unix_new (fifofd);
		g_io_add_watch (channel, G_IO_IN, handler, NULL);
		g_io_channel_unref (channel);
	//	watch_it ();
	}

	/* Gtk2->main; */
	gtk_main ();

	return 0;
}


//sub CmdFromFIFO
gboolean
handler (GIOChannel * channel,
	 GIOCondition condition G_GNUC_UNUSED,
	 gpointer data G_GNUC_UNUSED)
{
	int nread;
	char buffer[1024];
	g_printerr ("foo\n");
	/*while (my $line=<$fifofh>)
	{	print "got $line";
	}
	*/
	while (0 < (nread = read (g_io_channel_unix_get_fd (channel), buffer, 1024)))
	{ write (2, buffer, nread); write (2, "\n", 1);
	}

	return TRUE;
}

