예제 #1
0
파일: main.cpp 프로젝트: hgsteggles/Torch
int main (int argc, char** argv) {
	MPIW& mpihandler = MPIW::Instance();

	bool silent = mpihandler.getRank() != 0;
	std::string paramFile = "config/torch-config.lua";
	std::string setupFile = "config/torch-setup.lua";

	// Parse parameters
	if (argc > 4) {
		showUsage();
		return 0;
	}
	if (argc > 1) {
		for (int iarg = 1; iarg < argc; ++iarg) {
			std::string arg = argv[iarg];
			std::string prefix1("--paramfile=");
			std::string prefix2("--setupfile=");
			std::string prefix3("-s");

			if (!arg.compare(0, prefix1.size(), prefix1))
				paramFile = arg.substr(prefix1.size()).c_str();
			else if (!arg.compare(0, prefix2.size(), prefix2))
				setupFile = arg.substr(prefix2.size()).c_str();
			else if (!arg.compare(0, prefix3.size(), prefix3))
				silent = true;
			else {
				showUsage();
				return 0;
			}
		}
	}

	std::unique_ptr<LogPolicyInterface> consoleLogPolicy 
		= std::unique_ptr<ConsoleLogPolicy>(new ConsoleLogPolicy());
	consoleLogPolicy->setLogLevel(silent ? SeverityType::ERROR : SeverityType::DEBUG);
	Logger::Instance().registerLogPolicy("console", std::move(consoleLogPolicy));

	TorchParameters tpars;

	try {
		mpihandler.serial([&] () {
			tpars.outputDirectory = parseOutputDirectory(paramFile);
		});

		if (mpihandler.getRank() == 0) {
			FileManagement::makeDirectoryPath(tpars.outputDirectory);
			FileManagement::deleteFileContents(tpars.outputDirectory);
			FileManagement::makeDirectoryPath(tpars.outputDirectory + "/log");
			FileManagement::deleteFileContents(tpars.outputDirectory + "/log");
			FileManagement::copyConfigFile(setupFile, tpars.outputDirectory);
			FileManagement::copyConfigFile(paramFile, tpars.outputDirectory);
		}

		mpihandler.barrier();

		std::unique_ptr<LogPolicyInterface> fileLogPolicy 
			= std::unique_ptr<FileLogPolicy>(
				  new FileLogPolicy(tpars.outputDirectory + "/log/torch.log" + std::to_string(mpihandler.getRank()))
			  );
		fileLogPolicy->setLogLevel(SeverityType::NOTICE);
		Logger::Instance().registerLogPolicy("file", std::move(fileLogPolicy));
	}
	catch (std::exception& e) {
		Logger::Instance().print<SeverityType::FATAL_ERROR>(e.what());
		mpihandler.abort();
	}

	try {
		mpihandler.serial([&] () {
			parseParameters( paramFile, tpars);
			tpars.setupFile = setupFile;
		});

		Torch torch;
		torch.initialise(tpars);
		torch.run();
	}
	catch (std::exception& e) {
		Logger::Instance().print<SeverityType::FATAL_ERROR>(e.what());
		std::cout << "See " << tpars.outputDirectory << "/log/torch.log* for more details." << std::endl;
		MPIW::Instance().abort();
	}

	return 0;
}
예제 #2
0
파일: idwt2d.c 프로젝트: mousomer/xyntific
int main(int argc, char* argv[])
{
	if (parseParameters(argc, argv, USG_STRING,
			&verbose, outName, dataType, &lifting, &noRescale, &inPlace, &startHigh, &nC, &nR, waveName, inpName))
		return (FAIL);

	/* transform types:
			0: shuffled,	non lift
			1: inPlace, 	non lift
			2: shuffled, 	lifting implementation
			3: inPlace, 	lifting implementation	*/
	//int transformType = 4*(dataType[0]=='f') + 2*(lifting>0) + (inPlace>0);

	long len = getFileSize(inpName);
	int nBytes = (dataType[0]=='f') ? sizeof(float) : sizeof(int);
	len /= nBytes;
	if (nC == 0)
		nC = len/nR;

	if (verbose)
		printf("%s - verb(d): %d out(s): %s type(s): %s startHigh(d): %d length(%ld) = %d x %d\t wave(s): %s inp(s): %s\n",
				argv[0], verbose, outName, dataType, startHigh, len, nC, nR, waveName, inpName);

	if (nC != 0)
	{
		if ( nC * nR > len )
			perror("nC*nR too large, or file too small\n");
		len = nC * nR;
	}

	int		*intInput=NULL, *intOutput=NULL;
	float 	*floatInput=NULL, *floatOutput=NULL;

	if (verbose)
		printf("%s - verb(d): %d out(s): %s type(s): %s startHigh(d): %d length(%ld) = %d x %d\t wave(s): %s inp(s): %s\n",
				argv[0], verbose, outName, dataType, startHigh, len, nC, nR, waveName, inpName);

	if (stringNull(outName)) {
		stringCopy(outName, inpName);
		strcat(outName, ".fwd");
	}

	if (stringNull(dataType))
		stringCopy(dataType, "d");
	waveFilterPtr	wfp = wavGetWaveletName  (waveName);
	waveLiftPtr		wlp = wavGetLiftWaveName (waveName);
	assert(wfp);
	assert(wlp);

	if (verbose)
		printf("dwt1d %s: %s --> %s (type %c)\n", waveName, inpName, outName, dataType[0]);

	FILE* fpInp = fopen(inpName, "r");
	assert (fpInp);
	FILE* fpOut = fopen(outName, "w");
	assert (fpOut);


	if ( dataType[0] == 'd' ) {
		PREPARE_DATA(int);
		if (verbose) displayArrayNM_i( intOutput, nC, nR, stdout );
		if ( lifting )
			perror ("not implemented. try float\n");
			//liftTransform_i(intInput, len, startHigh, inPlace, wlp);
		else
			perror ("not implemented. try lifting\n");
			//wavTransform_i(intInput, intOutput, len, startHigh, wfp);

		if (verbose) displayArrayNM_i(intOutput, nC, nR, stdout );
		fwrite(intOutput, nBytes, len, fpOut);
	}
	else {
			PREPARE_DATA(float);
			if (verbose) displayArrayNM_f( floatOutput, nC, nR, stdout );
			if ( lifting )
			{
				liftInvTransform2d_f(floatInput, nC, nR, startHigh, startHigh, inPlace, noRescale, wlp);
				if (verbose) displayArrayNM_f(floatInput, nC, nR, stdout );
				fwrite(floatInput, nBytes, len, fpOut);
			}
			else
			{
				perror ("not implemented. try lifting\n");
				//wavInvTransform_f(floatInput, floatOutput, len, startHigh, wfp);
				if (verbose) displayArrayNM_f(floatOutput, nC, nR, stdout );
				fwrite(floatOutput, nBytes, len, fpOut);
			}
		}

	
	fclose(fpInp);fclose(fpOut);
	XYN_DPRINTF(DEBUG_PROCESS,"closed files\n");
	XynFree(intInput);	XynFree(floatInput);
	XynFree(intOutput);	XynFree(floatOutput);
	XYN_DPRINTF(DEBUG_PROCESS,"memory freed\n");
	return OK;
}
예제 #3
0
파일: Ping.cpp 프로젝트: dnwiebe/Emulator
bool Ping::parameterize (const char* string) {
	ParseState state;
	return parseParameters (string, "PING", 0, state);
}
bool XMLEnvelopeParser::parseData(const std::string& storage, ACLEnvelope& envelope)
{
    TiXmlDocument doc;
    LOG_INFO_S << "XMLEnvelopeParser: starting to parse: " << storage;

    std::string envelopeXML;
    std::string payloadData;

    // check whether we can split the document into envelope and content
    std::string envelopeEndMarker = "</envelope>";
    size_t pos = storage.find(envelopeEndMarker);
    if(pos == std::string::npos)
    {
        LOG_WARN_S << "XMLEnvelopeParser: this is not an XML envelope. Could not find </envelope>";
        return false;
    } else {
        envelopeXML = storage.substr(0, pos + envelopeEndMarker.size());

        size_t payloadPosition = pos + envelopeEndMarker.size();
        if(payloadPosition < storage.length());
        {
            envelope.setPayload(storage.substr(payloadPosition));
        }
    }
    
    // Load the string into XML doc
    const char* parseResult = doc.Parse(envelopeXML.c_str());
    // A non-null parseResult usually indicates an error, but we seem to get that every time.
    if(parseResult != NULL)
    {
        // non-null means some error
        LOG_WARN_S << "Parsing envelope XML failed for (probably the payload): " << parseResult;
    }
    LOG_INFO_S << "XMLEnvelopeParser: basic XML parsing complete.";
    
    // The main node (envelope)
    const TiXmlElement* envelopeElem = doc.FirstChildElement();
    
    if(envelopeElem == NULL)
    {
        LOG_WARN_S << "Parsing error: XML main node not found.";
        return false;
    }
    
    if(envelopeElem->ValueStr() != "envelope")
    {
        LOG_WARN_S << "Parsing error: XML main node not named 'fipa-message' but " << envelopeElem->ValueStr();
        return false;
    }
    
    // Parse all child elements
    const TiXmlElement* pChild = envelopeElem->FirstChildElement();
    
    if(pChild == NULL)
    {
        LOG_WARN_S << "Parsing error: XML first params node not found.";
        return false;
    }
    
    // We assume the params have raising indices, starting with one.
    int paramsIndex = 1;
    // The first params is the Base envelope
    try
    {
        envelope.setBaseEnvelope(parseParameters(pChild, paramsIndex++));
    }
    catch(std::exception& e)
    {
        LOG_WARN_S << "Parsing error base envelope: " << e.what();
        return false;
    }
    
    // All remaining params are extra envelopes
    for ( pChild = pChild->NextSiblingElement(); pChild != 0; pChild = pChild->NextSiblingElement()) 
    {
        try
        {
            envelope.addExtraEnvelope(parseParameters(pChild, paramsIndex++));
        }
        catch(std::exception& e)
        {
            LOG_WARN_S << "Parsing error extra envelope: " << e.what();
            return false;
        }
    }
    
    return true;
}
예제 #5
0
modelCoupled *parseCoupled()
{
	bool ok;
	int inPorts, outPorts;
	modelCoupled *ret = new modelCoupled();
	QList < modelChild * >childs;
	QList < modelPoint * >points;
	QList < modelLine * >lines;
	QList < modelPort * >lsPorts;

	QString strLine = getLine();
	checkEqual(strLine, TOKOBRACE);
	strLine = getLine();
	QString type = getValue(strLine, TOKTYPE);
	strLine = getLine();
	QString name = getValue(strLine, TOKNAME);
	//printf("Parsing a coupled named:%s\n", QSTR(name));

	strLine = getLine();
	QString ports = getValue(strLine, TOKPORTS);
	QStringList slports = ports.split(TOKCOLON, QString::SkipEmptyParts);
	inPorts = slports.first().toInt(&ok);
	outPorts = slports.last().toInt(&ok);

	strLine = getLine();
	QString desc = getValue(strLine, TOKDESCRIPTION);

	strLine = getLine();
	checkEqual(strLine, TOKGRAPHIC);
	skipSection();

	strLine = getLine();
	checkEqual(strLine, TOKPARAMETERS);
	QList < modelParameter * >params = parseParameters();

	strLine = getLine();
	checkEqual(strLine, TOKSYSTEM);
	strLine = getLine();
	checkEqual(strLine, TOKOBRACE);
	do {
		strLine = getLine();
		if (strLine == TOKATOMIC) {
			modelChild *c = new modelChild();
			c->childType = ATOMIC;
			c->atomic = parseAtomic();
			c->atomic->father = ret;
			childs.append(c);
		}
		if (strLine == TOKCOUPLED) {
			modelChild *c = new modelChild();
			c->childType = COUPLED;
			c->coupled = parseCoupled();
			c->coupled->father = ret;
			childs.append(c);
		}
		if (strLine == TOKINPORT) {
			lsPorts.append(parseInport());
		}
		if (strLine == TOKOUTPORT) {
			lsPorts.append(parseOutport());
		}
		if (strLine == TOKPOINT) {
			points.append(parsePoint());
		}
		if (strLine == TOKLINE) {
			lines.append(parseLine());
		}
		if (strLine == TOKEXTRA) {
			ret->extra = parseExtra();
    }
	} while (strLine != TOKCBRACE);
	strLine = getLine();
	checkEqual(strLine, TOKCBRACE);

	ret->name = name;
	ret->type = type;
	ret->lsPorts = lsPorts;
	ret->params = params;
	ret->childs = childs;
	ret->points = points;
	ret->lines = lines;

  checkLinesWithPoints(ret);
	return ret;
}
예제 #6
0
int main(int argc, char* argv[])
{
	if (parseParameters(argc, argv, USG_STRING,
			&verbose, outName, &noRescale, &startHigh, &nC, &nR, waveName, inpName))
		return (FAIL);

	/* transform types:
			0: shuffled,	non lift
			1: inPlace, 	non lift
			2: shuffled, 	lifting implementation
			3: inPlace, 	lifting implementation	*/
	//int transformType = 4*(dataType[0]=='f') + 2*(lifting>0) + (inPlace>0);

	long len = getFileSize(inpName);
	int nBytes = sizeof(float);
	len /= nBytes;
	if (nC == 0)
		nC = len/nR;

	if (verbose)
		printf("%s - verb(d): %d out(s): %s type(s): float startHigh(d): %d length(%ld) = %d x %d\t wave(s): %s inp(s): %s\n",
				argv[0], verbose, outName, startHigh, len, nC, nR, waveName, inpName);

	if (nC != 0)
	{
		if ( nC * nR > len )
			perror("nC*nR too large, or file too small\n");
		len = nC * nR;
	}

	float 	*floatInput=NULL, *floatOutput=NULL;

	if (verbose)
		printf("%s - verb(d): %d out(s): %s type(s): float startHigh(d): %d length(%ld) = %d x %d\t wave(s): %s inp(s): %s\n",
				argv[0], verbose, outName, startHigh, len, nC, nR, waveName, inpName);

	if (stringNull(outName)) {
		stringCopy(outName, inpName);
	}
	stringCopy(outNameLL, outName);
	stringCopy(outNameLH, outName);
	stringCopy(outNameHL, outName);
	stringCopy(outNameHH, outName);
	strcat(outNameLL, "_LL.fwd");
	strcat(outNameLH, "_LH.fwd");
	strcat(outNameHL, "_HL.fwd");
	strcat(outNameHH, "_HH.fwd");
	
	waveFilterPtr	wfp = wavGetWaveletName  (waveName);
	waveLiftPtr		wlp = wavGetLiftWaveName (waveName);
	assert(wfp);
	assert(wlp);

	if (verbose)
		printf("dwt1d %s: %s --> %s (type float)\n", waveName, inpName, outName);

	FILE* fpInp = fopen(inpName, "r");
	assert (fpInp);
	
	PREPARE_DATA(float);
	fclose(fpInp);
	if (verbose) displayArrayNM_f( floatOutput, nC, nR, stdout );
	
	liftTransform2d_f(floatInput, nC, nR, startHigh, startHigh, false, noRescale, wlp);
	if (verbose) displayArrayNM_f(floatInput, nC, nR, stdout );
				
	float *outLL=NULL, *outLH=NULL, *outHL=NULL, *outHH=NULL;
	long low_nC, low_nR, high_nC, high_nR;
	wavPack_lineBuffers_f ( floatInput, nC, nR, startHigh, startHigh, &outLL, &outHL, &outLH, &outHH, &low_nC, &low_nR, &high_nC, &high_nR);
	if (verbose) 
	{
		printf("\n sizes: low nC nR high nC nR \n %ld %ld %ld %ld \n pointers: %p %p %p %p\n", low_nC, low_nR, high_nC, high_nR, outLL, outHL, outLH, outHH);
		printf("\n\n -------- LL band---------------\n");
		displayArrayNM_f(outLL, low_nC, low_nR, stdout );
		
		printf("\n\n -------- HL band---------------\n");
		displayArrayNM_f(outHL, high_nC, low_nR, stdout );

		printf("\n\n -------- LH band---------------\n");
		displayArrayNM_f(outLH, low_nC, high_nR, stdout );
		
		printf("\n\n -------- HH band---------------\n");
		displayArrayNM_f(outHH, high_nC, high_nR, stdout );
	}
	
	
	FILE* fpOut = fopen(outNameLL, "w");
	assert (fpOut);
	fwrite(outLL, nBytes, low_nC*low_nR, fpOut);
	fclose(fpOut);
	
	fpOut = fopen(outNameHL, "w");
	assert (fpOut);
	fwrite(outHL, nBytes, high_nC*low_nR, fpOut);
	fclose(fpOut);
	
	fpOut = fopen(outNameLH, "w");
	assert (fpOut);
	fwrite(outLH, nBytes, low_nC*high_nR, fpOut);
	fclose(fpOut);

	fpOut = fopen(outNameHH, "w");
	assert (fpOut);
	fwrite(outHH, nBytes, high_nC*high_nR, fpOut);
	fclose(fpOut);

	XYN_DPRINTF(DEBUG_PROCESS,"closed files\n");
	XynFree(floatInput);
	XynFree(floatOutput);
	XynFree(outLL);
	XYN_DPRINTF(DEBUG_PROCESS,"memory freed\n");
	return OK;
}
int main(int argc, char **argv) {
    parseParameters(argc, argv);

    if (pthread_mutex_init(&lock, NULL) != 0) {
        printf("ERROR: cannot initialize mutex! \n");
        exit(1);
    }

    connectToDFServer();

    connectToPeers();

    unsigned long t1, t2;
    struct timespec clock;
    unsigned long sleep_time;

    char buffer[MSG_SIZE];
    int num_received_bytes;
    int num_sent_bytes;

    /* Start by resetting the inputs and outputs to their default values */
    pthread_mutex_lock(&lock);
    clear_ua_inputs();
    clear_ua_outputs();
    initializeCustomLogic();
    pthread_mutex_unlock(&lock);

    while (1) {
        clock_gettime(CLOCK_REALTIME, &clock);
        t1 = clock.tv_sec * 1000000L;

        pthread_mutex_lock(&lock);

        /* Receive all input signals from DF server */
        num_received_bytes = recv(DF_server_socket, buffer, MSG_SIZE, MSG_DONTWAIT);
        if (num_received_bytes > 0)
            ua_receive((buffer_el *) buffer, num_received_bytes, &ua_inputs, NULL);

        /* Call the User Application generated by SCADE */
		executeOperator();

        /* Clear inputs after each cycle update */
        clear_ua_inputs();

        pthread_mutex_unlock(&lock);

        /* Send all output signals to DF server */
        num_sent_bytes = ua_send((buffer_el *) buffer, &ua_outputs, NULL);
        send(DF_server_socket, buffer, num_sent_bytes, MSG_DONTWAIT);

        /* Send messages to each peer */
        sendMessagesToPeers();

        executeCustomLogic();

        clock_gettime(CLOCK_REALTIME, &clock);
        t2 = clock.tv_sec * 1000000L;

        sleep_time = 100000L;
        if (t2 - t1 > sleep_time)
            printf("Timing: cycle delayed by %d milliseconds! \n", (int) (((t2 - t1) - sleep_time)/1000L));
        else
            usleep(sleep_time - (t2 - t1));
    }

    pthread_join(thread_receiver, NULL);

    close(DF_server_socket);
    close(broadcast_socket);
    close(listening_socket);

    pthread_mutex_destroy(&lock);

    return 0;
}
예제 #8
0
//Main program
int main(void) {
	int receivedBytes;//, sentBytes;
	//unsigned char outBuff[BUFFER_MAX];
	unsigned char inBuff[BUFFER_MAX];
	//Reserve memory
	char* cmd = malloc((BUFFER_MAX+1) * sizeof(char));
	char* par = malloc((BUFFER_MAX+1) * sizeof(char));
	struct commandStructure command;
	
	//Threads variables
	pthread_t logThread;
	pthread_t emailThread;
	//pthread_t debugThread;
	pthread_t webcamThread;
	pthread_t emailPhotoThread;
	
	//Empty buffers
	init();
	
	// Open serial file descriptor
	int fd = openSerial();
		
	//Loop to scan
	while(1){
		receivedBytes = read(fd,inBuff,BUFFER_MAX);
		if(receivedBytes > 0){						// Data found!
			
			if(DEBUG){ 
				printf("\nPayload size: %d\n",receivedBytes);
				int i;
				for(i=0;i<receivedBytes;i++){
					printf("%c",inBuff[i]);
				}
				printf("\n");
			}

			getCmd(inBuff,cmd);
			getPar(inBuff,par);
			int pars = parseParameters(par);
			
			if(!validCommand(cmd)){
				printf("Invalid Command: %s\n\n",cmd);
				continue;
			}else{	
				//printf("Command: %s\n",cmd);
				//int i = 0;
				//printf("Parameters found: %d\n",pars);
				//for(i=0;i<pars;i++) printf("Parameter %d - %s\n",i,PARAMETERS[i]);			
			}
			
			if(compareText(cmd,"Debug")){ //thread is detached so resources can be recycled.
				command.cmd = cmd;
				command.par[0] = PARAMETERS[0];
				
				time_t now = time(NULL);
				printf("%s - %s",PARAMETERS[0],ctime(&now));

				/*
				//=======Call debugFunc in thread======
				int rc;
				pthread_attr_t attr;
				pthread_attr_init(&attr);
				pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
				
				if((rc = pthread_create(&debugThread,&attr,debugFunc,&command))){
					fprintf(stderr,"Error: Could not create thread: %d\n",rc);
				}
				
				pthread_attr_destroy(&attr);
				*/
			}

			if(compareText(cmd,"Log")){
				if(pars < 1){
					printf("Error: No message sent\n");
					continue;
				}
				command.cmd = cmd;
				command.par[0] = PARAMETERS[0];

				//=======Call logFunc in thread======
				int rc;
				pthread_attr_t attr;
				pthread_attr_init(&attr);
				pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
				
				if((rc = pthread_create(&logThread,&attr,logFunc,&command))){
					fprintf(stderr,"Error: Could not create thread: %d\n",rc);
				}
				
				pthread_attr_destroy(&attr);
			}
			
			if(compareText(cmd,"Email")){
				if(pars < 3){  //Need at least the email address and a subject
					printf("Error: Need 3 parameters: address, subject and message\n");
					continue;
				}
				
				command.cmd = cmd;
				command.par[0] = PARAMETERS[0];
				command.par[1] = PARAMETERS[1];
				command.par[2] = PARAMETERS[2];
				
				//=======Call logFunc in thread======
				int rc;
				pthread_attr_t attr;
				pthread_attr_init(&attr);
				pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
				
				if((rc = pthread_create(&emailThread,&attr,emailFunc,&command))){
					fprintf(stderr,"Error: Could not create thread: %d\n",rc);
				}
				
				pthread_attr_destroy(&attr);
			}
			
			if(compareText(cmd,"Webcam")){
				command.cmd = cmd;
				command.par[0] = PARAMETERS[0];

				//=======Call debugFunc in thread======
				int rc;
				pthread_attr_t attr;
				pthread_attr_init(&attr);
				pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
				
				if((rc = pthread_create(&webcamThread,&attr,webcamFunc,&command))){
					fprintf(stderr,"Error: Could not create webcam thread: %d\n",rc);
				}
				
				pthread_attr_destroy(&attr);				
			}

			if(compareText(cmd,"EmailPhoto")){
				command.cmd = cmd;
				command.par[0] = PARAMETERS[0];
				command.par[1] = PARAMETERS[1];
				command.par[2] = PARAMETERS[2];

				//=======Call debugFunc in thread======
				int rc;
				pthread_attr_t attr;
				pthread_attr_init(&attr);
				pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
				
				if((rc = pthread_create(&emailPhotoThread,&attr,emailPhotoFunc,&command))){
					fprintf(stderr,"Error: Could not create emailPhoto thread: %d\n",rc);
				}
				
				pthread_attr_destroy(&attr);
			}
			
		}else if(receivedBytes == 0){				//No data yet! go back to loop
			continue;					
		}else if(receivedBytes < 0){				//Error reading, exit.
			printf("Error reading from file!\n");
			perror("Error: " );
			close(fd);
			return -1;
		}
		usleep(UDOONEO_POLL_DELAY);	// poll time approx 50mS (faster crashes the app)
	}

	//Free reserved memory
	free((void*)cmd);
	free((void*)par);

	//Close serial's file descriptor
	close(fd);	
}
예제 #9
0
int
main( int argc, char **argv ) {

    signal( SIGPIPE, SIG_IGN );

    int status;
    rodsEnv myEnv;
    rErrMsg_t errMsg;
    rcComm_t *conn;
    boost::program_options::variables_map argsMap;
    irods::error err;
    bool useSaveFile = false;
    execMyRuleInp_t execMyRuleInp;
    msParamArray_t *outParamArray = NULL;
    msParamArray_t msParamArray;
    int rulegen;

    int connFlag = 0;
    char saveFile[MAX_NAME_LEN];
    char ruleFile[MAX_NAME_LEN];
    char cmdLineInput[MAX_NAME_LEN];
    err = parseProgramOptions( argc, argv, argsMap ); 

    if ( !err.ok() ) {
        std::cerr << "Error in parsing command line arguments" << std::endl;
        exit( 1 );
    }

    if ( argsMap.count( "help" ) ) {
        usage(/*std::cout*/);
        exit( 0 );
    }

    /* init data structures */
    memset( &execMyRuleInp, 0, sizeof( execMyRuleInp ) );
    memset( &msParamArray, 0, sizeof( msParamArray ) );
    execMyRuleInp.inpParamArray = &msParamArray;
    execMyRuleInp.condInput.len = 0;

    /* add key val for test mode */
    if ( argsMap.count( "test" ) ) {
        addKeyVal( &execMyRuleInp.condInput, "looptest", "true" );
    }
    /* add key val for specifying instance on which to run rule */
    if ( argsMap.count( "rule-engine-plugin-instance" ) ) {
        addKeyVal( &execMyRuleInp.condInput, irods::CFG_INSTANCE_NAME_KW.c_str(), argsMap["rule-engine-plugin-instance"].as<std::string>().c_str() );
    }
    /* Don't need to parse parameters if just listing available rule_engine_instances */
    if ( argsMap.count( "available" ) ) {
        /* add key val for listing available rule engine instances */
        addKeyVal( &execMyRuleInp.condInput, "available", "true" );
    } else {
        /* read rules from the input file */
        if ( argsMap.count( "file" ) ) {
            FILE *fptr;
            int len;
            int gotRule = 0;
            char buf[META_STR_LEN];
            const char* fileName;

            try {
                fileName = argsMap["file"].as< std::string >().c_str();
            } catch ( boost::bad_any_cast& e ) {
                std::cerr << "Bad filename provided to --file option\n";
                std::cerr << "Use -h or --help for help\n";
                exit( 10 );
            } catch ( std::out_of_range& e ) {
                std::cerr << "No filename provided to --file option\n";
                std::cerr << "Use -h or --help for help\n";
                exit( 10 );
            }

            // =-=-=-=-=-=-=-
            // initialize pluggable api table
            irods::api_entry_table&  api_tbl = irods::get_client_api_table();
            irods::pack_entry_table& pk_tbl  = irods::get_pack_table();
            init_api_table( api_tbl, pk_tbl );

            /* if the input file name starts with "i:", the get the file from iRODS server */
            if ( !strncmp( fileName, "i:", 2 ) ) {
                status = getRodsEnv( &myEnv );

                if ( status < 0 ) {
                    rodsLogError( LOG_ERROR, status, "main: getRodsEnv error. " );
                    exit( 1 );
                }

                conn = rcConnect( myEnv.rodsHost, myEnv.rodsPort, myEnv.rodsUserName,
                        myEnv.rodsZone, 0, &errMsg );

                if ( conn == NULL ) {
                    exit( 2 );
                }

                status = clientLogin( conn );
                if ( status != 0 ) {
                    rcDisconnect( conn );
                    exit( 7 );
                }
                if ( status == 0 ) {
                    char *myargv[3];
                    int myargc, myoptind;
                    rodsPathInp_t rodsPathInp;
                    rodsArguments_t myRodsArgs;
                    connFlag = 1;

                    myargv[0] = strdup( fileName + 2 );
                    myargv[1] = saveFile;
                    myargc = 2;
                    myoptind = 0;
                    const char *fileType = strrchr( fileName, '.' );
                    if ( fileType == NULL ) {
                        printf( "Unsupported input file type\n" );
                        exit( 10 );
                    }
                    if ( strcmp( fileType, ".r" ) == 0 ) {
                        rulegen = 1;
                    }
                    else if ( strcmp( fileType, ".ir" ) == 0 || strcmp( fileType, ".irb" ) == 0 ) {
                        rulegen = 0;
                    }
                    else {
                        rodsLog( LOG_ERROR,
                                "Unsupported input file type %s\n", fileType );
                        exit( 10 );
                    }
                    snprintf( saveFile, MAX_NAME_LEN, "/tmp/tmpiruleFile.%i.%i.%s",
                            ( unsigned int ) time( 0 ), getpid(), rulegen ? "r" : "ir" );
                    status = parseCmdLinePath( myargc, myargv, myoptind, &myEnv,
                            UNKNOWN_OBJ_T, UNKNOWN_FILE_T, 0, &rodsPathInp );
                    status = getUtil( &conn, &myEnv, &myRodsArgs, &rodsPathInp );
                    if ( status < 0 ) {
                        rcDisconnect( conn );
                        exit( 3 );
                    }

                    useSaveFile = true;
                    connFlag = 1;
                }
            }

            if ( useSaveFile ) {
                rstrcpy( ruleFile, saveFile, MAX_NAME_LEN );
            } else {
                rstrcpy( ruleFile, fileName, MAX_NAME_LEN );
            }

            fptr = fopen( ruleFile, "r" );

            /* test if the file can be opened */
            if ( fptr == NULL ) {
                rodsLog( LOG_ERROR, "Cannot open input file %s. errno = %d\n",
                        ruleFile, errno );
                exit( 1 );
            }

            /* test if the file extension is supported */
            const char *fileType = strrchr( ruleFile, '.' );
            if ( fileType == NULL ) {
                printf( "Unsupported input file type\n" );
                exit( 10 );

            }
            else if ( strcmp( fileType, ".r" ) == 0 ) {
                rulegen = 1;
            }
            else if ( strcmp( fileType, ".ir" ) == 0 || strcmp( fileType, ".irb" ) == 0 ) {
                rulegen = 0;
            }
            else {
                rodsLog( LOG_ERROR,
                        "Unsupported input file type %s\n", fileType );
                exit( 10 );
            }

            /* add the @external directive in the rule if the input file is in the new rule engine syntax */
            if ( rulegen ) {
                rstrcpy( execMyRuleInp.myRule, "@external\n", META_STR_LEN );
            }

            while ( ( len = getLine( fptr, buf, META_STR_LEN ) ) > 0 ) {
                if ( argsMap.count( "list" ) ) {
                    puts( buf );
                }

                /* skip comments if the input file is in the old rule engine syntax */
                if ( !rulegen && buf[0] == '#' ) {
                    continue;
                }

                if ( rulegen ) {
                    if ( startsWith( buf, "INPUT" ) || startsWith( buf, "input" ) ) {
                        gotRule = 1;
                        trimSpaces( trimPrefix( buf ) );
                    }
                    else if ( startsWith( buf, "OUTPUT" ) || startsWith( buf, "output" ) ) {
                        gotRule = 2;
                        trimSpaces( trimPrefix( buf ) );
                    }
                }

                if ( gotRule == 0 ) {
                    if ( !rulegen ) {
                        /* the input is a rule */
                        snprintf( execMyRuleInp.myRule + strlen( execMyRuleInp.myRule ), META_STR_LEN - strlen( execMyRuleInp.myRule ), "%s\n", buf );
                    }
                    else {
                        snprintf( execMyRuleInp.myRule + strlen( execMyRuleInp.myRule ), META_STR_LEN - strlen( execMyRuleInp.myRule ), "%s\n", buf );
                    }
                }
                else if ( gotRule == 1 ) {
                    if ( rulegen ) {
                        if ( convertListToMultiString( buf, 1 ) != 0 ) {
                            rodsLog( LOG_ERROR,
                                "Input parameter list format error for %s\n", ruleFile );
                            exit( 10 );
                        }
                    }
                    parseParameters( argsMap, rulegen, &execMyRuleInp, buf );
                }
                else if ( gotRule == 2 ) {
                    if ( rulegen ) {
                        if ( convertListToMultiString( buf, 0 ) != 0 ) {
                            rodsLog( LOG_ERROR,
                                "Output parameter list format error for %s\n", ruleFile );
                            exit( 10 );
                        }
                    }
                    if ( strcmp( buf, "null" ) != 0 ) {
                        rstrcpy( execMyRuleInp.outParamDesc, buf, LONG_NAME_LEN );
                    }
                    break;
                }
                else {
                    break;
                }
                if ( !rulegen ) {
                    gotRule++;
                }
            }

            if ( argsMap.count( "list" ) ) {
                puts( "-----------------------------------------------------------------" );
            }

            if ( gotRule != 2 ) {
                rodsLog( LOG_ERROR, "Incomplete rule input for %s", ruleFile );
                //                     argsMap["file"].as<std::string>().c_str() );
                exit( 2 );
            }
            if ( connFlag == 1 ) {
                fclose( fptr );
                unlink( saveFile );
            }
        }
        else {	/* command line input */
            std::vector< std::string > parameters;
            try {
                parameters = argsMap["parameters"].as< std::vector< std::string> >();
            } catch ( boost::bad_any_cast& e ) {
                std::cerr << "Bad parameter list provided\n";
                std::cerr << "Use -h or --help for help\n";
                exit( 10 );
            } catch ( std::out_of_range& e ) {
                std::cerr << "No parameters list provided\n";
                std::cerr << "Use -h or --help for help\n";
                exit( 10 );
            }

            rulegen = 1;
            if ( parameters.size() < 3 ) {
                rodsLog( LOG_ERROR, "incomplete input" );
                fprintf(stderr, "Use -h for help.\n" );
                exit( 3 );
            }
            
            snprintf( execMyRuleInp.myRule, META_STR_LEN, "@external rule { %s }", parameters.at(0).c_str() );
            rstrcpy( cmdLineInput, parameters.at(1).c_str(), MAX_NAME_LEN );

            if (0 != parseParameters( argsMap, 1, &execMyRuleInp, cmdLineInput )) {
                rodsLog (LOG_ERROR, "Invalid input parameter list specification");
                fprintf( stderr, "Use -h for help.\n" );
                exit(10);
            }

            if ( parameters.at(2) != "null") {
                rstrcpy( execMyRuleInp.outParamDesc, parameters.at(2).c_str(), LONG_NAME_LEN );
            }
        }
    }

    if ( connFlag == 0 ) {
        status = getRodsEnv( &myEnv );

        if ( status < 0 ) {
            rodsLogError( LOG_ERROR, status, "main: getRodsEnv error. " );
            exit( 1 );
        }

        conn = rcConnect( myEnv.rodsHost, myEnv.rodsPort, myEnv.rodsUserName,
                          myEnv.rodsZone, 0, &errMsg );

        if ( conn == NULL ) {
            rodsLogError( LOG_ERROR, errMsg.status, "rcConnect failure %s",
                          errMsg.msg );
            exit( 2 );
        }

        status = clientLogin( conn );
        if ( status != 0 ) {
            rcDisconnect( conn );
            exit( 7 );
        }
    }

    if ( argsMap.count( "verbose" ) ) {
        printf( "rcExecMyRule: %s\n", rulegen ? execMyRuleInp.myRule + 10 : execMyRuleInp.myRule );
        printf( "outParamDesc: %s\n", execMyRuleInp.outParamDesc );
    }

    status = rcExecMyRule( conn, &execMyRuleInp, &outParamArray );

    if ( argsMap.count( "test" ) ) {
        printErrorStack( conn->rError );
    }

    if ( status < 0 ) {
        msParam_t *mP;
        execCmdOut_t *execCmdOut;

        if ( !rulegen ) {
            rodsLogError( LOG_ERROR, status, "rcExecMyRule error. The rule engine is running under backward compatible mode. To run the rule(s) under normal mode, try renaming the file extension to \".r\". " );

        }
        else {
            rodsLogError( LOG_ERROR, status, "rcExecMyRule error. " );

        }
        printErrorStack( conn->rError );
        if ( ( mP = getMsParamByType( outParamArray, ExecCmdOut_MS_T ) ) != NULL ) {
            execCmdOut = ( execCmdOut_t * ) mP->inOutStruct;
            if ( execCmdOut->stdoutBuf.buf != NULL ) {
                fprintf( stdout, "%s", ( char * ) execCmdOut->stdoutBuf.buf );
            }
            if ( execCmdOut->stderrBuf.buf != NULL ) {
                fprintf( stderr, "%s", ( char * ) execCmdOut->stderrBuf.buf );
            }
        }
        rcDisconnect( conn );
        exit( 4 );
    }

    if ( argsMap.count( "verbose" ) ) {
        printf( "ExecMyRule completed successfully.    Output \n\n" );
        printMsParamNew( outParamArray, 1 );
    }
    else {
        printMsParamNew( outParamArray, 0 );
        msParam_t *mP;
        execCmdOut_t *execCmdOut;
        if ( ( mP = getMsParamByType( outParamArray, ExecCmdOut_MS_T ) ) != NULL ) {
            execCmdOut = ( execCmdOut_t * ) mP->inOutStruct;
            if ( execCmdOut->stdoutBuf.buf != NULL ) {
                fprintf( stdout, "%s", ( char * ) execCmdOut->stdoutBuf.buf );
            }
            if ( execCmdOut->stderrBuf.buf != NULL ) {
                fprintf( stderr, "%s", ( char * ) execCmdOut->stderrBuf.buf );
            }
        }
    }
    if ( argsMap.count( "verbose" ) && conn->rError != NULL ) {
        int i, len;
        rErrMsg_t *errMsg;
        len = conn->rError->len;
        for ( i = 0; i < len; i++ ) {
            errMsg = conn->rError->errMsg[i];
            printf( "%s\n", errMsg->msg );
        }
    }

    printErrorStack( conn->rError );
    rcDisconnect( conn );
    exit( 0 );

}
void parseCommandArguments(
int argc,  // in
char *argv[],   //in
Parameters *params, //in/out
char *paramFile, //out
char *additionalParams, //out
char *Error, // aux
char *prefix //out
)
{
	additionalParams[0]=0;

	if(argc<2)
	{
		puts("Usage: ./calculateFreeEnergy prefix [parameters.txt] [Additional parameters string]");
		puts("For proper work of the program one shoud have the following files:");
		puts("\t- ${prefix}gamma${site}.3d");
		puts("\t- ${prefix}c${site}.3d");
		puts("\t- ${prefix}clong${site}.3d");
		puts("\t- ${prefix}X.grd");
		puts("\t- ${prefix}Y.grd");
		puts("\t- ${prefix}Z.grd");
		puts("If no parameters file is given, the file ${prefix}_parameters.txt is used");

		throw new Exception(NULL,"incorrect command line arguments");
		return;
	}

	strcpy(prefix,argv[1]);

	if(argc>2)
		strcpy(paramFile,argv[2]);
	else
		sprintf(paramFile,"%sparameters.txt",prefix);

	if(argc>3)
	{
		strcpy(additionalParams,argv[3]);
	}

	Integer L=sizeOfFile(paramFile);

	FILE *f=fopen(paramFile,"r");

	if(L==0 || f==NULL)
	{	
		sprintf(Error,"Cannot read parameters form file %s",paramFile);	
		throw new Exception(NULL,Error);
	}

	char *str = (char*)malloc(L+1);
	fread(str,1,L,f);
	fclose(f);


	StringParser spFile(str);

	ParseParameters parseParameters("Bohr",		//const char *distanceUnits,
					"Hartree",	//const char * energyUnits,
					params		//Parameters *parameters
					);

	parseParameters.parse(&spFile);


	free(str);	

	StringParser spArg(additionalParams);

	parseParameters.parse(&spArg);

}
예제 #11
0
void
AGActivityGenHandler::myStartElement(int element, const SUMOSAXAttributes& attrs) {
    try {
        switch (element) {
        case AGEN_TAG_GENERAL:
            parseGeneralCityInfo(attrs);
            break;
        case AGEN_TAG_STREET:
            parseStreets(attrs);
            break;
        case AGEN_TAG_WORKHOURS:
            parseWorkHours();
            break;
        case AGEN_TAG_OPENING:
            parseOpeningHour(attrs);
            break;
        case AGEN_TAG_CLOSING:
            parseClosingHour(attrs);
            break;
        case AGEN_TAG_SCHOOLS:
            parseSchools();
            break;
        case AGEN_TAG_SCHOOL:
            parseSchool(attrs);
            break;
        case AGEN_TAG_BUSSTATION:
            parseBusStation(attrs);
            break;
        case AGEN_TAG_BUSLINE:
            parseBusLine(attrs);
            break;
        case AGEN_TAG_STATIONS:
            parseStations();
            break;
        case AGEN_TAG_REV_STATIONS:
            parseRevStations();
            break;
        case AGEN_TAG_STATION:
            parseStation(attrs);
            break;
        case AGEN_TAG_FREQUENCY:
            parseFrequency(attrs);
            break;
        case AGEN_TAG_POPULATION:
            parsePopulation();
            break;
        /*case AGEN_TAG_CHILD_ACOMP:
            parseChildrenAccompaniment();
            break;*/
        case AGEN_TAG_BRACKET:
            parseBracket(attrs);
            break;
        case AGEN_TAG_PARAM:
            parseParameters(attrs);
            break;
        case AGEN_TAG_ENTRANCE:
            parseCityGates(attrs);
            break;
        default:
            break;
        }
    } catch (const std::exception& e) {
        throw ProcessError(e.what());
    }
}
ConstitutiveModelParameters<EvalT, Traits>::
ConstitutiveModelParameters(Teuchos::ParameterList& p,
    const Teuchos::RCP<Albany::Layouts>& dl) :
    have_temperature_(false),
    dl_(dl)
{
  // get number of integration points and spatial dimensions
  std::vector<PHX::DataLayout::size_type> dims;
  dl_->qp_vector->dimensions(dims);
  num_pts_ = dims[1];
  num_dims_ = dims[2];

  // get the Parameter Library
  Teuchos::RCP<ParamLib> paramLib =
      p.get<Teuchos::RCP<ParamLib> >("Parameter Library", Teuchos::null);

  // get the material parameter list
  Teuchos::ParameterList* mat_params =
      p.get<Teuchos::ParameterList*>("Material Parameters");

  // Check for optional field: temperature
  if (p.isType<std::string>("Temperature Name")) {
    have_temperature_ = true;
    PHX::MDField<ScalarT, Cell, QuadPoint>
    tmp(p.get<std::string>("Temperature Name"), dl_->qp_scalar);
    temperature_ = tmp;
    this->addDependentField(temperature_);
  }

  // step through the possible parameters, registering as necessary
  //
  // elastic modulus
  std::string e_mod("Elastic Modulus");
  if (mat_params->isSublist(e_mod)) {
    PHX::MDField<ScalarT, Cell, QuadPoint> tmp(e_mod, dl_->qp_scalar);
    elastic_mod_ = tmp;
    field_map_.insert(std::make_pair(e_mod, elastic_mod_));
    parseParameters(e_mod, p, paramLib);
  }
  // Poisson's ratio
  std::string pr("Poissons Ratio");
  if (mat_params->isSublist(pr)) {
    PHX::MDField<ScalarT, Cell, QuadPoint> tmp(pr, dl_->qp_scalar);
    poissons_ratio_ = tmp;
    field_map_.insert(std::make_pair(pr, poissons_ratio_));
    parseParameters(pr, p, paramLib);
  }
  // bulk modulus
  std::string b_mod("Bulk Modulus");
  if (mat_params->isSublist(b_mod)) {
    PHX::MDField<ScalarT, Cell, QuadPoint> tmp(b_mod, dl_->qp_scalar);
    bulk_mod_ = tmp;
    field_map_.insert(std::make_pair(b_mod, bulk_mod_));
    parseParameters(b_mod, p, paramLib);
  }
  // shear modulus
  std::string s_mod("Shear Modulus");
  if (mat_params->isSublist(s_mod)) {
    PHX::MDField<ScalarT, Cell, QuadPoint> tmp(s_mod, dl_->qp_scalar);
    shear_mod_ = tmp;
    field_map_.insert(std::make_pair(s_mod, shear_mod_));
    parseParameters(s_mod, p, paramLib);
  }
  // yield strength
  std::string yield("Yield Strength");
  if (mat_params->isSublist(yield)) {
    PHX::MDField<ScalarT, Cell, QuadPoint> tmp(yield, dl_->qp_scalar);
    yield_strength_ = tmp;
    field_map_.insert(std::make_pair(yield, yield_strength_));
    parseParameters(yield, p, paramLib);
  }
  // hardening modulus
  std::string h_mod("Hardening Modulus");
  if (mat_params->isSublist(h_mod)) {
    PHX::MDField<ScalarT, Cell, QuadPoint> tmp(h_mod, dl_->qp_scalar);
    hardening_mod_ = tmp;
    field_map_.insert(std::make_pair(h_mod, hardening_mod_));
    parseParameters(h_mod, p, paramLib);
  }
  // recovery modulus
  std::string r_mod("Recovery Modulus");
  if (mat_params->isSublist(r_mod)) {
    PHX::MDField<ScalarT, Cell, QuadPoint> tmp(r_mod, dl_->qp_scalar);
    recovery_mod_ = tmp;
    field_map_.insert(std::make_pair(r_mod, recovery_mod_));
    parseParameters(r_mod, p, paramLib);
  }
  // concentration equilibrium parameter
  std::string c_eq("Concentration Equilibrium Parameter");
  if (mat_params->isSublist(c_eq)) {
    PHX::MDField<ScalarT, Cell, QuadPoint> tmp(c_eq, dl_->qp_scalar);
    conc_eq_param_ = tmp;
    field_map_.insert(std::make_pair(c_eq, conc_eq_param_));
    parseParameters(c_eq, p, paramLib);
  }
  // diffusion coefficient
  std::string d_coeff("Diffusion Coefficient");
  if (mat_params->isSublist(d_coeff)) {
    PHX::MDField<ScalarT, Cell, QuadPoint> tmp(d_coeff, dl_->qp_scalar);
    diff_coeff_ = tmp;
    field_map_.insert(std::make_pair(d_coeff, diff_coeff_));
    parseParameters(d_coeff, p, paramLib);
  }
  // thermal conductivity
  std::string th_cond("Thermal Conductivity");
  if (mat_params->isSublist(th_cond)) {
    PHX::MDField<ScalarT, Cell, QuadPoint> tmp(th_cond, dl_->qp_scalar);
    thermal_cond_ = tmp;
    field_map_.insert(std::make_pair(th_cond, thermal_cond_));
    parseParameters(th_cond, p, paramLib);
  }
  // flow rule coefficient
  std::string f_coeff("Flow Rule Coefficient");
  if (mat_params->isSublist(f_coeff)) {
    PHX::MDField<ScalarT, Cell, QuadPoint> tmp(f_coeff, dl_->qp_scalar);
    flow_coeff_ = tmp;
    field_map_.insert(std::make_pair(f_coeff, flow_coeff_));
    parseParameters(f_coeff, p, paramLib);
  }
  // flow rule exponent
  std::string f_exp("Flow Rule Exponent");
  if (mat_params->isSublist(f_exp)) {
    PHX::MDField<ScalarT, Cell, QuadPoint> tmp(f_exp, dl_->qp_scalar);
    flow_exp_ = tmp;
    field_map_.insert(std::make_pair(f_exp, flow_exp_));
    parseParameters(f_exp, p, paramLib);
  }

  // register evaluated fields
  typename
  std::map<std::string, PHX::MDField<ScalarT, Cell, QuadPoint> >::iterator it;
  for (it = field_map_.begin();
      it != field_map_.end();
      ++it) {
    this->addEvaluatedField(it->second);
  }
  this->setName(
      "Constitutive Model Parameters" + PHX::TypeString<EvalT>::value);
}
예제 #13
0
bool GetDataSpace::parameterize (const char* string) {
	ParseState state;
	if (!parseParameters (string, "GD", 1, state)) {return false;}
	address = Utils::fromDecimal (state.parms[0]);
	return true;
}
예제 #14
0
void ContentType::parse( const EString &s )
{
    EmailParser p( s );
    p.whitespace();
    while ( p.present( ":" ) )
        p.whitespace();

    bool mustGuess = false;

    if ( p.atEnd() ) {
        t = "text";
        st = "plain";
    }
    else {
        uint x = p.mark();
        if ( p.nextChar() == '/' )
            mustGuess = true;
        else
            t = p.mimeToken().lower();
        if ( p.atEnd() ) {
            if ( s == "text" ) {
                t = "text"; // elm? mailtool? someone does this, anyway.
                st = "plain";
            }
            // the remainder is from RFC 1049
            else if ( s == "postscript" ) {
                t = "application";
                st = "postscript";
            }
            else if ( s == "postscript" ) {
                t = "application";
                st = "postscript";
            }
            else if ( s == "sgml" ) {
                t = "text";
                st = "sgml";
            }
            else if ( s == "tex" ) {
                t = "application";
                st = "x-tex";
            }
            else if ( s == "troff" ) {
                t = "application";
                st = "x-troff";
            }
            else if ( s == "dvi" ) {
                t = "application";
                st = "x-dvi";
            }
            else if ( s.startsWith( "x-" ) ) {
                st = "x-rfc1049-" + s;
                t = "application";
            }
            else {
                // scribe and undefined types
                setError( "Invalid Content-Type: " + s.quoted() );
            }
        }
        else {
            if ( p.nextChar() == '/' ) {
                p.step();
                if ( !p.atEnd() || p.nextChar() != ';' )
                    st = p.mimeToken().lower();
                if ( st.isEmpty() )
                    mustGuess = true;
            }
            else if ( p.nextChar() == '=' ) {
                // oh no. someone skipped the content-type and
                // supplied only some parameters. we'll assume it's
                // text/plain and parse the parameters.
                t = "text";
                st = "plain";
                p.restore( x );
                mustGuess = true;
            }
            else {
                addParameter( "original-type", t + "/" + st );
                t = "application";
                st = "octet-stream";
                mustGuess = true;
            }
            parseParameters( &p );
        }
    }

    if ( mustGuess ) {
        EString fn = parameter( "name" );
        if ( fn.isEmpty() )
            fn = parameter( "filename" );
        while ( fn.endsWith( "." ) )
            fn.truncate( fn.length() - 1 );
        fn = fn.lower();
        if ( fn.endsWith( "jpg" ) || fn.endsWith( "jpeg" ) ) {
            t = "image";
            st = "jpeg";
        }
        else if ( fn.endsWith( "htm" ) || fn.endsWith( "html" ) ) {
            t = "text";
            st = "html";
        }
        else if ( fn.isEmpty() && st.isEmpty() && t == "text" ) {
            st = "plain";
        }
        else if ( t == "text" ) {
            addParameter( "original-type", t + "/" + st );
            st = "plain";
        }
        else {
            addParameter( "original-type", t + "/" + st );
            t = "application";
            st = "octet-stream";
        }
    }

    if ( t.isEmpty() || st.isEmpty() )
        setError( "Both type and subtype must be nonempty: " + s.quoted() );

    if ( valid() && t == "multipart" && st == "appledouble" &&
         parameter( "boundary" ).isEmpty() ) {
        // some people send appledouble without the header. what can
        // we do? let's just call it application/octet-stream. whoever
        // wants to decode can try, or reply.
        t = "application";
        st = "octet-steam";
    }

    if ( valid() && !p.atEnd() &&
         t == "multipart" && parameter( "boundary" ).isEmpty() &&
         s.lower().containsWord( "boundary" ) ) {
        EmailParser csp( s.mid( s.lower().find( "boundary" ) ) );
        csp.require( "boundary" );
        csp.whitespace();
        if ( csp.present( "=" ) )
            csp.whitespace();
        uint m = csp.mark();
        EString b = csp.string();
        if ( b.isEmpty() || !csp.ok() ) {
            csp.restore( m );
            b = csp.input().mid( csp.pos() ).section( ";", 1 ).simplified();
            if ( !b.isQuoted() )
                b.replace( "\\", "" );
            if ( b.isQuoted() )
                b = b.unquoted();
            else if ( b.isQuoted( '\'' ) )
                b = b.unquoted( '\'' );
        }
        if ( !b.isEmpty() )
            addParameter( "boundary", b );
    }

    if ( valid() && t == "multipart" && parameter( "boundary" ).isEmpty() )
        setError( "Multipart entities must have a boundary parameter." );

    if ( !parameter( "charset" ).isEmpty() ) {
        Codec * c = Codec::byName( parameter( "charset" ) );
        if ( c ) {
            EString cs = c->name().lower();
            if ( t == "text" && cs == "us-ascii" )
                removeParameter( "charset" );
            else if ( cs != parameter( "charset" ).lower() )
                addParameter( "charset", cs );
        }
    }

    if ( valid() && !p.atEnd() &&
         t == "text" && parameter( "charset" ).isEmpty() &&
         s.mid( p.pos() ).lower().containsWord( "charset" ) ) {
        EmailParser csp( s.mid( s.lower().find( "charset" ) ) );
        csp.require( "charset" );
        csp.whitespace();
        if ( csp.present( "=" ) )
            csp.whitespace();
        Codec * c = Codec::byName( csp.dotAtom() );
        if ( c )
            addParameter( "charset", c->name().lower() );
    }

    if ( !valid() )
        setUnparsedValue( s );
}
예제 #15
0
int main(int argc, char *argv[])
{	
	string chrName = "", chrNameB = "";
	CLineFields inputReferenceGenomeFile;
	CLineFields genotypesFile;

	if (parseParameters (argc, argv) == false) 	{
		cerr << "Version: 1.0-r7" << endl;
		cerr << "Contact: [email protected]" << endl << endl;		
		cerr << "Usage: " << argv[0] <<" -r haploid.fa -g genotypes -l length -o diploid.fa" << endl << endl;
		cerr << "Convert haploid reference genome to diploid reference genome according to the genotypes and sequencing read length" << endl << endl;
		cerr << "Example: " << argv[0] << " -r hg19.fa -g known.genotypes -l 36 -o diploid.fa" << endl;
		cerr << endl << "Parameters (mandatory): " << endl;
		cerr << "  -r\t\thaploid reference genome file " << endl;
		cerr << "  -g\t\tgenotypes file" << endl;
		cerr << "  -l\t\tread length" << endl;
		cerr << "  -o\t\toutput diploid reference genome file " << endl;
		cerr << endl << "Parameters (optional): " << endl;
		cerr << "  -d\t\tmaximal deletion in a read and mapped to alternative alleles [default=0]" << endl;
		cerr << "  -s\t\tsex of the individual [default=\"m\"]" << endl;
		exit(-1);
	}
	
	if (inputReferenceGenomeFile.openFile(inputReferenceGenomeFileName)==false) {
		cerr << "Can not open file: " << inputReferenceGenomeFileName << endl;
		exit (-1);
	}

	if (genotypesFile.openFile(genotypesFileName)==false) {
		cerr << "Can not open file: " << genotypesFileName << endl;
		exit (-1);
	}	

	// step 1: read haploid reference genome file, double the total number of chromosomes.
	bool readin = false;
	inputReferenceGenomeFile.readline();
	while (inputReferenceGenomeFile.endofFile()==false) {
		if (inputReferenceGenomeFile.line[0]=='>') {
			chrName = inputReferenceGenomeFile.line.substr(1);
			chrNameB = chrName+"b";
			if (chrName != "chrY" || gender=='m') {
				chrMap[chrName] = "";
				chrMap[chrNameB] = "";
				chrNameList.push_back(chrName);			
				chrNameList.push_back(chrNameB);
				readin = true;
			} else {
				readin = false;  // skip chromosome Y for female individuals.
			}
		} else if (readin){
			
			chrMap[chrName] += inputReferenceGenomeFile.line;
			chrMap[chrNameB] += inputReferenceGenomeFile.line;
		}
		inputReferenceGenomeFile.readline();
	}	
	inputReferenceGenomeFile.closeFile();

	// step 2: use genotype file to modify the chromosomes. double the chromosome numbers.
	if (genotypesFile.isOpen()) {
		int refColumn = -1, altColumn=-1;
		genotypesFile.readline();
		while(genotypesFile.endofFile()==false) {
			unsigned int pos = atoi(genotypesFile.field[2].c_str());
			chrName = genotypesFile.field[1];
			chrNameB = chrName+"b";
			
			if (chrMap[chrName].length()<pos) {
				cerr << "Warning!!! genotype is out of range at: " << chrName << ": " << genotypesFile.field[2] << endl;
			} else {
				// decide which is ref and which is non-ref
				if (toupper(chrMap[chrName][pos-1]) == toupper(genotypesFile.field[4][0])) {						
					refColumn = 4;
					altColumn = 3;
				}
				else {
					refColumn = 3;
					altColumn = 4;
				}

				// if genotype is alt/alt, then we still need to change reference allele.
				if (chrMap[chrName][pos-1] >='A' && chrMap[chrName][pos-1] <='Z') {
					chrMap[chrName][pos-1] = toupper(genotypesFile.field[refColumn][0]);
					chrMap[chrNameB][pos-1] = toupper(genotypesFile.field[altColumn][0]);
				}
				else {
					chrMap[chrName][pos-1] = tolower(genotypesFile.field[refColumn][0]);
					chrMap[chrNameB][pos-1] = tolower(genotypesFile.field[altColumn][0]);
				}
			}
			genotypesFile.readline();
		}
		genotypesFile.closeFile();
	} 
	contextLength = 2*readLength - 1 + 2*maxDeletion;
	outputReferenceGenomeFile.open(outputReferenceGenomeFileName);
	dipmapFile.open(dipmapFileName);

	// step 3: create mini chromosomes and append them to the end of reference allele.
	for (int i=0; i<(int)chrNameList.size(); i++) {
		chrName = chrNameList[i];		
		if (chrName[chrName.length()-1] == 'b')
			extendFromDiploid(chrName);
	}

	// step 4: print out the reference allele, which has already been extended by mini chromosomes.
	for (int i=0; i<(int)chrNameList.size(); i++) {
		chrName = chrNameList[i];		
		if (chrName[chrName.length()-1] != 'b')
			printHaploid(chrName);
	}
	outputReferenceGenomeFile << endl;
	dipmapFile.close();
	outputReferenceGenomeFile.close();
	
	return 0;
}
예제 #16
0
// ParticleAttribute, ParticleBehavior, ParticleShader name
bool PSClass::parseClass(istringstream &token)
{
	bool result=true;
	// class type
	if (!nextToken.compare("Attribute"))
		classType=ATTRIBUTE;
	else if (!nextToken.compare("Behavior"))
		classType=BEHAVIOR;
	else if (!nextToken.compare("Shader"))
		classType=SHADER;
	else
	{
		cout << "Translation stopped because no such class type: " << nextToken <<endl;
		result=false;
	}
	baseClassName="Particle"+nextToken;
	// name
	token >> className;
	// open {
	token >> nextToken;
	if (nextToken.compare("{"))
		result=false;
	// can be parameters or functions
	token >> nextToken;
	// parse rest
	while(true)
	{
		if (!nextToken.compare("Parameters"))
		{
			result = result && parseParameters(token);
			if (!result) break;
		}
		else if (!nextToken.compare("attachAttributes"))
		{
			result = result && parseAttachAttributes(token);
			if (!result) break;
		}
		else if (!nextToken.compare("Behavior"))
		{
			result = result && parseBehavior(token);
			if (!result) break;
		}
		else if (!nextToken.compare("Shader"))
		{
			result = result && parseShader(token);
			if (!result) break;
		}
		else if (!nextToken.compare("}"))
			break;
		else
		{
			cout << "Translation stopped because cannot parse token: " << nextToken<< ". Expecting end of class." <<endl;
			break;
		}
	}
	// close }
	if (nextToken.compare("}"))
		result=false;

	return result;
}
예제 #17
0
MODULE* GPCB_FPL_CACHE::parseMODULE( LINE_READER* aLineReader ) throw( IO_ERROR, PARSE_ERROR )
{
    #define TEXT_DEFAULT_SIZE  ( 40*IU_PER_MILS )
    #define OLD_GPCB_UNIT_CONV IU_PER_MILS

    // Old version unit = 1 mil, so conv_unit is 10 or 0.1
    #define NEW_GPCB_UNIT_CONV ( 0.01*IU_PER_MILS )

    int                   paramCnt;
    double                conv_unit = NEW_GPCB_UNIT_CONV; // GPCB unit = 0.01 mils and Pcbnew 0.1
    wxPoint               textPos;
    wxString              msg;
    wxArrayString         parameters;
    std::auto_ptr<MODULE> module( new MODULE( NULL ) );


    if( aLineReader->ReadLine() == NULL )
        THROW_IO_ERROR( "unexpected end of file" );

    parameters.Clear();
    parseParameters( parameters, aLineReader );
    paramCnt = parameters.GetCount();

    /* From the Geda PCB documentation, valid Element definitions:
     *   Element [SFlags "Desc" "Name" "Value" MX MY TX TY TDir TScale TSFlags]
     *   Element (NFlags "Desc" "Name" "Value" MX MY TX TY TDir TScale TNFlags)
     *   Element (NFlags "Desc" "Name" "Value" TX TY TDir TScale TNFlags)
     *   Element (NFlags "Desc" "Name" TX TY TDir TScale TNFlags)
     *   Element ("Desc" "Name" TX TY TDir TScale TNFlags)
     */

    if( parameters[0].CmpNoCase( wxT( "Element" ) ) != 0 )
    {
        msg.Printf( _( "unknown token \"%s\"" ), GetChars( parameters[0] ) );
        THROW_PARSE_ERROR( msg, aLineReader->GetSource(), (const char *)aLineReader,
                           aLineReader->LineNumber(), 0 );
    }

    if( paramCnt < 10 || paramCnt > 14 )
    {
        msg.Printf( _( "Element token contains %d parameters." ), paramCnt );
        THROW_PARSE_ERROR( msg, aLineReader->GetSource(), (const char *)aLineReader,
                           aLineReader->LineNumber(), 0 );
    }

    // Test symbol after "Element": if [ units = 0.01 mils, and if ( units = 1 mil
    if( parameters[1] == wxT( "(" ) )
        conv_unit = OLD_GPCB_UNIT_CONV;

    if( paramCnt > 10 )
    {
        module->SetDescription( parameters[3] );
        module->SetReference( parameters[4] );
    }
    else
    {
        module->SetDescription( parameters[2] );
        module->SetReference( parameters[3] );
    }

    // Read value
    if( paramCnt > 10 )
        module->SetValue( parameters[5] );
    // With gEDA/pcb, value is meaningful after instantiation, only, so it's
    // often empty in bare footprints.
    if( module->Value().GetText().IsEmpty() )
        module->Value().SetText( wxT( "Val**" ) );


    if( paramCnt == 14 )
    {
        textPos = wxPoint( parseInt( parameters[8], conv_unit ),
                           parseInt( parameters[9], conv_unit ) );
    }
    else
    {
        textPos = wxPoint( parseInt( parameters[6], conv_unit ),
                           parseInt( parameters[7], conv_unit ) );
    }

    int orientation = parseInt( parameters[paramCnt-4], 1.0 );
    module->Reference().SetOrientation( (orientation % 2) ? 900 : 0 );

    // Calculate size: default height is 40 mils, width 30 mil.
    // real size is:  default * ibuf[idx+3] / 100 (size in gpcb is given in percent of default size
    int thsize = parseInt( parameters[paramCnt-3], TEXT_DEFAULT_SIZE ) / 100;
    thsize = std::max( (int)( 5 * IU_PER_MILS ), thsize ); // Ensure a minimal size = 5 mils
    int twsize = thsize * 30 / 40;
    int thickness = thsize / 8;

    // gEDA/pcb aligns top/left, not pcbnew's default, center/center.
    // Compensate for this by shifting the insertion point instead of the
    // aligment, because alignment isn't changeable in the GUI.
    textPos.x = textPos.x + twsize * module->GetReference().Len() / 2;
    textPos.y += thsize / 2;

    // gEDA/pcb draws a bit too low/left, while pcbnew draws a bit too
    // high/right. Compensate for similar appearance.
    textPos.x -= thsize / 10;
    textPos.y += thsize / 2;

    module->Reference().SetTextPosition( textPos );
    module->Reference().SetPos0( textPos );
    module->Reference().SetSize( wxSize( twsize, thsize ) );
    module->Reference().SetThickness( thickness );

    // gEDA/pcb shows only one of value/reference/description at a time. Which
    // one is selectable by a global menu setting. pcbnew needs reference as
    // well as value visible, so place the value right below the reference.
    module->Value().SetOrientation( module->Reference().GetOrientation() );
    module->Value().SetSize( module->Reference().GetSize() );
    module->Value().SetThickness( module->Reference().GetThickness() );
    textPos.y += thsize * 13 / 10;  // 130% line height
    module->Value().SetTextPosition( textPos );
    module->Value().SetPos0( textPos );

    while( aLineReader->ReadLine() )
    {
        parameters.Clear();
        parseParameters( parameters, aLineReader );

        if( parameters.IsEmpty() || parameters[0] == wxT( "(" ) )
            continue;

        if( parameters[0] == wxT( ")" ) )
            break;

        paramCnt = parameters.GetCount();

        // Test units value for a string line param (more than 3 parameters : ident [ xx ] )
        if( paramCnt > 3 )
        {
            if( parameters[1] == wxT( "(" ) )
                conv_unit = OLD_GPCB_UNIT_CONV;
            else
                conv_unit = NEW_GPCB_UNIT_CONV;
        }

        wxLogTrace( traceFootprintLibrary, wxT( "%s parameter count = %d." ),
                    GetChars( parameters[0] ), paramCnt );

        // Parse a line with format: ElementLine [X1 Y1 X2 Y2 Thickness]
        if( parameters[0].CmpNoCase( wxT( "ElementLine" ) ) == 0 )
        {
            if( paramCnt != 8 )
            {
                msg.Printf( wxT( "ElementLine token contains %d parameters." ), paramCnt );
                THROW_PARSE_ERROR( msg, aLineReader->GetSource(), (const char *)aLineReader,
                                   aLineReader->LineNumber(), 0 );
            }

            EDGE_MODULE* drawSeg = new EDGE_MODULE( module.get() );
            drawSeg->SetLayer( F_SilkS );
            drawSeg->SetShape( S_SEGMENT );
            drawSeg->SetStart0( wxPoint( parseInt( parameters[2], conv_unit ),
                                         parseInt( parameters[3], conv_unit ) ) );
            drawSeg->SetEnd0( wxPoint( parseInt( parameters[4], conv_unit ),
                                       parseInt( parameters[5], conv_unit ) ) );
            drawSeg->SetWidth( parseInt( parameters[6], conv_unit ) );
            drawSeg->SetDrawCoord();
            module->GraphicalItems().PushBack( drawSeg );
            continue;
        }

        // Parse an arc with format: ElementArc [X Y Width Height StartAngle DeltaAngle Thickness]
        if( parameters[0].CmpNoCase( wxT( "ElementArc" ) ) == 0 )
        {
            if( paramCnt != 10 )
            {
                msg.Printf( wxT( "ElementArc token contains %d parameters." ), paramCnt );
                THROW_PARSE_ERROR( msg, aLineReader->GetSource(), (const char *)aLineReader,
                                   aLineReader->LineNumber(), 0 );
            }

            // Pcbnew does know ellipse so we must have Width = Height
            EDGE_MODULE* drawSeg = new EDGE_MODULE( module.get() );
            drawSeg->SetLayer( F_SilkS );
            drawSeg->SetShape( S_ARC );
            module->GraphicalItems().PushBack( drawSeg );

            // for and arc: ibuf[3] = ibuf[4]. Pcbnew does not know ellipses
            int     radius = ( parseInt( parameters[4], conv_unit ) +
                               parseInt( parameters[5], conv_unit ) ) / 2;

            wxPoint centre( parseInt( parameters[2], conv_unit ),
                            parseInt( parameters[3], conv_unit ) );

            drawSeg->SetStart0( centre );

            // Pcbnew start angles are inverted and 180 degrees from Geda PCB angles.
            double start_angle = parseInt( parameters[6], -10.0 ) + 1800.0;

            // Pcbnew delta angle direction is the opposite of Geda PCB delta angles.
            double sweep_angle = parseInt( parameters[7], -10.0 );

            // Geda PCB does not support circles.
            if( sweep_angle == -3600.0 )
                drawSeg->SetShape( S_CIRCLE );

            // Angle value is clockwise in gpcb and Pcbnew.
            drawSeg->SetAngle( sweep_angle );
            drawSeg->SetEnd0( wxPoint( radius, 0 ) );

            // Calculate start point coordinate of arc
            wxPoint arcStart( drawSeg->GetEnd0() );
            RotatePoint( &arcStart, -start_angle );
            drawSeg->SetEnd0( centre + arcStart );
            drawSeg->SetWidth( parseInt( parameters[8], conv_unit ) );
            drawSeg->SetDrawCoord();
            continue;
        }

        // Parse a Pad with no hole with format:
        //   Pad [rX1 rY1 rX2 rY2 Thickness Clearance Mask "Name" "Number" SFlags]
        //   Pad (rX1 rY1 rX2 rY2 Thickness Clearance Mask "Name" "Number" NFlags)
        //   Pad (aX1 aY1 aX2 aY2 Thickness "Name" "Number" NFlags)
        //   Pad (aX1 aY1 aX2 aY2 Thickness "Name" NFlags)
        if( parameters[0].CmpNoCase( wxT( "Pad" ) ) == 0 )
        {
            if( paramCnt < 10 || paramCnt > 13 )
            {
                msg.Printf( wxT( "Pad token contains %d parameters." ), paramCnt );
                THROW_PARSE_ERROR( msg, aLineReader->GetSource(), (const char *)aLineReader,
                                   aLineReader->LineNumber(), 0 );
            }

            D_PAD* pad = new D_PAD( module.get() );

            static const LSET pad_front( 3, F_Cu, F_Mask, F_Paste );
            static const LSET pad_back(  3, B_Cu, B_Mask, B_Paste );

            pad->SetShape( PAD_SHAPE_RECT );
            pad->SetAttribute( PAD_ATTRIB_SMD );
            pad->SetLayerSet( pad_front );

            if( testFlags( parameters[paramCnt-2], 0x0080, wxT( "onsolder" ) ) )
                pad->SetLayerSet( pad_back );

            // Set the pad name:
            // Pcbnew pad name is used for electrical connection calculations.
            // Accordingly it should be mapped to gEDA's pin/pad number,
            // which is used for the same purpose.
            // gEDA also features a pin/pad "name", which is an arbitrary string
            // and set to the pin name of the netlist on instantiation. Many gEDA
            // bare footprints use identical strings for name and number, so this
            // can be a bit confusing.
            pad->SetPadName( parameters[paramCnt-3] );

            int x1 = parseInt( parameters[2], conv_unit );
            int x2 = parseInt( parameters[4], conv_unit );
            int y1 = parseInt( parameters[3], conv_unit );
            int y2 = parseInt( parameters[5], conv_unit );
            int width = parseInt( parameters[6], conv_unit );
            wxPoint delta( x2 - x1, y2 - y1 );
            double angle = atan2( (double)delta.y, (double)delta.x );

            // Get the pad clearance and the solder mask clearance.
            if( paramCnt == 13 )
            {
                int clearance = parseInt( parameters[7], conv_unit );
                // One of gEDA's oddities is that clearance between pad and polygon
                // is given as the gap on both sides of the pad together, so for
                // KiCad it has to halfed.
                pad->SetLocalClearance( clearance / 2 );

                // In GEDA, the mask value is the size of the hole in this
                // solder mask. In Pcbnew, it is a margin, therefore the distance
                // between the copper and the mask
                int maskMargin = parseInt( parameters[8], conv_unit );
                maskMargin = ( maskMargin - width ) / 2;
                pad->SetLocalSolderMaskMargin( maskMargin );
            }

            // Negate angle (due to Y reversed axis) and convert it to internal units
            angle = - RAD2DECIDEG( angle );
            pad->SetOrientation( KiROUND( angle ) );

            wxPoint padPos( (x1 + x2) / 2, (y1 + y2) / 2 );

            pad->SetSize( wxSize( KiROUND( EuclideanNorm( delta ) ) + width,
                                  width ) );

            padPos += module->GetPosition();
            pad->SetPos0( padPos );
            pad->SetPosition( padPos );

            if( !testFlags( parameters[paramCnt-2], 0x0100, wxT( "square" ) ) )
            {
                if( pad->GetSize().x == pad->GetSize().y )
                    pad->SetShape( PAD_SHAPE_CIRCLE );
                else
                    pad->SetShape( PAD_SHAPE_OVAL );
            }

            module->Add( pad );
            continue;
        }

        // Parse a Pin with through hole with format:
        //    Pin [rX rY Thickness Clearance Mask Drill "Name" "Number" SFlags]
        //    Pin (rX rY Thickness Clearance Mask Drill "Name" "Number" NFlags)
        //    Pin (aX aY Thickness Drill "Name" "Number" NFlags)
        //    Pin (aX aY Thickness Drill "Name" NFlags)
        //    Pin (aX aY Thickness "Name" NFlags)
        if( parameters[0].CmpNoCase( wxT( "Pin" ) ) == 0 )
        {
            if( paramCnt < 8 || paramCnt > 12 )
            {
                msg.Printf( wxT( "Pin token contains %d parameters." ), paramCnt );
                THROW_PARSE_ERROR( msg, aLineReader->GetSource(), (const char *)aLineReader,
                                   aLineReader->LineNumber(), 0 );
            }

            D_PAD* pad = new D_PAD( module.get() );

            pad->SetShape( PAD_SHAPE_CIRCLE );

            static const LSET pad_set = LSET::AllCuMask() | LSET( 3, F_SilkS, F_Mask, B_Mask );

            pad->SetLayerSet( pad_set );

            if( testFlags( parameters[paramCnt-2], 0x0100, wxT( "square" ) ) )
                pad->SetShape( PAD_SHAPE_RECT );

            // Set the pad name:
            // Pcbnew pad name is used for electrical connection calculations.
            // Accordingly it should be mapped to gEDA's pin/pad number,
            // which is used for the same purpose.
            pad->SetPadName( parameters[paramCnt-3] );

            wxPoint padPos( parseInt( parameters[2], conv_unit ),
                            parseInt( parameters[3], conv_unit ) );

            int padSize = parseInt( parameters[4], conv_unit );

            pad->SetSize( wxSize( padSize, padSize ) );

            int drillSize = 0;

            // Get the pad clearance, solder mask clearance, and drill size.
            if( paramCnt == 12 )
            {
                int clearance = parseInt( parameters[5], conv_unit );
                // One of gEDA's oddities is that clearance between pad and polygon
                // is given as the gap on both sides of the pad together, so for
                // KiCad it has to halfed.
                pad->SetLocalClearance( clearance / 2 );

                // In GEDA, the mask value is the size of the hole in this
                // solder mask. In Pcbnew, it is a margin, therefore the distance
                // between the copper and the mask
                int maskMargin = parseInt( parameters[6], conv_unit );
                maskMargin = ( maskMargin - padSize ) / 2;
                pad->SetLocalSolderMaskMargin( maskMargin );

                drillSize = parseInt( parameters[7], conv_unit );
            }
            else
            {
                drillSize = parseInt( parameters[5], conv_unit );
            }

            pad->SetDrillSize( wxSize( drillSize, drillSize ) );
            padPos += module->GetPosition();
            pad->SetPos0( padPos );
            pad->SetPosition( padPos );

            if( pad->GetShape() == PAD_SHAPE_CIRCLE  &&  pad->GetSize().x != pad->GetSize().y )
                pad->SetShape( PAD_SHAPE_OVAL );

            module->Add( pad );
            continue;
        }
    }

    // Recalculate the bounding box
    module->CalculateBoundingBox();
    return module.release();
}