/* 
   common.m

   Copyright (C) 1995, 1996 Ovidiu Predescu and Mircea Oancea.
   All rights reserved.

   Author: Ovidiu Predescu <ovidiu@bx.logicnet.ro>
	   Mircea Oancea <mircea@jupiter.elcom.pub.ro>
	   Florin Mihaila <phil@pathcom.com>
	   Bogdan Baliuc <stark@protv.ro>

   This file is part of libFoundation.

   Permission to use, copy, modify, and distribute this software and its
   documentation for any purpose and without fee is hereby granted, provided
   that the above copyright notice appear in all copies and that both that
   copyright notice and this permission notice appear in supporting
   documentation.

   We disclaim all warranties with regard to this software, including all
   implied warranties of merchantability and fitness, in no event shall
   we be liable for any special, indirect or consequential damages or any
   damages whatsoever resulting from loss of use, data or profits, whether in
   an action of contract, negligence or other tortious action, arising out of
   or in connection with the use or performance of this software.
*/

#include <Foundation/common.h>
#include <Foundation/NSString.h>
#include <Foundation/NSData.h>
#include <Foundation/NSPosixFileDescriptor.h>
#include <Foundation/NSFileManager.h>
#include <Foundation/NSException.h>
#include <Foundation/exceptions/GeneralExceptions.h>
#include <extensions/PrintfFormatScanner.h>
#include <extensions/PrintfScannerHandler.h>

/* Non OpenStep useful things */

void vaRelease(id obj, ...)
{
    va_list args;
    id next_obj;
	
    va_start(args, obj);
    next_obj = obj;
    while(next_obj) {
	[next_obj release];
	next_obj = va_arg(args, id);
    }
	
    va_end(args);
}

BOOL writeToFile(NSString* path, NSData* data, BOOL atomically)
{
    NSString* filename = atomically ?
			      [path stringByAppendingString:@"~"]
			    : path;
    NSPosixFileDescriptor* file;
    BOOL result = YES;

    file = [[[NSPosixFileDescriptor alloc]
		initWithPath:filename flags:O_RDWR|O_CREAT createMode:0666]
		autorelease];
    if (!file)
	return NO;

    TRY {
	[file writeData:data];

	if(atomically)
	    result = [[NSFileManager defaultManager]
			movePath:filename toPath:path handler:nil];
    } END_TRY
    CATCH(PosixFileOperationException) {
	result = NO;
	// Remove the filename from file system
	if (atomically)
	    [[NSFileManager defaultManager]
		removeFileAtPath:filename handler:nil];
    }
    END_CATCH

    return result;
}

char *Ltoa(long nr, char *str, int base)
{
    char buff[34], rest, is_negative;
    int ptr;

    ptr = 32;
    buff[33] = '\0';
    if(nr < 0) {
	is_negative = 1;
	nr = -nr;
    }
    else
	is_negative = 0;

    while(nr != 0) {
	rest = nr % base;
	if(rest > 9)
	    rest += 'A' - 10;
	else
	    rest += '0';
	buff[ptr--] = rest;
	nr /= base;
    }
    if(ptr == 32)
	buff[ptr--] = '0';
    if(is_negative)
	buff[ptr--] = '-';

    Strcpy(str, &buff[ptr+1]);

    return(str);
}

unsigned int hashpjw(const char* name, int len)
{
    register const char* p = name;
    register unsigned hash = 0, hash2;
    register int i, n = len;

    for(i=0; i < n; i++) {
        hash <<= 4;
        hash += *p++;
        if((hash2 = hash & 0xf0000000))
            hash ^= (hash2 >> 24) ^ hash2;
    }
    return hash;
}

NSString* Asprintf(NSString* format, ...)
{
    id string;
    va_list ap;

    va_start(ap, format);
    string = Avsprintf(format, ap);
    va_end(ap);
    return string;
}

NSString* Avsprintf(NSString* format, va_list args)
{
    static BOOL initialized = NO;
    static id objectFormat = nil;
    id formatScanner = [PrintfFormatScanner new];
    id string;

    if(!initialized) {
	initialized = YES;
	objectFormat = [FSObjectFormat new];
    }

    [formatScanner setFormatScannerHandler:objectFormat];
    string = [formatScanner stringWithFormat:format arguments:args];
    [formatScanner release];

    return string;
}
