/*************************************************************************
 * QMan
 * Nils L. Corneliusen, PCTVnet ASA 1999
 *************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <env.h>
#include <fcntl.h>
#include <process.h>
#include <termios.h>
#include <sys/name.h>
#include <sys/sched.h>
#include <sys/proxy.h>
#include <sys/kernel.h>
#include <sys/osinfo.h>
#include <sys/psinfo.h>
#include <sys/qnx_glob.h>

#include "imports/qman_lib.h"
#include "imports/ini.h"
#include "imports/fields.h"
#include "imports/cfgio.h"
#include "imports/led.h"
#include "qman.h"
#include "qman_internal.h"
#include "event.h"
#include "threads.h"

#define TRUE 1
#define FALSE 0

// Static events
Event onmail;
Event offmail1;
Event offmail2;

// *** Event lists:
EventList OnlineApps = { 0 };
EventList OfflineApps = { 0 };

// *** Simple start lists
// really related to eventlists.
StartList LoginApps = { 0 };
StartList StartupApps = { 0 };

// *** More complex lists.
App *applist = NULL;
IniApp *iniapplist = NULL;

// *** The hibernation stack.
IniApp *AppStack[16] = { 0 };
int NoStackApps = 0;

// *** Friends
pid_t AgentX;	// Memory agent (thread)
pid_t Ticker;	// Timeout keeper (thread)
pid_t led_pid;	// Led server (service)

// *** Memagent message stuff
int AgentX_ok = FALSE;
Xmsg xmo;

// *** Other convenient globals
int conn_type = CONN_TYPE_NONE;					// connection type
int userID = -1;								// user online
int timeout = 0;								// current inactivity timeout
unsigned long system_status = STATUS_HIBERNATE; // active status w/o change flags

// *** Prototypes
void AppRemove( pid_t app_pid );
void RereadSettings( void );
int SpawnApp( pid_t app_pid, qman_smsg *inb, qman_rmsg *outb );
void ConnectionOffline( pid_t app_pid, qman_smsg *inb, qman_rmsg *outb );
static int DoMemStuff( pid_t app_pid, int limit, qman_smsg *inb );
void nextXevent( void );


IniApp *IniAppFind( int id )
{
	IniApp *iniapp;

	iniapp = iniapplist;

	while( iniapp ) {
		if( iniapp->id == id )
			return iniapp;
		iniapp = iniapp->next;
	}

	return NULL;
}

static int PidAlive( pid_t pid )
{
	pid_t rc;
	struct _psinfo data;
	int bodycount = 0;

	rc = qnx_psinfo(0, pid, &data, 0, 0 );
	if( rc == -1 ) return FALSE;		

	if( data.pid != pid ) return FALSE;

	return TRUE;
}

App *AppFind( pid_t app_pid )
{
	App *this_app;

	this_app = applist;

	while( this_app ) {
		if( this_app->app_pid == app_pid ) {
			if( PidAlive( this_app->app_pid ) )
				return this_app;
			else {
				AppRemove( app_pid );
				return NULL;
			}
		}

		this_app = this_app->next;
	}

	return NULL;
}


App *AppFindByID( int id )
{
	App *this_app;

	this_app = applist;

	while( this_app ) {
		if( this_app->iniapp && this_app->iniapp->id == id ) {
			if( PidAlive( this_app->app_pid ) )
				return this_app;
			else {
				AppRemove( this_app->app_pid );
				return NULL;
			}

		}
				
		this_app = this_app->next;
	}

	return NULL;
}


void AppRemove( pid_t app_pid )
{
	App *this_app;
	App *prev_app;

	this_app = applist;
	prev_app = applist;

	while( this_app ) {

		if( this_app->app_pid == app_pid )
			break;

		prev_app = this_app;
		this_app = this_app->next;

	}

	if( this_app ) {

		// check for head
		if( this_app == applist )
			applist = applist->next;
		else
			prev_app->next = this_app->next;

		free( this_app );

	}

}

int AppAdd( pid_t app_pid, pid_t proxy, unsigned long mask, int id, char *args )
{
	App *new_app;

	new_app = (App *)malloc( sizeof(App) );
	if( new_app == NULL ) {
		return QMAN_RETVAL_NOMEM;
	}

	new_app->app_pid   = app_pid;
	new_app->proxy     = proxy;
	new_app->mask      = mask;
	new_app->status    = system_status;
	new_app->triggered = FALSE;

	strcpy( new_app->args, args );

	// check return?
	new_app->iniapp = IniAppFind( id );

	new_app->next = applist;
	applist = new_app;

	return QMAN_RETVAL_OK;
}



void SpawnApplist( StartList *applist )
{
	qman_smsg inb2;
	qman_rmsg outb2;
	int i;

	inb2.sh.type = TYPE_QMAN_SPAWN_APP;
	inb2.param.sa.memlimit = QMAN_SPAWN_APP_MEMORY_DEFAULT;
	inb2.req_reissue = FALSE;
	inb2.req_internal = TRUE;
	inb2.param.sa.useargs = TRUE;

	for( i = 0; i < applist->no_starts; i++ ) {
		inb2.param.sa.appid = applist->starts[i].id;
		strcpy( inb2.param.sa.args, applist->starts[i].args );
		printf( "SpawnApplist: Spawn 0x%x - args '%s'\n", applist->starts[i].id, applist->starts[i].args );
		SpawnApp( NULL, &inb2, &outb2 );
	}


}



// caveat: calling get without notify first only gives persistant status
void StatusGet( pid_t app_pid, qman_smsg *inb, qman_rmsg *outb )
{
	App *this_app;

	printf( "StatusGet:\n" );

	this_app = AppFind( app_pid );
	if( !this_app ) {
		printf( "statusget: not found\n" );
		outb->SGR.status = system_status;
		outb->rh.retval = QMAN_RETVAL_OK;
		return;
	}

	outb->SGR.status = this_app->status;
	outb->rh.retval = QMAN_RETVAL_OK;

	// ditch not persistent flags
	this_app->status &= STATUS_PERSISTENT;
	this_app->triggered = FALSE;
}


void StatusSet( pid_t app_pid, qman_smsg *inb, qman_rmsg *outb )
{
	App *this_app;
	App *next_app;
	int rc;

	unsigned long newval;
	unsigned long newchanged;
	unsigned long newflag;

	ULONG newstatus;

	printf( "StatusSet: Flag id %d, value %d\n", inb->SS.flag, inb->SS.value );

	switch( inb->SS.flag ) {

	case STATUS_MAIL_ID:
		newchanged = STATUS_MAIL_CHANGED;
		newflag = STATUS_MAIL;
		newval = inb->SS.value == 1 ? STATUS_MAIL : 0;
		break;
	case STATUS_MEMLOW_ID:
		newchanged = STATUS_MEMLOW_CHANGED;
		newflag = STATUS_MEMLOW;
		newval = inb->SS.value == 1 ? STATUS_MEMLOW : 0;
		break;
	case STATUS_SMARTCARD_ID:
		newchanged = STATUS_SMARTCARD_CHANGED;
		newflag = STATUS_SMARTCARD;
		newval = inb->SS.value == 1 ? STATUS_SMARTCARD : 0;
		break;
	case STATUS_HIBERNATE_ID:
		newchanged = STATUS_HIBERNATE_CHANGED;
		newflag = STATUS_HIBERNATE;
		newval = inb->SS.value == 1 ? STATUS_HIBERNATE : 0;
		break;
	case STATUS_SETUP_CHANGED_ID:
		newchanged = 0;
		newflag = STATUS_SETUP_CHANGED;
		newval = inb->SS.value == 1 ? STATUS_SETUP_CHANGED : 0;
		break;
	case STATUS_USERID_CHANGED_ID:
		newchanged = 0;
		newflag = STATUS_USERID_CHANGED;
		newval = inb->SS.value == 1 ? STATUS_USERID_CHANGED : 0;
		break;

	case STATUS_ONLINE_ID:
		newchanged = STATUS_ONLINE_CHANGED;
		newflag = STATUS_ONLINE;
		newval = inb->SS.value == 1 ? STATUS_ONLINE : 0;
		break;

	default:
		outb->rh.retval = QMAN_RETVAL_ILLEGAL_ARGS;
		return;
		break;
	}

	this_app = applist;
	while( this_app ) {
		printf( "Considering pid %d (mask=0x%x, status=0x%x, newflag=0x%x, newval=0x%x)\n", this_app->app_pid, this_app->mask, this_app->status, newflag, newval );

		if( !PidAlive( this_app->app_pid ) ) {
			printf( "StatusSet: pid %d dead. Removing.\n", this_app->app_pid );
			next_app = this_app->next;
			AppRemove( this_app->app_pid );
			this_app = next_app;
			continue;
		}


		newstatus = this_app->status;
		newstatus &= ~(newflag | newchanged);
		newstatus |= newval | newchanged;

		// if changed flag set or
		// new flag is in mask or and it is changed
		if( (newchanged & this_app->mask) ||
			( (newflag & this_app->mask) && ((newflag & this_app->status) != newval) ) ) {

			this_app->status = newstatus;

			// already triggered?
			if( this_app->triggered ) {

				// Should check if it is alive here!
				printf( "already triggered\n" );

			} else {
				printf( "triggering\n" );
				// attempt a trigger
				rc = Trigger( this_app->proxy );
				if( rc == -1 ) {
					printf( "trigger failed!\n" );
					next_app = this_app->next;
					AppRemove( this_app->app_pid );
					this_app = next_app;
					continue;
				}
				this_app->triggered = TRUE;

			}

		} else
			this_app->status = newstatus;


		this_app = this_app->next;

	}

	system_status &= ~newflag;
	system_status |= newval;
	system_status &= ~(STATUS_SETUP_CHANGED|STATUS_USERID_CHANGED); // special case. User changeable but not sticky.
	system_status |= STATUS_HIBERNATE;

	outb->rh.retval = QMAN_RETVAL_OK;

	if( newflag & STATUS_SETUP_CHANGED ) RereadSettings();
}

unsigned long run_id = 0xffff;

void StatusNotify( pid_t app_pid, qman_smsg *inb, qman_rmsg *outb )
{
	App *this_app;

	printf( "StatusNotify: mask 0x%x, proxy %d\n", inb->SN.mask, inb->SN.proxy );

	this_app = AppFind( app_pid );

	if( !this_app ) {
		printf( "QMan: App requesting notification was not spawned by QMan.\n" );
		outb->rh.retval = AppAdd( app_pid, inb->SN.proxy, inb->SN.mask, run_id++, "" );
		if( outb->rh.retval != 0 ) return;
	} else {
		this_app->mask  = inb->SN.mask;
		this_app->proxy = inb->SN.proxy;
		outb->rh.retval = QMAN_RETVAL_OK;
	}
}

qman_smsg lockmsg[16];
pid_t lockpid[16];
int lockmem[16];
int lockcount = 0;

static int DoMemStuff( pid_t app_pid, int limit, qman_smsg *inb )
{
	struct _osinfo osdata;
	qman_smsg inb2;
	qman_rmsg outb2;

	inb2.req_reissue  = FALSE;
	inb2.req_internal = TRUE;

	printf( "DoMemStuff: %d limit\n", limit );

	// first check if there's enough free already
	qnx_osinfo( 0, &osdata );
	if( osdata.freememk >= limit ) return 1;

	// if the request is internal, don't do anything. just return nomem.
	if( inb->req_internal == TRUE ) {
		printf( "*** *** *** Internal requst denied!\n" );
		return 2;
	}

	// Not enough. Invoke handling.
	printf( "*** *** *** pid %d locked! (%dk free)\n", app_pid, osdata.freememk );

	// Send off memlow status to all tasks.
	inb2.sh.type = TYPE_QMAN_STATUS_SET;
	inb2.SS.flag = STATUS_MEMLOW_ID;
	inb2.SS.value = TRUE;
	StatusSet( 0, &inb2, &outb2 );

	// Lock this task until freecall done
	lockpid[lockcount] = app_pid;
	lockmem[lockcount] = limit;
	lockmsg[lockcount++] = *inb;

	// Process next if possible.
	nextXevent();

	return 0;

}


void nextXevent( void )
{
	IniApp *iniapp;

	printf( "nextXevent: from %d, type %d\n", lockpid[0], lockmsg[0].sh.type );
	
	if( AgentX_ok == TRUE && lockcount ) {

		xmo.memory = lockmem[0];

		printf( "Wanted limit is %d\n", xmo.memory );

		Reply( AgentX, &xmo, sizeof(xmo) );
		AgentX_ok = FALSE;
	}

}


int MemLimit( pid_t app_pid, qman_smsg *inb, qman_rmsg *outb )
{
	int rc;

	outb->rh.retval = QMAN_RETVAL_OK;

	if( inb->req_reissue == FALSE ) {
		rc = DoMemStuff( app_pid, inb->MF.memlimit, inb );
	} else {
		printf( "Reissued memlimit... enough mem by default\n" );
		return TRUE;
	}

	if( rc == 2 ) {
		outb->rh.retval = QMAN_RETVAL_NOMEM;
		return TRUE;
	}

	return rc;
	
}


void UserSet( pid_t app_pid, qman_smsg *inb, qman_rmsg *outb )
{
	qman_smsg inb2;
	qman_rmsg outb2;

	inb2.req_reissue  = FALSE;
	inb2.req_internal = TRUE;

	printf( "UserSet:\n" );

	userID = inb->param.us.userid;
	outb->rh.retval = QMAN_RETVAL_OK;

	inb2.sh.type = TYPE_QMAN_STATUS_SET;
	inb2.SS.flag = STATUS_USERID_CHANGED_ID;
	inb2.SS.value = TRUE;
	StatusSet( 0, &inb2, &outb2 );

	// go offline.
	inb2.sh.type = TYPE_QMAN_CONNECTION_OFFLINE;
	ConnectionOffline( 0, &inb2, &outb2 );

	RereadSettings();

	if( userID != -1 ) {
		printf( "New user logged in! Spawn login applist\n" );
		SpawnApplist( &LoginApps );
	}
}

void UserGet( pid_t app_pid, qman_smsg *inb, qman_rmsg *outb )
{
	printf( "UserGet:\n" );

	outb->param.ug.userid = userID;
	outb->rh.retval = QMAN_RETVAL_OK;
}

// rc = 0 : none killed
//     >0 : number killed
static int KillByName( char *szPrgName, int sig )
{
	pid_t id = 1;
	struct _psinfo data;
	int bodycount = 0;

	while( (id = qnx_psinfo(0, id, &data, 0, 0)) != -1 ) {
		if( (data.flags & (_PPF_MID | _PPF_VID)) == 0 )
			if( strstr( data.un.proc.name, szPrgName ) != NULL ) {
				kill( id, sig );
				bodycount++;
			}
		id++;
	}

	return bodycount;
}


void RemoveNetwork( void )
{
	int killed = FALSE;
	int sig = SIGTERM;   // convincing at first...
	int kills;

	while( TRUE ) {

		kills = KillByName( "pppd", sig );
		if(	kills > 0 ) killed = TRUE;

		// if pppd killed nasty, be sure to drop line
		if( sig == SIGKILL && killed == TRUE ) {
			printf( "pppd killed nasty. Doing hangup.\n" );
			int fd;
			fd = open( "/dev/ser2", O_RDWR );
			if( fd != -1 ) {
				tcdropline( fd, 0 );
				close( fd );
			}
		}

		kills = KillByName( "dhcp.client", sig );
		if( kills > 0 ) killed = TRUE;

		kills = KillByName( "Socklet", sig );
		if( kills > 0 ) killed = TRUE;

		if( killed == FALSE || sig == SIGKILL ) break;

		// nasty at last.
		killed = FALSE;
		sig = SIGKILL;

		delay( 500 );

	}

	// lose related files
	remove( "/etc/resolv.conf" );
	remove( "/etc/ppp/chap-secrets" );
	remove( "/etc/ppp/pap-secrets" );

}


// Remove network and send status change
void ConnectionOffline( pid_t app_pid, qman_smsg *inb, qman_rmsg *outb )
{
	qman_smsg inb2;
	qman_rmsg outb2;

	App *this_app;
	App *next_app;

	int rc, i;

	inb2.req_reissue  = FALSE;
	inb2.req_internal = TRUE;

	printf( "ConnectionOffline called\n" );

	RemoveNetwork();

	// Break blocked applications.
	// only trigger and remove ORBLOCKED. Rest is fixed in StatusSet.
	this_app = applist;
	while( this_app ) {

		if( this_app->status & STATUS_ORBLOCKED ) {

			qman_rmsg rmsg;

			this_app->status &= ~STATUS_ORBLOCKED;

			rmsg.rh.retval = QMAN_RETVAL_CONN_ONLINE_FAILED;
			rc = Reply( this_app->app_pid, &rmsg, sizeof(rmsg) );

			if( rc == -1 ) {
				printf( "Offline break: pid %d dead!\n", this_app->app_pid );
				next_app = this_app->next;
				AppRemove( this_app->app_pid );
				this_app = next_app;
				continue;
			}

		}

		this_app = this_app->next;
	}

	printf( "Cancelling online timers\n" );

	// cancel online timing
	event_disable_all( &OnlineApps );

	printf( "Setting led to green\n" );
	if( led_pid != -1 ) {
		led_smsg leds;
		led_rmsg ledr;

		leds.sh.sid = SERVER_ID_LED;
		leds.sh.type = TYPE_LED_COLOR;
		leds.param.ledc.id = 0;
		leds.param.ledc.color = LED_ON_GREEN;
		Send( led_pid, &leds, &ledr, sizeof(leds), sizeof(ledr) );
	}

	// Set new status
	inb2.sh.type = TYPE_QMAN_STATUS_SET;
	inb2.SS.flag = STATUS_ONLINE_ID;
	inb2.SS.value = FALSE;
	StatusSet( 0, &inb2, &outb2 );

	outb->rh.retval = QMAN_RETVAL_OK;

}

// requires notify!
// return value TRUE = reply, FALSE = don't reply, blocked application
int ConnectionOnline( pid_t app_pid, qman_smsg *inb, qman_rmsg *outb )
{
	App *this_app;
	App *tapp;

	qman_smsg inb2;
	qman_rmsg outb2;

	IniApp *iniapp;

	int rc;

	inb2.req_reissue  = FALSE;
	inb2.req_internal = TRUE;

	printf( "ConnectionOnline:\n" );


	this_app = AppFind( app_pid );
	if( !this_app ) {
		outb->rh.retval = QMAN_RETVAL_NOT_REGISTERED;
		return TRUE;
	}

	// already online?
	if( system_status & STATUS_ONLINE ) {
		if( inb->param.co.reset_timeout ) {
			printf( "Resetting timeout\n" );
			Send( Ticker, &timeout, NULL, sizeof(timeout), 0 );
		}

		outb->rh.retval = QMAN_RETVAL_CONN_ONLINE_ALREADY;
		return TRUE;
	}


	// Implicit spawn later on. Limit memory.
	iniapp = IniAppFind( QMAN_APP_ID_DIALER );

	if( inb->req_reissue == FALSE ) {
		rc = DoMemStuff( app_pid, iniapp->lowmem, inb );
		if( rc == 0 ) return FALSE;
		if( rc == 2 ) { outb->rh.retval = QMAN_RETVAL_NOMEM; return TRUE; }
	} else
		printf( "Reissued connectiononline... enough mem by default\n" );



	// we're offline. Go online. Mark app as blocked.
	this_app->status |= STATUS_ORBLOCKED;

	// kill off any old Dialers first (may have requester stuck)
	// also kill off any dialup processes running. (%%¤#"% qnx threads)
	tapp = AppFindByID( QMAN_APP_ID_DIALER );
	if( tapp ) {
		int rc;
		int pid;
		fprintf( stderr, "dialer running. killing %d\n", tapp->app_pid );
		rc = kill( tapp->app_pid, SIGKILL );

		pid = qnx_name_locate( 0, "hp/dialup", 0, NULL );
		if( pid != -1 ) {
			printf( "dialup running. killing %d\n", pid );
			kill( pid, SIGKILL );
		}

		sleep( 1 );
		
		RemoveNetwork();
	} else
		fprintf( stderr, "no dialer?\n" );

	// spawnapp( dialer );
	inb2.req_reissue = TRUE; // Since check is done above!
	inb2.sh.type = TYPE_QMAN_SPAWN_APP;
	inb2.param.sa.memlimit = QMAN_SPAWN_APP_MEMORY_DEFAULT;
	inb2.param.sa.appid = QMAN_APP_ID_DIALER;

	// add -c for confirmation if needed
	if( inb->param.co.confirm == 0 ) {
		inb2.param.sa.useargs = FALSE;
		inb2.param.sa.args[0] = 0;
	} else {
		inb2.param.sa.useargs = TRUE;
		strcpy( inb2.param.sa.args, "-c" );
	}

	printf( "qman spawning dialer...\n" );
	SpawnApp( NULL, &inb2, &outb2 ); // ERROR CHECKING!! POTENTIAL ORBLOCKED DEADLOCK IF FAIL!

	return FALSE;
}


// same code as in offline. move to new function?
void ConnectionIsOnline( pid_t app_pid, qman_smsg *inb, qman_rmsg *outb )
{
	qman_smsg inb2;
	qman_rmsg outb2;

	App *this_app;
	App *next_app;

	int rc, i;

	inb2.req_reissue  = FALSE;
	inb2.req_internal = TRUE;

	printf( "ConnectionIsOnline called\n" );

	// Break blocked applications.
	// only trigger and remove ORBLOCKED. Rest is fixed in StatusSet.
	this_app = applist;
	while( this_app ) {

		if( this_app->status & STATUS_ORBLOCKED ) {

			qman_rmsg rmsg;

			this_app->status &= ~STATUS_ORBLOCKED;

			rmsg.rh.retval = QMAN_RETVAL_OK;
			rc = Reply( this_app->app_pid, &rmsg, sizeof(rmsg) );
			if( rc == -1 ) {
				printf( "IsOnline: pid %d dead!\n", this_app->app_pid );
				next_app = this_app->next;
				AppRemove( this_app->app_pid );
				this_app = next_app;
				continue;
			}

		}

		this_app = this_app->next;
	}


	// Set new status
	inb2.sh.type = TYPE_QMAN_STATUS_SET;
	inb2.SS.flag = STATUS_ONLINE_ID;
	inb2.SS.value = TRUE;
	StatusSet( 0, &inb2, &outb2 );

	// reset timeout
	Send( Ticker, &timeout, NULL, sizeof(timeout), 0 );

	outb->rh.retval = QMAN_RETVAL_OK;

	printf( "Start online timers\n" );

	// fire online timers (scheduling)
	event_activate_all( &OnlineApps );

	printf( "Set led to orange\n" );
	if( led_pid != -1 ) {
		led_smsg leds;
		led_rmsg ledr;

		leds.sh.sid = SERVER_ID_LED;
		leds.sh.type = TYPE_LED_COLOR;
		leds.param.ledc.id = 0;
		leds.param.ledc.color = LED_ON_ORANGE;
		Send( led_pid, &leds, &ledr, sizeof(leds), sizeof(ledr) );
	}

}


// NOTE: internal spawn should lock special!
int SpawnApp( pid_t app_pid, qman_smsg *inb, qman_rmsg *outb )
{
	IniApp *iniapp;
	App *app;

	pid_t newpid;
	int rc;

	char *args;
	int memlimit;

	printf( "SpawnApp: id=0x%x\n", inb->param.sa.appid );

	outb->rh.retval = QMAN_RETVAL_OK;

	iniapp = IniAppFind( inb->param.sa.appid );
	if( !iniapp ) {
		printf( "The app is not registered in qman.ini!\n" );
		outb->rh.retval = QMAN_RETVAL_ILLEGAL_ARGS;
		return TRUE;
	}

	app = AppFindByID( inb->param.sa.appid );
	if( app ) {
		printf( "This app seems to be already running!\n" );

		// The app is already running. Set its params changed flag and notify
		// if it wants it. This is a special case of StatusSet.
		// Only trigger if flag is needed and not already set and not already triggered.

		if(	app->mask & STATUS_ARGS_CHANGED &&
			!(app->status & STATUS_ARGS_CHANGED) &&
			!app->triggered ) {

			app->status |= STATUS_ARGS_CHANGED;
			Trigger( app->proxy );

		} else {
			printf( "Application is running, but doesn't want args_changed messages! uh-huh?\n", app->mask );

		// Otherwise we just set the flag to be sure.
			app->status |= STATUS_ARGS_CHANGED;
		}

		if( inb->param.sa.useargs )
			strcpy( app->args, inb->param.sa.args );
		else
			strcpy( app->args, iniapp->args );

		return TRUE;

	}

	printf( "The app is not running already...\n" );

	if( inb->param.sa.memlimit == QMAN_SPAWN_APP_MEMORY_DEFAULT )
		memlimit = iniapp->lowmem;
	else
		memlimit = inb->param.sa.memlimit;

	if( inb->req_reissue == FALSE ) {
		rc = DoMemStuff( app_pid, memlimit, inb );
		if( rc == 0 ) return FALSE;
		if( rc == 2 ) { outb->rh.retval = QMAN_RETVAL_NOMEM; return TRUE; }
	} else
		printf( "Reissued spawn... enough mem by default\n" );

	if( inb->param.sa.useargs ) args = inb->param.sa.args;
	else args = iniapp->args;

	printf( "Spawn '%s' with args '%s'\n", iniapp->name, args );
	newpid = spawnl( P_NOWAITO, iniapp->name, iniapp->name, args, NULL );

	if( newpid == -1 ) {
		outb->rh.retval = QMAN_RETVAL_NOMEM;
		return TRUE;
	}

	outb->param.sa.pid = newpid;

	outb->rh.retval = AppAdd( newpid, NULL, 0, inb->param.sa.appid, args );

	// NOTE: SHOULD HANDLE ERROR RETURN FROM APPADD!

	return TRUE;
}

void SpawnGetPid( pid_t app_pid, qman_smsg *inb, qman_rmsg *outb )
{
	App *app;
	app = AppFindByID( inb->param.sgp.appid );

	printf( "SpawnGetPid:\n" );

	if( app ) {
		outb->param.sgp.pid = app->app_pid;
		outb->rh.retval = QMAN_RETVAL_OK;
	} else {
		outb->param.sgp.pid = -1;
		outb->rh.retval = QMAN_RETVAL_SPAWN_GETPID_NOT_RUNNING;
	}

}

void SpawnArgsGet( pid_t app_pid, qman_smsg *inb, qman_rmsg *outb )
{
	App *app;
	app = AppFind( app_pid );

	if( app ) {
		printf( "Get args: found app. Args = '%s'\n", app->args );
		outb->rh.retval = QMAN_RETVAL_OK;
		strncpy( outb->param.spg.args, app->args, 128 );
		outb->param.spg.args[127] = 0;
	} else {
		printf( "Get args: Sorry mac, your app is not registered with big Mr Q!\n" );
		outb->rh.retval = QMAN_RETVAL_NOT_REGISTERED;
	}

}

void Hibernate( pid_t app_pid, qman_smsg *inb, qman_rmsg *outb )
{
	App *app;
	IniApp *iniapp;
	int stackoffset = -1;
	IniApp *stackapp = NULL;

	int i;
	int j;

	qman_smsg inb2;
	qman_rmsg outb2;

	inb2.req_reissue  = FALSE;
	inb2.req_internal = TRUE;

	app = AppFind( app_pid );

//	printf( "Hibernate: %d\n", inb->param.hi.hibernate );

//	printf( "Stack debug before call (none if empty)\n" );
//	for( i = 0; i < NoStackApps; i++ ) {
//		printf( "Stack entry %d: 0x%x\n", i, AppStack[i]->id );
//	}

	if( app == NULL ) {
//		printf( "Hibernate: Sorry mac, your app is not registered with big Mr Q!\n" );
		outb->rh.retval = QMAN_RETVAL_NOT_REGISTERED;
		return;
	}

	iniapp = app->iniapp;
	if( iniapp == NULL ) {
//		printf( "Hibernate: Your application is not registered in qman.ini! (were you started by qman?)\n" );
		outb->rh.retval = QMAN_RETVAL_ILLEGAL_ARGS;
		return;
	}


	outb->rh.retval = QMAN_RETVAL_OK;

	// is app already in stack?
	for( i = 0; i < NoStackApps; i++ ) {
		if( AppStack[i] == iniapp ) {
			stackoffset = i;
			break;
		}
	}

//	printf( "stackoffset is %d\n", stackoffset );

	if( stackoffset == -1 ) {

		// app not in stack, add it to top or bottom
//		printf( "App not in stack\n" );

		if( inb->param.hi.hibernate ) {

//			printf( "Hibernate new app, add to bottom\n" );

			AppStack[NoStackApps] = iniapp;
			stackoffset = NoStackApps++;

		} else {

//			printf( "Unhibernate new app, add to top\n" );

			for( i = NoStackApps; i > 0; i-- ) {
				AppStack[i] = AppStack[i-1];
			}
			AppStack[0] = iniapp;
			stackoffset = 0;
			NoStackApps++;

		}

	} else {

		// app in stack, pop to top or bottom.
//		printf( "App in stack\n" );

		// first remove object.
		if( NoStackApps ) {
			for( i = stackoffset; i < NoStackApps; i++ ) {
				AppStack[i] = AppStack[i+1];
			}
			NoStackApps--;
		}

		// hibernation: add to bottom
		// unhibernation : add to top
		if( inb->param.hi.hibernate ) {

//			printf( "Add to bottom\n" );
			AppStack[NoStackApps++] = iniapp;

		} else {

//			printf( "Add to top\n" );
			for( i = NoStackApps; i > 0; i-- ) {
				AppStack[i] = AppStack[i-1];
			}
			AppStack[0] = iniapp;
			NoStackApps++;

		}


	}

//	printf( "Recirculate dead apps...\n" );

	// Remove dead apps. Obs! Ineffective code!
	for( i = 0; i < NoStackApps; i++ ) {

		app = AppFindByID( AppStack[i]->id );
		if( !app ||
			(app && !PidAlive( app->app_pid )) ) {

			printf( "*** found a stiff!\n" );

			// dead. remove.
			for( j = i; j < NoStackApps; j++ ) {
				AppStack[j] = AppStack[j+1];
			}
			NoStackApps--;
			i--; // !!!

		}

	}

	// All statuses to HIBERNATE=TRUE.
	// StatusSet will trigger appropriately.
	inb2.sh.type = TYPE_QMAN_STATUS_SET;
	inb2.SS.flag = STATUS_HIBERNATE_ID;
	inb2.SS.value = TRUE;
	StatusSet( 0, &inb2, &outb2 );

	// Handle top app.
	// Set HIBERNATE=FALSE and trigger if not triggered.
	app = AppFindByID( AppStack[0]->id ); // should always work!

	if( app ) {

		// should really check flags etc. here. Changed is set by StatusSet.
		app->status &= ~STATUS_HIBERNATE;
		if( !app->triggered ) Trigger( app->proxy );

	} else
		printf( "bad craziness.\n" );

//	printf( "Stack debug after call (none if empty)\n" );
//	for( i = 0; i < NoStackApps; i++ ) {
//		printf( "Stack entry %d: 0x%x, status 0x%x\n", i, AppStack[i]->id, (AppFindByID(AppStack[i]->id))->status );
//	}

//	printf( "hibernatio done.\n" );
}

int ParseIniFile( char *inifile )
{
	char szBuffer[128];
	char szEntry[128];
	int i;
	IniHandle ih;
	IniApp *app_entry;
	char *token;
	int appID;

	Event ev;

	int rc;

	printf( "*** ParseIniFile\n" );

	ih = INIOpenFile( inifile );
	if( ih == NULL ) {
		puts( "Fatal error: Could not open inifile!" );
		return -1;
	}

	// Parse application list
	printf( "\nApplication list\n" );
	while( TRUE ) {

		if( ININextString( ih, inifile, "apps", "*",
		                   sizeof(szBuffer), szBuffer, NULL, szEntry ) != 0 )
			break;

		if( szEntry[0] == '#' ) continue;

		// build entry and add to list
		app_entry = (IniApp *)calloc( sizeof(IniApp), 1 );
		if( app_entry == NULL ) return -1;

		app_entry->next = iniapplist;
		iniapplist = app_entry;

		// get id
		app_entry->id = strtol( szEntry, NULL, 16 );

		// get flags
		token = strtok( szBuffer, " " );
		if( token == NULL ) return -1;
		app_entry->flags = strtol( token, NULL, 16 );

		// get lowmem
		token = strtok( NULL, " " );
		if( token == NULL ) return -1;
		app_entry->lowmem = strtol( token, NULL, 10 );

		// get name
		token = strtok( NULL, " " );
		if( token == NULL ) return -1;
		strncpy( app_entry->name, token, 64 );
		app_entry->name[63] = 0;

		// get arguments
		token = strtok( NULL, "" );
		if( token == NULL )
			strcpy( app_entry->args, "" );
		else
			strncpy( app_entry->args, token, 128 );
		app_entry->args[127] = 0;

		printf( "App: app=0x%x, flags=0x%x, lowmem=%d, name='%s', args='%s'\n",
			app_entry->id, app_entry->flags, app_entry->lowmem, app_entry->name, app_entry->args );

	}

	// Parse startup list
	printf( "\nStartup list\n" );
	for( i = 0; i < 16; i++ ) {

		if( ININextString( ih, inifile, "startup", "*",
		                   sizeof(szBuffer), szBuffer, NULL, szEntry ) != 0 )
			break;

		if( szEntry[0] == '#' ) continue;

		// get id
		StartupApps.starts[i].id = strtol( szEntry, NULL, 16 );

		// get startup args
		strncpy( StartupApps.starts[i].args, szBuffer, 128 );
		StartupApps.starts[i].args[127] = 0;

		StartupApps.no_starts++;

		printf( "Startup app %d: id=0x%x, args='%s'\n", i, StartupApps.starts[i].id, StartupApps.starts[i].args );

	}

	// Parse login list
	printf( "\nLogin list\n" );
	for( i = 0; i < 16; i++ ) {

		if( ININextString( ih, inifile, "login", "*",
		                   sizeof(szBuffer), szBuffer, NULL, szEntry ) != 0 )
			break;

		if( szEntry[0] == '#' ) continue;

		// get id
		LoginApps.starts[i].id = strtol( szEntry, NULL, 16 );

		// get startup args
		strncpy( LoginApps.starts[i].args, szBuffer, 128 );
		LoginApps.starts[i].args[127] = 0;

		LoginApps.no_starts++;

		printf( "Login app %d: id=0x%x, args='%s'\n", i, LoginApps.starts[i].id, LoginApps.starts[i].args );

	}


	// Parse online list
	printf( "\nOnline list\n" );
	for( i = 0; i < 16; i++ ) {

		if( ININextString( ih, inifile, "online", "*",
		                   sizeof(szBuffer), szBuffer, NULL, szEntry ) != 0 )
			break;

		if( szEntry[0] == '#' ) continue;

		// get id
		ev.s.id = strtol( szEntry, NULL, 16 );

		ev.time_type = 1;

		// get inidelay
		token = strtok( szBuffer, " " );
		if( token == NULL ) return -1;
		ev.t1_inidelay = strtol( token, NULL, 10 );

		// get delay
		token = strtok( NULL, " " );
		if( token == NULL ) return -1;
		ev.t1_delay = strtol( token, NULL, 10 );

		// get arguments
		token = strtok( NULL, "" );
		if( token == NULL )
			strcpy( ev.s.args, "" );
		else
			strncpy( ev.s.args, token, 128 );
		ev.s.args[127] = 0;

		ev.proxy = 0;

		// does not track event id. app is persistent.
		rc = event_add( &OnlineApps, &ev, EVENT_ID_MAKE_NEW );
		if( rc == -1 ) return -1;

		printf( "Online app %d: id=0x%x, app=%d, args='%s', inidelay=%d, delay=%d\n", 
				i,
				OnlineApps.events[i].event_id, OnlineApps.events[i].s.id,
				OnlineApps.events[i].s.args,
				OnlineApps.events[i].t1_inidelay, OnlineApps.events[i].t1_delay );

	}


	printf( "\n" );

	return 0;
}

void RereadSettings( void )
{
	char szTmp[80];

	int new_conntype;
	int new_timeout;

	qman_smsg inb2;
	qman_rmsg outb2;

	char user[2] = { 0 };

	int rc;

	Event ev;

	inb2.req_reissue  = FALSE;
	inb2.req_internal = TRUE;

	printf( "*** Reread settings\n" );

	// Get userid as string
	if( userID == -1 )
		user[0] = 0;
	else
		user[0] = userID + '0';

	printf( "Userid is %d\n", userID );

	// Determine connection type
	new_conntype = CONN_TYPE_MODEM;

	rc = CfgIOGetValue( "Connect", "Type", user, szTmp );
	if( rc == 0 ) {
		printf( "Found connection type '%s'\n", szTmp );
		if( !strcmp( szTmp, "ethernet" ) )
			new_conntype = CONN_TYPE_ETHERNET;
		if( !strcmp( szTmp, "modem" ) )
			new_conntype = CONN_TYPE_MODEM;
	}

	if( new_conntype != conn_type ) {
		printf( "Changed connection type, going offline\n" );
		conn_type = new_conntype;
		ConnectionOffline( 0, &inb2, &outb2 );
	}

	// Determine timeout
	new_timeout = 300;

	rc = CfgIOGetValue( "Connect", "Timeout", user, szTmp );
	if( rc == 0 ) {
		printf( "Found timeout '%s'\n", szTmp );
		new_timeout = atoi( szTmp );
	}

	if( new_timeout != timeout ) {
		printf( "Changed timeout\n" );
		timeout = new_timeout;
		Send( Ticker, &timeout, NULL, sizeof(timeout), 0 );
	}


	// Determine timezone
	// watch hardcoded id!!!
	rc = CfgIOGetValue( "Time", "TZEnvVar", "0", szTmp );
	if( rc == 0 ) {
		printf( "Found TZEnvVar '%s'\n", szTmp );
		rc = setenv( "TZ", szTmp, 1 );
		if( rc == -1 ) {
			printf( "Could not set envvar, errno=%d\n", rc );
		}
	}

	// Determine online mail check
	rc = CfgIOGetValue( "Mail", "OnlineCheck", user, szTmp );
	if( rc == 0 ) {

		printf( "Onlinecheck is '%s'\n", szTmp );

		if( !strcmp( szTmp, "off" ) ) {
			event_remove( &OnlineApps, EVENT_ID_ON_MAIL );
		} else {

			rc = CfgIOGetValue( "MailOnline", "Interval", user, szTmp );
			if( rc == 0 ) {
				printf( "Interval is '%s'\n", szTmp );
				onmail.t1_delay = atoi( szTmp ) * 60;
			} else {
				printf( "Could not get interval, default 180\n" );
				onmail.t1_delay = 180;
			}

			event_add( &OnlineApps, &onmail, EVENT_ID_ON_MAIL );

			if( system_status & STATUS_ONLINE )
				event_activate_one( &OnlineApps, EVENT_ID_ON_MAIL );

		}

	} else
		printf( "****** Return code from cfgiogetvalue is %d\n", rc );

	// Determine offline mail check
	rc = CfgIOGetValue( "Mail", "OfflineCheck", user, szTmp );
	if( rc == 0 ) {

		printf( "Offlinecheck is '%s'\n", szTmp );

		if( !strcmp( szTmp, "off" ) ) {
			event_disable_one( &OfflineApps, EVENT_ID_OFF_MAIL_1 );
			event_disable_one( &OfflineApps, EVENT_ID_OFF_MAIL_2 );
		} else {

			rc = CfgIOGetValue( "MailOffline", "Time1", user, szTmp );
			if( rc == 0 ) {
				offmail1.t2_hour = (szTmp[0]-'0')*10 + szTmp[1]-'0';
				offmail1.t2_min  = (szTmp[3]-'0')*10 + szTmp[4]-'0';

				if( offmail1.t2_hour >= 0 && offmail1.t2_hour <= 23 &&
					offmail1.t2_min  >= 0 && offmail1.t2_min  <= 59 ) {
					printf( "offchk1 is valid. time is %02d:%02d\n", offmail1.t2_hour, offmail1.t2_min );

					event_add( &OfflineApps, &offmail1, EVENT_ID_OFF_MAIL_1 );
					event_activate_one( &OfflineApps, EVENT_ID_OFF_MAIL_1 );
				
				} else {
					printf( "offchk1 is invalid! disabled\n" );
					event_disable_one( &OfflineApps, EVENT_ID_OFF_MAIL_1 );
				}

			}

			rc = CfgIOGetValue( "MailOffline", "Time2", user, szTmp );
			if( rc == 0 ) {
				offmail2.t2_hour = (szTmp[0]-'0')*10 + szTmp[1]-'0';
				offmail2.t2_min  = (szTmp[3]-'0')*10 + szTmp[4]-'0';

				if( offmail2.t2_hour >= 0 && offmail2.t2_hour <= 23 &&
					offmail2.t2_min  >= 0 && offmail2.t2_min  <= 59 ) {
					printf( "offchk2 is valid. time is %02d:%02d\n", offmail2.t2_hour, offmail2.t2_min );

					event_add( &OfflineApps, &offmail2, EVENT_ID_OFF_MAIL_2 );
					event_activate_one( &OfflineApps, EVENT_ID_OFF_MAIL_2 );
				
				} else {
					printf( "offchk2 is invalid! disabled\n" );
					event_disable_one( &OfflineApps, EVENT_ID_OFF_MAIL_2 );
				}

			}

		}

	}

}

void HandleMsg( pid_t pid, qman_smsg *inb, qman_rmsg *outb )
{
	int rc;

	printf( "\n*** Message type 0x%x from pid %d\n", inb->sh.type, pid );


	switch( inb->sh.type ) {

	case TYPE_QMAN_STATUS_GET:
		StatusGet( pid, inb, outb );
		Reply( pid, outb, sizeof(qman_rmsg) );
		break;
	case TYPE_QMAN_STATUS_SET:
		StatusSet( pid, inb, outb );
		Reply( pid, outb, sizeof(qman_rmsg) );
		break;
	case TYPE_QMAN_STATUS_NOTIFY:
		StatusNotify( pid, inb, outb );
		Reply( pid, outb, sizeof(qman_rmsg) );
		break;

	case TYPE_QMAN_SPAWN_APP:
		rc = SpawnApp( pid, inb, outb );
		if( rc == TRUE ) Reply( pid, outb, sizeof(qman_rmsg) );
		break;
	case TYPE_QMAN_SPAWN_GETPID:
		SpawnGetPid( pid, inb, outb );
		Reply( pid, outb, sizeof(qman_rmsg) );
		break;
	case TYPE_QMAN_SPAWN_ARGS_GET:
		SpawnArgsGet( pid, inb, outb );
		Reply( pid, outb, sizeof(qman_rmsg) );
		break;

	case TYPE_QMAN_MEMORY_FREE:
		rc = MemLimit( pid, inb, outb );
		if( rc == TRUE ) Reply( pid, outb, sizeof(qman_rmsg) );
		break;

	case TYPE_QMAN_USER_SET:
		UserSet( pid, inb, outb );
		Reply( pid, outb, sizeof(qman_rmsg) );
		break;
	case TYPE_QMAN_USER_GET:
		UserGet( pid, inb, outb );
		Reply( pid, outb, sizeof(qman_rmsg) );
		break;

	case TYPE_QMAN_CONNECTION_OFFLINE:
		ConnectionOffline( pid, inb, outb );
		Reply( pid, outb, sizeof(qman_rmsg) );
		break;
	case TYPE_QMAN_CONNECTION_ONLINE:
		rc = ConnectionOnline( pid, inb, outb );
		if(rc == TRUE ) Reply( pid, outb, sizeof(qman_rmsg) );
		break;
	case TYPE_QMAN_CONNECTION_ISONLINE:
		ConnectionIsOnline( pid, inb, outb );
		Reply( pid, outb, sizeof(ReplyHeader) );
		break;

	case TYPE_QMAN_HIBERNATE:
		Hibernate( pid, inb, outb );
		Reply( pid, outb, sizeof(ReplyHeader) );
		break;

	default:
		outb->rh.retval = SERVER_RETVAL_UNKNOWN_TYPE;
		Reply( pid, outb, sizeof(ReplyHeader) );
		break;

	}
}


int main( int argc, char *argv[] )
{
	int devno;

	qman_smsg *inb;
	qman_rmsg *outb;
	qman_smsg inb2;
	qman_rmsg outb2;

	pid_t pid;
	int rc;

	int i;

	pid_t timeout_proxy;

	int WasOnlineApp = FALSE;


	inb2.req_reissue  = FALSE;
	inb2.req_internal = TRUE;

	// Initialize static events
	onmail.s.id = QMAN_APP_ID_MAIL_CHECK;
	strcpy( onmail.s.args, "-c" );
	onmail.time_type = 1;
	onmail.t1_inidelay = 1;
	onmail.t1_delay = 20;

	offmail1.s.id = QMAN_APP_ID_MAIL_CHECK;
	strcpy( offmail1.s.args, "-c" );
	offmail1.time_type = 2;
	offmail1.t2_hour = 9;
	offmail1.t2_min  = 0;

	offmail2.s.id = QMAN_APP_ID_MAIL_CHECK;
	strcpy( offmail2.s.args, "-c" );
	offmail2.time_type = 2;
	offmail2.t2_hour = 17;
	offmail2.t2_min  = 0;

	// Locate services
	led_pid = qnx_name_locate( 0, SERVER_NAME_LED, 0, 0 );
	if( led_pid == -1 ) {
		printf( "No hp/led service found!\n" );
	}

	// It's much more convenient to have these as pointers...
	inb  = (qman_smsg *)malloc( sizeof(qman_smsg) );
	outb = (qman_rmsg *)malloc( sizeof(qman_rmsg) );

	if( (devno = qnx_name_attach( 0, SERVER_NAME_QMAN )) == -1 ) {
	    puts( "qman already running!" );
		return -1;
	}

	setprio( 0, 12 );
	qnx_spawn_options.flags = _SPAWN_NOZOMBIE;
	qnx_spawn_options.priority = 10;

	if( argc == 1 )
		rc = ParseIniFile( "/app/config/qman.ini" );
	else
		rc = ParseIniFile( argv[1] );

	if( rc != 0 ) {
		printf( "Error parsing inifile!\n" );
		return -1;
	}

	AgentX = _beginthread( memagent, NULL, 8192, NULL );
	if( AgentX == -1 ) {
		perror( "_beginthread AgentX" );
		return -1;
	}

	timeout_proxy = qnx_proxy_attach( 0, 0, 0, -1 );
	if( timeout_proxy == -1 ) {
		perror( "proxy_attach" );
		return -1;
	}

	Ticker = _beginthread( ticker, NULL, 8192, (void *)timeout_proxy );
	if( Ticker == -1 ) {
		perror( "_beginthread Ticker" );
		return -1;
	}

	ConnectionOffline( 0, &inb2, &outb2 );

	RereadSettings();

	printf( "Exec startup apps\n" );
	SpawnApplist( &StartupApps );

	while( TRUE ) {

		pid = Receive( 0, inb, 4096 );

		if( pid == -1 ) {
			perror( "Receive" );
			return -1;
		}

		if( pid == timeout_proxy ) {
			printf( "\n*** timeout!!!\n" );
			if( system_status & STATUS_ONLINE ) {
				inb2.sh.type = TYPE_QMAN_CONNECTION_OFFLINE;
				ConnectionOffline( 0, &inb2, &outb2 );
			}
			continue;
		}


		for( i = 0; (system_status & STATUS_ONLINE) && i < OnlineApps.no_events; i++ ) {
			if( OnlineApps.events[i].proxy && pid == OnlineApps.events[i].proxy ) {
				printf( "*** Online app %d (id 0x%x) wants to run\n", i, OnlineApps.events[i].s.id );

				inb2.sh.type = TYPE_QMAN_SPAWN_APP;
				inb2.param.sa.memlimit = QMAN_SPAWN_APP_MEMORY_DEFAULT;
				inb2.param.sa.useargs = TRUE;
				inb2.param.sa.appid = OnlineApps.events[i].s.id;
				strcpy( inb2.param.sa.args, OnlineApps.events[i].s.args );
				SpawnApp( NULL, &inb2, &outb2 );

				WasOnlineApp = TRUE;
				break;
			}
		}

		if( WasOnlineApp == TRUE ) {
			WasOnlineApp = FALSE;
			continue;			 
		}


		for( i = 0; i < OfflineApps.no_events; i++ ) {
			if( OfflineApps.events[i].proxy && pid == OfflineApps.events[i].proxy ) {
				printf( "*** Offline app %d (id 0x%x) wants to run\n", i, OfflineApps.events[i].s.id );

				inb2.sh.type = TYPE_QMAN_SPAWN_APP;
				inb2.param.sa.memlimit = QMAN_SPAWN_APP_MEMORY_DEFAULT;
				inb2.param.sa.useargs = TRUE;
				inb2.param.sa.appid = OfflineApps.events[i].s.id;
				strcpy( inb2.param.sa.args, OfflineApps.events[i].s.args );
				SpawnApp( NULL, &inb2, &outb2 );

				WasOnlineApp = TRUE;
				break;
			}
		}


		if( WasOnlineApp == TRUE ) {
			WasOnlineApp = FALSE;
			continue;			 
		}


		if( pid == AgentX ) {

			printf( "AgentX active\n" );
			AgentX_ok = TRUE;

			// If AgentX sends a message and we have locks,
			// the application request should be reissued if
			// there is enough mem.

			if( lockcount ) {

				if( ((Xmsg *)inb)->retval == QMAN_RETVAL_NOMEM ) {
					printf( "Locked request junked - no memory. From %d, type %d\n", lockpid[0], lockmsg[0].sh.type );
					outb->rh.retval = QMAN_RETVAL_NOMEM;
					Reply( lockpid[0], outb, sizeof(qman_rmsg) );

				} else {
					// Reissue request.
					printf( "Reissue locked request from %d, type %d\n", lockpid[0], lockmsg[0].sh.type );
					*inb = lockmsg[0];
					inb->req_reissue = TRUE;
					HandleMsg( lockpid[0], inb, outb );
				}
					
				for( i = 0; i < lockcount; i++ ) {
					lockmsg[i] = lockmsg[i+1];
					lockpid[i] = lockpid[i+1];
				}

				lockcount--;
				if( lockcount ) nextXevent();
				else {
					printf( "Last locked request done. Clearing memlow.\n" );
					// last event. Reset memlow.
					// Memory may still be low, but all requests have been responded to.
					inb2.sh.type = TYPE_QMAN_STATUS_SET;
					inb2.SS.flag = STATUS_MEMLOW_ID;
					inb2.SS.value = FALSE;
					StatusSet( 0, &inb2, &outb2 );
				}

			}

			continue;
		}


		if( inb->sh.sid != SERVER_ID_QMAN ) {
			printf( "Unknown server request: id 0x%x!\n", inb->sh.sid );
			continue;
		}

		inb->req_reissue  = FALSE;
		inb->req_internal = FALSE;

		HandleMsg( pid, inb, outb );



	}

	qnx_name_detach( 0, devno );

	return 0;
}
