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

int main (int argc, char * argv [])
{	NXStream * inp, * outp = NXOpenFile(1, NX_WRITEONLY),
		* errp = NXOpenFile(2, NX_WRITEONLY);
	NXAtom type = argc <= 1 ? NXAsciiPboardType :
		argv[1][0] == '-' ? [[PBTypes new] type:argv[1]+1] :
		NXUniqueString(argv[1]);
	NXAtom pbKey = argc <= 2 ? NXGeneralPboard :
		argv[2][0] == '-' ? [[PBNames new] key:argv[2]+1] :
		NXUniqueString(argv[2]);
	id pb = [Pasteboard newName:pbKey];
	const NXAtom * types;

	if (type)
		type = [pb findAvailableTypeFrom:&type num:1];
	else if (types = [pb types])
		type = types[0];

	if (! type)
		[pb error:"no type\n"];
	else if (inp = [pb readTypeToStream:type])
	{	char * buf; int len, maxlen;

		NXPrintf(errp, "'%s' from '%s'\n", type, pbKey), NXFlush(errp);
		NXGetMemoryBuffer(inp, &buf, &len, &maxlen);
		if (len)
		{	NXWrite(outp, buf, len);
			if (buf[len-1] != '\n')
				NXPutc(outp, '\n');
		}
		NXCloseMemory(inp, NX_FREEBUFFER);
	}
	else
		[pb error:"no data\n"];
	NXClose(outp);	// exception bei Fehler
	return 0;
}
