1//
2//  main.m
3//  namebench
4//
5//  Created by Thomas Stromberg on 9/10/09.
6//  Copyright __MyCompanyName__ 2009. All rights reserved.
7//
8
9#import <Python/Python.h>
10#import <Cocoa/Cocoa.h>
11
12int main(int argc, char *argv[])
13{
14    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
15
16    NSBundle *mainBundle = [NSBundle mainBundle];
17    NSString *resourcePath = [mainBundle resourcePath];
18    NSArray *pythonPathArray = [NSArray arrayWithObjects: resourcePath, [resourcePath stringByAppendingPathComponent:@"PyObjC"], nil];
19
20    setenv("PYTHONPATH", [[pythonPathArray componentsJoinedByString:@":"] UTF8String], 1);
21
22    NSArray *possibleMainExtensions = [NSArray arrayWithObjects: @"py", @"pyc", @"pyo", nil];
23    NSString *mainFilePath = nil;
24
25    for (NSString *possibleMainExtension in possibleMainExtensions) {
26        mainFilePath = [mainBundle pathForResource: @"main" ofType: possibleMainExtension];
27        if ( mainFilePath != nil ) break;
28    }
29
30	if ( !mainFilePath ) {
31        [NSException raise: NSInternalInconsistencyException format: @"%s:%d main() Failed to find the Main.{py,pyc,pyo} file in the application wrapper's Resources directory.", __FILE__, __LINE__];
32    }
33
34    Py_SetProgramName("/usr/bin/python");
35    Py_Initialize();
36    PySys_SetArgv(argc, (char **)argv);
37
38    const char *mainFilePathPtr = [mainFilePath UTF8String];
39    FILE *mainFile = fopen(mainFilePathPtr, "r");
40    int result = PyRun_SimpleFile(mainFile, (char *)[[mainFilePath lastPathComponent] UTF8String]);
41
42    if ( result != 0 )
43        [NSException raise: NSInternalInconsistencyException
44                    format: @"%s:%d main() PyRun_SimpleFile failed with file '%@'.  See console for errors.", __FILE__, __LINE__, mainFilePath];
45
46    [pool drain];
47
48    return result;
49}
50