#import <Cocoa/Cocoa.h>
#include <OpenGL/OpenGL.h>

@interface YsMacDelegate : NSObject /* < NSApplicationDelegate > */
/* Example: Fire has the same problem no explanation */
{
}
- (BOOL) applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication;
@end

@implementation YsMacDelegate
- (BOOL) applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
{
	return YES;
}
@end



static void YsPollEvent(void)
{
	NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];

	while(1)
	{
		[pool release];
		pool=[[NSAutoreleasePool alloc] init];
	
		NSEvent *event;
		event=[NSApp
			   nextEventMatchingMask:NSAnyEventMask
			   untilDate: [NSDate distantPast]
			   inMode: NSDefaultRunLoopMode
			   dequeue:YES];
		if(event!=nil)
		{
			[NSApp sendEvent:event];
			[NSApp updateWindows];
		}
		else
		{
			break;
		}
	}

	[pool release];	
}



@interface YsOpenGLWindow : NSWindow
{
}
- (void) keyDown:(NSEvent *)theEvent;
@end

@implementation YsOpenGLWindow
- (void) keyDown:(NSEvent *)theEvent
{
	exit(1);
}

@end


@interface YsOpenGLView : NSOpenGLView 
{
}
- (void) drawRect: (NSRect) bounds;
@end

@implementation YsOpenGLView
-(void) drawRect: (NSRect) bounds
{
 	static float top=0.0;
	
	glClearColor(0,0,0,0);
	glClear(GL_COLOR_BUFFER_BIT);
	
	glColor3ub(0,255,0);
	
	glBegin(GL_POLYGON);
	glVertex2f(top,0.1);
	glVertex2f(0.3,0.8);
	glVertex2f(0.7,0.8);
	glEnd();
	
	top+=0.1;
	if(top>1.0)
	{
		top=0.0;
	}
	glFlush();
	
	[[self openGLContext] flushBuffer];
}
@end


static YsOpenGLWindow *ysWnd=nil;
static YsOpenGLView *ysView=nil;

static void YsOpenWindow(void)
{
	NSRect contRect;
	contRect=NSMakeRect(32, 32, 800, 600);  // Top-Y coordinate is neglected.  Why?
	
	unsigned int winStyle=NSTitledWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask;
	
	ysWnd=[YsOpenGLWindow alloc];
	[ysWnd
		initWithContentRect:contRect
		styleMask:winStyle
		backing:NSBackingStoreBuffered 
		defer:NO];

	NSOpenGLPixelFormat *format;
	NSOpenGLPixelFormatAttribute formatAttrib[]=
	{
		NSOpenGLPFAWindow,
		NSOpenGLPFADepthSize,(NSOpenGLPixelFormatAttribute)32,
		NSOpenGLPFADoubleBuffer,
		0
	};
	format=[NSOpenGLPixelFormat alloc];
	[format initWithAttributes: formatAttrib];
	
	ysView=[YsOpenGLView alloc];
	contRect=NSMakeRect(0,0,800,600);
	[ysView
		initWithFrame:contRect
		pixelFormat:format];
	
	[ysWnd setContentView:ysView];
	[ysWnd makeFirstResponder:ysView];
	
	[ysWnd makeKeyAndOrderFront:nil];
	[ysWnd makeMainWindow];
}

int main(int argc, char *argv[])
{
    // return NSApplicationMain(argc,  (const char **) argv);
	
	[NSApplication sharedApplication];
	[NSBundle loadNibNamed:@"MainMenu" owner:NSApp];

	YsMacDelegate *delegate;
	delegate=[YsMacDelegate alloc];
	[delegate init];
	[NSApp setDelegate: delegate];
	
	[NSApp finishLaunching];

	YsOpenWindow();
	
	while(1)
	{
		YsPollEvent();
		[ysView setNeedsDisplay: YES];
	}
}
