#import <Foundation/Foundation.h>

void usage() {
    printf("Usage: osascript -e <script source>\n");
}

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    int retVal = 0;

    // check arguments
    if (argc < 3) {
        usage();
        retVal = 1;
    } else if (strcmp(argv[1], "-e") != 0) {
        usage();
        retVal = 1;
    } else {
        // main part
        NSAppleScript* as = [[NSAppleScript alloc] initWithSource:
                             [NSString stringWithUTF8String:argv[2]]];
        if (as == nil) {
            printf("Error creating a script object.\n");
            retVal = 1;
        } else {
            NSDictionary* errorInfo;
            NSAppleEventDescriptor* desc = [as executeAndReturnError:&errorInfo];
            if (desc == nil) {
                printf("Error running script.\n");
                retVal = 1;
            }
            if ([desc descriptorType] != typeNull) {
                printf("%s\n", [[desc stringValue] UTF8String]);
            }
        }
    }

    [pool release];
    return 0;
}
