/*
 *  MWFile.c
 *  TEST2
 *
 *  Created by matthew on Tue Apr 29 2003.
 *  Copyright (c) 2003 __MyCompanyName__. All rights reserved.
 *
 */
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
#include "MWPath.h"
BOOL isAbsPath(NSString *who)
{
    unsigned len;
    len = [who length];
	NSLog(@"who = %d\n", len);
    if(len == 0) return NO;
    if([who characterAtIndex: 0] == '/') return YES;
    else return NO;
}
#define LASTCHAR(X) [X characterAtIndex: [X length] - 1]
NSString *rel2abs(NSString *rootPath, NSString *myPath)
{
    NSArray *rtarray, *patharray;
    int i, n,  l1, l2;
    NSMutableString *absString;

    if(isAbsPath(myPath)) return myPath;

    absString = [[NSMutableString alloc ] init];
    //count how many levels in root and total
   rtarray = [rootPath pathComponents];
    l1 = [rtarray count];
    //count how many ups in path and total
   patharray = [myPath pathComponents];
    l2 = [patharray count];
    n = 0;
    for(i = 0; i < l2; i++)
    {
        if([[patharray objectAtIndex: i] isEqualToString: @".."])
            n++;
        else
            break;
    }
     //copy the root up to the number of ups
     for(i = 0; i < l1 - n; i++)
     {
        [absString appendString: [rtarray objectAtIndex: i]];
        if (i > 0) [absString appendString: @"/"];
    }
    
     for(i = n; i < l2; i++)
     {
        [absString appendString: [patharray objectAtIndex: i]];
        [absString appendString: @"/"];
    }
    if(LASTCHAR(myPath) != '/') //eat the last character
        [absString deleteCharactersInRange: NSMakeRange([absString length] - 1, 1)];
    
    
    //and then the rest of the way down
    [absString autorelease];
    return absString;
}

NSString *abs2rel(NSString *rootPath, NSString *aPath)
{
    NSArray *rtarray, *patharray;
    int i,  l1, l2, ll, rc;
    NSMutableString *relString; NSString *myPath;
    myPath =  [aPath stringByStandardizingPath];
    
    if(!isAbsPath(myPath)) return myPath;

    relString = [[NSMutableString alloc ] init];
    //root to array
    rtarray = [rootPath pathComponents];
    l1 = [rtarray count];
    //path to array
    patharray = [myPath pathComponents];
    l2 = [patharray count];
    ll = (l1 < l2)? l1 : l2;
    //count how many levels are in common
    for(i = 0, rc = 0; i < ll; i++)
    {
    //how many to root after that
        if([[rtarray objectAtIndex: i] isEqualToString: [patharray objectAtIndex: i]])
            rc++;
        else
            break;
    }
    //make dots up
    for (i = 0; i < l1 - rc; i++)
    {
        [relString appendString: @"../"];
    }
    //make path back down
    for (i =  rc; i < l2 ; i++)
    {
        [relString appendString: [patharray objectAtIndex: i]];
        [relString appendString: @"/"];
    }

    if(LASTCHAR(myPath) != '/') //eat the last character
        [relString deleteCharactersInRange: NSMakeRange([relString length] - 1, 1)];

    //return it
    [relString autorelease];
    return relString;
}