/* bvadnais Wed Apr 24 14:23:21 PDT 1996
 * 
 * Since PDO 4.0 does not contain the projectInfo command, this
 * provides the same functionality for the purposes of our project
 * makefile extensions.  It it not a perfect replacement.
 */

#import <Foundation/Foundation.h>

static NSString *DefaultDictionaryFile = @"PB.project";
static NSString *DefaultDirectory = @".";

volatile void usage(const char *pgm)
{
    fprintf(stderr, "Usage:  %s key1 [key2 key3 ...] [-inDirectory <path>] [-file <file>]\n", pgm);
    exit(1);
}

/* A set of categories to make objects polymorphic would be cleaner,
 * but this is just a quick and dirty program.
 */

void printObject(id anObject)
{
    NSString *printString;
    
    if ([anObject isKindOfClass:[NSArray class]]) {
        printString = [anObject componentsJoinedByString:@" "];
    } else {
        printString = [anObject description];
    } /* What about dictionaries, etc?  Description should do for most cases */

    printf("%s\n", [printString cString]);
}

void main (int argc, const char *argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSString *dictionaryFile = DefaultDictionaryFile;
    NSString *dictionaryDirectory = DefaultDirectory;    
    NSString *dictionaryPath;
    NSDictionary *dictionary;
    NSMutableArray *keysArray = [NSMutableArray array];
    NSEnumerator *keyEnum;
    NSString *key;
    NSString *argument;
    int i;
    int exitValue;
    id collection;

    if (argc < 2)
        usage(argv[0]);

    for (i = 1; i < argc; i++) {
	argument = [NSString stringWithCString:argv[i]];
        if ([argument isEqualToString:@"-inDirectory"]) {
            if (++i == argc)
		usage(argv[0]);
            dictionaryDirectory = [NSString stringWithCString:argv[i]];
        } else if ([argument isEqualToString:@"-file"]) {
            if (++i == argc)
                usage(argv[0]);
            dictionaryFile = [NSString stringWithCString:argv[i]];
        } else {
            [keysArray addObject:argument];
        }
    }

    dictionaryPath = [dictionaryDirectory stringByAppendingPathComponent:dictionaryFile];
    dictionary = [[NSDictionary alloc] initWithContentsOfFile:dictionaryPath];
    if (!dictionary) {
        NSLog(@"Could not find or open the file '%@'", dictionaryPath);
        exit(1);
    }

    collection = dictionary;
    keyEnum = [keysArray objectEnumerator];
    while ((key = [keyEnum nextObject])) {
        collection = [collection objectForKey:key];
    }

    if (collection) {
	exitValue = 0;
        printObject(collection);
    } else {
        exitValue = 1;
    }

    [pool release];
    exit(exitValue);
}
