/***********************************************************************
 * Common Tools -- Common classes used in various projects
 *
 * Copyright (C) 2002 Cyrius
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *   
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *   
 * You should have received a copy of the GNU General Public License along
 * with this program (see the file COPYING); if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * or visit http://www.gnu.org/copyleft/gpl.html
 *
 ***********************************************************************
 * InputStream.cpp
 *
 *
 */

#include "OGMInputStream.h"
#include <fcntl.h>
#include "../Error.h"

/*
 * Constructor
 */
InputStream::InputStream(void) {
	_initialize();
}

/*
 * Initialize values
 */
void InputStream::_initialize(void) {
	name = NULL;
	size = -1;
}

/*
 * Constructor
 */
InputStream::InputStream(char *name, s64 size) {
	_initialize();
	if(name) {
		this->name = strdup(name);
		if(!this->name)
			throw MyError("Could not duplicate the string [%s]\n", name);
	}
	this->size = size;
}

/*
 * Destructor
 */
InputStream::~InputStream(void) {
	if(name)
		free(name);
}

/*
 * Will try to synch the stream on a pattern (within a maximum search length)
 */
bool InputStream::SynchOn(unsigned short synch, unsigned short synch_bits, long max_search, long *search_length) {
	synch = SWAP_SHORT_ENDIAN(synch&synch_bits);
	synch_bits = SWAP_SHORT_ENDIAN(synch_bits);
	s64 position = get_pos();
	long search = 0;
	// The "compatible" version (compatible with derived classes)
	unsigned short s = 0;
	while(true) {
		if(search>max_search) {
			Seek(position, SEEK_SET);
			if(search_length)
				*search_length = search;
			return false;
		}
		if(Read(&s, 2)!=2) {
			if(search_length)
				*search_length = search;
			return false;
		}
		if((s&synch_bits)==synch) {
			if(search_length)
				*search_length = search;
			if(Seek(-2, SEEK_CUR)==-1)
				return false;
			return true;
		}
		if(Seek(-1, SEEK_CUR)==-1) {
			if(search_length)
				*search_length = search;
			return false;
		}
		search++;
	}
}