Exemplo n.º 1
0
void abort_message(const char *format, ...)
{
    va_list vargs;
    char  emessage[1024];

    if (dpsTimer || nomessageflag)
    {
        closeFiles();
        close_error(1);       /* 1 arg means fail/abort */
        exit(1);
    }
    va_start(vargs, format);
    vfprintf(stdout,format,vargs);
    va_end(vargs);
    if ( *(format+(strlen(format)-1)) != '\n')
        fprintf(stdout,"\n");
    if (!erroropen)
    {
        if (P_getstring(GLOBAL, "userdir", errorpath, 1, MAXPATHL) >= 0)
        {
            strcat(errorpath,"/psg.error");
            if ( (errorfile=fopen(errorpath,"w+")) )
                erroropen = 1;
        }
    }
    if (erroropen)
    {
        va_start(vargs, format);
        vfprintf(errorfile,format,vargs);
        va_end(vargs);
        fprintf(errorfile,"P.S.G. Aborted....\n");
        fprintf(stdout,"P.S.G. Aborted....\n");
    }
    va_start(vargs, format);
    vsprintf(emessage,format,vargs);
    va_end(vargs);
    closeFiles();
    if (newacq)
    {
        while (emessage[strlen(emessage)-1] == '\n')
            emessage[strlen(emessage)-1] = '\0';
        vnmremsg(emessage);
        if (!acqiflag && !dps_flag)
            release_console();
    }
    close_error(1);    /* 1 arg means fail/abort */
    exit(1);
}
Exemplo n.º 2
0
//---------------------------------------------------------------------------
void CADUSplitterDialog::on_genAHRPTDataBtn_clicked()
{
    if(!openFiles(true))
        return;

    closeFiles();
}
Exemplo n.º 3
0
void hgLoadOutJoined(char *database, int rmskCount, char *rmskFileNames[], char *suffix)
/* hgLoadOutJoined - load RepeatMasker .out files into database. */
{
struct sqlConnection *conn = NULL;
int i;

if (tabFileName == NULL)
    {
    conn = hAllocConn(database);
    verbose(2,"#\thgLoadOutJoined: connected to database: %s\n", database);
    }
for (i=0; i<rmskCount; ++i)
    {
    readOneOut(rmskFileNames[i]);
    }
closeFiles();
if (tabFileName == NULL)
    {
    loadOneTable(database, conn, defaultTempName, suffix);
    }
hFreeConn(&conn);
if (badRepCnt > 0)
    {
    warn("note: %d records dropped due to repEnd < 0 or repStart > repEnd\n", badRepCnt);
    if (verboseLevel() < 2)
        warn("      run with -verbose=2 for details\n");
    }
}
Exemplo n.º 4
0
RHEX_sample::~RHEX_sample()
{
//    FP.close();
  closeFiles();
  delete [] Pgain;
  delete [] Dgain;
}
Exemplo n.º 5
0
Arquivo: sup2.c Projeto: daydin/maze
int main()
{

	/* necessary to initialize webots stuff */
	wb_robot_init();

	reset();
	int result=0;


	/* main loop
	 * Perform simulation steps of TIME_STEP milliseconds
	 * and leave the loop when the simulation is over
	 */
	while (wb_robot_step(TIME_STEP) != -1) {

		result=run();
		if (result!=TIME_STEP) break;
	};
	closeFiles();
	//	quit the sim
	wb_supervisor_simulation_quit(EXIT_SUCCESS);
	/* This is necessary to cleanup webots resources */
	wb_robot_cleanup();

	return 0;
}
Exemplo n.º 6
0
// Open new file for reading
bool LineParser::openInput(QString filename)
{
	Messenger::enter("LineParser::openInput");

	// Check existing input file
	if (inputFile_ != NULL)
	{
		printf("Warning - LineParser already appears to have an open file...\n");
		inputFile_->close();
		delete inputFile_;
		inputFile_ = NULL;
	}

	// Open new file
	inputFile_ = new std::ifstream(qPrintable(filename), std::ios::in | std::ios::binary);
	if (!inputFile_->is_open())
	{
		closeFiles();
		Messenger::print("Error: Failed to open file '%s' for reading.", qPrintable(filename));
		Messenger::exit("LineParser::openInput");
		return false;
	}

	// Reset variables
	lastLineNo_ = 0;
	inputFilename_ = filename;

	Messenger::exit("LineParser::openInput");
	return true;
}
Exemplo n.º 7
0
//---------------------------------------------------------------------------
CADUSplitterDialog::~CADUSplitterDialog()
{
    delete ui;

    closeFiles();
    delete cadu;
}
Exemplo n.º 8
0
int main( int argc, char **argv ) {
    int defs_ok = _LANG_DEFS_OK();

    if( argc < 5 || argc > 10 ) {
        fatal( "usage: msgencod [-w] [-i] [-ip] [-q] [-p] <gml> <msgc> <msgh> <levh>" );
    }
    if( ! defs_ok ) {
        fatal( "language index mismatch" );
    }
    processOptions( argv + 1 );
    readGML();
    if( flags.gen_gpick ) {
        writeMsgHGP();
        writeMsgCGP();
        writeLevHGP();
    }else{
        compressMsgs();
        writeMsgH();
        writeMsgC();
        writeLevH();
    }
    closeFiles();
    if( flags.international ) {
        dumpInternational();
    }
    if( ! flags.quiet ) {
        dumpStats();
    }
    if( warnings != 0 && flags.warnings_always_rebuild ) {
        forceRebuild();
    }
    return( errors ? EXIT_FAILURE : EXIT_SUCCESS );
}
Exemplo n.º 9
0
int 
main(int argc, const char **argv) {

    struct CmdlineInfo cmdline;
    struct pam * imgPam;  /* malloced */
    struct pam outimg;
    unsigned int fileCt;
    Coord * coords;  /* malloced */
    FILE * headerFileP;
    FILE * dataFileP;
    const char ** names; /* malloced */
    unsigned int qfactor;  /* In per cent */

    pm_proginit(&argc, argv);

    parseCommandLine(argc, argv, &cmdline);

    headerFileP = cmdline.header ? pm_openw(cmdline.header) : NULL;
    dataFileP = cmdline.data ? pm_openw(cmdline.data) : NULL;

    qfactor = qfactorFromQuality(cmdline.quality, cmdline.quality2);

    openFiles(cmdline, &fileCt, &imgPam, &names);

    readFileHeaders(imgPam, fileCt);

    sortImagesByArea(fileCt, imgPam, names);

    findpack(imgPam, fileCt, &coords, cmdline.quality2, qfactor);

    computeOutputType(&outimg.maxval, &outimg.format, outimg.tuple_type,
                      &outimg.depth, fileCt, imgPam);

    computeOutputDimensions(&outimg.width, &outimg.height, fileCt,
                            imgPam, coords);
    outimg.size = sizeof(outimg);
    outimg.len = PAM_STRUCT_SIZE(allocation_depth);
    pnm_setminallocationdepth(&outimg, outimg.depth);
    outimg.plainformat = false;
    outimg.file = stdout;
 
    writePam(&outimg, fileCt, coords, imgPam);

    if (dataFileP)
        writeData(dataFileP, outimg.width, outimg.height,
                  fileCt, names, coords, imgPam);

    if (headerFileP)
        writeHeader(headerFileP, cmdline.prefix, outimg.width, outimg.height,
                    fileCt, names, coords, imgPam);

    closeFiles(imgPam, fileCt, headerFileP, dataFileP);

    free(coords);
    free(imgPam);
    free(names);

    return 0;
}
Exemplo n.º 10
0
 ~CWriteIntercept()
 {
     closeFiles();
     if (dataFile)
         dataFile->remove();
     if (idxFile)
         idxFile->remove();
 }
Exemplo n.º 11
0
//====================================
void stopEncoding()
//====================================
{

  fprintf(f_event,"# ENDOFSIM\n");
  saveScenario();
  //saveScenarioExpanded();
  closeFiles();
  exit(0);
}
Exemplo n.º 12
0
void
backupfsExit (bkupInfo* info, int exitStatus)
{
    assert(info);

    closeFiles(info);
    removeFiles(info);
    moveFile(info->oldJpath, info->jpath);
    exit(exitStatus);
}
Exemplo n.º 13
0
//---------------------------------------------------------------------------
bool CADUSplitterDialog::openFiles(bool ahrpt)
{
    closeFiles();

    QString outfile = ahrpt ? ui->ahrptoutfileEd->text():ui->lritoutfileEd->text();

    if(ui->infileEd->text().isEmpty() || outfile.isEmpty() ||
       ui->infileEd->text() == outfile)
        return false;

    infp = fopen(ui->infileEd->text().toStdString().c_str(), "rb");
    if(!infp) {
        QMessageBox::critical(this, "Error: Failed to open file!", ui->infileEd->text());
        return false;
    }

#if 0
    outfp = fopen(outfile.toStdString().c_str(), "wb");
    if(!outfp) {
        closeFiles();

        QMessageBox::critical(this, "Error: Failed to open file!", outfile);
        return false;
    }
#endif

    cadu->reed_solomon(ui->rsdecodeCb->isChecked());
    cadu->derandomize(ui->derandomizeCb->isChecked());
    cadu->lrit_cadu(ahrpt ? false:true);

    if(!cadu->init(infp, CADU_PACKET_SIZE, outfp)) {
        closeFiles();

        QMessageBox::critical(this, "Error: Failed to initialize CCSDS class!", "Out of memory?");
        return false;
    }

    return true;
}
Exemplo n.º 14
0
/*maxDigits; 1 otherwise */
int genOffset(int symbol_location, int maxDigits)
{
	int offset, upper_bound, lower_bound;
	offset = (symbol_location - (PC+2)) / 2;
	if(maxDigits == 9) {
		upper_bound=255;
		lower_bound=-256;
	} else if(maxDigits == 11) {
		upper_bound=1023;
		lower_bound=-1024;
	} else {
		printf("Error: PCoffset must be 9 or 11");
		closeFiles();
		exit(4);	
	}
	if(offset<lower_bound || offset>upper_bound){
		printf("Error: PCoffset out of bounds\n");
		closeFiles();
		exit(4);
	}	
	return offset;
}
Exemplo n.º 15
0
static void showUsage(void)
{
  fprintf(stderr, "USAGE:\n");
  fprintf(stderr, "  %s [options] <filename>\n", programName);
  fprintf(stderr, "[options]\n");
  fprintf(stderr, "  -I<include-path>\n");
  fprintf(stderr, "    Search in <include-path> for additional file\n");
  fprintf(stderr, "    A maximum of %d pathes may be specified\n",
          MAX_INCPATHES);
  fprintf(stderr, "    (default is current directory)\n");
  closeFiles();
  exit(1);
} /* end showUsage */
Exemplo n.º 16
0
static void signalHandler(int signo)
{
#ifdef  _GNU_SOURCE
  fprintf(errFile, "Received signal: %s\n", strsignal(signo));
  fprintf(lstFile, "Received signal: %s\n", strsignal(signo));
#else
  fprintf(errFile, "Received signal %d\n", signo);
  fprintf(lstFile, "Received signal %d\n", signo);
#endif
  closeFiles();
  error(eRCVDSIGNAL);
  exit(1);
}
Exemplo n.º 17
0
/* initializeCommand ()
**
** Initialize the BLITZ DISK file by writing out an empty directory.
*/
void initializeCommand () {

  if (commandOptionV) printf ("INITIALIZING THE FILE SYSTEM...\n");

  openDiskFile (0);               /* Existing = false */

  seekTo (4);                     /* Skip past "BLZd" magic number */
  writeInteger (0x73747562);      /* Magic number = "stub" */
  writeInteger (0);               /* Number of file */
  writeInteger (1);               /* Next Free Sector */

  if (commandOptionV) printf ("Number of files on disk = 0\n");
  if (commandOptionV) printf ("Next free sector = 1\n");
  if (commandOptionV) printf ("Number of available sectors = %d\n", numberSectorsOnDisk-1);

  closeFiles ();
}
Exemplo n.º 18
0
void psg_abort(int error)
{
    closeFiles();
    if (dpsTimer)
    {
        close_error(1);   /* 1 arg means failure/abort */
        exit(1);
    }
    text_error("P.S.G. Aborted.");
    if (newacq)
    {
        if (!acqiflag && !dps_flag)
            release_console();
    }
    close_error(1);     /* 1 arg means failure/abort */
    exit(error);
}
Exemplo n.º 19
0
/**
 * Create [gnuplot](http://www.gnuplot.info/) ".gpl" file from ".dat" binary file with header section.
 * This program is developed to plot the input file of [maxximino/dpacalc](https://github.com/maxximino/dpacalc)
 */
int main(int argc, char** argv) {

    parseParams(argc, argv);
   
    openFiles();
    
    parseInputFile();
        
    createDat();
    createGpl();
        
    closeFiles();
        
    cout << endl << "[FINISHED]" << endl << endl;
    
    return 0;
}
Exemplo n.º 20
0
void processOneOut(char *database, struct sqlConnection *conn, char *rmskFile, char *suffix)
/* Read one RepeatMasker .out file and load it into database. */
{
verbose(1, "Processing %s\n", rmskFile);

readOneOut(rmskFile);

/* Create database table (if not -tabFile). */
if (tabFileName == NULL)
    {
    char dir[256], base[128], extension[64];
    char tableName[256];
    splitPath(rmskFile, dir, base, extension);
    chopSuffix(base);
    safef(tableName, sizeof(tableName), "%s_%s", base, suffix);
    closeFiles();
    loadOneTable(database, conn, defaultTempName, tableName);
    }
}
Exemplo n.º 21
0
// Import data from the specified file
bool DLP4TrajectoryPlugin::importData()
{
	// Read header information from trajectory file, if there is any
	QString name;
	if ( !fileParser_.readLine ( name ) ) {
		return false;
	}
	targetModel()->setName ( name );
	if ( !fileParser_.skipLines ( 1 ) ) {
		return false;
	}

	// Read the first trajectory frame.
	// The model where we should put the frame data will have been set in the FileParser (in parentModel()).
	// Calling FilePluginInterface::importPart(0) will set the file positions we need, and read in the first frame.
	Model* frame = createFrame();
	if (!importPart(0))
	{
		discardFrame(frame);
		return false;
	}

	if (standardOptions_.isSetAndOn(FilePluginStandardImportOptions::CacheAllSwitch))
	{
		Messenger::print("Caching all frames from HISTORY file (%i %s)...", nDataParts(), isNPartialDataEstimated() ? "estimated" : "actual");
		int count = 0;
		bool frameResult;
		do
		{
			// Add a new trajectory frame
			Model* frame = createFrame();

			// Attempt to read in the next data part in the file
			frameResult = importPart(++count);
			if (!frameResult) discardFrame(frame);
			
		} while (frameResult && (!fileParser_.eofOrBlank()));

		closeFiles();
	}

	return true;
}
Exemplo n.º 22
0
// Open new stream for writing
bool LineParser::openOutput(QString filename, bool directOutput)
{
	Messenger::enter("LineParser::openOutput");

	// Check existing input file
	if ((outputFile_ != NULL) || (cachedFile_ != NULL))
	{
		printf("Warning - LineParser already appears to have an open file/cache...\n");
		if (outputFile_ != NULL)
		{
			outputFile_->close();
			delete outputFile_;
			outputFile_ = NULL;
		}
		if (cachedFile_ != NULL)
		{
			delete cachedFile_;
			cachedFile_ = NULL;
		}
	}

	// Open new file
	directOutput_ = directOutput;
	if (directOutput_)
	{
		outputFile_ = new std::ofstream(qPrintable(filename), std::ios::out);
		if (!outputFile_->is_open())
		{
			closeFiles();
			Messenger::print("Error: Failed to open file '%s' for writing.", qPrintable(filename));
			Messenger::exit("LineParser::openOutput");
			return false;
		}
	}
	else cachedFile_ = new std::stringstream;
	outputFilename_ = filename;

	Messenger::exit("LineParser::openOutput");
	return true;
}
Exemplo n.º 23
0
int userLogout(LUser* luser,char* nick,char* pass){
	int found = 0;
	int i = 0;
	User *user = NULL;
	while(i < luser->numUser && found == 0){
		if(strcmp(nick,luser->listU[i]->nick) == 0){
			found = 1;
			user = luser->listU[i];
		}
		i++;
	}
	if(found == 1 && strcmp(pass,user->pass) == 0){
		if(user->online == 0){
			return -2;
		}
		user->online = 0;
		closeFiles(user);
		return 0;
	}

	return -1;
}
Exemplo n.º 24
0
Arquivo: main.c Projeto: Futame/cell
int main(){
    openFiles();
    FILE *inap;
    inap = fopen("./tests/INaP.txt","w");
    printf("files are opened\n");
    REAL time;
    int  f = 0;
    REAL timeStep = 5e-3;
    REAL Itotal;
    parametersInitialisation();
    stateInitialisation();
    bufferInitialisation();
    
    for (time = 0.0; time <= 1000.0; time = time + timeStep)
    {

        //printf("%e\n",time);
        nernstPotentials();
        if((time >= 99000)&&(f%100 == 0))
        {
            printState(time, &CurrentState, &IValues);
            printCurrents(time, &IValues);
        }
       f++;
        
        Itotal = totalCurrent(time,&CurrentState, &NextState, timeStep, &ModelParameters, &IValues, &JValues, &CurrentBuffersState, &NextBuffersState);

        NextState.E = (((int) time) % 1000 < 5.0)? CurrentState.E - (Itotal - 10.0)*timeStep : CurrentState.E - Itotal*timeStep;
        fprintf(inap, "%e %e\n",time, IValues.INaJuncp + IValues.INaSlp);
        CurrentState = NextState;
        CurrentBuffersState = NextBuffersState;
    }

    closeFiles();
    fclose(inap);
    printf("\ndone\n");
    return 0;
}
//----------------------------------------------------------------------
// The Class destructor.
// Delete all indirect space in ScratchFileMap.
//----------------------------------------------------------------------
ScratchFileMap::~ScratchFileMap(void)
{
    closeFiles();
    heap_->deallocateMemory((void*)fileMap_);
    fileMap_ = NULL;
}
Exemplo n.º 26
0
/* Note that this procedure leaks memory like mad. */
static void
applyPlugin(const char               * pcInputFilename,
	    const char               * pcOutputFilename,
	    const LADSPA_Data          fExtraSeconds,
	    const unsigned long        lPluginCount,
	    const LADSPA_Descriptor ** ppsPluginDescriptors,
	    LADSPA_Data             ** ppfPluginControlValues) {

  LADSPA_PortDescriptor iPortDescriptor;
  LADSPA_Handle * ppsPlugins;
  LADSPA_Data ** ppfBuffers;
  long lFrameSize;
  unsigned long lAudioInputCount;
  unsigned long lAudioOutputCount;
  unsigned long lPreviousAudioOutputCount;
  unsigned long lBufferCount;
  unsigned long lBufferIndex;
  unsigned long lControlIndex;
  unsigned long lInputFileChannelCount;
  unsigned long lInputFileLength;
  unsigned long lOutputFileChannelCount;
  unsigned long lOutputFileLength;
  unsigned long lPluginIndex;
  unsigned long lPortIndex;
  unsigned long lSampleRate;
  unsigned long lTimeAt;
  LADSPA_Data fDummyControlOutput;

  /* Open input file and output file: 
     -------------------------------- */

  lOutputFileChannelCount
    = getPortCountByType(ppsPluginDescriptors[lPluginCount - 1],
			 LADSPA_PORT_AUDIO | LADSPA_PORT_OUTPUT);
  if (lOutputFileChannelCount == 0) {
    fprintf(stderr,
	    "The last plugin in the chain has no audio outputs.\n");
    exit(1);
  }

  openWaveFile(pcInputFilename, 
	       &lInputFileChannelCount, 
	       &lSampleRate,
	       &lInputFileLength);
  if (lInputFileChannelCount
      != getPortCountByType(ppsPluginDescriptors[0],
			    LADSPA_PORT_AUDIO | LADSPA_PORT_INPUT)) {
    fprintf(stderr,
	    "Mismatch between channel count in input file and audio inputs "
	    "on first plugin in chain.\n");
    exit(1);
  }

  lOutputFileLength 
    = lInputFileLength + (unsigned long)(fExtraSeconds * lSampleRate);

  createWaveFile(pcOutputFilename,
		 lOutputFileChannelCount,
		 lSampleRate,
		 lOutputFileLength);

  /* Count buffers and sanity-check the flow graph:
     ---------------------------------------------- */

  lBufferCount = 0;
  lPreviousAudioOutputCount = 0;
  for (lPluginIndex = 0; lPluginIndex < lPluginCount; lPluginIndex++) {

    lAudioInputCount
      = getPortCountByType(ppsPluginDescriptors[lPluginIndex],
			   LADSPA_PORT_AUDIO | LADSPA_PORT_INPUT);
    lAudioOutputCount
      = getPortCountByType(ppsPluginDescriptors[lPluginIndex],
			   LADSPA_PORT_AUDIO | LADSPA_PORT_OUTPUT);

    if (lBufferCount < lAudioInputCount)
      lBufferCount = lAudioInputCount;

    if (lPluginIndex > 0) 
      if (lAudioInputCount != lPreviousAudioOutputCount) {
	fprintf(stderr,
		"There is a mismatch between the number of output channels "
		"on plugin \"%s\" (%ld) and the number of input channels on "
		"plugin \"%s\" (%ld).\n",
		ppsPluginDescriptors[lPluginIndex - 1]->Name,
		lPreviousAudioOutputCount,
		ppsPluginDescriptors[lPluginIndex]->Name,
		lAudioInputCount);
	exit(1);
      }

    lPreviousAudioOutputCount = lAudioOutputCount;

    if (lBufferCount < lAudioOutputCount)
      lBufferCount = lAudioOutputCount;
  }

  /* Create the buffers, create instances, wire them up:
     --------------------------------------------------- */

  ppsPlugins = (LADSPA_Handle *)calloc(lPluginCount, sizeof(LADSPA_Handle));
  ppfBuffers = (LADSPA_Data **)calloc(lBufferCount, sizeof(LADSPA_Data *));
  for (lBufferIndex = 0; lBufferIndex < lBufferCount; lBufferIndex++)
    ppfBuffers[lBufferIndex] 
      = (LADSPA_Data *)calloc(BUFFER_SIZE, sizeof(LADSPA_Data));

  for (lPluginIndex = 0; lPluginIndex < lPluginCount; lPluginIndex++) {

    ppsPlugins[lPluginIndex]
      = ppsPluginDescriptors[lPluginIndex]
      ->instantiate(ppsPluginDescriptors[lPluginIndex],
		    lSampleRate);
    if (!ppsPlugins[lPluginIndex]) {
      fprintf(stderr,
	      "Failed to instantiate plugin of type \"%s\".\n",
	      ppsPluginDescriptors[lPluginIndex]->Name);
      exit(1);
    }

    /* Controls:
       --------- */

    lControlIndex = 0;
    for (lPortIndex = 0;
	 lPortIndex < ppsPluginDescriptors[lPluginIndex]->PortCount; 
	 lPortIndex++) {

      iPortDescriptor 
	= ppsPluginDescriptors[lPluginIndex]->PortDescriptors[lPortIndex];
      
      if (LADSPA_IS_PORT_CONTROL(iPortDescriptor)) {
	if (LADSPA_IS_PORT_INPUT(iPortDescriptor))
	  ppsPluginDescriptors[lPluginIndex]->connect_port
	    (ppsPlugins[lPluginIndex],
	     lPortIndex,
	     ppfPluginControlValues[lPluginIndex] + (lControlIndex++));
	if (LADSPA_IS_PORT_OUTPUT(iPortDescriptor))
	  ppsPluginDescriptors[lPluginIndex]->connect_port
	    (ppsPlugins[lPluginIndex],
	     lPortIndex,
	     &fDummyControlOutput);
      }
    }

    /* Input Buffers:
       -------------- */

    lBufferIndex = 0;
    for (lPortIndex = 0;
	 lPortIndex < ppsPluginDescriptors[lPluginIndex]->PortCount; 
	 lPortIndex++) {
      iPortDescriptor 
	= ppsPluginDescriptors[lPluginIndex]->PortDescriptors[lPortIndex];
      if (LADSPA_IS_PORT_INPUT(iPortDescriptor) 
	  && LADSPA_IS_PORT_AUDIO(iPortDescriptor))
	ppsPluginDescriptors[lPluginIndex]->connect_port
	  (ppsPlugins[lPluginIndex],
	   lPortIndex,
	   ppfBuffers[lBufferIndex++]);
    }
    

    /* Output Buffers:
       --------------- */

    lBufferIndex = 0;
    for (lPortIndex = 0;
	 lPortIndex < ppsPluginDescriptors[lPluginIndex]->PortCount; 
	 lPortIndex++) {
      iPortDescriptor 
	= ppsPluginDescriptors[lPluginIndex]->PortDescriptors[lPortIndex];
      if (LADSPA_IS_PORT_OUTPUT(iPortDescriptor) 
	  && LADSPA_IS_PORT_AUDIO(iPortDescriptor))
	ppsPluginDescriptors[lPluginIndex]->connect_port
	  (ppsPlugins[lPluginIndex],
	   lPortIndex,
	   ppfBuffers[lBufferIndex++]);
    }
  }

  /* Activate:
     --------- */

  for (lPluginIndex = 0; lPluginIndex < lPluginCount; lPluginIndex++) 
    if (ppsPluginDescriptors[lPluginIndex]->activate != NULL)
      ppsPluginDescriptors[lPluginIndex]->activate(ppsPlugins[lPluginIndex]);

  /* Run:
     ---- */

  lTimeAt = 0;
  while (lTimeAt < lOutputFileLength) {

    lFrameSize = lInputFileLength - lTimeAt;
    if (lFrameSize > BUFFER_SIZE)
      lFrameSize = BUFFER_SIZE;
    else {
      /* We've reached or are reaching the end of the file. We're not
         going to fill the buffer from file. Could just memset the end
         part, but there's only one frame where this is worth the
         effort. */
      for (lBufferIndex = 0; lBufferIndex < lBufferCount; lBufferIndex++)
	memset(ppfBuffers[lBufferIndex], 0, sizeof(LADSPA_Data) * BUFFER_SIZE);
    }

    if (lFrameSize > 0) {
      /* Read from disk. */
      readIntoBuffers(ppfBuffers, lFrameSize);
    }

    /* Run the plugins: */
    lFrameSize = lOutputFileLength - lTimeAt;
    if (lFrameSize > BUFFER_SIZE)
      lFrameSize = BUFFER_SIZE;

    for (lPluginIndex = 0; lPluginIndex < lPluginCount; lPluginIndex++) 
      ppsPluginDescriptors[lPluginIndex]
	->run(ppsPlugins[lPluginIndex],
	      lFrameSize);
    
    /* Write the output to disk. */
    writeFromBuffers(ppfBuffers, lFrameSize);

    lTimeAt += lFrameSize;
  }

  /* Deactivate:
     ----------- */

  for (lPluginIndex = 0; lPluginIndex < lPluginCount; lPluginIndex++) 
    if (ppsPluginDescriptors[lPluginIndex]->deactivate != NULL)
      ppsPluginDescriptors[lPluginIndex]->deactivate(ppsPlugins[lPluginIndex]);

  /* Cleanup:
     -------- */

  for (lPluginIndex = 0; lPluginIndex < lPluginCount; lPluginIndex++) 
    ppsPluginDescriptors[lPluginIndex]->cleanup(ppsPlugins[lPluginIndex]);

  /* Close the input and output files:
     --------------------------------- */

  closeFiles();

}
ApplicationProperties::~ApplicationProperties()
{
    closeFiles();
    clearSingletonInstance();
}
Exemplo n.º 28
0
Bam2FastQ::~Bam2FastQ()
{
    closeFiles();
}
Exemplo n.º 29
0
int Bam2FastQ::execute(int argc, char **argv)
{
    // Extract command line arguments.
    String inFile = "";
    bool readName = false;
    String refFile = "";
    String firstOut = "";
    String secondOut = "";
    String unpairedOut = "";

    bool interleave = false;
    bool noeof = false;
    bool gzip = false;
    bool params = false;

    myOutBase = "";
    myNumMateFailures = 0;
    myNumPairs = 0;
    myNumUnpaired = 0;
    mySplitRG = false;
    myQField = "";
    myNumQualTagErrors = 0;
    myReverseComp = true;
    myRNPlus = false;
    myFirstRNExt = DEFAULT_FIRST_EXT;
    mySecondRNExt = DEFAULT_SECOND_EXT;
    myCompression = InputFile::DEFAULT;

    ParameterList inputParameters;
    BEGIN_LONG_PARAMETERS(longParameterList)
        LONG_PARAMETER_GROUP("Required Parameters")
        LONG_STRINGPARAMETER("in", &inFile)
        LONG_PARAMETER_GROUP("Optional Parameters")
        LONG_PARAMETER("readName", &readName)
        LONG_PARAMETER("splitRG", &mySplitRG)
        LONG_STRINGPARAMETER("qualField", &myQField)
        LONG_PARAMETER("merge", &interleave)
        LONG_STRINGPARAMETER("refFile", &refFile)
        LONG_STRINGPARAMETER("firstRNExt", &myFirstRNExt)
        LONG_STRINGPARAMETER("secondRNExt", &mySecondRNExt)
        LONG_PARAMETER("rnPlus", &myRNPlus)
        LONG_PARAMETER("noReverseComp", &myReverseComp)
        LONG_PARAMETER("gzip", &gzip)
        LONG_PARAMETER("noeof", &noeof)
        LONG_PARAMETER("params", &params)
        LONG_PARAMETER_GROUP("Optional OutputFile Names")
        LONG_STRINGPARAMETER("outBase", &myOutBase)
        LONG_STRINGPARAMETER("firstOut", &firstOut)
        LONG_STRINGPARAMETER("secondOut", &secondOut)
        LONG_STRINGPARAMETER("unpairedOut", &unpairedOut)
        LONG_PHONEHOME(VERSION)
        END_LONG_PARAMETERS();
   
    inputParameters.Add(new LongParameters ("Input Parameters", 
                                            longParameterList));

    // parameters start at index 2 rather than 1.
    inputParameters.Read(argc, argv, 2);

    // If no eof block is required for a bgzf file, set the bgzf file type to 
    // not look for it.
    if(noeof)
    {
        // Set that the eof block is not required.
        BgzfFileType::setRequireEofBlock(false);
    }

    if(gzip)
    {
        myCompression = InputFile::GZIP;
    }

    // Check to see if the in file was specified, if not, report an error.
    if(inFile == "")
    {
        usage();
        inputParameters.Status();
        // In file was not specified but it is mandatory.
        std::cerr << "--in is a mandatory argument, "
                  << "but was not specified" << std::endl;
        return(-1);
    }

    // Cannot specify both interleaved & secondOut since secondOut would be N/A.
    if(interleave && !secondOut.IsEmpty())
    {
        usage();
        inputParameters.Status();
        std::cerr << "ERROR: Cannot specify --merge & --secondOut.\n";
        return(-1);
    }

    // Cannot specify both interleaved & secondOut since secondOut would be N/A.
    if(interleave && !secondOut.IsEmpty())
    {
        usage();
        inputParameters.Status();
        std::cerr << "ERROR: Cannot specify --merge & --secondOut.\n";
        return(-1);
    }

    // Cannot specify both splitRG & firstOut/secondOut/unpairedOut
    // since it needs a different file for each RG.
    if(mySplitRG && (!firstOut.IsEmpty() || 
                   !secondOut.IsEmpty() || !unpairedOut.IsEmpty()))
    {
        usage();
        inputParameters.Status();
        std::cerr << "ERROR: Cannot specify --splitRG & --firstOut/--secondOut/--unpairedOut.\n";
        std::cerr << "Use --outBase instead.\n";
        return(-1);
    }
    // Cannot specify splitRG & output to stdout.
    if(mySplitRG && (myOutBase[0] == '-'))
    {
        usage();
        inputParameters.Status();
        std::cerr << "ERROR: Cannot specify --splitRG & write to stdout.\n";
        return(-1);
    }

    // Check to see if the out file was specified, if not, generate it from
    // the input filename.
    if(myOutBase == "")
    {
        // Just remove the extension from the input filename.
        int extStart = inFile.FastFindLastChar('.');
        if(extStart <= 0)
        {
            myOutBase = inFile;
        }
        else
        {
            myOutBase = inFile.Left(extStart);
        }
    }

    if(mySplitRG)
    {
        std::string fqList = myOutBase.c_str();
        fqList += ".list";
        myFqList = ifopen(fqList.c_str(), "w");
        ifprintf(myFqList, "MERGE_NAME\tFASTQ1\tFASTQ2\tRG\n");
    }

    // Check to see if the first/second/single-ended were specified and
    // if not, set them.
    myFirstFileNameExt = "_1.fastq";
    mySecondFileNameExt = "_2.fastq";
    myUnpairedFileNameExt = ".fastq";
    if(interleave)
    {
        myFirstFileNameExt = "_interleaved.fastq";
        myFirstFileNameExt = "_interleaved.fastq";
    }
    getFileName(firstOut, myFirstFileNameExt);
    getFileName(secondOut, mySecondFileNameExt);
    getFileName(unpairedOut, myUnpairedFileNameExt);

    if(params)
    {
        inputParameters.Status();
    }

    // Open the files for reading/writing.
    // Open prior to opening the output files,
    // so if there is an error, the outputs don't get created.
    SamFile samIn;
    samIn.OpenForRead(inFile, &mySamHeader);
    // Skip non-primary reads.
    samIn.SetReadFlags(0, 0x0100);

    // Open the output files if not splitting RG
    if(!mySplitRG)
    {
        myUnpairedFile = ifopen(unpairedOut, "w", myCompression);

        // Only open the first file if it is different than an already opened file.
        if(firstOut != unpairedOut)
        {
            myFirstFile = ifopen(firstOut, "w", myCompression);
        }
        else
        {
            myFirstFile = myUnpairedFile;
        }

        // If it is interleaved or the 2nd file is not a new name, set it appropriately.
        if(interleave || secondOut == firstOut)
        {
            mySecondFile = myFirstFile;
        }
        else if(secondOut == unpairedOut)
        {
            mySecondFile = myUnpairedFile;
        }
        else
        {
            mySecondFile = ifopen(secondOut, "w", myCompression);
        }
    
        if(myUnpairedFile == NULL)
        {
            std::cerr << "Failed to open " << unpairedOut
                      << " so can't convert bam2FastQ.\n";
            return(-1);
        }
        if(myFirstFile == NULL)
        {
            std::cerr << "Failed to open " << firstOut
                      << " so can't convert bam2FastQ.\n";
            return(-1);
        }
        if(mySecondFile == NULL)
        {
            std::cerr << "Failed to open " << secondOut
                      << " so can't convert bam2FastQ.\n";
            return(-1);
        }
    }

    if((readName) || (strcmp(mySamHeader.getSortOrder(), "queryname") == 0))
    {
        readName = true;
    }
    else
    {
        // defaulting to coordinate sorted.
        samIn.setSortedValidation(SamFile::COORDINATE);
    }

    // Setup the '=' translation if the reference was specified.
    if(!refFile.IsEmpty())
    {
        GenomeSequence* refPtr = new GenomeSequence(refFile);
        samIn.SetReadSequenceTranslation(SamRecord::BASES);
        samIn.SetReference(refPtr);
    }

    SamRecord* recordPtr;
    int16_t samFlag;

    SamStatus::Status returnStatus = SamStatus::SUCCESS;
    while(returnStatus == SamStatus::SUCCESS)
    {
        recordPtr = myPool.getRecord();
        if(recordPtr == NULL)
        {
            // Failed to allocate a new record.
            throw(std::runtime_error("Failed to allocate a new SAM/BAM record"));
        }
        if(!samIn.ReadRecord(mySamHeader, *recordPtr))
        {
            // Failed to read a record.
            returnStatus = samIn.GetStatus();
            continue;
        }

        // Have a record.  Check to see if it is a pair or unpaired read.
        samFlag = recordPtr->getFlag();
        if(SamFlag::isPaired(samFlag))
        {
            if(readName)
            {
                handlePairedRN(*recordPtr);
            }
            else
            {
                handlePairedCoord(*recordPtr);
            }
        }
        else
        {
            ++myNumUnpaired;
            writeFastQ(*recordPtr, myUnpairedFile,
                       myUnpairedFileNameExt);
        }
    }

    // Flush All
    cleanUpMateMap(0, true);

    if(returnStatus == SamStatus::NO_MORE_RECS)
    {
        returnStatus = SamStatus::SUCCESS;
    }

    samIn.Close();
    closeFiles();
    
    // Output the results
    std::cerr << "\nFound " << myNumPairs << " read pairs.\n";
    std::cerr << "Found " << myNumUnpaired << " unpaired reads.\n";
    if(myNumMateFailures != 0)
    {
        std::cerr << "Failed to find mates for " << myNumMateFailures
                  << " reads, so they were written as unpaired\n"
                  << "  (not included in either of the above counts).\n";
    }
    if(myNumQualTagErrors != 0)
    {
        std::cerr << myNumQualTagErrors << " records did not have tag "
                  << myQField.c_str() << " or it was invalid, so the quality field was used for those records.\n";
    }

    return(returnStatus);
}
Exemplo n.º 30
0
DataHandler::~DataHandler()
{
  closeFiles();
}