//
//  main.m
//  Shiira
//
//  Created by Makoto Kinoshita on 06/02/06.
//  Copyright __MyCompanyName__ 2006 . All rights reserved.
//

#import <Cocoa/Cocoa.h>
#import <ExceptionHandling/NSExceptionHandler.h>

void printStackTrace(NSException* ex)
{
     NSString *stack = [[ex userInfo] objectForKey:NSStackTraceKey];
     NSTask *ls=[[NSTask alloc] init];
     NSString *pid = [[NSNumber numberWithInt:getpid()] stringValue];
     NSMutableArray *args = [NSMutableArray arrayWithCapacity:20];

     [args addObject:@"-p"];
     [args addObject:pid];
     [args addObjectsFromArray:[stack componentsSeparatedByString:@"  "]];

     [ls setLaunchPath:@"/usr/bin/atos"];
     [ls setArguments:args];
     [ls launch];
     [ls waitUntilExit];
     
     [ls release];
}

@interface SRExceptionHandler : NSObject
{
}
@end

@implementation SRExceptionHandler

- (BOOL)exceptionHandler:(NSExceptionHandler*)exHandler 
        shouldLogException:(NSException*)exception mask:(unsigned int)mask
{
    printStackTrace(exception);
    return YES;
}

@end

int main(int argc, char *argv[])
{
#if 0
    return NSApplicationMain(argc, (const char **) argv);
#else
    SRExceptionHandler* srHandler;
    NSExceptionHandler* exHandler;
    srHandler = [[SRExceptionHandler alloc] init];
    exHandler = [NSExceptionHandler defaultExceptionHandler];
    [exHandler setExceptionHandlingMask:NSLogAndHandleEveryExceptionMask];
    [exHandler setDelegate:srHandler];
    
    int result = 0;
    @try {
        result = NSApplicationMain(argc, (const char **) argv);
    }
    @catch (NSException* ex) {
        NSLog(@"Exception: %@, %@", [ex name], [ex reason]);
        printStackTrace(ex);
    }
    
    return result;
#endif
}
