// THIS FILE IS VERY BROKEN.  DO NO USE

#import <Foundation/Foundation.h>
#include <assert.h>

@interface Datagram : NSObject
{
	int dgId;
}
-(id)initWithDatagramType:(int)datagramType;
-(void)dealloc;
-(NSString *)description;
@property (readonly) int dgId;
@end

@implementation Datagram
@synthesize dgId;
- (NSString *)description {
	return [NSString stringWithFormat: @"Datagram: dgId:", dgId];
}

-(id)initWithDatagramType:(int)datagramType {
	self = [super init];
	if (!self) return self;
	dgId = datagramType; 
	return self;
}

-(void)dealloc {
	NSLog(@"dealloc datagram: %d",dgId);
	[super dealloc];
}
@end

// Pretend sequence of packet ID's coming from a sonar
int testSeq[] = {
	3, 12, 4, 19, 8, 
	2, 2, 2, 2, 2, 2, 2, 2, 2, 9, 
	2, 2, 2, 2, 9, 
	2,2,2,2,9,
	1,2,3,4,5,6,7,8,9,
	11,12,13,14,15,16,17,18,19,
	3, 
	0 // End of sequence / array sentinal
};

@interface DatagramFile : NSObject <NSFastEnumeration>
{
    // No ivars
}
-(id)init;
@end

@implementation DatagramFile
-(id)init {
    self = [super init];
    if (!self) return self;
    // NOP
    return self;
}

- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len
{
	NSLog(@"In countByEnumeratingWithState: stackbuf: %p, count: %d", stackbuf, len);
	NSLog(@"\t state struct: state=%d %p %p", state->state, state->itemsPtr, state->mutationsPtr);
	if (stackbuf) {
		NSLog(@"***INSPECTING STACKBUF\n");
		for(int i=0;i<1000 && stackbuf[i]!=0;i++) {
			NSLog(@"Stackbuf %d: %p",i,stackbuf[i]); // What should I do with stackbuf[i]?
		}
	}
	if (0 == state->state) {	
		NSLog(@"Initializing loop");
		assert(0==state->itemsPtr);
		state->itemsPtr = malloc(sizeof(id)*16);
		memset(state->itemsPtr, 0, sizeof(id)*16);
	} else if (0==len) {
		// Will this get called if the call uses break inside the for loop?
		NSLog(@"Finished loop.  cleanup");
		free(state->itemsPtr);
		state->itemsPtr = 0;
        return 0;
	}
	state->mutationsPtr = (unsigned long *)self; // Tell the caller that the file has not changed
	
	NSUInteger count=0;
	for (; count < len && testSeq[state->state]!=0; count++, state->state++) {
		NSLog(@"Creating datagram of type %d state: %d count %d",testSeq[state->state], state->state, count);
		Datagram *dg = [[Datagram alloc] initWithDatagramType:testSeq[state->state]];
		state->itemsPtr[count] = dg;
		[dg autorelease];
	}
	NSLog(@"countByEnumeratingWithState read %d datagrams.  state->state: %d",count, state->state);
	return count;
}
@end // implementation DatagramFile

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	
    DatagramFile *df = [[DatagramFile alloc] init];
    for (Datagram *dg in df) {
        NSLog(@"About to read datagram in for");
        NSLog(@"  Datagram type: %d", [dg dgId]);
    }
	
    NSLog(@"about to drain pool");
    [pool drain];
    NSLog(@"pool drained.  ready for winter");
    return 0;
}
