/* tpgMain.cpp */
/* Author:  Marty Kraimer Date:    17MAR2000 */

#include <stddef.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <stdio.h>
#include <sys/resource.h>

#include "epicsExit.h"
#include "epicsThread.h"
#include "iocsh.h"
#include <cpsw_api_user.h>
#include <yamlLoader.h>
#include <epicsExport.h>

static const iocshArg statsArg0 = {"path",      iocshArgString };
static const iocshArg * const statsArgs[] = { &statsArg0 };

static const iocshFuncDef cpswDumpDef = {"cpswDumpStats", sizeof(statsArgs)/sizeof(statsArgs[0]), statsArgs };

static void  cpswDumpStats(const iocshArgBuf *args)
{
Path   r;
Path   elp;
Child  el;
	if (   ( r = cpswGetRoot() )
		&& ( elp = r->findByName( args[0].sval ) )
        && ( el  = elp->tail() ) ) {
		el->dump( stdout );
	} else {
		fprintf(stderr,"'%s' not found!\n", args[0].sval);
	}
}

static const iocshFuncDef cpswFailDef = {"cpswFail", 0, 0 };

static void cpswFail(const iocshArgBuf *args)
{
	throw CPSWError("Testing");
}

static const iocshArg debugArg0 = {"facility",      iocshArgString };
static const iocshArg debugArg1 = {"level",         iocshArgInt    };
static const iocshArg * const debugArgs[] = { &debugArg0, &debugArg1 };
static const iocshFuncDef cpswDebugDef = {"setCPSWVerbosity", 2, debugArgs };

static void cpswDebug(const iocshArgBuf *args)
{
	setCPSWVerbosity( args[0].sval, args[1].ival );
}

static const iocshFuncDef noCoreDef = {"noCore", 0, 0};
static void noCore(const iocshArgBuf *args)
{
struct rlimit l;
	l.rlim_cur = 0;
	l.rlim_max = 0;
	if ( setrlimit( RLIMIT_CORE, &l ) ) {
		perror("Unable to set RLIMIT_CORE");
	}
}


int main(int argc,char *argv[])
{
   	iocshRegister(&cpswDumpDef , cpswDumpStats );
   	iocshRegister(&cpswFailDef , cpswFail      );
   	iocshRegister(&cpswDebugDef, cpswDebug     );
   	iocshRegister(&noCoreDef   , noCore        );
	try {
		if(argc>=2) {    
			iocsh(argv[1]);
			epicsThreadSleep(.2);
		}
		iocsh(NULL);
	} catch (CPSWError &e) {
		fprintf( stderr,"%s\n", e.what() );
		cpswDumpStats( 0 );
	}
    epicsExit(0);
    return(0);
}
