#import <appkit/appkit.h>
#import "PBNames.h"

static void show (NXStream * outp, const char * name)
{	NXAtom pbKey = ! name ? NXGeneralPboard :
		name[0] == '-' ? [[PBNames new] key:name+1] :
		NXUniqueString(name);
	id pb = [Pasteboard newName:pbKey];
	const NXAtom * t;

	NXPrintf(outp, "%s\t%d\n", [pb name], [pb changeCount]);
	for (t = [pb types]; *t; ++ t)
		NXPrintf(outp, "\t%s\n", *t);
}
static void listener ()
{	id myListener = [[Listener new] setServicesDelegate:[Object new]];

	if ([myListener checkInAs:"pbtool"])
		[myListener error:"pbtool in use\n"];
	[myListener addPort];
	[Listener run];
}
@implementation Object (show)
- show:pb userData:(const char *)ud error:(char **)msg
{	NXStream * outp = NXOpenFile(1, NX_WRITEONLY);

	show(outp, [pb name]);
	NXClose(outp);
	return self;
}
@end
@implementation Object (pipe)
- pipe:pb userData:(const char *)ud error:(char **)msg
{	const NXAtom * types = [pb types];
	char * buf; int len;
	char cmd [BUFSIZ];
	FILE * fp;

	if (types[0])
		[pb readType:types[0] data:&buf length:&len];

	sprintf(cmd, "%s | %s/put -ascii '%s'", ud, PATH, [pb name]);
	fp = popen(cmd, "w");

	if (types[0])
	{	fwrite(buf, len, 1, fp);	// Vorsicht: SIGPIPE...
		if (len && buf[len-1] != '\n')
			putc('\n', fp);
	}
	pclose(fp);

	if (types[0])
		[pb deallocatePasteboardData:buf length:len];
	return self;
}
@end
int main (int argc, char * argv [])
{
	if (argc > 1)
	{	NXStream * outp = NXOpenFile(1, NX_WRITEONLY);

		while (++ argv, -- argc)
			show(outp, *argv);
		NXFlush(outp);
	}
	else
		listener();
	return 0;
}
