#import "MiscVolumeLight.h"
#import <stdio.h>

@implementation MiscVolumeLight

- drawSelf:(const NXRect*) rects:(int) rectCount
	{
	int just_erase=0;
	float left,right;
	NXRect backgroundRect=bounds;
	
	//printf ("Displaying\n");
	
	if ([delegate respondsTo:@selector(meterWillUpdate:)])
		[delegate meterWillUpdate:self];

//	if (![window isVisible]) return self;		// no window to draw in.
	
	//printf ("Window Visible\n");
	
	//if (![window isVisible]) return NULL;		// no window to draw in.
	// the above has been turned off because when loading Resound,
	// the sound meter wouldn't display until a sound was being played
	// or recorded!
	
	
	// first to check to see if the sound lock is current
	////printf ("Meter\n");
	if (sound!=NULL)
		{
		int status=NX_SoundStopped;
		id actual_sound=NULL;			// quiets compiler complaints
		
		//printf ("Sound ain't Null\n");
		
		if ([sound isKindOf:[Sound class]]) 
			{actual_sound=sound;}
		else if ([sound isKindOf:[SoundView class]])
			{actual_sound=[sound soundBeingProcessed];}
		status=[actual_sound status];
		if (status==NX_SoundStopped||
			status==NX_SoundInitialized||
			status==NX_SoundFreed) 
		{just_erase=1;}
			
		// Then modify the meter to match the sound	
		
		else if (status==NX_SoundRecordingPaused||
				 status==NX_SoundRecording||
				 status==NX_SoundRecordingPending)
		{[self setToInput];}
		
		else if (status==NX_SoundPlayingPaused||
				 status==NX_SoundPlaying||
				 status==NX_SoundPlayingPending)
		{[self setToOutput];}
		
		if ([actual_sound channelCount]>1)
			{[self setStereo];}
		else {[self setMono];}
		}
	

	
	
	
	if (bezeled)
		{
		backgroundRect.origin.x		+=VOLUMEMETER_BACKGROUND_INSET; 
		backgroundRect.size.width	-=VOLUMEMETER_BACKGROUND_INSET*2;
		backgroundRect.origin.y		+=VOLUMEMETER_BACKGROUND_INSET; 
		backgroundRect.size.height	-=VOLUMEMETER_BACKGROUND_INSET*2;
		}
	
	if (!VOLUMEMETER_can_draw(&bounds)) return self;	// can't draw
	//printf("Big enough\n");
	if (bezeled) NXDrawGrayBezel(&bounds,NULL);

	if (running&&!just_erase)
		{
		//printf ("DRAWING!\n");
		left=0;right=0;
		
		if (input&&input_device!=NULL) 
			[input_device getPeakLeft:&left right:&right];
		
		if ((!input)&&output_device!=NULL)
			[output_device getPeakLeft:&left right:&right];
			
		PSsetgray((left+right)/2.0);
		NXRectFill(&backgroundRect);
		}
	just_erase=0;
	NXPing();
	if ([delegate respondsTo:@selector(meterDidUpdate:)])
		[delegate meterDidUpdate:self];
	return self;
	}

@end