Пример #1
0
bool Mp3PspStream::seek(const Timestamp &where) {
	DEBUG_ENTER_FUNC();

	if (where == _length) {
		_state = MP3_STATE_EOS;
		return true;
	} else if (where > _length) {
		return false;
	}

	const uint32 time = where.msecs();

	mad_timer_t destination;
	mad_timer_set(&destination, time / 1000, time % 1000, 1000);

	// Important to release and re-init the ME
	releaseStreamME();
	initStreamME();

	// Check if we need to rewind
	if (_state != MP3_STATE_READY || mad_timer_compare(destination, _totalTime) < 0) {
		initStream();
	}

	// Skip ahead
	while (mad_timer_compare(destination, _totalTime) > 0 && _state != MP3_STATE_EOS)
		findValidHeader();

	return (_state != MP3_STATE_EOS);
}
Пример #2
0
Mp3PspStream::Mp3PspStream(Common::SeekableReadStream *inStream, DisposeAfterUse::Flag dispose) :
	_inStream(inStream),
	_disposeAfterUse(dispose),
	_pcmLength(0),
	_posInFrame(0),
	_state(MP3_STATE_INIT),
	_length(0, 1000),
	_sampleRate(0),
	_totalTime(mad_timer_zero) {

	DEBUG_ENTER_FUNC();

	assert(_decoderInit);	// must be initialized by now

	// let's leave the buffer guard -- who knows, it may be good?
	memset(_buf, 0, sizeof(_buf));
	memset(_codecInBuffer, 0, sizeof(_codecInBuffer));

	initStream();	// init needed stuff for the stream

	findValidHeader();	// get a first header so we can read basic stuff

	_sampleRate = _header.samplerate;	// copy it before it gets destroyed
	_stereo = (MAD_NCHANNELS(&_header) == 2);

	while (_state != MP3_STATE_EOS)
		findValidHeader();	// get a first header so we can read basic stuff

	_length = Timestamp(mad_timer_count(_totalTime, MAD_UNITS_MILLISECONDS), getRate());

	deinitStream();

	_state = MP3_STATE_INIT;
}
Пример #3
0
rtspStream::rtspStream(int ID,int width,int height,int fps,int bitrate,rtspStreamSendData& lpCallback)
	:m_nStreamID(ID)
	,m_nStreamPort(12000+ID)
	,estBitrate(500)
	,fSDPLines(NULL)
	,fTrackId(NULL)
	,m_nSSRC(ID)
	,fSeqNo(0)
	,fRTPPayloadType(96)
	,m_hSendThread(NULL)
	,m_nTimeStamp(0)
	,m_nWidth(width)
	,m_nHeight(height)
{
	lpCallback = SendData;
	PYUVBuf = new unsigned char[width*height+(width * height)];
	pLoadBuf = new unsigned char[width*height+(width * height)]; 
	initH264Encoder(width,height,fps,bitrate);
	initStream();
	m_pRtpHeader = new RTPHeader;
	m_pSendData = new unsigned char[RTP_PACKAGE_MAX_SIZE+RTP_HEADER_SIZE +2];

	m_hSendThread = CreateThread(NULL,NULL,InitSendThread,this,NULL,NULL);
	m_hExitEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
	m_hDelIPEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
	m_hSendEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
	InitializeCriticalSection(&cs);
}
int QCameraStream_preview::prepareStream()
{
    mm_camera_img_mode img_mode;
    cam_format_t format;
    struct private_handle_t *private_handle = mPreviewMemory.private_buffer_handle[0];

    ALOGE("%s: private_handle->format = %d, flags = %d", __func__,
        private_handle->format, private_handle->flags);
    if (private_handle->flags & private_handle_t::PRIV_FLAGS_VIDEO_ENCODER)
        img_mode = MM_CAMERA_VIDEO;
    else if (private_handle->flags & private_handle_t::PRIV_FLAGS_CAMERA_WRITE)
        img_mode = MM_CAMERA_PREVIEW;
    else {
        ALOGE("%s: Invalid flags %d\n", __func__, private_handle->flags);
        return BAD_VALUE;
    }

    switch (private_handle->format) {
    case HAL_PIXEL_FORMAT_YCbCr_420_SP:
        format = CAMERA_YUV_420_NV12;
        break;
    case HAL_PIXEL_FORMAT_YCrCb_420_SP:
        format = CAMERA_YUV_420_NV21;
        break;
    default:
        ALOGE("%s: Invalid format!!!", __func__);
        return BAD_VALUE;
    }
    if(NO_ERROR!=initStream(img_mode, format)) {
        ALOGE("Init stream failed");
        return BAD_VALUE;
    }
    return OK;
}
Пример #5
0
int EncoderWave::initEncoder(int samplerate, QString errorMessage) {

    // set sfInfo.
    // m_sfInfo.format is setup on setEncoderSettings previous to calling initEncoder.
    m_sfInfo.samplerate = samplerate;
    m_sfInfo.channels = 2;
    m_sfInfo.frames = 0;
    m_sfInfo.sections = 0;
    m_sfInfo.seekable = 0;

    // Opens a soundfile from a virtual file I/O context which is provided by the caller.
    // This is usually used to interface libsndfile to a stream or buffer based system.
    // Apart from the sfvirtual and the user_data parameters this function behaves like sf_open.
    m_pSndfile = sf_open_virtual (&m_virtualIo, SFM_WRITE, &m_sfInfo, m_pCallback) ;

    int ret=0;
    if (m_pSndfile == nullptr) {
        errorMessage = QString("Error initializing Wave recording. sf_open_virtual returned: ")
            +  sf_strerror(nullptr);
        qDebug() << errorMessage;
        ret = -1;
    } else {
        initStream();
    };
    return ret;
}
Пример #6
0
    void AudioPlayer::play(const AudioData& data) {
	if (_stream == NULL)
	    initStream(data.format());
	if (!Pa_IsStreamActive(_stream))
	    Pa_StartStream(_stream);
	std::lock_guard<std::mutex> lock(_mutex);
	_buffer.write((Byte*)data.frames(), (Byte*)data.frames() + (data.nbFrames() * data.format().frameSize()));
    }
Пример #7
0
ScPageOutput_Ps2::ScPageOutput_Ps2(QIODevice* dev, ScribusDoc* doc, int pageIndex, ScPs2OutputParams& options)
				: ScPageOutput(doc, options.reloadImages, options.resolution, options.useProfiles)
{
	m_device = dev;
	m_pageIndex = pageIndex;
	m_options = options;
	m_options.document = doc;
	initStream(dev);
}
Пример #8
0
//////////////////////////////////////////////////////////////////////////
// Init
//////////////////////////////////////////////////////////////////////////
void SaveLoad::create(GameId id) {
	initStream();

	Common::Serializer ser(NULL, _savegame);
	SavegameMainHeader header;
	header.saveLoadWithSerializer(ser);

	flushStream(id);
}
bool JavaInputStream::open() {
	if (myJavaInputStream == 0) {
		JNIEnv *env = AndroidUtil::getEnv();
		initStream(env);
	} else {
		myNeedRepositionToStart = true;
	}
	return myJavaInputStream != 0;
}
Пример #10
0
LRESULT CStreamEditorView::OnInitDialog(HWND /*hWnd*/, LPARAM /*lParam*/)
{
	SetMsgHandled(false);
	DlgResize_Init(false,false);

	m_edit.SubclassWindow(GetDlgItem(IDC_EDIT_OUTPUT));
	m_editLog.SetEditCtrl(m_edit);
	initStream();

	return 0;
}
void QCameraHAL3RawSnapshotTest::configureRawSnapshotStream(hal3_camera_test_obj_t *my_test_obj,
                                    int camid, int w, int h)
{
    camera3_device_t *device_handle = my_test_obj->device;
    LOGD(" configureSnapshotStream testcase dim :%d  X %d", w, h);
    mPreviewStream = new camera3_stream_t;
    mRawSnapshotStream = new camera3_stream_t;

    memset(mPreviewStream, 0, sizeof(camera3_stream_t));
    memset(mRawSnapshotStream, 0, sizeof(camera3_stream_t));

    mPreviewStream = initStream(CAMERA3_STREAM_OUTPUT, camid, PREVIEW_WIDTH, PREVIEW_HEIGHT, 0,
            HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, HAL3_DATASPACE_UNKNOWN);
    mRawSnapshotStream = initStream(CAMERA3_STREAM_OUTPUT, camid, RAWSNAPSHOT_CAPTURE_WIDTH,
            RAWSNAPSHOT_CAPTURE_HEIGHT, 0, HAL_PIXEL_FORMAT_RAW16, HAL3_DATASPACE_ARBITRARY);
    mRawSnapshotConfig = configureStream(CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE, 2);

    mRawSnapshotConfig.streams[0] = mPreviewStream;
    mRawSnapshotConfig.streams[1] = mRawSnapshotStream;
    device_handle->ops->configure_streams(my_test_obj->device, &(mRawSnapshotConfig));
}
Пример #12
0
bool MP3Stream::rewind() {
	mad_timer_t destination;
	mad_timer_set(&destination, 0, 0, 1000);

	if (_state != MP3_STATE_READY || mad_timer_compare(destination, _totalTime) < 0)
		initStream();

	while (mad_timer_compare(destination, _totalTime) > 0 && _state != MP3_STATE_EOS)
		readHeader();

	return (_state != MP3_STATE_EOS);
}
Пример #13
0
int EncoderVorbis::initEncoder(int bitrate, int samplerate) {
    vorbis_info_init(&m_vinfo);

    // initialize VBR quality based mode
    int ret = vorbis_encode_init(&m_vinfo, 2, samplerate, -1, bitrate*1000, -1);

    if (ret == 0) {
        initStream();
    } else {
        ret = -1;
    };
    return ret;
}
Пример #14
0
void RobotDecoder::open(const GuiResourceId robotId, const reg_t plane, const int16 priority, const int16 x, const int16 y, const int16 scale) {
	if (_status != kRobotStatusUninitialized) {
		close();
	}

	initStream(robotId);

	_version = _stream->readUint16();

	// TODO: Version 4 for PQ:SWAT demo?
	if (_version < 5 || _version > 6) {
		error("Unsupported version %d of Robot resource", _version);
	}

	debugC(kDebugLevelVideo, "Opening version %d robot %d", _version, robotId);

	initPlayback();

	_audioBlockSize = _stream->readUint16();
	_primerZeroCompressFlag = _stream->readSint16();
	_stream->seek(2, SEEK_CUR); // unused
	_numFramesTotal = _stream->readUint16();
	const uint16 paletteSize = _stream->readUint16();
	_primerReservedSize = _stream->readUint16();
	_xResolution = _stream->readSint16();
	_yResolution = _stream->readSint16();
	const bool hasPalette = (bool)_stream->readByte();
	_hasAudio = (bool)_stream->readByte();
	_stream->seek(2, SEEK_CUR); // unused
	_frameRate = _normalFrameRate = _stream->readSint16();
	_isHiRes = (bool)_stream->readSint16();
	_maxSkippablePackets = _stream->readSint16();
	_maxCelsPerFrame = _stream->readSint16();

	// used for memory preallocation of fixed cels
	_maxCelArea.push_back(_stream->readSint32());
	_maxCelArea.push_back(_stream->readSint32());
	_maxCelArea.push_back(_stream->readSint32());
	_maxCelArea.push_back(_stream->readSint32());
	_stream->seek(8, SEEK_CUR); // reserved

	if (_hasAudio) {
		initAudio();
	} else {
		_stream->seek(_primerReservedSize, SEEK_CUR);
	}

	_priority = priority;
	initVideo(x, y, scale, plane, hasPalette, paletteSize);
	initRecordAndCuePositions();
}
Пример #15
0
uint32 SaveLoad::init(GameId id, bool resetHeaders) {
	initStream();

	// Load game data
	loadStream(id);

	// Get the main header
	Common::Serializer ser(_savegame, NULL);
	SavegameMainHeader mainHeader;
	mainHeader.saveLoadWithSerializer(ser);
	if (!mainHeader.isValid())
		error("SaveLoad::init - Savegame seems to be corrupted (invalid header)");

	// Reset cached entry headers if needed
	if (resetHeaders) {
		clear();

		SavegameEntryHeader *entryHeader = new SavegameEntryHeader();
		entryHeader->time = kTimeCityParis;
		entryHeader->chapter = kChapter1;

		_gameHeaders.push_back(entryHeader);
	}

	// Read the list of entry headers
	if (_savegame->size() > 32) {
		while (_savegame->pos() < _savegame->size() && !_savegame->eos() && !_savegame->err()) {

			// Update sound queue while we go through the savegame
			getSound()->updateQueue();

			SavegameEntryHeader *entry = new SavegameEntryHeader();
			entry->saveLoadWithSerializer(ser);

			if (!entry->isValid())
				break;

			_gameHeaders.push_back(entry);

			_savegame->seek(entry->offset, SEEK_CUR);
		}
	}

	// return the index to the current save game entry (we store count + 1 entries, so we're good)
	return mainHeader.count;
}
Пример #16
0
bool PaPlayer::openFile(const std::string &fileName)
{
    std::ifstream wav_fin;
    wav_fin.open(fileName.c_str(), std::ios_base::binary);
    ByteOrderStreamIn<> bytestream(wav_fin);


    WavFileFormat wavFile;
    if (!wavFile.readFromStream(bytestream) ){
        m_lastError = wavFile.lastError();
        return false;
    }
    wav_fin.close();
    *m_wavFile = wavFile;
    m_fullSize = m_wavFile->fullSize();

    return initStream();
}
Пример #17
0
bool SGFParser::writeStream(Tree *tree)
{
	CHECK_PTR(stream);
	if (!initStream(stream))
	{
		QMessageBox::critical(0, PACKAGE, Board::tr("Invalid text encoding given. Please check preferences!"));
		delete stream;
		return false;
	}
	
	Move *root = tree->getRoot();
	if (root == NULL)
		return false;
	
	GameData *gameData = boardHandler->getGameData();
	
	// Traverse the tree recursive in pre-order
	isRoot = true;
	traverse(root, gameData);
	
	return true;
}
Пример #18
0
QString SGFParser::loadFile(const QString &fileName)
{
	qDebug("Trying to load file <%s>", fileName.latin1());
	
	QFile file(fileName);
	
	if (!file.exists())
	{
		QMessageBox::warning(0, PACKAGE, Board::tr("Could not find file:") + " " + fileName);
		return NULL;
	}
	
	if (!file.open(IO_ReadOnly))
	{
		QMessageBox::warning(0, PACKAGE, Board::tr("Could not open file:") + " " + fileName);
		return NULL;
	}
	
	QTextStream txt(&file);
	if (!initStream(&txt))
	{
		QMessageBox::critical(0, PACKAGE, Board::tr("Invalid text encoding given. Please check preferences!"));
		return NULL;
	}
	
	QString toParse;
	
	// Read file in string toParse
	while (!txt.eof())
		toParse.append(txt.readLine() + "\n");
	
	file.close();
#ifdef DEBUG_CODEC
	QMessageBox::information(0, "READING", toParse);
#endif

	return toParse;
}
Пример #19
0
bool MP3Stream::seek(const Timestamp &where) {
	if (where == _length) {
		_state = MP3_STATE_EOS;
		return true;
	} else if (where > _length) {
		return false;
	}

	const uint32 time = where.msecs();

	mad_timer_t destination;
	mad_timer_set(&destination, time / 1000, time % 1000, 1000);

	if (_state != MP3_STATE_READY || mad_timer_compare(destination, _totalTime) < 0)
		initStream();

	while (mad_timer_compare(destination, _totalTime) > 0 && _state != MP3_STATE_EOS)
		readHeader();

	decodeMP3Data();

	return (_state != MP3_STATE_EOS);
}
Пример #20
0
// Init
bool v4l2Camera::init()
{
	// locate the /dev/event* path for this device
	mFD = open(mDevicePath.c_str(), O_RDWR | O_NONBLOCK, 0 );

	if( mFD < 0 )
	{
		printf( "v4l2 -- failed to open %s\n", mDevicePath.c_str());
		return false;
	}

	// initialize
	if( !initCaps() )
		return false;

	if( !initFormats() )
		return false;

	if( !initStream() )
		return false;

	return true;
}
Пример #21
0
void Foam::functionObjectFile::createFiles()
{
    if (Pstream::master())
    {
        const word startTimeName =
            obr_.time().timeName(obr_.time().startTime().value());

        label i = 0;
        forAllConstIter(wordHashSet, names_, iter)
        {
            if (!filePtrs_.set(i))
            {
                fileName outputDir(baseFileDir()/prefix_/startTimeName);

                mkDir(outputDir);

                word fName(iter.key());

                // check if file already exists
                IFstream is(outputDir/(fName + ".dat"));
                if (is.good())
                {
                    fName = fName + "_" + obr_.time().timeName();
                }

                filePtrs_.set(i, new OFstream(outputDir/(fName + ".dat")));

                initStream(filePtrs_[i]);

                writeFileHeader(i);

                i++;
            }
        }
    }
}
Пример #22
0
command_stream_t
make_command_stream (int (*get_next_byte) (void *),
                     void *get_next_byte_argument)
{
    
    //current character
    char curr;
    int tree_number = 1;
    char prev_char_stored = '\0';
    int consecutive_newlines = 0;
    
    
    //buffer size = 1KB
    int BUFFER_SIZE = 1024;
    //buffer to read characters into; buffer can hold 1024 chars at once
    char *buffer = (char *) checked_malloc(BUFFER_SIZE * sizeof(char));
    
    //int to count how many chars are in buffer
    int numChars = 0;
    
    //int to count which line we are on
    //int syntax_line_counter = 0;
    int invalid_char_line_counter = 1;
    
    //if this is true, we are searching for the right operand of an operator
    bool found_AND_OR_PIPE_SEQUENCE = false; //looking for operand
    
    
    //declare command stream and allocate space
    //maybe dont need to allocate space because initStream() already does?
    command_stream_t theStream;    // = (command_stream_t) checked_malloc(sizeof(struct command_stream));
    
    //initialize command_stream
    theStream = initStream();
    
    //start reading the chars from the input
    while ((curr = get_next_byte(get_next_byte_argument)) != EOF ) {
        
        if (numChars > 0){
            //only stores previous meaningful character, i.e. not whitespace
            if ((buffer[numChars-1] != ' ' && buffer[numChars-1] != '#')){
                prev_char_stored = buffer[numChars-1];
            }
        }
        
        if (prev_char_stored == '&' || prev_char_stored == '|' || prev_char_stored == ';'){
            found_AND_OR_PIPE_SEQUENCE = true;
        }
        
        
        
        ////////////////////////////////////////////////////////////
        //////////////////      NEWLINE CHAR    ////////////////////
        ////////////////////////////////////////////////////////////
        
        /*
         New variables introduced:
         char prev_char_stored;
         int consecutive_newlines;
         bool command_has_ended; //haven't needed to use yet
         
         */
        if (identify_char_type(curr) == NEWLINE_CHAR || identify_char_type(curr) == HASHTAG_CHAR){
            
            //found a newline, increment counter
            consecutive_newlines++;
            
            //hit second (or more) newline
            if (consecutive_newlines > 1){
                //not looking for an operator and
                if (!found_AND_OR_PIPE_SEQUENCE){
                    if (identify_char_type(curr) == NEWLINE_CHAR) {
                    //add second newline to buffer
                    buffer[numChars] = '\n';
                    numChars++;
                    curr = get_next_byte(get_next_byte_argument);
                    }
                    /*
                     check for newlines, whitespaces, and hashtags after second newline
                     Store newlines on the buffer, ignore white spaces, and for hashtags:
                     put hashtag and newline on the buffer
                     */
                    while (identify_char_type(curr) == NEWLINE_CHAR || identify_char_type(curr) == WHITESPACE_CHAR || identify_char_type(curr) == HASHTAG_CHAR){
                        if (curr == '\n'){
                            buffer[numChars] = '\n';
                            numChars++;
                        } else if (curr == '#'){
                            //add hashtag to buffer
                            consecutive_newlines++;
                            buffer[numChars] = '#';
                            numChars++;
                            
                            //go to end of comment
                            while (identify_char_type(curr) != NEWLINE_CHAR){
                                if ((curr = get_next_byte(get_next_byte_argument)) == EOF) {
                                    break;
                                }
                            }
                            //broke out of loop, curr is now a newline char; add to buffer
                            buffer[numChars] = '\n';
                            numChars++;
                            
                        }
                        
                        if ((curr = get_next_byte(get_next_byte_argument)) == EOF) {
                            break;
                        }
                    }
                    
                    consecutive_newlines = 0;
                    
                    //create temporary array with size of numChars;
                    char* buffer_no_whitespaces = checked_malloc(BUFFER_SIZE * (sizeof(char)));  //the correct syntaxed command
                    memset(buffer_no_whitespaces, '\0', BUFFER_SIZE * sizeof(char));
                    
                    //run validation, then parse if correct
                    
                    eatWhiteSpaces(buffer, numChars, buffer_no_whitespaces);
                    
                    
                    int pos = 0;
                    
                    while (buffer_no_whitespaces[pos] != '\0'){
                        if (identify_char_type(buffer_no_whitespaces[pos]) == NEWLINE_CHAR){
                            invalid_char_line_counter++;
                        }
                        if (identify_char_type(buffer_no_whitespaces[pos]) == INVALID_CHAR){
                            identify_char_type(buffer_no_whitespaces[pos]);
                            fprintf(stderr, "%d: Invalid character: %c <---", invalid_char_line_counter, buffer_no_whitespaces[pos]);
                            exit(1);
                        }
                        pos++;
                    }
                    
                    checkAndSyntax(buffer_no_whitespaces);
                    checkForConsecutiveTokens(buffer_no_whitespaces);
                    checkIfOperatorsHaveOperands(buffer_no_whitespaces);
                    validParentheses(buffer_no_whitespaces);
                    
                    /*
                     int i;
                     for (i= 0; i<numChars; i++){
                     printf("%c", buffer_no_whitespaces[i]);
                     }
                     
                     //this just separates commands
                     printf("\n");
                     */
                    
                    commandNode_t root = createNodeFromCommand(make_command_tree(buffer_no_whitespaces));
                    
                    //printf("adding command node to stream: %s\n", root->cmd->u.word[0]);
                    
                    write_list_t write_list = init_write_list();
                    
                    //printf("adding command node to stream: %s\n", root->cmd->u.word[0]);
                    root->write_list = make_write_list(write_list, root->cmd);
                    read_list_t read_list = init_read_list();
                    root->read_list = make_read_list(read_list, root->cmd);
                    
                    root->tree_number=tree_number;
                    
                    root->dependency_list = (commandNode_t*)(checked_realloc(root->dependency_list, (tree_number) * sizeof(commandNode_t)));
                    memset (root -> dependency_list, '\0', (tree_number) * sizeof(commandNode_t));
                    
                    
                    //printf("adding command node to stream: %s\n", root->cmd->u.word[0]);
                    
                    addNodeToStream(theStream, root);
                    
                    
                    //reset everything with memset
                    memset(buffer, '\0', BUFFER_SIZE * sizeof(char));
                    free(buffer_no_whitespaces);
                    numChars = 0;
                    consecutive_newlines = 0;
                    
                    tree_number++;
                    
                    
                    if (curr == EOF)
                        break;
                    /*
                     We are now at a new command.
                     Add first character to buffer, whether valid or invalid.
                     Will check syntax later.
                     */
                    if (identify_char_type(curr) != HASHTAG_CHAR){
                        buffer[numChars] = curr;
                        numChars++;
                    } else {
                        //add a hashtag and newline to the buffer
                        buffer[numChars] = '#';
                        numChars++;
                        
                        //get to the end of the line
                        while (identify_char_type(curr) != NEWLINE_CHAR){
                            if ((curr = get_next_byte(get_next_byte_argument)) == EOF) {
                                break;
                            }
                        }
                        
                        //now we have a newline; add newline to buffer
                        buffer[numChars]=curr;
                        numChars++;
                        consecutive_newlines++;
                    }
                    continue;
                } else { //if we are looking for operand, don't end the commmand
                    
                    while (identify_char_type(curr) == NEWLINE_CHAR || identify_char_type(curr) == WHITESPACE_CHAR || identify_char_type(curr) == HASHTAG_CHAR){
                        if (curr == '\n'){
                            buffer[numChars] = '\n';
                            numChars++;
                        } else if (curr == '#'){
                            //add hashtag to buffer
                            buffer[numChars] = '#';
                            numChars++;
                            
                            while (identify_char_type(curr) != NEWLINE_CHAR){
                                if ((curr = get_next_byte(get_next_byte_argument)) == EOF) {
                                    break;
                                }
                            }
                            //broke out of loop, curr is now a newline char; add to buffer
                            buffer[numChars] = '\n';
                            numChars++;
                        }
                        
                        if ((curr = get_next_byte(get_next_byte_argument)) == EOF) {
                            break;
                        }
                        
                        
                    }
                    //broken out of while loop, we now have a regular character; add to buffer
                    
                    if (curr == EOF)
                        break;
                    
                    buffer[numChars] = curr;
                    numChars++;
                    found_AND_OR_PIPE_SEQUENCE = false;
                    consecutive_newlines = 0;
                    continue;
                }
            } else {
                //add newline to buffer; this is when number of newlines equals one
                if (identify_char_type(curr) == HASHTAG_CHAR) {
                    buffer[numChars] = '#';
                    numChars++;
                    
                    while (identify_char_type(curr) != NEWLINE_CHAR){
                        if ((curr = get_next_byte(get_next_byte_argument)) == EOF) {
                            break;
                        }
                    }
                    
                }
                buffer[numChars] = '\n';
                numChars++;
                continue;
            }
        } //end newline case
        else {
            
            
            if (!found_AND_OR_PIPE_SEQUENCE && consecutive_newlines == 1) {
                buffer[numChars] = ';';
                numChars++;
            }
            
            buffer[numChars] = curr;
            numChars++;
            consecutive_newlines = 0;
            
            //if we are here we no longer skip lines
            found_AND_OR_PIPE_SEQUENCE = false;
        }
    }
    
    char* buffer_no_whitespaces = checked_malloc(BUFFER_SIZE * (sizeof(char)));  //the correct syntaxed command
    memset(buffer_no_whitespaces, '\0', BUFFER_SIZE * sizeof(char));
    
    //run validation, then parse if correct
    //void eatWhiteSpaces(char *buffer, int bufferSize, char *newArray)
    eatWhiteSpaces(buffer, numChars, buffer_no_whitespaces);
    int pos = 0;
    
    while (buffer_no_whitespaces[pos] != '\0'){
        if (identify_char_type(buffer_no_whitespaces[pos]) == NEWLINE_CHAR){
            invalid_char_line_counter++;
        }
        if (identify_char_type(buffer_no_whitespaces[pos]) == INVALID_CHAR){
            identify_char_type(buffer_no_whitespaces[pos]);
            fprintf(stderr, "%d: Invalid character: %c <---", invalid_char_line_counter, buffer_no_whitespaces[pos]);
            exit(1);
        }
        pos++;
    }
    
    checkAndSyntax(buffer_no_whitespaces);
    checkForConsecutiveTokens(buffer_no_whitespaces);
    checkIfOperatorsHaveOperands(buffer_no_whitespaces);
    validParentheses(buffer_no_whitespaces);
    
    /*
     if (buffer_no_whitespaces[0] != '\0') {
     int i;
     for (i= 0; i<numChars; i++){
     printf("%c", buffer_no_whitespaces[i]);
     }
     printf("\n");
     }*/
    
    
    //make sure buffer_no_whitespace is not empty
    if (buffer_no_whitespaces[0] != '\0') {
        commandNode_t root = createNodeFromCommand(make_command_tree(buffer_no_whitespaces));
        
        write_list_t write_list = init_write_list();
        root->write_list = make_write_list(write_list, root->cmd);
        read_list_t read_list = init_read_list();
        root->read_list = make_read_list(read_list, root->cmd);
        root->tree_number=tree_number;
        
        
        root->dependency_list = (commandNode_t*)(checked_realloc(root->dependency_list, (tree_number) * sizeof(commandNode_t)));
        memset (root -> dependency_list, '\0', (tree_number) * sizeof(commandNode_t));
        
        //printf("adding command node to stream: %s\n", root->cmd->u.word[0]);
        
        addNodeToStream(theStream, root);
    }
    
    free(buffer);
    free(buffer_no_whitespaces);
    
    theStream->blocked_commands = (commandNode_t*)checked_realloc(theStream->blocked_commands, theStream->num_nodes * sizeof(commandNode_t));
    memset(theStream->blocked_commands, '\0', theStream->num_nodes * sizeof(commandNode_t));
    
    return theStream;
}
void JavaInputStream::rewind(JNIEnv *env) {
	if (myOffset > 0) {
		closeStream(env);
		initStream(env);
	}
}
Пример #24
0
command_stream_t
make_command_stream(int(*getbyte) (void *), void *arg)
{
  initStackc(&s);
  initStacko(&o);
  struct command_stream *command_stream_t = (struct command_stream *)malloc(sizeof(struct command_stream));
  initStream(command_stream_t);
  struct command*com = (struct command*)malloc(sizeof(struct command));
  com->type = SIMPLE_COMMAND;
  com->input = com->output = NULL;
  struct oper o;
  char c;
  bool extra = false;
  bool done = false;
  int csize = 10;
  com->u.word = (char**)malloc(10 * sizeof(char*));
  int count = 0;
  int length = 0;
  int mlength = 12;
  char* word = (char*)malloc(12 * sizeof(char));
  c = getbyte(arg);
  int curline = 1;
  skipws(getbyte, arg, &c, &curline);
  while (c >= 0)
    {
      done = false;
      if (!isValidChar(c))
	printError(curline);
      extra = false;
      if (isvalid(c))
	{
	  word[length] = c;
	  length++;
	  if (length >= mlength)
	    {
	      mlength += 5;
	      word = (char*)realloc(word, mlength*sizeof(char));
	    }
	}
      else
	{
	  if (c == '#')
	    {
	      while ((c = (char)getbyte(arg)) >= 0 && c != '\n');
	    }
	  else if (c == '\\')
	    {
	      while (c == '\\')
		{
		  c = (char)getbyte(arg);
		  c = (char)getbyte(arg);
		}
	      continue;
	    }
	  else if (c == ' ')
	    {
	      if (length > 0)
		{
		  addWord(&com, &count, &length, word);
		  if (count == csize - 1)
		    {
		      csize += 5;
		      com->u.word = (char**)realloc(com->u.word, csize*sizeof(int));
		    }
		}
	      else
		{
		  c = (char)getbyte(arg);
		  continue;
		}
	    }

	  else if (c == '|' || c == '&' || c == ';' || c == '\n' || c == '(' || c == ')')
	    {
	      /*if (com->type == SUBSHELL_COMMAND)
		{
		com = (struct command*)malloc(sizeof(struct command));
		com->type = SIMPLE_COMMAND;
		com->u.word = (char**)malloc(10 * sizeof(char*));
		com->input = com->output = NULL;
		count = 0;
		csize = 10;
		}
	      */
	      addWord(&com, &count, &length, word);
	      if (c == '|')
		{
		  c = (char)getbyte(arg);
		  if (c == '|')
		    {
		      o.type = OR;
		    }
		  else
		    {
		      o.type = PIPE;
		    }
		}
	      else if (c == '&')
		{
		  o.type = AND;
		  c = (char)getbyte(arg);
		  if (c != '&')
		    printError(curline);
		}
	      else if (c == ';')
		{
		  o.type = SEQ;
		  c = (char)getbyte(arg);
		}
	      else if (c == '(')
		{
		  o.type = LEFT;
		}
	      else if (c == ')')
		{
		  o.type = RIGHT;
		}
	      else if (c == '\n')
		{
		  curline += 1;
		  while ((c = (char)getbyte(arg)) == ' ');
		  if (c < 0) break;
		  while (c == '\\')
		    {
		      c = (char)getbyte(arg);
		      c = (char)getbyte(arg);
		    }
		  if (c == '#')
		    {
		      while ((c = getbyte(arg)) >= 0 && c != '\n');
		    }      
		  if (c != '\n' && (com->u.word != NULL || com->u.subshell_command != NULL))
		    {
		      o.type = SEQ;
		      extra = true;
		    }
		  else
		    {
		      extra = false;
		      if (count > 0)
			{
			  com->u.word[count] = '\0';
			  pushc(&s, com);
			}
		      o.type = SEQ;
		      add(o, 't', curline);
		      insert(command_stream_t, topc(&s));
		      popc(&s);
		      done = true;
		      reset(&com, &word, &length, &count, &csize, &mlength, 'f');
		      c = (char)getbyte(arg);
		      skipws(getbyte, arg, &c, &curline);
		      continue;
		    }
		}
	    
	  if (o.type != PIPE && o.type != SEQ)
	    {
	      c = (char)getbyte(arg);
	    }
	  if (count > 0)
	    {
	      com->u.word[count] = '\0';
	      pushc(&s, com);
	    }
	  add(o, 'f', curline);
	  if (o.type == RIGHT)
	    reset(&com, &word, &length, &count, &csize, &mlength, 't');
	  else
	    reset(&com, &word, &length, &count, &csize, &mlength, 'f');
	  if (o.type != RIGHT)
	    {
	      skipws(getbyte, arg, &c,&curline);
	    }
	  extra = true;
	}
      else if (c == '>' || c == '<')
	{
	  char* ptr;
	  int insize = 12;
	  ptr = (char*)malloc(insize * sizeof(char));
	  int i = 0;
	  char t = c;
	  while ((c = (char)getbyte(arg)) == ' ');
	  if (!isvalid(c))
	    printError(curline);
	  while ((c >= 0))
	    {
	      if (!isvalid(c))
		{
		  extra = true;
		  break;
		}
	      ptr[i] = c;
	      i++;
	      if (i == insize - 1)
		{
		  insize += 5;
		  ptr = (char*)realloc(ptr, insize*sizeof(char));
		}
	      c = (char)getbyte(arg);
	    }
	  ptr[i] = '\0';
	  if (t == '<')
	    com->input = ptr;
	  else com->output = ptr;
	}
    }

  if (!extra)
    c = (char)getbyte(arg);
}
if (!done)
  {
    addWord(&com, &count, &length, word);
    if (count > 0)
      {
	com->u.word[count] = '\0';
	pushc(&s, com);
      }
    o.type = SEQ;
    add(o, 't', curline);
    if (sizec(&s) != 1)
      printError(curline);
    insert(command_stream_t, topc(&s));
    popc(&s);
  }
return command_stream_t;

}
Пример #25
0
status_t WebmWriter::start(MetaData *params) {
    if (mInitCheck != OK) {
        return UNKNOWN_ERROR;
    }

    if (mStreams[kVideoIndex].mTrackEntry == NULL
            && mStreams[kAudioIndex].mTrackEntry == NULL) {
        ALOGE("No source added");
        return INVALID_OPERATION;
    }

    if (mMaxFileSizeLimitBytes != 0) {
        mIsFileSizeLimitExplicitlyRequested = true;
    }

    if (params) {
        int32_t isRealTimeRecording;
        params->findInt32(kKeyRealTimeRecording, &isRealTimeRecording);
        mIsRealTimeRecording = isRealTimeRecording;
    }

    if (mStarted) {
        if (mPaused) {
            mPaused = false;
            mStreams[kAudioIndex].mThread->resume();
            mStreams[kVideoIndex].mThread->resume();
        }
        return OK;
    }

    if (params) {
        int32_t tcsl;
        if (params->findInt32(kKeyTimeScale, &tcsl)) {
            mTimeCodeScale = tcsl;
        }
    }
    CHECK_GT(mTimeCodeScale, 0);
    ALOGV("movie time scale: %" PRIu64, mTimeCodeScale);

    /*
     * When the requested file size limit is small, the priority
     * is to meet the file size limit requirement, rather than
     * to make the file streamable. mStreamableFile does not tell
     * whether the actual recorded file is streamable or not.
     */
    mStreamableFile = (!mMaxFileSizeLimitBytes)
        || (mMaxFileSizeLimitBytes >= kMinStreamableFileSizeInBytes);

    /*
     * Write various metadata.
     */
    sp<WebmElement> ebml, segment, info, seekHead, tracks, cues;
    ebml = WebmElement::EbmlHeader();
    segment = new WebmMaster(kMkvSegment);
    seekHead = new EbmlVoid(kMaxMetaSeekSize);
    info = WebmElement::SegmentInfo(mTimeCodeScale, 0);

    List<sp<WebmElement> > children;
    for (size_t i = 0; i < kMaxStreams; ++i) {
        if (mStreams[i].mTrackEntry != NULL) {
            children.push_back(mStreams[i].mTrackEntry);
        }
    }
    tracks = new WebmMaster(kMkvTracks, children);

    if (!mStreamableFile) {
        cues = NULL;
    } else {
        int32_t bitRate = -1;
        if (params) {
            params->findInt32(kKeyBitRate, &bitRate);
        }
        mEstimatedCuesSize = estimateCuesSize(bitRate);
        CHECK_GE(mEstimatedCuesSize, 8);
        cues = new EbmlVoid(mEstimatedCuesSize);
    }

    sp<WebmElement> elems[] = { ebml, segment, seekHead, info, tracks, cues };
    static const size_t nElems = sizeof(elems) / sizeof(elems[0]);
    uint64_t offsets[nElems];
    uint64_t sizes[nElems];
    for (uint32_t i = 0; i < nElems; i++) {
        WebmElement *e = elems[i].get();
        if (!e) {
            continue;
        }

        uint64_t size;
        offsets[i] = ::lseek(mFd, 0, SEEK_CUR);
        sizes[i] = e->mSize;
        e->write(mFd, size);
    }

    mSegmentOffset = offsets[1];
    mSegmentDataStart = offsets[2];
    mInfoOffset = offsets[3];
    mInfoSize = sizes[3];
    mTracksOffset = offsets[4];
    mCuesOffset = offsets[5];

    // start threads
    if (params) {
        params->findInt64(kKeyTime, &mStartTimestampUs);
    }

    initStream(kAudioIndex);
    initStream(kVideoIndex);

    mStreams[kAudioIndex].mThread->start();
    mStreams[kVideoIndex].mThread->start();
    mSinkThread->start();

    mStarted = true;
    return OK;
}
Пример #26
0
void Mp3PspStream::decodeMP3Data() {
	DEBUG_ENTER_FUNC();

	do {
		if (_state == MP3_STATE_INIT) {
			initStream();
			initStreamME();
		}

		if (_state == MP3_STATE_EOS)
			return;

		findValidHeader();	// seach for next valid header

		while (_state == MP3_STATE_READY) {	// not a real 'while'. Just for easy flow
			_stream.error = MAD_ERROR_NONE;

			uint32 frame_size = _stream.next_frame - _stream.this_frame;

			updatePcmLength(); // Retrieve the number of PCM samples.
							   // We seem to change this, so it needs to be dynamic

			PSP_DEBUG_PRINT("MP3 frame size[%d]. pcmLength[%d]\n", frame_size, _pcmLength);

			memcpy(_codecInBuffer, _stream.this_frame, frame_size);	// we need it aligned

			// set up parameters for ME
			_codecParams[6] = (unsigned long)_codecInBuffer;
			_codecParams[8] = (unsigned long)_pcmSamples;
			_codecParams[7] = frame_size;
			_codecParams[9] = _pcmLength * 2;	// x2 for stereo, though this one's not so important

			// debug
#ifdef PRINT_BUFFERS
			PSP_DEBUG_PRINT("mp3 frame:\n");
			for (int i=0; i < (int)frame_size; i++) {
				PSP_DEBUG_PRINT_SAMELN("%x ", _codecInBuffer[i]);
			}
			PSP_DEBUG_PRINT("\n");
#endif
			// Decode the next frame
			// This function blocks. We'll want to put it in a thread
			int ret = sceAudiocodecDecode(_codecParams, 0x1002);
			if (ret < 0) {
				PSP_INFO_PRINT("failed to decode MP3 data in ME. sceAudiocodecDecode returned 0x%x\n", ret);
			}

#ifdef PRINT_BUFFERS
			PSP_DEBUG_PRINT("PCM frame:\n");
			for (int i=0; i < (int)_codecParams[9]; i+=2) {	// changed from i+=2
				PSP_DEBUG_PRINT_SAMELN("%d ", (int16)_pcmSamples[i]);
			}
			PSP_DEBUG_PRINT("\n");
#endif
			_posInFrame = 0;
			break;
		}
	} while (_state != MP3_STATE_EOS && _stream.error == MAD_ERROR_BUFLEN);

	if (_stream.error != MAD_ERROR_NONE)	// catch EOS
		_state = MP3_STATE_EOS;
}
Пример #27
0
  void EstimatePropagator::propagate(OptimizableGraph::VertexSet& vset, 
      const EstimatePropagator::PropagateCost& cost, 
       const EstimatePropagator::PropagateAction& action,
       double maxDistance, 
       double maxEdgeCost)
  {
    reset();

    PriorityQueue frontier;
    for (OptimizableGraph::VertexSet::iterator vit=vset.begin(); vit!=vset.end(); ++vit){
      OptimizableGraph::Vertex* v = static_cast<OptimizableGraph::Vertex*>(*vit);
      AdjacencyMap::iterator it = _adjacencyMap.find(v);
      assert(it != _adjacencyMap.end());
      it->second._distance = 0.;
      it->second._parent.clear();
      it->second._frontierLevel = 0;
      frontier.push(&it->second);
    }

    while(! frontier.empty()){
      AdjacencyMapEntry* entry = frontier.pop();
      OptimizableGraph::Vertex* u = entry->child();
      double uDistance = entry->distance();
      //cerr << "uDistance " << uDistance << endl;

      // initialize the vertex
      if (entry->_frontierLevel > 0) {
        action(entry->edge(), entry->parent(), u);
      }

      /* std::pair< OptimizableGraph::VertexSet::iterator, bool> insertResult = */ _visited.insert(u);
      OptimizableGraph::EdgeSet::iterator et = u->edges().begin();
      while (et != u->edges().end()){
        OptimizableGraph::Edge* edge = static_cast<OptimizableGraph::Edge*>(*et);
        ++et;

        int maxFrontier = -1;
        OptimizableGraph::VertexSet initializedVertices;
        for (size_t i = 0; i < edge->vertices().size(); ++i) {
          OptimizableGraph::Vertex* z = static_cast<OptimizableGraph::Vertex*>(edge->vertex(i));
          AdjacencyMap::iterator ot = _adjacencyMap.find(z);
          if (ot->second._distance != numeric_limits<double>::max()) {
            initializedVertices.insert(z);
            maxFrontier = (max)(maxFrontier, ot->second._frontierLevel);
          }
        }
        assert(maxFrontier >= 0);

        for (size_t i = 0; i < edge->vertices().size(); ++i) {
          OptimizableGraph::Vertex* z = static_cast<OptimizableGraph::Vertex*>(edge->vertex(i));
          if (z == u)
            continue;

          size_t wasInitialized = initializedVertices.erase(z);

          double edgeDistance = cost(edge, initializedVertices, z);
          if (edgeDistance > 0. && edgeDistance != std::numeric_limits<double>::max() && edgeDistance < maxEdgeCost) {
            double zDistance = uDistance + edgeDistance;
            //cerr << z->id() << " " << zDistance << endl;

            AdjacencyMap::iterator ot = _adjacencyMap.find(z);
            assert(ot!=_adjacencyMap.end());

            if (zDistance < ot->second.distance() && zDistance < maxDistance){
              //if (ot->second.inQueue)
                //cerr << "Updating" << endl;
              ot->second._distance = zDistance;
              ot->second._parent = initializedVertices;
              ot->second._edge = edge;
              ot->second._frontierLevel = maxFrontier + 1;
              frontier.push(&ot->second);
            }
          }

          if (wasInitialized > 0)
            initializedVertices.insert(z);

        }
      }
    }

    // writing debug information like cost for reaching each vertex and the parent used to initialize
#ifdef DEBUG_ESTIMATE_PROPAGATOR
    cerr << "Writing cost.dat" << endl;
    ofstream costStream("cost.dat");
    for (AdjacencyMap::const_iterator it = _adjacencyMap.begin(); it != _adjacencyMap.end(); ++it) {
      HyperGraph::Vertex* u = it->second.child();
      costStream << "vertex " << u->id() << "  cost " << it->second._distance << endl;
    }
    cerr << "Writing init.dat" << endl;
    ofstream initStream("init.dat");
    vector<AdjacencyMapEntry*> frontierLevels;
    for (AdjacencyMap::iterator it = _adjacencyMap.begin(); it != _adjacencyMap.end(); ++it) {
      if (it->second._frontierLevel > 0)
        frontierLevels.push_back(&it->second);
    }
    sort(frontierLevels.begin(), frontierLevels.end(), FrontierLevelCmp());
    for (vector<AdjacencyMapEntry*>::const_iterator it = frontierLevels.begin(); it != frontierLevels.end(); ++it) {
      AdjacencyMapEntry* entry       = *it;
      OptimizableGraph::Vertex* to   = entry->child();

      initStream << "calling init level = " << entry->_frontierLevel << "\t (";
      for (OptimizableGraph::VertexSet::iterator pit = entry->parent().begin(); pit != entry->parent().end(); ++pit) {
        initStream << " " << (*pit)->id();
      }
      initStream << " ) -> " << to->id() << endl;
    }
#endif

  }
Пример #28
0
bool SGFParser::parseASCII(const QString &fileName, ASCII_Import *charset, bool isFilename)
{
	QTextStream *txt = NULL;
	bool result = false;
	asciiOffsetX = asciiOffsetY = 0;
	
#if 0
	qDebug("BLACK STONE CHAR %c\n"
		"WHITE STONE CHAR %c\n"
		"STAR POINT  CHAR %c\n"
		"EMPTY POINT CHAR %c\n"
		"HOR BORDER CHAR %c\n"
		"VER BORDER CHAR %c\n",
		charset->blackStone,
		charset->whiteStone,
		charset->starPoint,
		charset->emptyPoint,
		charset->hBorder,
		charset->vBorder);
#endif
	
	if (isFilename)  // Load from file
	{
		QFile file;
		
		if (fileName.isNull() || fileName.isEmpty())
		{
			QMessageBox::warning(0, PACKAGE, Board::tr("No filename given!"));
			delete txt;
			return false;
		}
		
		file.setName(fileName);
		if (!file.exists())
		{
			QMessageBox::warning(0, PACKAGE, Board::tr("Could not find file:") + " " + fileName);
			delete txt;
			return false;
		}
		
		if (!file.open(IO_ReadOnly))
		{
			QMessageBox::warning(0, PACKAGE, Board::tr("Could not open file:") + " " + fileName);
			delete txt;
			return false;
		}
		
		txt = new QTextStream(&file);
		if (!initStream(txt))
		{
			QMessageBox::critical(0, PACKAGE, Board::tr("Invalid text encoding given. Please check preferences!"));
			delete txt;
			return false;
		}
		
		result = parseASCIIStream(txt, charset);
		file.close();
	}
	else  // a string was passed instead of a filename, copy from clipboard
	{
		if (fileName.isNull() || fileName.isEmpty())
		{
			QMessageBox::warning(0, PACKAGE, Board::tr("Importing ASCII failed. Clipboard empty?"));
			delete txt;
			return false;
		}
		
		QString buf(fileName);
		txt = new QTextStream(buf, IO_ReadOnly);
		if (!initStream(txt))
		{
			QMessageBox::critical(0, PACKAGE, Board::tr("Invalid text encoding given. Please check preferences!"));
			delete txt;
			return false;
		}
		
		result = parseASCIIStream(txt, charset);
	}
	
	delete txt;
	return result;
}
Пример #29
0
/* FIXME: Define the type 'struct command_stream' here. This should
complete the incomplete type declaration in command.h. */
command_stream_t make_command_stream(int(*get_next_byte) (void *),
	void *get_next_byte_argument)
{
	/* FIXME: Replace this with your implementation. You may need to
	add auxiliary functions and otherwise modify the source code.
	You can also use external functions defined in the GNU C Library. */
	if (DEBUG) printf("291 Begin make_command_stream\n");
	initStream();
	size_t sizeofBuffer = 1024;
	char* buffer = (char*)checked_malloc(sizeofBuffer);
	char curr;
	size_t filled = 0;
	while ((curr = get_next_byte(get_next_byte_argument)) != EOF) {
		buffer[filled] = curr;
		filled++;
		if (filled == sizeofBuffer) {
			sizeofBuffer *= 2;
			buffer = (char*)checked_grow_alloc(buffer, &sizeofBuffer);
		}
	}
	//***For the parser:
	//Word
	int bufferWordSize = 10;
	int currWord = 0;
	//char ** wordElement;
	char** wordElement = checked_malloc(sizeof(char*));
	wordElement[currWord] = (char*)checked_malloc(bufferWordSize);
	int usedWord = 0;
	//Input
	int bufferInputSize = 10;
	char* inputElement = (char*)checked_malloc(bufferInputSize);
	int usedInput = 0;
	//Output
	int bufferOutputSize = 10;
	char* outputElement = (char*)checked_malloc(bufferOutputSize);
	int usedOutput = 0;
	//***Initialize operator and command stacks
	initStacks();
	if (DEBUG) printf("333 Buffer created, initStacks()\n");
	
	int i = 0;
	while (i < (int)filled)
	{
		if (DEBUG) printf("on buffer %d\n", i);
		//***When you want to add a character*************************//
		int op = -1;
		int openCount = 0;
		int closedCount = 0;

		if (buffer[i] == '`')
			error(1, 0, "Line %d: %c", __LINE__, buffer[i]);

		if (buffer[i] == '(')
		{
			openCount = 1;
			closedCount = 0;
			int x = i;
			while (x < (int) filled)
			{
				x++;
				if (buffer[x] == '(')
					openCount++;
				if (buffer[x] == ')')
					closedCount++;
				if (closedCount == openCount)
					break;
			}
			if (closedCount != openCount)
				error(1, 0, "Line %d: Expected ')' for end of subshell", __LINE__);
		}
		if(buffer[i] == ')')
		{
			if(openCount == 0)
				error(1, 0, "Line %d: Expected '(' before ')'", __LINE__);
		}

		if(buffer[i] = '(') 
		{
			op = numberOfOper(&buffer[i]);
			processOperator(op);
		}

		//Case of ' '
		while (buffer[i] == ' ' && usedWord == 0)
			i++;

		if (buffer[i] == ' ' && usedWord != 0)
		{
			if (usedWord >= bufferWordSize)
			{
				bufferWordSize += 10;
				wordElement[currWord] = (char*)checked_realloc(wordElement[currWord], bufferWordSize);
			}
			//i++;
			wordElement[currWord][usedWord] = '\0';
			while (buffer[i + 1] == ' ')
				i++;
			usedWord = 0;
			bufferWordSize = 10;
			currWord++;
			wordElement[currWord] = (char*)checked_malloc(bufferWordSize);
			//wordElement[currWord][usedWord] = buffer[i];
			//usedWord++;
		}
		//Case of carrots
		//WHAT IF a<b>c>d<a....?! You're making a simple command out of a<b>c which then
		// must also be the word of >d<a
		//Case of '<' first
		else
			if (buffer[i] == '<')
			{
				int k = i;
				while (buffer[k-1] == ' ')
				{
					k--;
					if(buffer[k-1] == '\n')
						error(1, 0, "Line %d: Operator and word on diff lines", __LINE__);
				}
				if (wordElement[0][0] == '\0')
					error(1, 0, "Line %d: No command given to '<'", __LINE__);
				i++;
				while (buffer[i] != '<' && buffer[i] != '>' && buffer[i] != '&' && buffer[i] != '|' && buffer[i] != '(' && buffer[i] != ')' && buffer[i] != ';' && buffer[i] != '\n')
				{
					if (i == filled)
					{
						if (DEBUG) printf("378 Complete command, free buffer bc EOF\n");
						currWord++;
						wordElement[currWord] = '\0';
						if (usedInput == 0)
							inputElement = NULL;
						if (usedOutput == 0)
							outputElement = NULL;
						makeSimpleCommand(wordElement, inputElement, outputElement);
						completeCommand();
						//free(buffer);
						return headStream;
					}
					if (buffer[i] == ' ')
						i++;
					else
					{
						if (usedInput >= bufferInputSize)
						{
							bufferInputSize += 10;
							inputElement = (char*)checked_realloc(inputElement, bufferInputSize);
						}
						inputElement[usedInput] = buffer[i];
						usedInput++;
						i++;
					}
				}
				if (usedInput >= bufferInputSize)
				{
					bufferInputSize += 10;
					inputElement = (char*)checked_realloc(inputElement, bufferInputSize);
				}
				if (usedInput == 0)
					error(1, 0, "Line %d: No input after '<'", __LINE__);
				inputElement[usedInput] = '\0';
				usedInput++;
				if (buffer[i] == '>')
				{
					i++;
					while (buffer[i] != '<' && buffer[i] != '>' && buffer[i] != '&' && buffer[i] != '|' && buffer[i] != '(' && buffer[i] != ')' && buffer[i] != ';' && buffer[i] != '\n')
					{
						if (i == filled)
						{
							if (DEBUG) printf("413 Complete command, free buffer at EOF\n");
							currWord++;
							wordElement[currWord] = '\0';
							if (usedInput == 0)
								inputElement = NULL;
							if (usedOutput == 0)
								outputElement = NULL;
							makeSimpleCommand(wordElement, inputElement, outputElement);
							completeCommand();
							//free(buffer);
							return headStream;
						}
						if (buffer[i] == ' ')
							i++;
						else
						{
							if (usedOutput >= bufferOutputSize)
							{
								bufferOutputSize += 10;
								outputElement = (char*)checked_realloc(outputElement, bufferOutputSize);
							}
							outputElement[usedOutput] = buffer[i];
							usedOutput++;
							i++;
						}
					}
					if (usedOutput >= bufferOutputSize)
					{
						bufferOutputSize += 10;
						outputElement = (char*)checked_realloc(outputElement, bufferOutputSize);
					}
					if (usedOutput == 0)
						error(1, 0, "Line %d: No input after '<'", __LINE__);
					outputElement[usedOutput] = '\0';
					usedOutput++;
					//i--; //Check logic
				}
				i--;
			}
		/////CHECK FOR EXTRA i++!!!!!
		//Case of '>' first
			else
				if (buffer[i] == '>')
				{
					int k = i;
					while (buffer[k-1] == ' ')
					{
						k--;
						if(buffer[k-1] == '\n')
							error(1, 0, "Line %d: Operator and word on diff lines", __LINE__);
					}
					if (wordElement[0][0] == '\0')
					error(1, 0, "Line %d: No command given to '<'", __LINE__);
					i++;
					while (buffer[i] != '<' && buffer[i] != '>' && buffer[i] != '&' && buffer[i] != '|' && buffer[i] != '(' && buffer[i] != ')' && buffer[i] != ';' && buffer[i] != '\n')
					{
						if (i == filled)
						{
							if (DEBUG) printf("471 Complete Command, free buffer at EOF");
							currWord++;
							wordElement[currWord] = '\0';
							if (usedInput == 0)
								inputElement = NULL;
							if (usedOutput == 0)
								outputElement = NULL;
							makeSimpleCommand(wordElement, inputElement, outputElement);
							completeCommand();
							//free(buffer);
							return headStream;
						}
						if (buffer[i] == ' ')
							i++;
						else
						{
							if (usedOutput >= bufferOutputSize)
							{
								bufferOutputSize += 10;
								outputElement = (char*)checked_realloc(outputElement, bufferOutputSize);
							}
							outputElement[usedOutput] = buffer[i];
							usedOutput++;
							i++;
						}
					}
					if (usedOutput >= bufferOutputSize)
					{
						bufferOutputSize += 10;
						outputElement = (char*)checked_realloc(outputElement, bufferOutputSize);
					}
					if (usedOutput == 0)
						error(1, 0, "Line %d: No input after '<'", __LINE__);
					outputElement[usedOutput] = '\0';
					usedOutput++;
					if (buffer[i] == '<')
					{
						i++;
						while (buffer[i] != '<' && buffer[i] != '>' && buffer[i] != '&' && buffer[i] != '|' && buffer[i] != '(' && buffer[i] != ')' && buffer[i] != ';' && buffer[i] != '\n')
						{
							if (i == filled)
							{
								if (DEBUG) printf("505 Complete Command, free buffer at EOF");
								currWord++;
								wordElement[currWord] = '\0';
								if (usedInput == 0)
									inputElement = NULL;
								if (usedOutput == 0)
									outputElement = NULL;
								makeSimpleCommand(wordElement, inputElement, outputElement);
								completeCommand();
								//free(buffer);
								return headStream;
							}
							if (buffer[i] == ' ')
								i++;
							else
							{
								if (usedInput >= bufferInputSize)
								{
									bufferInputSize += 10;
									inputElement = (char*)checked_realloc(inputElement, bufferInputSize);
								}
								inputElement[usedInput] = buffer[i];
								usedInput++;
								i++;
							}
						}
						if (usedInput >= bufferInputSize)
						{
							bufferInputSize += 10;
							inputElement = (char*)checked_realloc(inputElement, bufferInputSize);
						}
						if (usedInput == 0)
							error(1, 0, "Line %d: No input after '<'", __LINE__);
						inputElement[usedInput] = '\0';
						usedInput++;
					}
					wordElement[currWord + 1] = '\0';
					/*if (usedInput == 0)
					inputElement = NULL;
					if (usedOutput == 0)
					outputElement = NULL;
					if(DEBUG) printf("makeSimpleCommand %s\n", wordElement[0]);
					makeSimpleCommand(wordElement, inputElement, outputElement);
					bufferWordSize = 10;
					currWord = 0;
					usedWord = 0;
					usedInput = 0;
					usedOutput = 0;
					wordElement = (char**)checked_malloc(sizeof(char*));
					wordElement[currWord] = (char*)checked_malloc(bufferWordSize);
					inputElement = (char*)checked_malloc(bufferInputSize);
					outputElement = (char*)checked_malloc(bufferOutputSize);*/
					i--;
				}
		//Operators
		//After every operator is encountered, use makeSimpleCommand to push the command on the stack
		//Case of '|'
				else
					if (buffer[i] == '|')
					{
						int k = i;
						while (buffer[k-1] == ' ')
						{
							k--;
							if(buffer[k-1] == '\n')
								error(1, 0, "Line %d: Operator and word on diff lines", __LINE__);
						}
						
						if (buffer[i+1] == '|' && operatorStack == NULL)
							error(1, 0, "Line %d: Missing pipe for '||'", __LINE__);
						if (wordElement[0][0] == '\0')
							error(1, 0, "Line %d: Nothing for '|'", __LINE__);
						//if (commandStack == NULL)
						//	error(1, 0, "Line %d: Nothing to run '|' on");
						if (buffer[i + 1] == '|' && buffer[i+2] == '|')
							error(1, 0, "Line %d: Invalid Command, too many '|'", i);
						op = numberOfOper(&buffer[i]);
						//error(1, 0, "Line %d: Nothing to pipe", __LINE__);
						if (buffer[i-1] != ' ')
							currWord++;
						wordElement[currWord] = '\0';
						if (usedInput == 0)
							inputElement = NULL;
						if (usedOutput == 0)
							outputElement = NULL;
						if (DEBUG) printf(" 566 makeSimpleCommand %s\n", wordElement[0]);
						makeSimpleCommand(wordElement, inputElement, outputElement);
						bufferWordSize = 10;
						currWord = 0;
						usedWord = 0;
						usedInput = 0;
						usedOutput = 0;
						wordElement = (char**)checked_malloc(sizeof(char*));
						wordElement[currWord] = (char*)checked_malloc(bufferWordSize);
						inputElement = (char*)checked_malloc(bufferInputSize);
						outputElement = (char*)checked_malloc(bufferOutputSize);
						if (DEBUG) printf("577 Process operator %d\n", op);
						processOperator(op);
						if (op == 3) 
							i++;
						if (buffer[i + 1] == ' ')
							i++;
						//i++;
					}
		//Case of '&'
					else
						if (buffer[i] == '&')
						{
							int k = i;
							while (buffer[k-1] == ' ')
							{
								k--;
								if(buffer[k-1] == '\n')
									error(1, 0, "Line %d: Operator and word on diff lines", __LINE__);
							}
							//if (buffer[i] == '&' && operatorStack == NULL)
							//	error(1, 0, "Line %d: Missing pipe for '&&'", __LINE__);
							if (wordElement[0][0] == '\0')
								error(1, 0, "Line %d: Nothing for '|'", __LINE__);
							if (buffer[i + 1] == '&' && buffer[i+2] == '&')
								error(1, 0, "Line %d: Invalid Command, too many '&'", i);
							op = numberOfOper(&buffer[i]);
							if (buffer[i-1] != ' ')
								currWord++;
							wordElement[currWord] = '\0';
							if (usedInput == 0)
								inputElement = NULL;
							if (usedOutput == 0)
								outputElement = NULL;
							if (DEBUG) printf("592 makeSimpleCommand %s\n", wordElement[0]);
							makeSimpleCommand(wordElement, inputElement, outputElement);
							bufferWordSize = 10;
							usedWord = 0;
							currWord = 0;
							usedInput = 0;
							usedOutput = 0;
							wordElement = (char**)checked_malloc(sizeof(char*));
							wordElement[currWord] = (char*)checked_malloc(bufferWordSize);
							inputElement = (char*)checked_malloc(bufferInputSize);
							outputElement = (char*)checked_malloc(bufferOutputSize);
							processOperator(op);
							i++;
							if (buffer[i + 1] == ' ')
								i++;
						}
		//Case of ';'
						else
							if (buffer[i] == ';')
							{
													int k = i;
						while (buffer[k-1] == ' ')
						{
							k--;
							if(buffer[k-1] == '\n')
								error(1, 0, "Line %d: Operator and word on diff lines", __LINE__);
						}
								if(wordElement[0][0] == '\0')
									error(1, 0, "Line %d: Nothing before sequence", i);
								op = numberOfOper(&buffer[i]);
								currWord++;
								wordElement[currWord] = '\0';
								if (usedInput == 0)
									inputElement = NULL;
								if (usedOutput == 0)
									outputElement = NULL;
								if (DEBUG) printf("617 makeSimpleCommand %s\n", wordElement[0]);
								if ((currWord = 0) || (currWord == 1))
									error(1, 0, "Line %d: Nothing to run ';' on", i);
								makeSimpleCommand(wordElement, inputElement, outputElement);
								bufferWordSize = 10;
								usedWord = 0;
								currWord = 0;
								usedInput = 0;
								usedOutput = 0;
								wordElement = (char**)checked_malloc(sizeof(char*));
								wordElement[currWord] = (char*)checked_malloc(bufferWordSize);
								inputElement = (char*)checked_malloc(bufferInputSize);
								outputElement = (char*)checked_malloc(bufferOutputSize);
								processOperator(op);
								//i++;
							}
		//Case of '\n'
							else
								if (buffer[i] == '\n' && i != 0)
								{
									/*int scChecker = i;
									while (buffer[i + 1] == ' ')
									{
										scChecker++;
										if (buffer[scChecker + 1] == ';')
											error(1, 0, "Line %d: Newline followed by ';'");
									}*/
									if (buffer[i+1] == ';')
										error(1, 0, "Line %d: Newline followed by ';'", i);
									if ((i + 1) == (int)filled)
									{
										currWord++;
										wordElement[currWord] = '\0';
										if (usedInput == 0)
											inputElement = NULL;
										if (usedOutput == 0)
											outputElement = NULL;
										if (DEBUG) printf("654 makeSimpleCommand %s\n", wordElement[0]);
										makeSimpleCommand(wordElement, inputElement, outputElement);
										bufferWordSize = 10;
										currWord = 0;
										usedWord = 0;
										usedInput = 0;
										usedOutput = 0;
										wordElement = (char**)checked_malloc(sizeof(char*));
										wordElement[currWord] = (char*)checked_malloc(bufferWordSize);
										inputElement = (char*)checked_malloc(bufferInputSize);
										outputElement = (char*)checked_malloc(bufferOutputSize);
										completeCommand();
										free(buffer);
										return headStream;
									}
									char lastC;
									int back = 1;
									while (buffer[i - back] == ' ' && i - back >= 0)
									{
										//lastC = buffer[i - back];
										back++;
									}
									lastC = buffer[i - back];
									if (buffer[i + 1] == '\n')
									{
										while (buffer[i + 1] == '\n')
											i++;
										if (lastC != '|' && lastC != '&')
										{
											currWord++;
											wordElement[currWord] = '\0';
											if (usedInput == 0)
												inputElement = NULL;
											if (usedOutput == 0)
												outputElement = NULL;
											if (DEBUG) printf("654 makeSimpleCommand %s\n", wordElement[0]);
											makeSimpleCommand(wordElement, inputElement, outputElement);
											bufferWordSize = 10;
											currWord = 0;
											usedWord = 0;
											usedInput = 0;
											usedOutput = 0;
											wordElement = (char**)checked_malloc(sizeof(char*));
											wordElement[currWord] = (char*)checked_malloc(bufferWordSize);
											inputElement = (char*)checked_malloc(bufferInputSize);
											outputElement = (char*)checked_malloc(bufferOutputSize);
											completeCommand();
										}
									}
									else
									{
										if (lastC == '|' || lastC == '&' || lastC == '<' || lastC || '>')
										{
											while (buffer[i + 1] == '\n')
												i++;//////SPIT ERROR?
										}
										else
										{
											char swap = ';';
											op = numberOfOper(&swap);
											wordElement[currWord + 1] = '\0';
											if (usedInput == 0)
												inputElement = NULL;
											if (usedOutput == 0)
												outputElement = NULL;
											if (DEBUG) printf(" 679 makeSimpleCommand %s\n", wordElement[0]);
											makeSimpleCommand(wordElement, inputElement, outputElement);
											bufferWordSize = 10;
											currWord = 0;
											usedWord = 0;
											usedInput = 0;
											usedOutput = 0;
											wordElement = (char**)checked_malloc(sizeof(char*));
											wordElement[currWord] = (char*)checked_malloc(bufferWordSize);
											inputElement = (char*)checked_malloc(bufferInputSize);
											outputElement = (char*)checked_malloc(bufferOutputSize);
											processOperator(op);
										}
									}
								}
		//Case of # (comment)
								else
									if (buffer[i] == '#')
									{
										if (DEBUG) printf("698 Got a comment!\n");
										while (buffer[i] != '\n')
											i++;
									}
									//Else
									else
									{
										if (buffer[i] == '\'')
										{
											if (buffer[i + 1] == 'E' && buffer[i + 2] == 'O' && buffer[i + 3] == 'F')
												break;
										}
										//if (buffer[i] != ' ')
										wordElement[currWord][usedWord] = buffer[i];
										usedWord++;
										if (i + 1 == filled)
										{
											currWord++;
											wordElement[currWord] = '\0';
											if (usedInput == 0)
												inputElement = NULL;
											if (usedOutput == 0)
												outputElement = NULL;
											makeSimpleCommand(wordElement, inputElement, outputElement);
											completeCommand();
										}
									}
		i++;
	}
	free(buffer);
	return headStream;
}