/* A variation on a command-line program to run a service.
 * Use it as you see fit.
 * Scott Hess <scott@nic.gac.edu>
 *
 * cc -o service -s -O service.m -lNeXT_s
 * cc -arch m68k -arch i386 -o service -s -O service.m -lNeXT_s
 * cc -arch m68k -arch i386 -arch hppa -o service -s -O service.m -lNeXT_s
 */
#import <appkit/appkit.h>

NXDefaultsVector defs={
    { "Input", "NeXT plain ascii pasteboard type"},
    { "Output", "NeXT plain ascii pasteboard type"},
    { "Service", NULL},
    { NULL, NULL},
};
void main( int argc, char **argv)
{
    Pasteboard *pb=[Pasteboard newUnique];
    const char *inType=NULL, *outType=NULL, *service=NULL;
    NXApp=[Application new];
    NXRegisterDefaults( "service", defs);
    inType=NXGetDefaultValue( "service", "Input");
    outType=NXGetDefaultValue( "service", "Output");
    service=NXGetDefaultValue( "service", "Service");
    if( inType && *inType) {
	NXStream *stream=NXOpenMemory( NULL, 0, NX_WRITEONLY);
	char *data;
	int length, maxLength;
	#define BUFSIZE 4096
	char buf[ BUFSIZE];
	while( (length=fread( buf, BUFSIZE, 1, stdin))>0) {
	    NXWrite( stream, buf, length);
	}
	[pb declareTypes:&inType num:1 owner:nil];
	NXGetMemoryBuffer( stream, &data, &length, &maxLength);
	[pb writeType:inType data:data length:length];
	NXCloseMemory( stream, NX_FREEBUFFER);
    }
    if( NXPerformService( service, pb) && outType && *outType) {
        const char *const *types=[pb types];
	char *data;
	int length;
	while( *types && strcmp( outType, *types)) {
	    types++;
	}
	if( *types) {
	    [pb readType:*types data:&data length:&length];
	    fwrite( data, length, 1, stdout);
	    [pb deallocatePasteboardData:data length:length];
	} else {
	    pb=[pb free];
	    exit( 1);
	}
    }
    pb=[pb free];
}
/*
Allow for a list of input types.
Allow for a list of output types.
Allow to specify file descriptors for input and output types.
Allow for an input source default.
*/
