/* File: SoundAndLight.m - Set screen brightness and speaker volume on login.
 *
 * By: Christopher Lane
 * Symbolic Systems Resources Group
 * Knowledge Systems Laboratory
 * Stanford University
 *
 * Date: 15 January 1991
 *
 * Copyright: 1989, 1990 & 1991 by The Leland Stanford Junior University.
 * This program may be distributed without restriction for non-commercial use.
 */

#import "SoundAndLight.h"

static NXDefaultsVector defaults = {
    {"Brightness", BRIGHTNESS},
    {"LeftVolume", LEFTVOLUME},
    {"RightVolume", RIGHTVOLUME},
    {"Mute", MUTE},
    {NULL}
    };
	
@implementation SoundAndLight

+ initialize
{
    NXRegisterDefaults(APPLICATION, defaults);
    return [super initialize];
}

- run
{
    [self setBrightness:[self getIntDefault:"Brightness"]];
    [self setVolume:[self getIntDefault:"LeftVolume"] :[self getIntDefault:"RightVolume"]];
    [self setMute:[self getBoolDefault:"Mute"]];
    
    return self;
}

- setBrightness:(int) value
{
    int device;
	
    if((device = open(DEVICE, O_RDWR, 0)) == CERROR) [self unix_error:"open"];
    if(ioctl(device, DKIOCBRIGHT, &value) == CERROR) [self unix_error:"ioctl"]; 
    if(close(device) == CERROR) [self unix_error:"close"];
    
    return self;
}

- setVolume:(int) lchan :(int) rchan
{
    int error;
    
    if((error = SNDSetVolume(lchan, rchan)) != SND_ERR_NONE)
        [self sound_error:"SNDSetVolume" errno:error];
        
    return self;
}

- setMute:(BOOL) state
{
    int error;
    
    if((error = SNDSetMute((state == YES) ? FALSE : TRUE)) != SND_ERR_NONE)
        [self sound_error:"SNDSetMute" errno:error];
    
    return self;
}

- (int) getIntDefault:(char *) string
{
   const char *value;
   
   if((value = NXGetDefaultValue(APPLICATION, string)) == NULL) {
	(void) fprintf(stderr, "%s default not defined for %d!\n", string, APPLICATION);
	exit(EXIT_FAILURE);
	}
	
   return atoi(value);
}

- (BOOL) getBoolDefault:(char *) string
{
   const char *value;
   
   if((value = NXGetDefaultValue(APPLICATION, string)) == NULL) {
	(void) fprintf(stderr, "%s default not defined for %d!\n", string, APPLICATION);
	exit(EXIT_FAILURE);
	}
	
   return (strncmp(value, "Yes", 1) == 0) ? YES : NO;
}

- (void) unix_error:(char *) string
{
    perror(string);
    exit(EXIT_FAILURE);
}

- (void) sound_error:(char *) string errno:(int) error
{
    (void) fprintf(stderr, "%s: %s\n", string, SNDSoundError(error));
    exit(EXIT_FAILURE);
}

@end
