Index: MPWriter/source/MPFileWriter.cpp
===================================================================
--- MPWriter/source/MPFileWriter.cpp	(revision 27480)
+++ MPWriter/source/MPFileWriter.cpp	(working copy)
@@ -558,11 +558,11 @@
 	return pSubChannel->SetTimeShiftFileName(pszFileName);
 }
 
-STDMETHODIMP CMPFileWriter::SetTimeShiftParams(int subChannelId, int minFiles, int maxFiles, ULONG maxFileSize)
+STDMETHODIMP CMPFileWriter::SetTimeShiftParams(int subChannelId, ULONG maxFileSize)
 {
 	CSubChannel* pSubChannel=GetSubChannel(subChannelId);
 	if (pSubChannel==NULL) return S_OK;
-	return pSubChannel->SetTimeShiftParams(minFiles, maxFiles,maxFileSize);
+	return pSubChannel->SetTimeShiftParams(maxFileSize);
 }
 STDMETHODIMP CMPFileWriter::StartTimeShifting(int subChannelId)
 {
Index: MPWriter/source/MPFileWriter.h
===================================================================
--- MPWriter/source/MPFileWriter.h	(revision 27480)
+++ MPWriter/source/MPFileWriter.h	(working copy)
@@ -49,7 +49,7 @@
 	STDMETHOD(StartTimeShifting)(THIS_ int subChannelId)PURE;
 	STDMETHOD(StopTimeShifting)(THIS_ int subChannelId)PURE;
 	STDMETHOD(PauseTimeShifting)(THIS_ int subChannelId, int onOff)PURE;
-	STDMETHOD(SetTimeShiftParams)(THIS_ int subChannelId, int minFiles, int maxFiles, ULONG maxFileSize)PURE;
+	STDMETHOD(SetTimeShiftParams)(THIS_ int subChannelId, ULONG maxFileSize)PURE;
 	STDMETHOD(TTxSetCallBack)(THIS_ int subChannelId, IAnalogTeletextCallBack* callback)PURE;
 	STDMETHOD(SetVideoAudioObserver)(THIS_ int subChannelId, IAnalogVideoAudioObserver* callback)PURE;
 	STDMETHOD(SetRecorderVideoAudioObserver)(THIS_ int subChannelId, IAnalogVideoAudioObserver* callback)PURE;
@@ -151,7 +151,7 @@
 	STDMETHODIMP StartTimeShifting(int subChannelId);
 	STDMETHODIMP StopTimeShifting(int subChannelId);
 	STDMETHODIMP PauseTimeShifting(int subChannelId, int onOff);
-	STDMETHODIMP SetTimeShiftParams(int subChannelId,  int minFiles, int maxFiles, ULONG maxFileSize);
+	STDMETHODIMP SetTimeShiftParams(int subChannelId, ULONG maxFileSize);
 	STDMETHODIMP TTxSetCallBack(int subChannelId, IAnalogTeletextCallBack* callback);
 	STDMETHODIMP SetVideoAudioObserver(int subChannelId, IAnalogVideoAudioObserver* callback);
 	STDMETHODIMP SetRecorderVideoAudioObserver(int subChannelId, IAnalogVideoAudioObserver* callback);
Index: MPWriter/source/MultiFileWriter.cpp
===================================================================
--- MPWriter/source/MultiFileWriter.cpp	(revision 27480)
+++ MPWriter/source/MultiFileWriter.cpp	(working copy)
@@ -36,16 +36,12 @@
 extern void LogDebug(const char *fmt, ...) ;
 
 MultiFileWriter::MultiFileWriter() :
-	m_hTSBufferFile(INVALID_HANDLE_VALUE),
-	m_pTSBufferFileName(NULL),
+	m_hTSShiftFile(INVALID_HANDLE_VALUE),
+	m_pTSShiftFileName(NULL),
 	m_pTSRegFileName(NULL),
 	m_pCurrentTSFile(NULL),
-	m_filesAdded(0),
-	m_filesRemoved(0),
 	m_currentFilenameId(0),
 	m_currentFileId(0),
-	m_minTSFiles(6),
-	m_maxTSFiles(20),
 	m_maxTSFileSize(268435424),	
 	m_chunkReserve(268435424) 
 {
@@ -56,8 +52,8 @@
 MultiFileWriter::~MultiFileWriter()
 {
 	CloseFile();
-	if (m_pTSBufferFileName)
-		delete[] m_pTSBufferFileName;
+	if (m_pTSShiftFileName)
+		delete[] m_pTSShiftFileName;
 
 	if (m_pTSRegFileName)
 		delete[] m_pTSRegFileName;
@@ -68,7 +64,7 @@
 
 HRESULT MultiFileWriter::GetFileName(LPOLESTR *lpszFileName)
 {
-	*lpszFileName = m_pTSBufferFileName;
+	*lpszFileName = m_pTSShiftFileName;
 	return S_OK;
 }
 
@@ -77,7 +73,7 @@
 	USES_CONVERSION;
 
 	// Is the file already opened
-	if (m_hTSBufferFile != INVALID_HANDLE_VALUE)
+	if (m_hTSShiftFile != INVALID_HANDLE_VALUE)
 	{
 		return E_FAIL;
 	}
@@ -91,15 +87,16 @@
 		return ERROR_FILENAME_EXCED_RANGE;
   }
 	// Take a copy of the filename
-	if (m_pTSBufferFileName)
+	if (m_pTSShiftFileName)
 	{
-		delete[] m_pTSBufferFileName;
-		m_pTSBufferFileName = NULL;
+		delete[] m_pTSShiftFileName;
+		m_pTSShiftFileName = NULL;
 	}
-	m_pTSBufferFileName = new WCHAR[1+lstrlenW(pszFileName)];
-	if (m_pTSBufferFileName == NULL)
+	m_pTSShiftFileName = new WCHAR[1+lstrlenW(pszFileName)];
+	if (m_pTSShiftFileName == NULL)
 		return E_OUTOFMEMORY;
-	wcscpy(m_pTSBufferFileName, pszFileName);
+
+	wcscpy(m_pTSShiftFileName, pszFileName);
 	
 	//check disk space first
 	__int64 llDiskSpaceAvailable = 0;
@@ -111,7 +108,7 @@
 	TCHAR *pFileName = NULL;
 
 	// Try to open the file
-	m_hTSBufferFile = CreateFile(W2T(m_pTSBufferFileName),  // The filename
+	m_hTSShiftFile = CreateFile(W2T(m_pTSShiftFileName),  // The filename
 								 (DWORD) GENERIC_WRITE,             // File access
 								 (DWORD) FILE_SHARE_READ,           // Share access
 								 NULL,                      // Security
@@ -119,7 +116,7 @@
 								 (DWORD) 0,                 // More flags
 								 NULL);                     // Template
 
-	if (m_hTSBufferFile == INVALID_HANDLE_VALUE)
+	if (m_hTSShiftFile == INVALID_HANDLE_VALUE)
 	{
         LogDebug("MultiFileWriter: fail to create buffer file");
         DWORD dwErr = GetLastError();
@@ -137,13 +134,13 @@
 {
 	CAutoLock lock(&m_Lock);
 
-	if (m_hTSBufferFile == INVALID_HANDLE_VALUE)
+	if (m_hTSShiftFile == INVALID_HANDLE_VALUE)
 	{
 		return S_OK;
 	}
 
-	CloseHandle(m_hTSBufferFile);
-	m_hTSBufferFile = INVALID_HANDLE_VALUE;
+	CloseHandle(m_hTSShiftFile);
+	m_hTSShiftFile = INVALID_HANDLE_VALUE;
 
 	m_pCurrentTSFile->CloseFile();
 
@@ -154,10 +151,10 @@
 
 HRESULT MultiFileWriter::GetFileSize(__int64 *lpllsize)
 {
-	if (m_hTSBufferFile == INVALID_HANDLE_VALUE)
+	if (m_hTSShiftFile == INVALID_HANDLE_VALUE)
 		*lpllsize = 0;
 	else
-		*lpllsize = max(0, (__int64)(((__int64)(m_filesAdded - m_filesRemoved - 1) * m_maxTSFileSize) + m_pCurrentTSFile->GetFilePointer()));
+		*lpllsize = max(0, (_wrappedcount * m_maxTSFileSize) + m_pCurrentTSFile->GetFilePointer());
 
 	return S_OK;
 }
@@ -171,7 +168,7 @@
 		return S_OK;
 
 	// If the file has already been closed, don't continue
-	if (m_hTSBufferFile == INVALID_HANDLE_VALUE)
+	if (m_hTSShiftFile == INVALID_HANDLE_VALUE)
 		return S_FALSE;
 
 	if (m_pCurrentTSFile->IsFileInvalid())
@@ -298,8 +295,7 @@
 	while (TRUE)
 	{
 		// Create new filename
-		m_currentFilenameId++;
-		swprintf(pFilename, L"%s%i.ts", m_pTSBufferFileName, m_currentFilenameId);
+		swprintf(pFilename, L"%s.ts", m_pTSShiftFileName);
 
 		// Check if file already exists
 		handleFound = FindFirstFile(W2T(pFilename), &findData);
@@ -308,7 +304,8 @@
 
 		LogDebug("MultiFileWriter: Newly generated filename already exists.");
 
-		// If it exists we loop and try the next number
+		// If it exists we delete it
+    DeleteFile(pFilename);
 		FindClose(handleFound);
 	}
 	
@@ -326,10 +323,7 @@
 		return hr;
 	}
 
-	m_tsFileNames.push_back(pFilename);
-	m_filesAdded++;
-
-	LPWSTR pos = pFilename + wcslen(m_pTSBufferFileName);
+	LPWSTR pos = pFilename + wcslen(m_pTSShiftFileName);
 	if (pos)
 		m_currentFileId = _wtoi(pos);
 	wchar_t msg[MAX_PATH];
@@ -340,9 +334,10 @@
 	return S_OK;
 }
 
-HRESULT MultiFileWriter::ReuseTSFile()
+HRESULT MultiFileWriter::ReuseTSFile_DELETEME()
 {
-	USES_CONVERSION;
+/*
+  USES_CONVERSION;
 	HRESULT hr;
   DWORD Tmo=5 ;
 
@@ -385,7 +380,7 @@
 	m_tsFileNames.push_back(pFilename);
 	m_filesAdded++;
 
-	LPWSTR pos = pFilename + wcslen(m_pTSBufferFileName);
+	LPWSTR pos = pFilename + wcslen(m_pTSShiftFileName);
 	if (pos)
 		m_currentFileId = _wtoi(pos);
 	wchar_t msg[MAX_PATH];
@@ -393,6 +388,7 @@
 	::OutputDebugString(W2T((LPWSTR)&msg));
 
 	LogDebug("MultiFileWriter: reuse old file");
+  */
 	return S_OK;
 }
 
@@ -404,13 +400,15 @@
 
 	// Move to the start of the file
 	li.QuadPart = 0;
-	SetFilePointer(m_hTSBufferFile, li.LowPart, &li.HighPart, FILE_BEGIN);
+	SetFilePointer(m_hTSShiftFile, li.LowPart, &li.HighPart, FILE_BEGIN);
 
 	// Write current position of most recent file.
 	__int64 currentPointer = m_pCurrentTSFile->GetFilePointer();
+	WriteFile(m_hTSShiftFile, &currentPointer, sizeof(currentPointer), &written, NULL);
 
-	BYTE* writeBuffer = new BYTE[65536];
-	BYTE* writePointer = writeBuffer;
+	// Write filesAdded and filesRemoved values
+	WriteFile(m_hTSShiftFile, &m_filesAdded, sizeof(m_filesAdded), &written, NULL);
+	WriteFile(m_hTSShiftFile, &m_filesRemoved, sizeof(m_filesRemoved), &written, NULL);
 
 	*((__int64*)writePointer) = currentPointer;
 	writePointer += sizeof(__int64);
@@ -428,38 +426,22 @@
 		LPWSTR pFilename = *it;
 		long length = wcslen(pFilename)+1;
 		length *= sizeof(wchar_t);
-		//WriteFile(m_hTSBufferFile, pFilename, length, &written, NULL);
-		memcpy(writePointer, pFilename, length);
-		writePointer += length;
-
-		if((writePointer - writeBuffer) > 60000)
-		{
-			LogDebug("MultiFileWriter: TS buffer file has exceeded maximum length.  Reduce the number of timeshifting files");
-			delete[] writeBuffer;
-			return S_FALSE;
-		}
+		WriteFile(m_hTSShiftFile, pFilename, length, &written, NULL);
 	}
 
 	// Finish up with a unicode null character in case we want to put stuff after this in the future.
 	wchar_t temp = 0;
-	*((wchar_t*)writePointer) = temp;
-	writePointer += sizeof(wchar_t);
-	
-	
-	*((long*)writePointer) = m_filesAdded;
-	writePointer += sizeof(long);
-	
-	*((long*)writePointer) = m_filesRemoved;
-	writePointer += sizeof(long);
+	WriteFile(m_hTSShiftFile, &temp, sizeof(temp), &written, NULL);
 
-	WriteFile(m_hTSBufferFile, writeBuffer, writePointer - writeBuffer, &written, NULL);
-	delete[] writeBuffer;
+	// Write again filesAdded and filesRemoved values for integrity check.
+	WriteFile(m_hTSShiftFile, &m_filesAdded, sizeof(m_filesAdded), &written, NULL);
+	WriteFile(m_hTSShiftFile, &m_filesRemoved, sizeof(m_filesRemoved), &written, NULL);
 
 	//randomly park the file pointer to help minimise HDD clogging
 //	if(m_pCurrentTSFile && m_pCurrentTSFile->GetFilePointer()&1)
-		SetFilePointer(m_hTSBufferFile, 0, NULL, FILE_END);
+		SetFilePointer(m_hTSShiftFile, 0, NULL, FILE_END);
 //	else
-//		SetFilePointer(m_hTSBufferFile, 0, NULL, FILE_BEGIN);
+//		SetFilePointer(m_hTSShiftFile, 0, NULL, FILE_BEGIN);
 
 	return S_OK;
 }
@@ -468,46 +450,33 @@
 {
 	USES_CONVERSION;
 
-	m_filesAdded = 0;
-	m_filesRemoved = 0;
-	m_currentFilenameId = 0;
 	m_currentFileId = 0;
 
 	// Check if .tsbuffer file is being read by something.
-	if (IsFileLocked(m_pTSBufferFileName) == TRUE)
+	if (IsFileLocked(m_pTSShiftFileName) == TRUE)
 		return S_OK;
 
-	std::vector<LPWSTR>::iterator it;
-	for (it = m_tsFileNames.begin() ; it < m_tsFileNames.end() ; it++ )
-	{
-		if (IsFileLocked(*it) == TRUE)
-		{
+  if (IsFileLocked(m_pCurrentTSFile) == TRUE)
+  {
 			// If any of the files are being read then we won't
 			// delete any so that the full buffer stays intact.
 			wchar_t msg[MAX_PATH];
-			swprintf((LPWSTR)&msg, L"CleanupFiles: A file is still locked : %s\n", *it);
+			swprintf((LPWSTR)&msg, L"CleanupFiles: A file is still locked : %s\n", m_pCurrentTSFile);
 			::OutputDebugString(W2T((LPWSTR)&msg));
 			LogDebug("MultiFileWriter: CleanupFiles: A file is still locked");
 			return S_OK;
-		}
 	}
 
 	// Now we know we can delete all the files.
-
-	for (it = m_tsFileNames.begin() ; it < m_tsFileNames.end() ; it++ )
+	if (DeleteFile(W2T(m_pCurrentTSFile)) == FALSE)
 	{
-		if (DeleteFile(W2T(*it)) == FALSE)
-		{
 			wchar_t msg[MAX_PATH];
-			swprintf((LPWSTR)&msg, L"Failed to delete file %s : 0x%x\n", *it, GetLastError());
+			swprintf((LPWSTR)&msg, L"Failed to delete file %s : 0x%x\n", m_pCurrentTSFile, GetLastError());
 			::OutputDebugString(W2T((LPWSTR)&msg));
 			LogDebug("MultiFileWriter: CleanupFiles: Failed to delete file");
-		}
-		delete[] *it;
 	}
-	m_tsFileNames.clear();
 
-	if (DeleteFile(W2T(m_pTSBufferFileName)) == FALSE)
+	if (DeleteFile(W2T(m_pTSShiftFileName)) == FALSE)
 	{
 		wchar_t msg[MAX_PATH];
 		swprintf((LPWSTR)&msg, L"Failed to delete tsbuffer file : 0x%x\n", GetLastError());
@@ -515,9 +484,6 @@
 			LogDebug("MultiFileWriter: CleanupFiles: Failed to delete tsbuffer file: 0x%x\n", GetLastError());
 
 	}
-	m_filesAdded = 0;
-	m_filesRemoved = 0;
-	m_currentFilenameId = 0;
 	m_currentFileId = 0;
 	return S_OK;
 }
@@ -551,9 +517,9 @@
 
 	char	*pszDrive = NULL;
 	char	szDrive[4];
-	if (m_pTSBufferFileName[1] == ':')
+	if (m_pTSShiftFileName[1] == ':')
 	{
-		szDrive[0] = (char)m_pTSBufferFileName[0];
+		szDrive[0] = (char)m_pTSShiftFileName[0];
 		szDrive[1] = ':';
 		szDrive[2] = '\\';
 		szDrive[3] = '\0';
@@ -602,7 +568,7 @@
 
 LPWSTR MultiFileWriter::getBufferFileName(void)
 {
-	return 	m_pTSBufferFileName;
+	return 	m_pTSShiftFileName;
 }
 
 void MultiFileWriter::setBufferFileName(LPWSTR fileName)
@@ -613,16 +579,16 @@
 		return;// ERROR_FILENAME_EXCED_RANGE;
 
 	// Take a copy of the filename
-	if (m_pTSBufferFileName)
+	if (m_pTSShiftFileName)
 	{
-		delete[] m_pTSBufferFileName;
-		m_pTSBufferFileName = NULL;
+		delete[] m_pTSShiftFileName;
+		m_pTSShiftFileName = NULL;
 	}
-	m_pTSBufferFileName = new WCHAR[1+lstrlenW(fileName)];
-	if (m_pTSBufferFileName == NULL)
+	m_pTSShiftFileName = new WCHAR[1+lstrlenW(fileName)];
+	if (m_pTSShiftFileName == NULL)
 		return;// E_OUTOFMEMORY;
 
-	wcscpy(m_pTSBufferFileName, fileName);
+	wcscpy(m_pTSShiftFileName, fileName);
 }
 
 FileWriter* MultiFileWriter::getCurrentTSFile(void)
@@ -630,41 +596,12 @@
 	return m_pCurrentTSFile;
 }
 
-long MultiFileWriter::getNumbFilesAdded(void)
-{
-	return m_filesAdded;
-}
 
-long MultiFileWriter::getNumbFilesRemoved(void)
-{
-	return m_filesRemoved;
-}
-
 long MultiFileWriter::getCurrentFileId(void)
 {
-	return m_currentFileId;//m_currentFilenameId;
+	return m_currentFileId;
 }
 
-long MultiFileWriter::getMinTSFiles(void)
-{
-	return m_minTSFiles;
-}
-
-void MultiFileWriter::setMinTSFiles(long minFiles)
-{
-	m_minTSFiles = minFiles;
-}
-
-long MultiFileWriter::getMaxTSFiles(void)
-{
-	return m_maxTSFiles;
-}
-
-void MultiFileWriter::setMaxTSFiles(long maxFiles)
-{
-	m_maxTSFiles = maxFiles;
-}
-
 __int64 MultiFileWriter::getMaxTSFileSize(void)
 {
 	return m_maxTSFileSize;
Index: MPWriter/source/MultiFileWriter.h
===================================================================
--- MPWriter/source/MultiFileWriter.h	(revision 27480)
+++ MPWriter/source/MultiFileWriter.h	(working copy)
@@ -48,13 +48,7 @@
 	LPWSTR getBufferFileName(void);
 	void setBufferFileName(LPWSTR fileName);
 	FileWriter* getCurrentTSFile(void);
-	long getNumbFilesAdded(void);
-	long getNumbFilesRemoved(void);
 	long getCurrentFileId(void);
-	long getMinTSFiles(void);
-	void setMinTSFiles(long minFiles);
-	long getMaxTSFiles(void);
-	void setMaxTSFiles(long maxFiles);
 	__int64 getMaxTSFileSize(void);
 	void setMaxTSFileSize(__int64 maxSize);
 	__int64 getChunkReserve(void);
@@ -69,21 +63,15 @@
 	HRESULT CleanupFiles();
 	BOOL IsFileLocked(LPWSTR pFilename);
 
-	HANDLE m_hTSBufferFile;
-	LPWSTR m_pTSBufferFileName;
+	HANDLE m_hTSShiftFile;
+	LPWSTR m_pTSShiftFileName;
 	LPTSTR m_pTSRegFileName;
 
 	CCritSec m_Lock;
 
 	FileWriter *m_pCurrentTSFile;
-	std::vector<LPWSTR> m_tsFileNames;
-	long m_filesAdded;
-	long m_filesRemoved;
-	long m_currentFilenameId;
 	long m_currentFileId;
 
-	long m_minTSFiles;
-	long m_maxTSFiles;
 	__int64 m_maxTSFileSize;
 	__int64 m_chunkReserve;
 };
Index: MPWriter/source/MultiWriterFileSink.cpp
===================================================================
--- MPWriter/source/MultiWriterFileSink.cpp	(revision 27480)
+++ MPWriter/source/MultiWriterFileSink.cpp	(working copy)
@@ -64,14 +64,12 @@
 	delete[] m_pWriteBuffer;
 }
 
-CMultiWriterFileSink* CMultiWriterFileSink::createNew(UsageEnvironment& env, char const* fileName,int minFiles, int maxFiles, ULONG maxFileSize,unsigned bufferSize, Boolean oneFilePerFrame, int channelType) 
+CMultiWriterFileSink* CMultiWriterFileSink::createNew(UsageEnvironment& env, char const* fileName, ULONG maxFileSize,unsigned bufferSize, Boolean oneFilePerFrame, int channelType) 
 {
 	do 
 	{
 		LogDebug("CMultiWriterFileSink::create file:%s",fileName);
 		MultiFileWriter* fid = new MultiFileWriter();
-		fid->setMinTSFiles(minFiles);
-		fid->setMaxTSFiles(maxFiles);
 		fid->setChunkReserve(maxFileSize);
 		fid->setMaxTSFileSize(maxFileSize);
 		WCHAR wstrFileName[2048];
Index: MPWriter/source/MultiWriterFileSink.h
===================================================================
--- MPWriter/source/MultiWriterFileSink.h	(revision 27480)
+++ MPWriter/source/MultiWriterFileSink.h	(working copy)
@@ -1,80 +1,80 @@
-
-#ifndef _MULTIFILE_SINK_HH
-#define _MULTI_SINK_HH
-
-#ifndef _MEDIA_SINK_HH
-#include "MediaSink.hh"
+
+#ifndef _MULTIFILE_SINK_HH
+#define _MULTI_SINK_HH
+
+#ifndef _MEDIA_SINK_HH
+#include "MediaSink.hh"
 #endif
 
 #include "MultiFileWriter.h"
-#include "packetsync.h" 
+#include "packetsync.h" 
 
-#define TS_PACKET_SIZE	188
-#define THROTTLE_MAXIMUM_RADIO_PACKETS			10		//	Throttle to 10 for radio
-#define THROTTLE_MAXIMUM_TV_PACKETS				172		//	Throttle to 172 fo tv for reduced disk IOs
+#define TS_PACKET_SIZE	188
+#define THROTTLE_MAXIMUM_RADIO_PACKETS			10		//	Throttle to 10 for radio
+#define THROTTLE_MAXIMUM_TV_PACKETS				172		//	Throttle to 172 fo tv for reduced disk IOs
 
-
-//	Incremental buffer sizes
-#define NUMBER_THROTTLE_BUFFER_SIZES	20
-
-
-enum ChannelType
-{
-	TV = 0,
-	Radio = 1,
-};
-
-
-class CMultiWriterFileSink: public MediaSink,public CPacketSync 
-{
-public:
-  static CMultiWriterFileSink* createNew(UsageEnvironment& env, char const* fileName,int minFiles, int maxFiles, ULONG maxFileSize,unsigned bufferSize = 20000,Boolean oneFilePerFrame = False, int channelType = 0);
-  // "bufferSize" should be at least as large as the largest expected
-  //   input frame.
-  // "oneFilePerFrame" - if True - specifies that each input frame will
-  //   be written to a separate file (using the presentation time as a
-  //   file name suffix).  The default behavior ("oneFilePerFrame" == False)
-  //   is to output all incoming data into a single file.
-
-  virtual ~CMultiWriterFileSink();
-  void addData(unsigned char* data, unsigned dataSize,struct timeval presentationTime);
-  // (Available in case a client wants to add extra data to the output file)
-
-  void SetChannelType(int channelType);
-	virtual void OnTsPacket(byte* tsPacket);
-  void ClearStreams();
-protected:
-  CMultiWriterFileSink(UsageEnvironment& env, MultiFileWriter* fid, unsigned bufferSize,char const* perFrameFileNamePrefix);
-      // called only by createNew()
-
-protected:
-  static void afterGettingFrame(void* clientData, unsigned frameSize,unsigned numTruncatedBytes,struct timeval presentationTime,
-				unsigned durationInMicroseconds);
-  virtual void afterGettingFrame1(unsigned frameSize,struct timeval presentationTime);
-
-  MultiFileWriter* fOutFid;
-  unsigned char* fBuffer;
-  unsigned fBufferSize;
-  char* fPerFrameFileNamePrefix; // used if "oneFilePerFrame" is True
-  char* fPerFrameFileNameBuffer; // used if "oneFilePerFrame" is True
-
+
+//	Incremental buffer sizes
+#define NUMBER_THROTTLE_BUFFER_SIZES	20
+
+
+enum ChannelType
+{
+	TV = 0,
+	Radio = 1,
+};
+
+
+class CMultiWriterFileSink: public MediaSink,public CPacketSync 
+{
+public:
+  static CMultiWriterFileSink* createNew(UsageEnvironment& env, char const* fileName, ULONG maxFileSize,unsigned bufferSize = 20000,Boolean oneFilePerFrame = False, int channelType = 0);
+  // "bufferSize" should be at least as large as the largest expected
+  //   input frame.
+  // "oneFilePerFrame" - if True - specifies that each input frame will
+  //   be written to a separate file (using the presentation time as a
+  //   file name suffix).  The default behavior ("oneFilePerFrame" == False)
+  //   is to output all incoming data into a single file.
+
+  virtual ~CMultiWriterFileSink();
+  void addData(unsigned char* data, unsigned dataSize,struct timeval presentationTime);
+  // (Available in case a client wants to add extra data to the output file)
+
+  void SetChannelType(int channelType);
+	virtual void OnTsPacket(byte* tsPacket);
+  void ClearStreams();
+protected:
+  CMultiWriterFileSink(UsageEnvironment& env, MultiFileWriter* fid, unsigned bufferSize,char const* perFrameFileNamePrefix);
+      // called only by createNew()
+
+protected:
+  static void afterGettingFrame(void* clientData, unsigned frameSize,unsigned numTruncatedBytes,struct timeval presentationTime,
+				unsigned durationInMicroseconds);
+  virtual void afterGettingFrame1(unsigned frameSize,struct timeval presentationTime);
+
+  MultiFileWriter* fOutFid;
+  unsigned char* fBuffer;
+  unsigned fBufferSize;
+  char* fPerFrameFileNamePrefix; // used if "oneFilePerFrame" is True
+  char* fPerFrameFileNameBuffer; // used if "oneFilePerFrame" is True
+
   
 	__int64 m_startPcr;
 	__int64 m_highestPcr;
-  bool    m_bDetermineNewStartPcr;
-  bool    m_bStartPcrFound;
+  bool    m_bDetermineNewStartPcr;
+  bool    m_bStartPcrFound;
   	byte*	m_pWriteBuffer;
 	int     m_iWriteBufferPos;
-	int		m_iWriteBufferSize;
-  int				m_iWriteBufferThrottle;
-  BOOL				m_bThrottleAtMax;
-  ChannelType		m_eChannelType;
-  int			m_iThrottleBufferSizes[NUMBER_THROTTLE_BUFFER_SIZES];
-
-private: // redefined virtual functions:
-  CCritSec m_Lock;
-  virtual Boolean continuePlaying();
-};
-
-
-#endif
+	int		m_iWriteBufferSize;
+  int				m_iWriteBufferThrottle;
+  BOOL				m_bThrottleAtMax;
+  ChannelType		m_eChannelType;
+  int			m_iThrottleBufferSizes[NUMBER_THROTTLE_BUFFER_SIZES];
+
+private: // redefined virtual functions:
+  CCritSec m_Lock;
+  virtual Boolean continuePlaying();
+};
+
+
+#endif
Index: MPWriter/source/ProgramToTransportStream.cpp
===================================================================
--- MPWriter/source/ProgramToTransportStream.cpp	(revision 27480)
+++ MPWriter/source/ProgramToTransportStream.cpp	(working copy)
@@ -50,7 +50,7 @@
 	// And, from this, a filter that converts to MPEG-2 Transport Stream frames:
 	m_tsFrames  = MPEG2TransportStreamFromPESSource::createNew(*m_env, pesSource);
 
-	m_outputSink = CMultiWriterFileSink::createNew(*m_env, fileNameOut,m_minFiles,m_maxFiles,m_maxFileSize);
+	m_outputSink = CMultiWriterFileSink::createNew(*m_env, fileNameOut,m_maxFileSize);
 	if (m_outputSink == NULL) 
 	{
 		*m_env << "Unable to open file \"" << fileNameOut << "\" as a file sink\n";
@@ -70,10 +70,8 @@
 	m_iPacketsToSkip=10;
 	m_buffer.Clear();
 }
-void CProgramToTransportStream::SetTimeShiftParams( int minFiles, int maxFiles, ULONG maxFileSize)
+void CProgramToTransportStream::SetTimeShiftParams(ULONG maxFileSize)
 {
-	m_minFiles=minFiles;
-	m_maxFiles=maxFiles;
 	m_maxFileSize=maxFileSize;
 }
 void CProgramToTransportStream::SetChannelType(int channelType)
Index: MPWriter/source/ProgramToTransportStream.h
===================================================================
--- MPWriter/source/ProgramToTransportStream.h	(revision 27480)
+++ MPWriter/source/ProgramToTransportStream.h	(working copy)
@@ -15,7 +15,7 @@
 	CProgramToTransportStream(void);
 	virtual ~CProgramToTransportStream(void);
 	void Initialize(char* fileNameOut);
-	void SetTimeShiftParams( int minFiles, int maxFiles, ULONG maxFileSize);
+	void SetTimeShiftParams(ULONG maxFileSize);
 	void SetChannelType(int channelType);
 	void ClearStreams();
 	void Close();
@@ -39,8 +39,6 @@
 	int  m_iPacketsToSkip;
 	bool m_bSendVideoAudioObserverEvents;
 
-	int m_minFiles;
-	int m_maxFiles;
 	ULONG m_maxFileSize;
 	IAnalogVideoAudioObserver* m_pCallback;
 };
Index: MPWriter/source/SubChannel.cpp
===================================================================
--- MPWriter/source/SubChannel.cpp	(revision 27480)
+++ MPWriter/source/SubChannel.cpp	(working copy)
@@ -100,10 +100,9 @@
 	m_pTsWriter->SetChannelType(channelType);
 	return S_OK;
 }
-
-STDMETHODIMP CSubChannel::SetTimeShiftParams(int minFiles, int maxFiles, ULONG maxFileSize)
+STDMETHODIMP CSubChannel::SetTimeShiftParams(ULONG maxFileSize)
 {
-	m_pTsWriter->SetTimeShiftParams(  minFiles,  maxFiles,  maxFileSize);
+	m_pTsWriter->SetTimeShiftParams(maxFileSize);
 	return S_OK;
 }
 STDMETHODIMP CSubChannel::StartTimeShifting()
Index: MPWriter/source/SubChannel.h
===================================================================
--- MPWriter/source/SubChannel.h	(revision 27480)
+++ MPWriter/source/SubChannel.h	(working copy)
@@ -43,7 +43,7 @@
 	STDMETHODIMP StartTimeShifting();
 	STDMETHODIMP StopTimeShifting();
 	STDMETHODIMP PauseTimeShifting(int onOff);
-	STDMETHODIMP SetTimeShiftParams(int minFiles, int maxFiles, ULONG maxFileSize);
+	STDMETHODIMP SetTimeShiftParams(ULONG maxFileSize);
 	STDMETHODIMP TTxSetCallBack(IAnalogTeletextCallBack* callback);
 	STDMETHODIMP SetVideoAudioObserver(IAnalogVideoAudioObserver* callback);
 	STDMETHODIMP SetRecorderVideoAudioObserver(IAnalogVideoAudioObserver* callback);
Index: TsReader/source/DeMultiplexer.cpp
===================================================================
--- TsReader/source/DeMultiplexer.cpp	(revision 27480)
+++ TsReader/source/DeMultiplexer.cpp	(working copy)
@@ -914,10 +914,15 @@
           {
             LogDebug("DeMultiplexer::FillAudio pts jump found : %f %f, %f", (float) diff, (float)pts.ToClock(), (float)m_lastAudioPTS.ToClock());
             m_AudioValidPES=false;
+			if (m_FailedToDecryptAudio)
+			{
+				m_lastAudioPTS=pts;
+			}
           }
           else
           {
             m_lastAudioPTS=pts;
+			m_FailedToDecryptAudio=true;
           }
 
           Cbuf->SetPts(pts);
@@ -960,6 +965,7 @@
       {
         LogDebug("Pes header 0-0-1 fail");
         m_AudioValidPES=false;
+		m_FailedToDecryptAudio=true;
       }
 
       if (m_AudioValidPES)
@@ -1122,6 +1128,7 @@
       m_VideoValidPES=false;
       m_p->rtStart = Packet::INVALID_TIME;
       m_WaitHeaderPES = -1;
+	  m_FailedToDecryptVideo=true;
     }   
     else
     {
@@ -1149,11 +1156,16 @@
           {
             LogDebug("DeMultiplexer::FillVideo pts jump found : %f %f, %f", (float) diff, (float)pts.ToClock(), (float)m_lastVideoPTS.ToClock());
             m_VideoValidPES=false;
+			if (m_FailedToDecryptVideo)
+			{
+			m_lastVideoPTS=pts;
+			}
           }
           else
           {
             // LogDebug("DeMultiplexer::FillVideo pts : %f ", (float)pts.ToClock());
             m_lastVideoPTS=pts;
+			m_FailedToDecryptVideo=true;
           }
         }
         m_lastStart -= 9+start[8];
@@ -1447,11 +1459,16 @@
           {
             LogDebug("DeMultiplexer::FillVideo pts jump found : %f %f, %f", (float) diff, (float)pts.ToClock(), (float)m_lastVideoPTS.ToClock());
             m_VideoValidPES=false;
+			if (m_FailedToDecryptVideo)
+			{
+			m_lastVideoPTS=pts;
+			}
           }
           else
           {
 //            LogDebug("DeMultiplexer::FillVideo pts : %f ", (float)pts.ToClock());
             m_lastVideoPTS=pts;
+		  m_FailedToDecryptVideo=true;
           }
           m_VideoPts = pts;
         }
@@ -1491,6 +1508,7 @@
       if (next < m_p->GetData() + m_lastStart)
       {
         next = m_p->GetData() + m_lastStart;
+		m_FailedToDecryptVideo=true;
       }
 
       while(next <= end-4 && ((*(DWORD*)next & 0xFFFFFFFF) != 0xb3010000) && ((*(DWORD*)next & 0xFFFFFFFF) != 0x00010000)) next++;
Index: TsReader/source/DeMultiplexer.h
===================================================================
--- TsReader/source/DeMultiplexer.h	(revision 27480)
+++ TsReader/source/DeMultiplexer.h	(working copy)
@@ -174,6 +174,8 @@
   bool m_AudioValidPES;
   bool m_VideoValidPES;
   bool m_mVideoValidPES;
+  bool m_FailedToDecryptVideo;
+  bool m_FailedToDecryptAudio;
   int  m_WaitHeaderPES;
   CRefTime  m_FirstAudioSample;
   CRefTime  m_LastAudioSample;
Index: TsReader/source/FileReader.cpp
===================================================================
--- TsReader/source/FileReader.cpp	(revision 27480)
+++ TsReader/source/FileReader.cpp	(working copy)
@@ -119,11 +119,15 @@
 //#else
 
 	pFileName = m_pFileName;
+
+  LogDebug("FileReader::OpenFile() Filename: %ws", pFileName);
+
 //#endif
 	do
 	{
 		// do not try to open a tsbuffer file without SHARE_WRITE so skip this try if we have a buffer file
-		if (wcsstr(pFileName, L".ts.tsbuffer") == NULL) 
+		if (wcsstr(pFileName, L".ts.tsbuffer") == NULL
+			&& wcsstr(pFileName, L".tshift") == NULL) 
 		{
 			// Try to open the file
 			m_hFile = ::CreateFileW(pFileName,      // The filename
Index: TsReader/source/MpegPesParser.h
===================================================================
--- TsReader/source/MpegPesParser.h	(revision 27480)
+++ TsReader/source/MpegPesParser.h	(working copy)
@@ -21,6 +21,7 @@
 #pragma once
 #include "buffer.h"
 #include "MultiFileReader.h"
+#include "TimeshiftFileReader.h"
 #include "tsDuration.h"
 #include "pcrdecoder.h"
 #include "..\..\shared\packetSync.h"
Index: TsReader/source/TimeshiftFileReader.cpp
===================================================================
--- TsReader/source/TimeshiftFileReader.cpp	(revision 0)
+++ TsReader/source/TimeshiftFileReader.cpp	(revision 0)
@@ -0,0 +1,557 @@
+/**
+*  TimeshiftFileReader.cpp
+*  Copyright (C) 2005      nate
+*  Copyright (C) 2006      bear
+*
+*  This file is part of TSFileSource, a directshow push source filter that
+*  provides an MPEG transport stream output.
+*
+*  TSFileSource 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.
+*
+*  TSFileSource 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 TSFileSource; if not, write to the Free Software
+*  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+*
+*  nate can be reached on the forums at
+*    http://forums.dvbowners.com/
+*/
+#include "StdAfx.h"
+
+#include "TimeshiftFileReader.h"
+#include <atlbase.h>
+
+// For more details for memory leak detection see the alloctracing.h header
+#include "..\..\alloctracing.h"
+
+//Maximum time in msec to wait for the buffer file to become available - Needed for DVB radio (this sometimes takes some time)
+#define MAX_BUFFER_TIMEOUT	1500
+
+#define BUFFER_IGNORE_MARGIN	(100 * 188)
+
+// A safety margin right behind the live-point to account for the server writing to the file
+// even before we got a chance to look at it.
+#define BUFFER_SAFETY_MARGIN	(10000 * 188)
+
+// Easy macro to see if the timeshift has wrapped back to the beginning or not.
+#define IS_WRAPPED				(_wrappedCount > 0)
+
+extern void LogDebug(const char *fmt, ...) ;
+TimeshiftFileReader::TimeshiftFileReader(BOOL bDebugOutput) :
+	_tshiftFileReader(),
+	_tsFileReader(),
+	m_bDebugOutput(bDebugOutput)
+{
+	_livePosition = 0;
+	_position = 0;
+	_wrappedCount = 0;
+	_tsFilename = NULL;
+	m_bReadOnly = 1;
+	m_bDelay = 0;
+	m_llBufferPointer = 0;	
+}
+
+TimeshiftFileReader::~TimeshiftFileReader()
+{
+}
+
+HRESULT TimeshiftFileReader::GetFileName(LPOLESTR *lpszFileName)
+{
+	return _tshiftFileReader.GetFileName(lpszFileName);
+}
+
+HRESULT TimeshiftFileReader::SetFileName(LPCOLESTR pszFileName)
+{
+	return _tshiftFileReader.SetFileName(pszFileName);
+}
+
+//
+// OpenFile
+//
+HRESULT TimeshiftFileReader::OpenFile()
+{
+	HRESULT hr = _tshiftFileReader.OpenFile();
+	if (!FAILED(hr))
+	{
+		// do some retries for cases that needs some time to startup.
+		DWORD tc = GetTickCount();
+		while (!RefreshTShiftFile())
+		{
+			if (GetTickCount() - tc > MAX_BUFFER_TIMEOUT)
+			{
+				LogDebug("TimeshiftFileReader: timedout while waiting for buffer file to become available");
+				return S_FALSE;
+			}
+		}
+		_position = 0;
+	}
+	return hr;
+}
+
+//
+// CloseFile
+//
+HRESULT TimeshiftFileReader::CloseFile()
+{
+	_tshiftFileReader.CloseFile();
+	return _tsFileReader.CloseFile();
+}
+
+BOOL TimeshiftFileReader::IsFileInvalid()
+{
+	return _tshiftFileReader.IsFileInvalid();
+}
+
+HRESULT TimeshiftFileReader::GetFileSize(__int64 *pStartPosition, __int64 *pLength)
+{
+	RefreshTShiftFile();
+
+	if (IS_WRAPPED)
+	{
+		*pStartPosition = _livePosition + BUFFER_SAFETY_MARGIN;
+		*pLength = _tsFileLength - BUFFER_SAFETY_MARGIN - BUFFER_IGNORE_MARGIN;
+	}
+	else
+	{
+		*pStartPosition = 0;
+		*pLength = _livePosition - BUFFER_IGNORE_MARGIN;
+	}
+	return S_OK;
+}
+
+__int64 TimeshiftFileReader::GetFileSize()
+{
+	if (IS_WRAPPED)
+	{
+		return _tsFileLength - BUFFER_SAFETY_MARGIN - BUFFER_IGNORE_MARGIN;
+	}
+	RefreshTShiftFile();
+	return max(0, _livePosition - BUFFER_IGNORE_MARGIN);
+}
+
+DWORD TimeshiftFileReader::SetFilePointer(__int64 llDistanceToMove, DWORD dwMoveMethod)
+{
+	if (m_bDebugOutput)
+		LogDebug("TimeshiftFileReader::SetFilePointer(%I64d, %d)", llDistanceToMove, dwMoveMethod);
+
+	RefreshTShiftFile();
+
+	if (IS_WRAPPED)
+	{
+		__int64 startPosition = _livePosition + BUFFER_SAFETY_MARGIN;
+		bool positionInFront = true;
+
+		if (dwMoveMethod == FILE_END)
+		{
+			_position = _livePosition + llDistanceToMove;
+		}
+		else if (dwMoveMethod == FILE_CURRENT)
+		{
+			positionInFront = (_position <= _livePosition);
+			_position += llDistanceToMove;
+		}
+		else
+		{
+			positionInFront = false;
+			_position = startPosition + llDistanceToMove;
+		}
+
+		if (positionInFront)
+		{
+			if (_position > _livePosition)
+			{
+				_position = _livePosition;
+			}
+			if (_position < 0)
+			{
+				_position += _tsFileLength;
+				if (_position < startPosition)
+				{
+					_position = startPosition;
+				}
+			}
+		}
+		else
+		{
+			if (_position < startPosition)
+			{
+				_position = startPosition;
+			}
+			if (_position >= _tsFileLength)
+			{
+				_position -= _tsFileLength;
+				if (_position > _livePosition)
+				{
+					_position = _livePosition;
+				}
+			}
+		}
+	}
+	else
+	{
+		if (dwMoveMethod == FILE_END)
+		{
+			_position = _livePosition + llDistanceToMove - BUFFER_IGNORE_MARGIN;
+		}
+		else if (dwMoveMethod == FILE_CURRENT)
+		{
+			_position += llDistanceToMove;
+		}
+		else
+		{
+			_position = llDistanceToMove;
+		}
+		if (_position > _livePosition - BUFFER_IGNORE_MARGIN)
+		{
+			_position = _livePosition - BUFFER_IGNORE_MARGIN;
+		}
+		if (_position < 0)
+		{
+			_position = 0;
+		}
+	}
+
+	if (m_bDebugOutput)
+		LogDebug("TimeshiftFileReader::SetFilePointer - moved to %I64d (live pos: %I64d)", _position, _livePosition);
+
+	//LOG_MSG("SetFilePointer - leave");
+	return S_OK;
+}
+
+__int64 TimeshiftFileReader::GetFilePointer()
+{
+	return _position;
+}
+
+HRESULT TimeshiftFileReader::Read(PBYTE pbData, ULONG lDataLength, ULONG *dwReadBytes)
+{
+	HRESULT hr;
+
+	// If the file has already been closed, don't continue
+	if (_tshiftFileReader.IsFileInvalid())
+	{
+		return S_FALSE;
+	}
+
+	RefreshTShiftFile();
+
+	if (m_bDebugOutput)
+		LogDebug("TimeshiftFileReader::Read - reading %d bytes at %I64d (live pos: %I64d)", lDataLength, _position, _livePosition);
+
+	if (_position < 0)
+	{
+		_position = 0;
+	}
+	if (_position > _tsFileLength)
+	{
+		_position = _tsFileLength;
+	}
+
+	bool positionInFirstPart = (_position < _livePosition);
+
+	if (m_bDebugOutput)
+		LogDebug("TimeshiftFileReader::Read - %s part, pos %I64d", positionInFirstPart ? "first" : "second", _position);
+
+	__int64 bytesLeftInFile;
+	if (positionInFirstPart)
+	{
+		bytesLeftInFile = _livePosition - _position - BUFFER_IGNORE_MARGIN;
+	}
+	else
+	{
+		bytesLeftInFile = _tsFileLength - _position;
+	}
+
+	if (lDataLength > bytesLeftInFile)
+	{
+		if (m_bDebugOutput)
+			LogDebug("TimeshiftFileReader::Reading the end of the file, %d", bytesLeftInFile);
+
+		ULONG bytesReadAtEnd = 0;
+		if (bytesLeftInFile > 0)
+		{
+			_tsFileReader.SetFilePointer(_position, FILE_BEGIN);
+			hr = _tsFileReader.Read(pbData, (ULONG)bytesLeftInFile, &bytesReadAtEnd);
+			_position += bytesLeftInFile;
+		}
+
+		if (positionInFirstPart)
+		{
+			*dwReadBytes = bytesReadAtEnd;
+		}
+		else
+		{
+			_tsFileReader.SetFilePointer(0, FILE_BEGIN);
+			lDataLength -= (ULONG)bytesLeftInFile;
+
+			if (m_bDebugOutput)
+				LogDebug("TimeshiftFileReader::Reading the beginning of the file, %d", lDataLength);
+
+			hr = _tsFileReader.Read(pbData + bytesLeftInFile, lDataLength, dwReadBytes);
+			_position = *dwReadBytes;
+
+			*dwReadBytes += bytesReadAtEnd;
+		}
+	}
+	else 
+	{
+		if (m_bDebugOutput)
+			LogDebug("TimeshiftFileReader::Reading bytes %I64d -> %I64d", _position, _position + lDataLength);
+
+		_tsFileReader.SetFilePointer(_position, FILE_BEGIN);
+		hr = _tsFileReader.Read(pbData, lDataLength, dwReadBytes);
+		_position += *dwReadBytes;
+	}
+
+	return S_OK;
+}
+
+HRESULT TimeshiftFileReader::Read(PBYTE pbData, ULONG lDataLength, ULONG *dwReadBytes, __int64 llDistanceToMove, DWORD dwMoveMethod)
+{
+	//If end method then we want llDistanceToMove to be the end of the buffer that we read.
+	if (dwMoveMethod == FILE_END)
+		llDistanceToMove = 0 - llDistanceToMove - lDataLength;
+
+	SetFilePointer(llDistanceToMove, dwMoveMethod);
+
+	return Read(pbData, lDataLength, dwReadBytes);
+}
+
+HRESULT TimeshiftFileReader::get_ReadOnly(WORD *ReadOnly)
+{
+//	CheckPointer(ReadOnly, E_POINTER);
+
+	if (!_tshiftFileReader.IsFileInvalid())
+		return _tshiftFileReader.get_ReadOnly(ReadOnly);
+
+	*ReadOnly = m_bReadOnly;
+	return S_OK;
+}
+        //ensures that there's always a back slash at the end
+//        wPathName[wcslen(wPathName)] = char(92*(int)(wPathName[wcslen(wPathName)-1]!=char(92)));
+
+HRESULT TimeshiftFileReader::RefreshTShiftFile()
+{
+	if (_tshiftFileReader.IsFileInvalid())
+	{
+		return S_FALSE;
+	}
+
+	//LOG_MSG("ParseTsBufferFile - enter");
+
+	ULONG bytesRead;
+
+	HRESULT result;
+	__int64 currentPosition;
+	long wrappedCount;
+
+	long errorCode;
+	long loopCounter = 0;
+
+	LPWSTR pBuffer = NULL;
+  	
+	do
+	{
+		errorCode = 0;
+		_tshiftFileReader.SetFilePointer(0, FILE_END);
+		__int64 fileLength = _tshiftFileReader.GetFilePointer();
+		if (fileLength == 0)
+		{
+			return false;
+		}
+
+		if (fileLength <= (sizeof(__int64) + sizeof(long) + sizeof(wchar_t)))
+		{
+			errorCode |= 0x01;
+		}
+		_tshiftFileReader.SetFilePointer(0, FILE_BEGIN);
+	
+		result = _tshiftFileReader.Read((LPBYTE)&currentPosition, sizeof(currentPosition), &bytesRead);
+		if (!SUCCEEDED(result) || bytesRead != sizeof(currentPosition))
+		{
+			errorCode |= 0x02;
+		}
+
+		result = _tshiftFileReader.Read((LPBYTE)&wrappedCount, sizeof(wrappedCount), &bytesRead);
+		if (!SUCCEEDED(result) || bytesRead != sizeof(wrappedCount))
+		{
+			errorCode = 0x04;
+		}
+
+		// If no files added or removed, break the loop !
+		if (_tsFilename != NULL)
+		{
+			break;
+		}
+
+		__int64 remainingLength = fileLength - sizeof(__int64) - sizeof(long);
+
+		// Above 10kb or below 0 seems stupid and figure out a problem !!!
+		if ((remainingLength > 10000) || (remainingLength < 0)) 
+		{
+			errorCode = 0x10;
+		}
+
+		if (errorCode == 0)
+		{
+			pBuffer = (LPWSTR)new BYTE[(UINT)remainingLength];
+			result = _tshiftFileReader.Read((LPBYTE)pBuffer, (ULONG)remainingLength, &bytesRead);
+			if (!SUCCEEDED(result) ||  bytesRead != remainingLength)
+			{
+				errorCode = 0x20;
+				delete[] pBuffer;
+				pBuffer = NULL;
+			}
+		}
+
+		loopCounter++;
+	} 
+	while (errorCode && loopCounter <= 10);
+
+	if (loopCounter == 10 && errorCode)
+	{
+		return false;
+	}
+
+	// Is this the very first time we parse the .tshift file?
+	if (_tsFilename == NULL)
+	{
+		__int64 nextStartPosition = 0;
+
+		//Get the real path of the buffer file
+		LPWSTR wfilename;
+		_tshiftFileReader.GetFileName(&wfilename);
+		
+		LPWSTR path = NULL;
+		LPWSTR name = wcsrchr(wfilename, 92);
+		if (name)
+		{
+			name++;
+			long len = name - wfilename;
+			path = new wchar_t[len+1];
+			lstrcpynW(path, wfilename, len+1);
+		}
+
+		// Get the filename in the .tshift file.
+		LPWSTR filename;
+
+		//modify filename path here to include the real path
+		LPWSTR temp = wcsrchr(pBuffer, 92);
+		if (path && temp)
+		{
+			temp++;
+			int fileNameLength = wcslen(path) + wcslen(temp) + 1;
+			filename = new wchar_t[fileNameLength];
+			wcscpy_s(filename, fileNameLength, path);
+			wcscat_s(filename, fileNameLength, temp);
+		}
+		else
+		{
+			int fileNameLength = wcslen(pBuffer) + + 1;
+			filename = new wchar_t[fileNameLength];
+			wcscpy_s(filename, fileNameLength, pBuffer);
+		}
+
+		if (path)
+		{
+			delete[] path;
+		}
+
+		// Open the .ts file
+		_tsFilename = filename;
+		GetFileLength(filename, _tsFileLength);
+
+		_tsFileReader.SetFileName(_tsFilename);
+		_tsFileReader.OpenFile();
+		_position = 0;
+	}
+
+	if (pBuffer != NULL)
+	{
+		delete[] pBuffer;
+		pBuffer = NULL;
+	}
+
+	_wrappedCount = wrappedCount;
+	_livePosition = currentPosition;
+
+	return S_OK;
+}
+
+HRESULT TimeshiftFileReader::GetFileLength(LPWSTR pFilename, __int64 &length)
+{
+	USES_CONVERSION;
+
+	length = 0;
+
+	// Try to open the file
+	HANDLE hFile = ::CreateFileW(pFilename,		// The filename
+						 (DWORD) GENERIC_READ,      // File access
+						 (DWORD) (FILE_SHARE_READ |
+						 FILE_SHARE_WRITE),			// Share access
+						 NULL,						// Security
+						 (DWORD) OPEN_EXISTING,     // Open flags
+						 (DWORD) 0,					// More flags
+						 NULL);						// Template
+	if (hFile != INVALID_HANDLE_VALUE)
+	{
+		LARGE_INTEGER li;
+		li.QuadPart = 0;
+		li.LowPart = ::SetFilePointer(hFile, 0, &li.HighPart, FILE_END);
+		::CloseHandle(hFile);
+		
+		length = li.QuadPart;
+	}
+	else
+	{
+		DWORD dwErr = GetLastError();
+		return HRESULT_FROM_WIN32(dwErr);
+	}
+
+	return S_OK;
+}
+
+HRESULT TimeshiftFileReader::get_DelayMode(WORD *DelayMode)
+{
+	*DelayMode = m_bDelay;
+	return S_OK;
+}
+
+HRESULT TimeshiftFileReader::set_DelayMode(WORD DelayMode)
+{
+	m_bDelay = DelayMode;
+	return S_OK;
+}
+
+HRESULT TimeshiftFileReader::get_ReaderMode(WORD *ReaderMode)
+{
+	*ReaderMode = TRUE;
+	return S_OK;
+}
+
+DWORD TimeshiftFileReader::setFilePointer(__int64 llDistanceToMove, DWORD dwMoveMethod)
+{
+	return SetFilePointer(llDistanceToMove, dwMoveMethod);
+}
+
+__int64 TimeshiftFileReader::getFilePointer()
+{
+	return GetFilePointer();
+}
+
+__int64 TimeshiftFileReader::getBufferPointer()
+{
+	return 	m_llBufferPointer;	
+}
+
+void TimeshiftFileReader::setBufferPointer()
+{
+	m_llBufferPointer = GetFilePointer();	
+}
Index: TsReader/source/TimeshiftFileReader.h
===================================================================
--- TsReader/source/TimeshiftFileReader.h	(revision 0)
+++ TsReader/source/TimeshiftFileReader.h	(revision 0)
@@ -0,0 +1,82 @@
+/**
+*  MultiFileReader.h
+*  Copyright (C) 2005      nate
+*  Copyright (C) 2006      bear
+*
+*  This file is part of TSFileSource, a directshow push source filter that
+*  provides an MPEG transport stream output.
+*
+*  TSFileSource 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.
+*
+*  TSFileSource 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 TSFileSource; if not, write to the Free Software
+*  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+*
+*  nate can be reached on the forums at
+*    http://forums.dvbowners.com/
+*/
+
+#ifndef TIMESHIFTFILEREADER
+#define TIMESHIFTFILEREADER
+
+#include "FileReader.h"
+#include <vector>
+
+class TimeshiftFileReader : public FileReader
+{
+public:
+	TimeshiftFileReader(BOOL bDebugOutput);
+	virtual ~TimeshiftFileReader();
+
+	virtual HRESULT GetFileName(LPOLESTR *lpszFileName);
+	virtual HRESULT SetFileName(LPCOLESTR pszFileName);
+	virtual HRESULT OpenFile();
+	virtual HRESULT CloseFile();
+	virtual HRESULT Read(PBYTE pbData, ULONG lDataLength, ULONG *dwReadBytes);
+	virtual HRESULT Read(PBYTE pbData, ULONG lDataLength, ULONG *dwReadBytes, __int64 llDistanceToMove, DWORD dwMoveMethod);
+	virtual HRESULT get_ReadOnly(WORD *ReadOnly);
+	virtual HRESULT set_DelayMode(WORD DelayMode);
+	virtual HRESULT get_DelayMode(WORD *DelayMode);
+	virtual HRESULT get_ReaderMode(WORD *ReaderMode);
+	virtual DWORD setFilePointer(__int64 llDistanceToMove, DWORD dwMoveMethod);
+	virtual __int64 getFilePointer();
+	virtual __int64 getBufferPointer();
+	virtual void setBufferPointer();
+
+	//TODO: GetFileSize should go since get_FileSize should do the same thing.
+	virtual HRESULT GetFileSize(__int64 *pStartPosition, __int64 *pLength);
+
+	virtual BOOL IsFileInvalid();
+
+	virtual DWORD SetFilePointer(__int64 llDistanceToMove, DWORD dwMoveMethod);
+	virtual __int64 GetFilePointer();
+	virtual __int64 GetFileSize();
+
+protected:
+	HRESULT RefreshTShiftFile();
+	HRESULT GetFileLength(LPWSTR filename, __int64 &length);
+
+	FileReader _tshiftFileReader;
+	__int64 _livePosition;
+	__int64 _position;
+	long _wrappedCount;
+
+	LPWSTR _tsFilename;
+	__int64 _tsFileLength;
+
+	FileReader _tsFileReader;
+
+	BOOL     m_bReadOnly;
+	BOOL     m_bDelay;
+	BOOL     m_bDebugOutput;
+};
+
+#endif
Index: TsReader/source/TsReader.cpp
===================================================================
--- TsReader/source/TsReader.cpp	(revision 27480)
+++ TsReader/source/TsReader.cpp	(working copy)
@@ -734,8 +734,16 @@
   }
   else
   {
-    if ((length < 9) || (_strcmpi(&url[length-9], ".tsbuffer") != 0))
+    if ((length > 7) && _strcmpi(&url[length-7], ".tshift") == 0)
     {
+      //local single-looping timeshift file
+      m_bTimeShifting = true;
+      m_bLiveTv = true;
+      m_fileReader = new TimeshiftFileReader(false);
+      m_fileDuration = new TimeshiftFileReader(false);
+    }
+    else if ((length < 9) || (_strcmpi(&url[length-9], ".tsbuffer") != 0))
+    {
       //local .ts file
       m_bTimeShifting = false;
       m_bLiveTv = false ;
Index: TsReader/TsReader.vcproj
===================================================================
--- TsReader/TsReader.vcproj	(revision 27480)
+++ TsReader/TsReader.vcproj	(working copy)
@@ -315,6 +315,10 @@
 				>
 			</File>
 			<File
+				RelativePath=".\source\TimeshiftFileReader.cpp"
+				>
+			</File>
+			<File
 				RelativePath=".\source\TsDuration.cpp"
 				>
 			</File>
@@ -452,6 +456,10 @@
 				>
 			</File>
 			<File
+				RelativePath=".\source\TimeshiftFileReader.h"
+				>
+			</File>
+			<File
 				RelativePath=".\source\TsDuration.h"
 				>
 			</File>
Index: TsWriter/source/DiskRecorder.cpp
===================================================================
--- TsWriter/source/DiskRecorder.cpp	(revision 27480)
+++ TsWriter/source/DiskRecorder.cpp	(working copy)
@@ -81,10 +81,9 @@
 	m_recordingMode=mode;
 	m_hFile=INVALID_HANDLE_VALUE;
 	m_bPaused=FALSE;
+  m_params.m_wrappedCount=0;
 	m_params.chunkSize=268435424;
-	m_params.maxFiles=20;
 	m_params.maxSize=268435424;
-	m_params.minFiles=6;
 
 	m_iPmtPid=-1;
 	m_pcrPid=-1;
@@ -195,7 +194,7 @@
 		m_bDetermineNewStartPcr=false;
 		strcpy(m_szFileName,pszFileName);
 		if (m_recordingMode == TimeShift)
-			strcat(m_szFileName,".tsbuffer");
+			strcat(m_szFileName,".tshift");
 	}
 	catch(...)
 	{
@@ -429,41 +428,12 @@
 	*size = 0;
 }
 
-void CDiskRecorder::GetNumbFilesAdded(WORD *numbAdd)
-{
-	*numbAdd = (WORD)m_pTimeShiftFile->getNumbFilesAdded();
-}
-
-void CDiskRecorder::GetNumbFilesRemoved(WORD *numbRem)
-{
-	*numbRem = (WORD)m_pTimeShiftFile->getNumbFilesRemoved();
-}
-
 void CDiskRecorder::GetCurrentFileId(WORD *fileID)
 {
 	*fileID = (WORD)m_pTimeShiftFile->getCurrentFileId();
 }
 
-void CDiskRecorder::GetMinTSFiles(WORD *minFiles)
-{
-	*minFiles = (WORD) m_params.minFiles;
-}
 
-void CDiskRecorder::SetMinTSFiles(WORD minFiles)
-{
-	m_params.minFiles=(long)minFiles;
-}
-
-void CDiskRecorder::GetMaxTSFiles(WORD *maxFiles)
-{
-	*maxFiles = (WORD) m_params.maxFiles;
-}
-
-void CDiskRecorder::SetMaxTSFiles(WORD maxFiles)
-{
-	m_params.maxFiles=(long)maxFiles;
-}
-
 void CDiskRecorder::GetMaxTSFileSize(__int64 *maxSize)
 {
 	*maxSize = m_params.maxSize;
Index: TsWriter/source/DiskRecorder.h
===================================================================
--- TsWriter/source/DiskRecorder.h	(revision 27480)
+++ TsWriter/source/DiskRecorder.h	(working copy)
@@ -95,13 +95,7 @@
 	// Only needed for timeshifting
 	void SetVideoAudioObserver (IVideoAudioObserver* callback);
 	void GetBufferSize( long * size) ;
-	void GetNumbFilesAdded( WORD *numbAdd) ;
-	void GetNumbFilesRemoved( WORD *numbRem) ;
 	void GetCurrentFileId( WORD *fileID) ;
-	void GetMinTSFiles( WORD *minFiles) ;
-	void SetMinTSFiles( WORD minFiles) ;
-	void GetMaxTSFiles( WORD *maxFiles) ;
-	void SetMaxTSFiles( WORD maxFiles) ;
 	void GetMaxTSFileSize( __int64 *maxSize) ;
 	void SetMaxTSFileSize( __int64 maxSize) ;
 	void GetChunkReserve( __int64 *chunkSize) ;
Index: TsWriter/source/FileWriter.cpp
===================================================================
--- TsWriter/source/FileWriter.cpp	(revision 27480)
+++ TsWriter/source/FileWriter.cpp	(working copy)
@@ -230,6 +230,7 @@
 
 void FileWriter::SetChunkReserve(BOOL bEnable, __int64 chunkReserveSize, __int64 maxFileSize)
 {
+  LogDebug("SetChunkReserve called with: chunkReserveSize: %I64d maxFileSize: %I64d", chunkReserveSize, maxFileSize);
 	m_bChunkReserve = bEnable;
 	if (m_bChunkReserve)
 	{
Index: TsWriter/source/MultiFileWriter.cpp
===================================================================
--- TsWriter/source/MultiFileWriter.cpp	(revision 27480)
+++ TsWriter/source/MultiFileWriter.cpp	(working copy)
@@ -33,16 +33,12 @@
 extern void LogDebug(const char *fmt, ...) ;
 
 MultiFileWriter::MultiFileWriter(MultiFileWriterParam *pWriterParams) :
-	m_hTSBufferFile(INVALID_HANDLE_VALUE),
-	m_pTSBufferFileName(NULL),
+	m_hTSShiftFile(INVALID_HANDLE_VALUE),
+	m_pTSShiftFileName(NULL),
 	m_pTSRegFileName(NULL),
 	m_pCurrentTSFile(NULL),
-	m_filesAdded(0),
-	m_filesRemoved(0),
-	m_currentFilenameId(0),
 	m_currentFileId(0),
-	m_minTSFiles(pWriterParams->minFiles),
-	m_maxTSFiles(pWriterParams->maxFiles),
+  m_wrappedCount(pWriterParams->m_wrappedCount),
 	m_maxTSFileSize(pWriterParams->maxSize),	
 	m_chunkReserve(pWriterParams->chunkSize) 
 {
@@ -53,8 +49,8 @@
 MultiFileWriter::~MultiFileWriter()
 {
 	CloseFile();
-	if (m_pTSBufferFileName)
-		delete[] m_pTSBufferFileName;
+	if (m_pTSShiftFileName)
+		delete[] m_pTSShiftFileName;
 
 	if (m_pTSRegFileName)
 		delete[] m_pTSRegFileName;
@@ -65,7 +61,7 @@
 
 HRESULT MultiFileWriter::GetFileName(LPOLESTR *lpszFileName)
 {
-	*lpszFileName = m_pTSBufferFileName;
+	*lpszFileName = m_pTSShiftFileName;
 	return S_OK;
 }
 
@@ -74,7 +70,7 @@
 	USES_CONVERSION;
 
 	// Is the file already opened
-	if (m_hTSBufferFile != INVALID_HANDLE_VALUE)
+	if (m_hTSShiftFile != INVALID_HANDLE_VALUE)
 	{
 		return E_FAIL;
 	}
@@ -88,15 +84,15 @@
 		return ERROR_FILENAME_EXCED_RANGE;
   }
 	// Take a copy of the filename
-	if (m_pTSBufferFileName)
+	if (m_pTSShiftFileName)
 	{
-		delete[] m_pTSBufferFileName;
-		m_pTSBufferFileName = NULL;
+		delete[] m_pTSShiftFileName;
+		m_pTSShiftFileName = NULL;
 	}
-	m_pTSBufferFileName = new WCHAR[1+lstrlenW(pszFileName)];
-	if (m_pTSBufferFileName == NULL)
+	m_pTSShiftFileName = new WCHAR[1+lstrlenW(pszFileName)];
+	if (m_pTSShiftFileName == NULL)
 		return E_OUTOFMEMORY;
-	wcscpy(m_pTSBufferFileName, pszFileName);
+	wcscpy(m_pTSShiftFileName, pszFileName);
 	
 	//check disk space first
 	__int64 llDiskSpaceAvailable = 0;
@@ -108,7 +104,7 @@
 	TCHAR *pFileName = NULL;
 
 	// Try to open the file
-	m_hTSBufferFile = CreateFile(W2T(m_pTSBufferFileName),  // The filename
+	m_hTSShiftFile = CreateFile(W2T(m_pTSShiftFileName),  // The filename
 								 (DWORD) GENERIC_WRITE,             // File access
 								 (DWORD) FILE_SHARE_READ,           // Share access
 								 NULL,                      // Security
@@ -116,7 +112,7 @@
 								 (DWORD) 0,                 // More flags
 								 NULL);                     // Template
 
-	if (m_hTSBufferFile == INVALID_HANDLE_VALUE)
+	if (m_hTSShiftFile == INVALID_HANDLE_VALUE)
 	{
         LogDebug("MultiFileWriter: fail to create buffer file");
         DWORD dwErr = GetLastError();
@@ -134,13 +130,13 @@
 {
 	CAutoLock lock(&m_Lock);
 
-	if (m_hTSBufferFile == INVALID_HANDLE_VALUE)
+	if (m_hTSShiftFile == INVALID_HANDLE_VALUE)
 	{
 		return S_OK;
 	}
 
-	CloseHandle(m_hTSBufferFile);
-	m_hTSBufferFile = INVALID_HANDLE_VALUE;
+	CloseHandle(m_hTSShiftFile);
+	m_hTSShiftFile = INVALID_HANDLE_VALUE;
 
 	m_pCurrentTSFile->CloseFile();
 
@@ -151,10 +147,10 @@
 
 HRESULT MultiFileWriter::GetFileSize(__int64 *lpllsize)
 {
-	if (m_hTSBufferFile == INVALID_HANDLE_VALUE)
+	if (m_hTSShiftFile == INVALID_HANDLE_VALUE)
 		*lpllsize = 0;
 	else
-		*lpllsize = max(0, (__int64)(((__int64)(m_filesAdded - m_filesRemoved - 1) * m_maxTSFileSize) + m_pCurrentTSFile->GetFilePointer()));
+		*lpllsize = max(0, (__int64)(((__int64)m_wrappedCount * m_maxTSFileSize) + m_pCurrentTSFile->GetFilePointer()));
 
 	return S_OK;
 }
@@ -164,17 +160,18 @@
 	HRESULT hr;
 
 	CheckPointer(pbData,E_POINTER);
+
 	if (lDataLength == 0)
 		return S_OK;
 
 	// If the file has already been closed, don't continue
-	if (m_hTSBufferFile == INVALID_HANDLE_VALUE)
+	if (m_hTSShiftFile == INVALID_HANDLE_VALUE)
 		return S_FALSE;
 
 	if (m_pCurrentTSFile->IsFileInvalid())
 	{
-		//::LogDebug("Creating first file");
-		if FAILED(hr = PrepareTSFile())
+		::LogDebug("Creating first TS file");
+    if FAILED(hr = CreateNewTSFile())
 			return hr;
 	}
 
@@ -192,17 +189,14 @@
 			m_pCurrentTSFile->Write(pbData, (ULONG)dataToWrite);
 		}
 
-		// Try to create a new file
-		if FAILED(hr = PrepareTSFile())
-		{
-			// Buffer is probably full and the oldest file is still locked.
-			// We'll just start dropping data
-			return hr;
-		}
+    // Wrap around
+		::LogDebug("Wrap TS file");
+    m_wrappedCount++;
+    m_pCurrentTSFile->SetFilePointer(0, FILE_BEGIN);    
 
 		// Try writing the remaining data now that a new file has been created.
 		pbData += dataToWrite;
-		lDataLength -= dataToWrite;
+		lDataLength -= (ULONG)dataToWrite;
 		return Write(pbData, lDataLength);
 	}
 	else
@@ -215,73 +209,6 @@
 	return S_OK;
 }
 
-HRESULT MultiFileWriter::PrepareTSFile()
-{
-	USES_CONVERSION;
-	HRESULT hr;
-
-	//LogDebug("PrepareTSFile()");
-
-//	m_pCurrentTSFile->FlushFile())
-
-	// Make sure the old file is closed
-	m_pCurrentTSFile->CloseFile();
-
-
-	//TODO: disk space stuff
-	/*
-	if (m_diskSpaceLimit > 0)
-	{
-		diskSpaceAvailable = WhateverFunctionDoesThat();
-		if (diskSpaceAvailable < m_diskSpaceLimit)
-		{
-			hr = ReuseTSFile();
-		}
-		else
-		{
-			hr = CreateNewTSFile();
-		}
-	}
-	else */
-
-	__int64 llDiskSpaceAvailable = 0;
-	if (SUCCEEDED(GetAvailableDiskSpace(&llDiskSpaceAvailable)) && (__int64)llDiskSpaceAvailable < (__int64)(m_maxTSFileSize*2))
-	{
-		hr = ReuseTSFile();
-	}
-	else
-	{
-		if (m_tsFileNames.size() >= (UINT)m_minTSFiles) 
-		{
-			if FAILED(hr = ReuseTSFile())
-			{
-				if (m_tsFileNames.size() < (UINT)m_maxTSFiles)
-				{
-					if (hr != 0x80070020) // ERROR_SHARING_VIOLATION
-						LogDebug("Failed to reopen old file. Unexpected reason. Trying to create a new file.");
-
-					hr = CreateNewTSFile();
-				}
-				else
-				{
-					if (hr != 0x80070020) // ERROR_SHARING_VIOLATION
-						LogDebug("Failed to reopen old file. Unexpected reason. Dropping data!");
-					else
-						LogDebug("Failed to reopen old file. It's currently in use. Dropping data!");
-
-					Sleep(500);
-				}
-			}
-		}	
-		else
-		{
-			hr = CreateNewTSFile();
-		}
-	}
-
-	return hr;
-}
-
 HRESULT MultiFileWriter::CreateNewTSFile()
 {
 	USES_CONVERSION;
@@ -291,109 +218,52 @@
 	WIN32_FIND_DATA findData;
 	HANDLE handleFound = INVALID_HANDLE_VALUE;
 
-	//LogDebug("CreateNewTSFile.");
+	LogDebug("MultiFileWriter: CreateNewTSFile.");
 	while (TRUE)
 	{
 		// Create new filename
-		m_currentFilenameId++;
-		swprintf(pFilename, L"%s%i.ts", m_pTSBufferFileName, m_currentFilenameId);
+		swprintf(pFilename, L"%s.ts", m_pTSShiftFileName);
 
 		// Check if file already exists
 		handleFound = FindFirstFile(W2T(pFilename), &findData);
 		if (handleFound == INVALID_HANDLE_VALUE)
 			break;
 
-		//LogDebug("Newly generated filename already exists.");
+		LogDebug("MultiFileWriter: Newly generated filename already exists.");
 
-		// If it exists we loop and try the next number
+		// If it exists we delete it
+    DeleteFile(W2T(pFilename));
 		FindClose(handleFound);
 	}
 	
 	if FAILED(hr = m_pCurrentTSFile->SetFileName(pFilename))
 	{
-		LogDebug("Failed to set filename for new file.");
+		LogDebug("MultiFileWriter: Failed to set filename for new file.");
 		delete[] pFilename;
 		return hr;
 	}
 
 	if FAILED(hr = m_pCurrentTSFile->OpenFile())
 	{
-		LogDebug("Failed to open new file");
+		LogDebug("MultiFileWriter: Failed to open new file");
 		delete[] pFilename;
 		return hr;
 	}
 
-	m_tsFileNames.push_back(pFilename);
-	m_filesAdded++;
-
-	LPWSTR pos = pFilename + wcslen(m_pTSBufferFileName);
+	LPWSTR pos = pFilename + wcslen(m_pTSShiftFileName);
 	if (pos)
 		m_currentFileId = _wtoi(pos);
 	wchar_t msg[MAX_PATH];
 	swprintf((LPWSTR)&msg, L"New file created : %s\n", pFilename);
 	::OutputDebugString(W2T((LPWSTR)&msg));
 
-	//LogDebug("new file created");
-	return S_OK;
-}
 
-HRESULT MultiFileWriter::ReuseTSFile()
-{
-	USES_CONVERSION;
-	HRESULT hr;
-  DWORD Tmo=5 ;
 
-	LPWSTR pFilename = m_tsFileNames.at(0);
 
-	if FAILED(hr = m_pCurrentTSFile->SetFileName(pFilename))
-	{
-		LogDebug("Failed to set filename to reuse old file");
-		return hr;
-	}
-
-	// Check if file is being read by something.
-  TCHAR sz[MAX_PATH];
-  sprintf(sz, "%S", pFilename);
-  // Can be locked temporarily to update duration or definitely (!) if timeshift is paused.
-	do
-	{
-		DeleteFile(sz) ;	// Stupid function, return can be ok and file not deleted ( just tagged for deleting )!!!!
-		hr = m_pCurrentTSFile->OpenFile() ;
-		if (!FAILED(hr)) break ;
-		Sleep(20) ;
-	}
-	while (--Tmo) ;
-
-  if (Tmo)
-  {
-    if (Tmo<4) // 1 failed + 1 succeded is quasi-normal, more is a bit suspicious ( disk drive too slow or problem ? )
-			LogDebug("MultiFileWriter: %d tries to succeed deleting and re-opening %ws.", 6-Tmo, pFilename);
-  }
-  else
-	{
-    LogDebug("MultiFileWriter: failed to create file %ws",pFilename);
-		return hr ;
-	}
-
-	// if stuff worked then move the filename to the end of the files list
-	m_tsFileNames.erase(m_tsFileNames.begin());
-	m_filesRemoved++;
-
-	m_tsFileNames.push_back(pFilename);
-	m_filesAdded++;
-
-	LPWSTR pos = pFilename + wcslen(m_pTSBufferFileName);
-	if (pos)
-		m_currentFileId = _wtoi(pos);
-	wchar_t msg[MAX_PATH];
-	swprintf((LPWSTR)&msg, L"Old file reused : %s\n", pFilename);
-	::OutputDebugString(W2T((LPWSTR)&msg));
-
-	//LogDebug("reuse old file");
+	LogDebug("MultiFileWriter: new file created");
 	return S_OK;
 }
 
-
 HRESULT MultiFileWriter::WriteTSBufferFile()
 {
 	LARGE_INTEGER li;
@@ -401,58 +271,23 @@
 
 	// Move to the start of the file
 	li.QuadPart = 0;
-	SetFilePointer(m_hTSBufferFile, li.LowPart, &li.HighPart, FILE_BEGIN);
+	SetFilePointer(m_hTSShiftFile, li.LowPart, &li.HighPart, FILE_BEGIN);
 
 	// Write current position of most recent file.
 	__int64 currentPointer = m_pCurrentTSFile->GetFilePointer();
+	WriteFile(m_hTSShiftFile, &currentPointer, sizeof(currentPointer), &written, NULL);
 
-	BYTE* writeBuffer = new BYTE[65536];
-	BYTE* writePointer = writeBuffer;
+  // write wrap count
+  WriteFile(m_hTSShiftFile, &m_wrappedCount, sizeof(m_wrappedCount), &written, NULL);
 
-	*((__int64*)writePointer) = currentPointer;
-	writePointer += sizeof(__int64);
-	
-	*((long*)writePointer) = m_filesAdded;
-	writePointer += sizeof(long);
-	
-	*((long*)writePointer) = m_filesRemoved;
-	writePointer += sizeof(long);
+  // Finish up with unicode tsfilename
+  LPWSTR temp;
+  m_pCurrentTSFile->GetFileName(&temp);
+  long length = wcslen(temp)+1;   
+  length *= sizeof(WCHAR);
+  WriteFile(m_hTSShiftFile, temp, length, &written, NULL);
+  //LogDebug("STEFAN: Wrap: %ld Curpos: %I64d Name: %ws", m_wrappedCount, currentPointer, temp);
 
-	// Write out all the filenames (null terminated)
-	std::vector<LPWSTR>::iterator it = m_tsFileNames.begin();
-	for ( ; it < m_tsFileNames.end() ; it++ )
-	{
-		LPWSTR pFilename = *it;
-		long length = wcslen(pFilename)+1;
-		length *= sizeof(wchar_t);
-
-		memcpy(writePointer, pFilename, length);
-		writePointer += length;
-
-		if((writePointer - writeBuffer) > 60000)
-		{
-			LogDebug("MultiFileWriter: TS buffer file has exceeded maximum length.  Reduce the number of timeshifting files");
-			delete[] writeBuffer;
-			return S_FALSE;
-		}
-	}
-
-	// Finish up with a unicode null character in case we want to put stuff after this in the future.
-	wchar_t temp = 0;
-	*((wchar_t*)writePointer) = temp;
-	writePointer += sizeof(wchar_t);
-	
-	
-	*((long*)writePointer) = m_filesAdded;
-	writePointer += sizeof(long);
-	
-	*((long*)writePointer) = m_filesRemoved;
-	writePointer += sizeof(long);
-
-	WriteFile(m_hTSBufferFile, writeBuffer, writePointer - writeBuffer, &written, NULL);
-	delete[] writeBuffer;
-
-
 	return S_OK;
 }
 
@@ -460,56 +295,42 @@
 {
 	USES_CONVERSION;
 
-	m_filesAdded = 0;
-	m_filesRemoved = 0;
-	m_currentFilenameId = 0;
 	m_currentFileId = 0;
 
 	// Check if .tsbuffer file is being read by something.
-	if (IsFileLocked(m_pTSBufferFileName) == TRUE)
+	if (IsFileLocked(m_pTSShiftFileName) == TRUE)
 		return S_OK;
 
-	std::vector<LPWSTR>::iterator it;
-	for (it = m_tsFileNames.begin() ; it < m_tsFileNames.end() ; it++ )
-	{
-		if (IsFileLocked(*it) == TRUE)
-		{
+  LPWSTR temp;
+  m_pCurrentTSFile->GetFileName(&temp);
+  if (IsFileLocked(temp) == TRUE)
+  {
 			// If any of the files are being read then we won't
 			// delete any so that the full buffer stays intact.
 			wchar_t msg[MAX_PATH];
-			swprintf((LPWSTR)&msg, L"CleanupFiles: A file is still locked : %s\n", *it);
+			swprintf((LPWSTR)&msg, L"CleanupFiles: A file is still locked : %s\n", m_pCurrentTSFile);
 			::OutputDebugString(W2T((LPWSTR)&msg));
-			LogDebug("CleanupFiles: A file is still locked");
+			LogDebug("MultiFileWriter: CleanupFiles: A file is still locked");
 			return S_OK;
-		}
 	}
 
 	// Now we know we can delete all the files.
-
-	for (it = m_tsFileNames.begin() ; it < m_tsFileNames.end() ; it++ )
+	if (DeleteFile(W2T(temp)) == FALSE)
 	{
-		if (DeleteFile(W2T(*it)) == FALSE)
-		{
 			wchar_t msg[MAX_PATH];
-			swprintf((LPWSTR)&msg, L"Failed to delete file %s : 0x%x\n", *it, GetLastError());
+			swprintf((LPWSTR)&msg, L"Failed to delete file %s : 0x%x\n", temp, GetLastError());
 			::OutputDebugString(W2T((LPWSTR)&msg));
-			LogDebug("CleanupFiles: Failed to delete file");
-		}
-		delete[] *it;
+			LogDebug("MultiFileWriter: CleanupFiles: Failed to delete file");
 	}
-	m_tsFileNames.clear();
 
-	if (DeleteFile(W2T(m_pTSBufferFileName)) == FALSE)
+	if (DeleteFile(W2T(m_pTSShiftFileName)) == FALSE)
 	{
 		wchar_t msg[MAX_PATH];
 		swprintf((LPWSTR)&msg, L"Failed to delete tsbuffer file : 0x%x\n", GetLastError());
 		::OutputDebugString(W2T((LPWSTR)&msg));
-			LogDebug("CleanupFiles: Failed to delete tsbuffer file: 0x%x\n", GetLastError());
+			LogDebug("MultiFileWriter: CleanupFiles: Failed to delete tsbuffer file: 0x%x\n", GetLastError());
 
 	}
-	m_filesAdded = 0;
-	m_filesRemoved = 0;
-	m_currentFilenameId = 0;
 	m_currentFileId = 0;
 	return S_OK;
 }
@@ -543,9 +364,9 @@
 
 	char	*pszDrive = NULL;
 	char	szDrive[4];
-	if (m_pTSBufferFileName[1] == ':')
+	if (m_pTSShiftFileName[1] == ':')
 	{
-		szDrive[0] = (char)m_pTSBufferFileName[0];
+		szDrive[0] = (char)m_pTSShiftFileName[0];
 		szDrive[1] = ':';
 		szDrive[2] = '\\';
 		szDrive[3] = '\0';
@@ -594,7 +415,7 @@
 
 LPWSTR MultiFileWriter::getBufferFileName(void)
 {
-	return 	m_pTSBufferFileName;
+	return 	m_pTSShiftFileName;
 }
 
 void MultiFileWriter::setBufferFileName(LPWSTR fileName)
@@ -605,16 +426,16 @@
 		return;// ERROR_FILENAME_EXCED_RANGE;
 
 	// Take a copy of the filename
-	if (m_pTSBufferFileName)
+	if (m_pTSShiftFileName)
 	{
-		delete[] m_pTSBufferFileName;
-		m_pTSBufferFileName = NULL;
+		delete[] m_pTSShiftFileName;
+		m_pTSShiftFileName = NULL;
 	}
-	m_pTSBufferFileName = new WCHAR[1+lstrlenW(fileName)];
-	if (m_pTSBufferFileName == NULL)
+	m_pTSShiftFileName = new WCHAR[1+lstrlenW(fileName)];
+	if (m_pTSShiftFileName == NULL)
 		return;// E_OUTOFMEMORY;
 
-	wcscpy(m_pTSBufferFileName, fileName);
+	wcscpy(m_pTSShiftFileName, fileName);
 }
 
 FileWriter* MultiFileWriter::getCurrentTSFile(void)
@@ -622,41 +443,11 @@
 	return m_pCurrentTSFile;
 }
 
-long MultiFileWriter::getNumbFilesAdded(void)
-{
-	return m_filesAdded;
-}
-
-long MultiFileWriter::getNumbFilesRemoved(void)
-{
-	return m_filesRemoved;
-}
-
 long MultiFileWriter::getCurrentFileId(void)
 {
 	return m_currentFileId;//m_currentFilenameId;
 }
 
-long MultiFileWriter::getMinTSFiles(void)
-{
-	return m_minTSFiles;
-}
-
-void MultiFileWriter::setMinTSFiles(long minFiles)
-{
-	m_minTSFiles = minFiles;
-}
-
-long MultiFileWriter::getMaxTSFiles(void)
-{
-	return m_maxTSFiles;
-}
-
-void MultiFileWriter::setMaxTSFiles(long maxFiles)
-{
-	m_maxTSFiles = maxFiles;
-}
-
 __int64 MultiFileWriter::getMaxTSFileSize(void)
 {
 	return m_maxTSFileSize;
Index: TsWriter/source/MultiFileWriter.h
===================================================================
--- TsWriter/source/MultiFileWriter.h	(revision 27480)
+++ TsWriter/source/MultiFileWriter.h	(working copy)
@@ -31,8 +31,7 @@
 
 typedef struct 
 {
-	long 	minFiles;
-	long 	maxFiles;
+	long m_wrappedCount;
 	__int64	maxSize;
 	__int64	chunkSize;
 } MultiFileWriterParam;
@@ -56,13 +55,7 @@
 	LPWSTR getBufferFileName(void);
 	void setBufferFileName(LPWSTR fileName);
 	FileWriter* getCurrentTSFile(void);
-	long getNumbFilesAdded(void);
-	long getNumbFilesRemoved(void);
 	long getCurrentFileId(void);
-	long getMinTSFiles(void);
-	void setMinTSFiles(long minFiles);
-	long getMaxTSFiles(void);
-	void setMaxTSFiles(long maxFiles);
 	__int64 getMaxTSFileSize(void);
 	void setMaxTSFileSize(__int64 maxSize);
 	__int64 getChunkReserve(void);
@@ -70,29 +63,23 @@
 	void GetPosition(__int64 * position);
 
 protected:
-	HRESULT PrepareTSFile();
 	HRESULT CreateNewTSFile();
-	HRESULT ReuseTSFile();
 
 	HRESULT WriteTSBufferFile();
 	HRESULT CleanupFiles();
 	BOOL IsFileLocked(LPWSTR pFilename);
 
-	HANDLE m_hTSBufferFile;
-	LPWSTR m_pTSBufferFileName;
+	HANDLE m_hTSShiftFile;
+	LPWSTR m_pTSShiftFileName;
 	LPTSTR m_pTSRegFileName;
 
 	CCritSec m_Lock;
 
 	FileWriter *m_pCurrentTSFile;
-	std::vector<LPWSTR> m_tsFileNames;
-	long m_filesAdded;
-	long m_filesRemoved;
-	long m_currentFilenameId;
-	long m_currentFileId;
+  long m_currentFileId;
 
-	long m_minTSFiles;
-	long m_maxTSFiles;
+  long m_wrappedCount;
+
 	__int64 m_maxTSFileSize;
 	__int64 m_chunkReserve;
 };
Index: TsWriter/source/TsWriter.cpp
===================================================================
--- TsWriter/source/TsWriter.cpp	(revision 27480)
+++ TsWriter/source/TsWriter.cpp	(working copy)
@@ -763,12 +763,10 @@
 	return S_OK;
 }
 
-STDMETHODIMP CMpTs::TimeShiftSetParams(int handle, int minFiles, int maxFiles, ULONG chunkSize) 
+STDMETHODIMP CMpTs::TimeShiftSetParams(int handle, ULONG chunkSize) 
 {
   CTsChannel* pChannel=GetTsChannel(handle);
   if (pChannel==NULL) return S_OK;
-  pChannel->m_pTimeShifting->SetMinTSFiles(minFiles);
-  pChannel->m_pTimeShifting->SetMaxTSFiles(maxFiles);
   pChannel->m_pTimeShifting->SetMaxTSFileSize(chunkSize);
   pChannel->m_pTimeShifting->SetChunkReserve(chunkSize);
   return S_OK;
Index: TsWriter/source/TsWriter.h
===================================================================
--- TsWriter/source/TsWriter.h	(revision 27480)
+++ TsWriter/source/TsWriter.h	(working copy)
@@ -75,7 +75,7 @@
 	STDMETHOD(TimeShiftGetBufferSize) (THIS_ int handle, long * size) PURE;
 	STDMETHOD(TimeShiftSetPmtPid) (THIS_ int handle, int pmtPid,int serviceId,byte* pmtData,int pmtLength) PURE;
 	STDMETHOD(TimeShiftPause) (THIS_ int handle, BYTE onOff) PURE;
-	STDMETHOD(TimeShiftSetParams) (THIS_ int handle, int minFiles, int maxFiles, ULONG chunkSize) PURE;
+	STDMETHOD(TimeShiftSetParams) (THIS_ int handle, ULONG chunkSize) PURE;
 	STDMETHOD(TimeShiftGetCurrentFilePosition) (THIS_ int handle,__int64 * position, long * bufferId) PURE;
 	STDMETHOD(SetVideoAudioObserver)(THIS_ int handle, IVideoAudioObserver* callback)PURE;
 
@@ -196,7 +196,7 @@
 		STDMETHODIMP TimeShiftGetBufferSize( int handle, long * size) ;
 		STDMETHODIMP TimeShiftSetPmtPid( int handle, int pmtPid, int serviceId,byte* pmtData,int pmtLength) ;
 		STDMETHODIMP TimeShiftPause( int handle, BYTE onOff) ;
-	  STDMETHODIMP TimeShiftSetParams(int handle, int minFiles, int maxFiles, ULONG chunkSize) ;
+	  STDMETHODIMP TimeShiftSetParams(int handle, ULONG chunkSize) ;
 		STDMETHODIMP TimeShiftGetCurrentFilePosition(int handle,__int64 * position,long * bufferId);
 		STDMETHODIMP SetVideoAudioObserver(int handle, IVideoAudioObserver* callback);
 
