#include <stdlib.h>
#include <stdio.h>
#include <libsoup/soup.h>

char buffer[8192];
static GMainLoop *loop;

static void
close_callback (GObject      *object,
		GAsyncResult *result,
		gpointer      user_data)
{
  g_input_stream_close_finish (G_INPUT_STREAM (object), result, NULL);
  printf("closed\n");
}

static void
read_callback (GObject      *object,
	       GAsyncResult *result,
	       gpointer      user_data)
{
    GInputStream *stream = G_INPUT_STREAM (object);
    size_t nread = g_input_stream_read_finish (stream, result, NULL);
    if (nread > 0) {
        printf("read good!\n");
        g_input_stream_read_async (stream, buffer, 8192, 0, NULL, read_callback, NULL);
    }
    else if (nread == 0) {
        g_input_stream_close_async (stream, 0,
                NULL, close_callback, NULL);
    }
}

static void
send_callback (GObject      *object,
	       GAsyncResult *result,
	       gpointer      user_data)
{
    GInputStream *stream = soup_request_send_finish (SOUP_REQUEST (object), result, NULL);
    g_input_stream_read_async (stream, buffer, 8192, 0, NULL, read_callback, NULL);
}

int main(int argc, char **argv)
{
    SoupSession *s;
    SoupURI *uri;
    SoupRequest *req;
    s = soup_session_new_with_options ("user-agent",
            "gvfs/",
            NULL);
    uri = soup_uri_new (argv[1]);
    req = soup_session_request_uri (s, uri, NULL);
    soup_request_send_async (req, NULL, send_callback, NULL);

    loop = g_main_loop_new (NULL, TRUE);
    g_main_loop_run (loop);

    return 0;
}
