#import "XMovieDocument.h"
#import "MovieView.h"
#import "AppController.h"

int ImageSort(id num1, id num2, void *context)
{
    NSRange	r0, r1;
    NSString *s1, *s2;
    float v1, v2;

    r0 = [num1 rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]];
    r1 = [num1 rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet] options:NSBackwardsSearch];
    if (r0.length == 0)
        return [(NSString *)num1 compare:num2];

    r0.length += r1.location - r0.location;
    s1 = [num1 substringWithRange:r0];

    r0 = [num2 rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]];
    r1 = [num2 rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet] options:NSBackwardsSearch];
    if (r0.length == 0)
        return [(NSString *)num1 compare:num2];

    r0.length += r1.location - r0.location;
    s2 = [num2 substringWithRange:r0];

    v1 = [s1 floatValue];
    v2 = [s2 floatValue];
    
    if (v1 < v2)
        return NSOrderedAscending;
    else if (v1 > v2)
        return NSOrderedDescending;
    else
        return NSOrderedSame;
}

@implementation XMovieDocument

+ (NSSet *) readableFileTypes;
{
    return [NSSet setWithObject:@"xmovie"];
}

+ (void) load
{
    [[NSApp delegate] registerDocumentClass:[self class]];
}

- initWithContentsOfFile:(NSString *)path
{
    BOOL isDir=NO;
    NSArray *fileNames = nil;
    int		 i;
    NSString *imagePath;
    NSImage	 *image;
    NSSize    size;
    NSMutableArray *images;
    NSFileManager *manager = [NSFileManager defaultManager];

    [super initWithContentsOfFile:path];
    
    if (![NSBundle loadNibNamed:@"XMovieDocument.nib" owner: self])
    {
            [self autorelease];
            return nil;
    }

    if ([manager fileExistsAtPath:path isDirectory:&isDir] && isDir)
        fileNames = [[manager directoryContentsAtPath:path] sortedArrayUsingFunction:ImageSort context:NULL];

    if ([fileNames count] == 0)
    {
        [self autorelease];
        return nil;
    }

    images = [NSMutableArray arrayWithCapacity:[fileNames count]];
    
    for (i = 0; i < [fileNames count]; ++i)
    {
        imagePath = [path stringByAppendingPathComponent:[fileNames objectAtIndex:i]];
        NS_DURING
            image = [[NSImage allocWithZone:[self zone]] initWithContentsOfFile:imagePath];
        NS_HANDLER
            NSLog (@"'%@' does not appear to be an image", imagePath);
            image = nil;
        NS_ENDHANDLER

        if (image != nil)
            [images addObject:image];
        [image release];
    }
    [display setFrames:images];
    image = [images lastObject];

    size = [image size];
    size.height += 20;
    [window setContentSize:size];
    [window makeKeyAndOrderFront:nil];
    
    return self;
}

@end
