// OATextFieldFormatter:Object
// 
// COPYRIGHT 1994 BY M. ONYSCHUK AND ASSOCIATES INC.
// ALL RIGHTS RESERVED.

#import "OATextFieldFormatter.h"

#import <objc/hashtable.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

@implementation OATextFieldFormatter:Object


// Local Functions

static char *
build_string_from_format_v(const char   *format_str,
                           va_list       param_list)
// This function takes a format string and a variable argument
// list. It returns a pointer to a newly allocated chunk of
// memory containing the results of sprintf'ing the format string
// and va_list into the new memory.
// 
// This function does not limit input data to a predetermined
// size.
{
    long                l;
    char               *str;

    NXStream           *stream;

    stream = NXOpenMemory(NULL, 0, NX_READWRITE);
    
    NXVPrintf(stream, format_str, param_list);
    NXFlush(stream);
    
    NXSeek(stream, 0, NX_FROMEND);
    l = NXTell(stream);
    
    str = (char *)malloc(sizeof(char) * (l+1));
    
    NXSeek(stream, 0, NX_FROMSTART);
    NXRead(stream, str, l);

    str[l] = '\0';
    
    NXCloseMemory(stream, NX_FREEBUFFER);
    return str;
}


- free
{
    if (output) {
    	NXZoneFree([self zone], output);
    }
    return [super free];
}


- filterSubstring:(unsigned char *)inputText
    ofSize:(int)inputSize
    at:(int)position
{
    char               *myOutput;

    myOutput = NXZoneMalloc([self zone],
			    (sizeof(unsigned char) * inputSize) + 1);

    strncpy(myOutput, inputText, inputSize);
    myOutput[inputSize] = '\0';

    [self setOutputNoCopy:myOutput];

    return self;
}


- (BOOL)formatString:(unsigned char *)inputText
{
    [self setOutput:inputText];
    return NO;
}


- setTextFieldCell:aCell
{
    return self;
}


- (const char *)output
{
    return output;
}


- setOutput:(const char *)aValue
{	
    return [self setOutputNoCopy:(aValue) ?
    	NXCopyStringBufferFromZone(aValue, [self zone]) : NULL];
}


- setOutputNoCopy:(const char *)aValue
{
    if (output) {
    	NXZoneFree([self zone], output);
    }
    
    output = aValue;
    
    return self;
}


- setOutputFormat:(const char *)aFormat, ...
{
    char               *aString;
    va_list             paramList;

    va_start(paramList, aFormat);
    aString = build_string_from_format_v(aFormat, paramList);
    va_end(param_list);

    [self setOutput:aString];

    free(aString);

    return self;
}

@end
