------------------------------------------------------------------------
r1793 | aja_ | 2016-11-18 20:08:56 +0100 (vie, 18 nov 2016) | 2 lines

Address some of the issues reported by CoverityScan


Index: examples/helloworld/helloworld.cpp
===================================================================
--- examples/helloworld/helloworld.cpp	(revision 1792)
+++ examples/helloworld/helloworld.cpp	(revision 1793)
@@ -49,7 +49,7 @@
     std::cout << "  examplehelloworld [outputfile.pdf]" << std::endl << std::endl;
 }
 
-void HelloWorld( const char* pszFilename ) 
+void HelloWorld( const char* pszFilename )
 {
     /*
      * PdfStreamedDocument is the class that can actually write a PDF file.
@@ -68,7 +68,7 @@
     PdfPainter painter;
 
 	/*
-     * This pointer will hold the page object later. 
+     * This pointer will hold the page object later.
      * PdfSimpleWriter can write several PdfPage's to a PDF file.
      */
     PdfPage* pPage;
@@ -77,7 +77,7 @@
      * A PdfFont object is required to draw text on a PdfPage using a PdfPainter.
      * PoDoFo will find the font using fontconfig on your system and embedd truetype
      * fonts automatically in the PDF file.
-     */     
+     */
     PdfFont* pFont;
 
 	try {
@@ -98,7 +98,7 @@
 		 * The raise error macro initializes a PdfError object with a given error code and
 		 * the location in the file in which the error ocurred and throws it as an exception.
 		 */
-		if( !pPage ) 
+		if( !pPage )
 		{
 			PODOFO_RAISE_ERROR( ePdfError_InvalidHandle );
 		}
@@ -117,7 +117,7 @@
 		 * The created PdfFont will be deleted by the PdfDocument.
 		 */
 		pFont = document.CreateFont( "Arial" );
-	    
+
 		/*
 		 * If the PdfFont object cannot be allocated return an error.
 		 */
@@ -147,11 +147,11 @@
 
 		/*
 		 * Actually draw the line "Hello World!" on to the PdfPage at
-		 * the position 2cm,2cm from the top left corner. 
-		 * Please remember that PDF files have their origin at the 
-		 * bottom left corner. Therefore we substract the y coordinate 
+		 * the position 2cm,2cm from the top left corner.
+		 * Please remember that PDF files have their origin at the
+		 * bottom left corner. Therefore we substract the y coordinate
 		 * from the page height.
-		 * 
+		 *
 		 * The position specifies the start of the baseline of the text.
 		 *
 		 * All coordinates in PoDoFo are in PDF units.
@@ -180,7 +180,7 @@
 		 * The last step is to close the document.
 		 */
 		document.Close();
-	} catch ( const PdfError & e ) {
+	} catch ( PdfError & e ) {
 		/*
 		 * All PoDoFo methods may throw exceptions
 		 * make sure that painter.FinishPage() is called
@@ -227,7 +227,7 @@
          * with the filename of the output file as argument.
          */
          HelloWorld( argv[1] );
-    } catch( const PdfError & eCode ) {
+    } catch( PdfError & eCode ) {
         /*
          * We have to check if an error has occurred.
          * If yes, we return and print an error message
@@ -238,11 +238,27 @@
     }
 
 
-    /**
-     * Free global memory allocated by PoDoFo.
-     * This is normally not necessary.
#-     * This is normally not necessary as memory
#-     * will be free'd when the application terminates.
#-     * 
#-     * If you want to free all memory allocated by
#-     * PoDoFo you have to call this method.
#-     * 
#-     * PoDoFo will reallocate the memory if necessary.
-     */
-    PdfEncodingFactory::FreeGlobalEncodingInstances();
+    try {
+        /**
+         * Free global memory allocated by PoDoFo.
+         * This is normally not necessary as memory
+         * will be free'd when the application terminates.
+         *
+         * If you want to free all memory allocated by
+         * PoDoFo you have to call this method.
+         *
+         * PoDoFo will reallocate the memory if necessary.
+         */
+        PdfEncodingFactory::FreeGlobalEncodingInstances();
+    } catch( PdfError & eCode ) {
+        /*
+         * We have to check if an error has occurred.
+         * If yes, we return and print an error message
+         * to the commandline.
+         */
+        eCode.PrintErrorMsg();
+        return eCode.GetError();
+    }
 
     /*
      * The PDF was created sucessfully.
@@ -255,6 +265,6 @@
      */
     std::cout << std::endl
               << "Created a PDF file containing the line \"Hello World!\": " << argv[1] << std::endl << std::endl;
-    
+
     return 0;
 }
Index: examples/helloworld-base14/helloworld-base14.cpp
===================================================================
--- examples/helloworld-base14/helloworld-base14.cpp	(revision 1792)
+++ examples/helloworld-base14/helloworld-base14.cpp	(revision 1793)
@@ -174,7 +174,7 @@
 		 */
 		document.Close();
 
-	} catch ( const PdfError & e ) {
+	} catch ( PdfError & e ) {
 		/*
 		 * All PoDoFo methods may throw exceptions
 		 * make sure that painter.FinishPage() is called
@@ -221,7 +221,7 @@
          * with the filename of the output file as argument.
          */
          HelloWorld( argv[1] );
-    } catch( const PdfError & eCode ) {
+    } catch( PdfError & eCode ) {
         /*
          * We have to check if an error has occurred.
          * If yes, we return and print an error message
Index: examples/pdfcontentsgraph/PdfContentsGraph.cpp
===================================================================
--- examples/pdfcontentsgraph/PdfContentsGraph.cpp	(revision 1792)
+++ examples/pdfcontentsgraph/PdfContentsGraph.cpp	(revision 1793)
@@ -4,7 +4,6 @@
 #error This module requires boost::graph
 #endif
 
-#include <cassert>
 #include <string>
 #include <iostream>
 #include <map>
@@ -354,7 +353,7 @@
                 Vertex v = add_vertex( m_graph );
                 // Switch any waiting arguments into the new node's data.
                 m_graph[v].first.GetArgs().swap( args );
-                assert(!args.size());
+                PODOFO_ASSERT( !args.size() );
 
                 if (ki.kw == KW_Unknown)
                 {
@@ -361,40 +360,40 @@
                     // No idea what this keyword is. We have to assume it's an ordinary
                     // one, possibly with arguments, and just push it in as a node at the
                     // current level.
-                    assert(!m_graph[v].first.IsDefined());
+                    PODOFO_ASSERT( !m_graph[v].first.IsDefined() );
                     m_graph[v].first.SetKw( string(kwText) );
                     add_edge( parentage.top(), v, m_graph );
-                    assert( m_graph[v].first.GetKwId() == ki.kw );
-                    assert( m_graph[v].first.GetKwString() == kwText );
+                    PODOFO_ASSERT( m_graph[v].first.GetKwId() == ki.kw );
+                    PODOFO_ASSERT( m_graph[v].first.GetKwString() == kwText );
                 }
                 else if (ki.kt == KT_Standalone)
                 {
                     // Plain operator, shove it in the newly reserved vertex (which might already contain
                     // arguments) and add an edge from the top to it.
-                    assert(ki.kw != KW_Undefined && ki.kw != KW_Unknown && ki.kw != KW_RootNode );
-                    assert(!m_graph[v].first.IsDefined());
+                    PODOFO_ASSERT( ki.kw != KW_Undefined && ki.kw != KW_Unknown && ki.kw != KW_RootNode );
+                    PODOFO_ASSERT( !m_graph[v].first.IsDefined() );
                     m_graph[v].first.SetKw( ki.kw );
                     add_edge( parentage.top(), v, m_graph );
-                    assert( m_graph[v].first.GetKwId() == ki.kw );
-                    assert( m_graph[v].first.GetKwString() == kwText );
+                    PODOFO_ASSERT( m_graph[v].first.GetKwId() == ki.kw );
+                    PODOFO_ASSERT( m_graph[v].first.GetKwString() == kwText );
                 }
                 else if (ki.kt == KT_Opening)
                 {
                     PrintStack(m_graph, parentage, "OS: ");
-                    assert(ki.kw != KW_Undefined && ki.kw != KW_Unknown && ki.kw != KW_RootNode );
-                    assert(!m_graph[v].first.IsDefined());
+                    PODOFO_ASSERT( ki.kw != KW_Undefined && ki.kw != KW_Unknown && ki.kw != KW_RootNode );
+                    PODOFO_ASSERT( !m_graph[v].first.IsDefined() );
                     m_graph[v].first.SetKw( ki.kw );
                     // add an edge from the current top to it
                     add_edge( parentage.top(), v, m_graph );
                     // and push it to the top of the parentage stack
                     parentage.push( v );
-                    assert( m_graph[v].first.GetKwId() == ki.kw );
-                    assert( m_graph[v].first.GetKwString() == kwText );
+                    PODOFO_ASSERT( m_graph[v].first.GetKwId() == ki.kw );
+                    PODOFO_ASSERT( m_graph[v].first.GetKwString() == kwText );
                     PrintStack(m_graph, parentage, "OF: ");
                 }
                 else
                 {
-                    assert(false);
+                    PODOFO_ASSERT( false );
                 }
             }
             else if (ki.kt == KT_Closing)
@@ -403,7 +402,7 @@
                 // be a node whose KWInstance is the matching opening keyword. We'll check
                 // that, then set the second KWInstance appropriately.
                 PrintStack(m_graph, parentage, "CS: ");
-                assert(ki.kw != KW_Undefined && ki.kw != KW_Unknown && ki.kw != KW_RootNode );
+                PODOFO_ASSERT( ki.kw != KW_Undefined && ki.kw != KW_Unknown && ki.kw != KW_RootNode );
                 // Get a reference to the node data for the current parent
                 NodeData & n ( m_graph[parentage.top()] );
                 PODOFO_RAISE_LOGIC_IF( n.second.IsDefined(), "Closing already closed group" );
@@ -411,7 +410,7 @@
                 // a valid match for
                 PdfContentStreamKeyword expectedCloseKw = n.first.GetKwInfo().kwClose;
                 // Ensure there aren't any args to the close kw
-                assert(!args.size());
+                PODOFO_ASSERT( !args.size() );
                 // and handle the close matching
                 if ( ki.kw != expectedCloseKw )
                 {
@@ -437,12 +436,12 @@
             }
             else
             {
-                assert(false);
+                PODOFO_ASSERT( false );
             }
         }
         else
         {
-            assert(false);
+            PODOFO_ASSERT( false );
         }
     }
 
Index: examples/pdfcontentsgraph/main.cpp
===================================================================
--- examples/pdfcontentsgraph/main.cpp	(revision 1792)
+++ examples/pdfcontentsgraph/main.cpp	(revision 1793)
@@ -85,7 +85,7 @@
             cout << " - page ok" << endl;
         }
     }
-    catch( const PdfError & e )
+    catch( PdfError & e )
     {
         e.PrintErrorMsg();
         return e.GetError();
Index: src/base/PdfDataType.h
===================================================================
--- src/base/PdfDataType.h	(revision 1792)
+++ src/base/PdfDataType.h	(revision 1793)
@@ -145,7 +145,7 @@
 {
     if(m_bImmutable) 
     {
-        throw PdfError( ePdfError_ChangeOnImmutable );
+        PODOFO_RAISE_ERROR( ePdfError_ChangeOnImmutable );
     }
 }
 
Index: src/base/PdfDate.cpp
===================================================================
--- src/base/PdfDate.cpp	(revision 1792)
+++ src/base/PdfDate.cpp	(revision 1793)
@@ -56,6 +56,8 @@
 PdfDate::PdfDate( const PdfString & sDate )
     : m_bValid( false )
 {
+    m_time = -1;
+
     if ( !sDate.IsValid() ) 
     {
         m_szDate[0] = 0;
Index: src/base/PdfDate.h
===================================================================
--- src/base/PdfDate.h	(revision 1792)
+++ src/base/PdfDate.h	(revision 1793)
@@ -130,7 +130,7 @@
 
  private:
     time_t m_time;
-    char   m_szDate[PDF_DATE_BUFFER_SIZE];
+    char   m_szDate[PDF_DATE_BUFFER_SIZE + 1]; // include also room for a nul-terminator in the buffer
 
     bool   m_bValid;
 };
Index: src/base/PdfFilter.cpp
===================================================================
--- src/base/PdfFilter.cpp	(revision 1792)
+++ src/base/PdfFilter.cpp	(revision 1793)
@@ -187,7 +187,7 @@
         try {
             m_filter->DecodeBlock( pBuffer, lLen );
         }
-        catch( const PdfError & e ) 
+        catch( PdfError & e ) 
         {
             m_bFilterFailed = true;
             throw e;
Index: src/base/PdfFilter.h
===================================================================
--- src/base/PdfFilter.h	(revision 1792)
+++ src/base/PdfFilter.h	(revision 1793)
@@ -326,7 +326,7 @@
 
 	try {
 		BeginEncodeImpl();
-	} catch( const PdfError & e ) {
+	} catch( PdfError & e ) {
 		// Clean up and close stream
 		this->FailEncodeDecode();
 		throw e;
@@ -342,7 +342,7 @@
 
 	try {
 		EncodeBlockImpl(pBuffer, lLen);
-	} catch( const PdfError & e ) {
+	} catch( PdfError & e ) {
 		// Clean up and close stream
 		this->FailEncodeDecode();
 		throw e;
@@ -358,7 +358,7 @@
 
 	try {
 		EndEncodeImpl();
-	} catch( const PdfError & e ) {
+	} catch( PdfError & e ) {
 		// Clean up and close stream
 		this->FailEncodeDecode();
 		throw e;
@@ -378,7 +378,7 @@
 
 	try {
 		BeginDecodeImpl( pDecodeParms );
-	} catch( const PdfError & e ) {
+	} catch( PdfError & e ) {
 		// Clean up and close stream
 		this->FailEncodeDecode();
 		throw e;
@@ -394,7 +394,7 @@
 
 	try {
 		DecodeBlockImpl(pBuffer, lLen);
-	} catch( const PdfError & e ) {
+	} catch( PdfError & e ) {
 		// Clean up and close stream
 		this->FailEncodeDecode();
 		throw e;
@@ -410,7 +410,7 @@
 
 	try {
 	    EndDecodeImpl();
-	} catch( const PdfError & e ) {
+	} catch( PdfError & e ) {
 		// Clean up and close stream
 		this->FailEncodeDecode();
 		throw e;
@@ -442,7 +442,7 @@
     // Note that we can't do this for the user, since EndEncode() might
     // throw and we can't safely have that in a dtor. That also means
     // we can't throw here, but must abort.
-    assert(!m_pOutputStream);
+    assert( !m_pOutputStream );
 }
 
 
Index: src/base/PdfFiltersPrivate.cpp
===================================================================
--- src/base/PdfFiltersPrivate.cpp	(revision 1792)
+++ src/base/PdfFiltersPrivate.cpp	(revision 1793)
@@ -230,6 +230,11 @@
 // Hex
 // -------------------------------------------------------
 
+PdfHexFilter::PdfHexFilter()
+    : m_cDecodedByte( 0 ), m_bLow( true )
+{
+}
+
 void PdfHexFilter::EncodeBlockImpl( const char* pBuffer, pdf_long lLen )
 {
     char data[2];
@@ -301,6 +306,11 @@
 // Paul Haahr - http://www.webcom.com/~haahr/
 // -------------------------------------------------------
 
+PdfAscii85Filter::PdfAscii85Filter()
+    : m_count( 0 ), m_tuple( 0 )
+{
+}
+
 void PdfAscii85Filter::EncodeTuple( unsigned long tuple, int count )
 {
     int      i      = 5;
@@ -606,6 +616,11 @@
 // RLE
 // -------------------------------------------------------
 
+PdfRLEFilter::PdfRLEFilter()
+    : m_nCodeLen( 0 )
+{
+}
+
 void PdfRLEFilter::BeginEncodeImpl()
 {
     PODOFO_RAISE_ERROR( ePdfError_UnsupportedFilter );
@@ -862,6 +877,8 @@
 PdfDCTFilter::PdfDCTFilter()
     : m_pDevice( NULL )
 {
+    memset( &m_cinfo, 0, sizeof( struct jpeg_decompress_struct ) );
+    memset( &m_jerr, 0, sizeof( struct jpeg_error_mgr ) );
 }
 
 PdfDCTFilter::~PdfDCTFilter()
Index: src/base/PdfFiltersPrivate.h
===================================================================
--- src/base/PdfFiltersPrivate.h	(revision 1792)
+++ src/base/PdfFiltersPrivate.h	(revision 1793)
@@ -93,6 +93,8 @@
  */
 class PdfHexFilter : public PdfFilter {
  public:
+    PdfHexFilter();
+
     virtual ~PdfHexFilter() { }
 
     /** Check wether the encoding is implemented for this filter.
@@ -200,6 +202,7 @@
  */
 class PdfAscii85Filter : public PdfFilter {
  public:
+    PdfAscii85Filter();
     virtual ~PdfAscii85Filter() { }
 
     /** Check wether the encoding is implemented for this filter.
@@ -460,6 +463,7 @@
  */
 class PdfRLEFilter : public PdfFilter {
  public:
+    PdfRLEFilter();
     virtual ~PdfRLEFilter() {}
 
     /** Check wether the encoding is implemented for this filter.
Index: src/base/PdfImmediateWriter.cpp
===================================================================
--- src/base/PdfImmediateWriter.cpp	(revision 1792)
+++ src/base/PdfImmediateWriter.cpp	(revision 1793)
@@ -172,7 +172,7 @@
     if( pFileStream ) 
     {
         // Only one open file stream is allowed at a time
-        assert( !m_bOpenStream );
+        PODOFO_ASSERT( !m_bOpenStream );
         m_bOpenStream = true;
 
         if( m_pEncrypt )
@@ -186,7 +186,7 @@
     if( pFileStream ) 
     {
         // A PdfFileStream has to be opened before
-        assert( m_bOpenStream );
+        PODOFO_ASSERT( m_bOpenStream );
         m_bOpenStream = false;
     }
 }
Index: src/base/PdfInputDevice.cpp
===================================================================
--- src/base/PdfInputDevice.cpp	(revision 1792)
+++ src/base/PdfInputDevice.cpp	(revision 1793)
@@ -174,16 +174,23 @@
 
 int PdfInputDevice::Look() const 
 {
-	if (m_pStream)
-    return m_pStream->peek();
-	if (m_pFile) {
-		pdf_long lOffset = ftello( m_pFile );
-		int ch = GetChar();
-		fseeko( m_pFile, lOffset, SEEK_SET );
-		return ch;
-	}
+    if (m_pStream)
+        return m_pStream->peek();
+    if (m_pFile) {
+        pdf_long lOffset = ftello( m_pFile );
 
-	return 0;
+        if( lOffset == -1 )
+            PODOFO_RAISE_ERROR_INFO( ePdfError_InvalidDeviceOperation, "Failed to read the current file position" );
+
+        int ch = GetChar();
+
+        if( fseeko( m_pFile, lOffset, SEEK_SET ) == -1 )
+            PODOFO_RAISE_ERROR_INFO( ePdfError_InvalidDeviceOperation, "Failed to seek back to the previous position" );
+
+        return ch;
+    }
+
+    return 0;
 }
 
 std::streamoff PdfInputDevice::Tell() const
@@ -229,7 +236,8 @@
#                     whence = SEEK_CUR;
#                     break;
#             }
#-            fseeko( m_pFile, off, whence );
#+            if( fseeko( m_pFile, off, whence ) == -1)
 
         if (m_pFile)
         {
-            fseeko( m_pFile, off, dir );
+            if( fseeko( m_pFile, off, dir ) == -1)
+                PODOFO_RAISE_ERROR_INFO( ePdfError_InvalidDeviceOperation, "Failed to seek to given position in the file" );
         }
     }
     else
Index: src/base/PdfInputStream.cpp
===================================================================
--- src/base/PdfInputStream.cpp	(revision 1792)
+++ src/base/PdfInputStream.cpp	(revision 1793)
@@ -91,10 +91,19 @@
     pdf_long lOffset = ftello( m_hFile );
     pdf_long lLen;
 
-    fseeko( m_hFile, 0L, SEEK_END );
+    if( lOffset == -1 )
+        PODOFO_RAISE_ERROR_INFO( ePdfError_InvalidDeviceOperation, "Failed to read current position in the file" );
+
+    if( fseeko( m_hFile, 0L, SEEK_END ) == -1 )
+        PODOFO_RAISE_ERROR_INFO( ePdfError_InvalidDeviceOperation, "Failed to seek at the end of the file" );
+
     lLen = ftello( m_hFile );
-    fseeko( m_hFile, lOffset, SEEK_SET );
+    if( lLen == -1 )
+        PODOFO_RAISE_ERROR_INFO( ePdfError_InvalidDeviceOperation, "Failed to read file length" );
 
+    if( fseeko( m_hFile, lOffset, SEEK_SET ) == -1 )
+        PODOFO_RAISE_ERROR_INFO( ePdfError_InvalidDeviceOperation, "Failed to seek back to the previous position of the file" );
+
     return lLen;
 }
 
Index: src/base/PdfLocale.cpp
===================================================================
--- src/base/PdfLocale.cpp	(revision 1792)
+++ src/base/PdfLocale.cpp	(revision 1793)
@@ -16,14 +16,14 @@
     try {
     	s.imbue( cachedLocale );
     } catch (const std::runtime_error & e) {
-        std::ostringstream s;
-        s << "Failed to set safe locale on stream being used for PDF I/O.";
-        s << "Locale set was: \"" << PdfIOLocale << "\".";
-        s << "Error reported by STL std::locale: \"" << e.what() << "\"";
+        std::ostringstream err;
+        err << "Failed to set safe locale on stream being used for PDF I/O.";
+        err << "Locale set was: \"" << PdfIOLocale << "\".";
+        err << "Error reported by STL std::locale: \"" << e.what() << "\"";
         // The info string is copied by PdfError so we're ok to just:
         PODOFO_RAISE_ERROR_INFO(
             ePdfError_InvalidDeviceOperation,
-            s.str().c_str()
+            err.str().c_str()
             );
     }
 #endif
Index: src/base/PdfMemStream.cpp
===================================================================
--- src/base/PdfMemStream.cpp	(revision 1792)
+++ src/base/PdfMemStream.cpp	(revision 1793)
@@ -87,8 +87,12 @@
     {
         m_pStream->Close();
 
-        if( !m_pBufferStream ) 
-            m_lLength = dynamic_cast<PdfBufferOutputStream*>(m_pStream)->GetLength();
+        if( !m_pBufferStream )
+        {
+            PdfBufferOutputStream* pBufferOutputStream = dynamic_cast<PdfBufferOutputStream*>(m_pStream);
+            if( pBufferOutputStream )
+                m_lLength = pBufferOutputStream->GetLength();
+        }
 
         delete m_pStream;
         m_pStream = NULL;
Index: src/base/PdfMemoryManagement.cpp
===================================================================
--- src/base/PdfMemoryManagement.cpp	(revision 1792)
+++ src/base/PdfMemoryManagement.cpp	(revision 1793)
@@ -32,6 +32,7 @@
  ***************************************************************************/
 
 #include "PdfMemoryManagement.h"
+#include "PdfDefines.h"
 #include "PdfDefinesPrivate.h"
 
# #ifndef SIZE_MAX
 namespace PoDoFo {
Index: src/base/PdfMemoryManagement.h
===================================================================
--- src/base/PdfMemoryManagement.h	(revision 1792)
+++ src/base/PdfMemoryManagement.h	(revision 1793)
@@ -34,7 +34,10 @@
 #ifndef _PDF_MEMORY_MANAGEMENT_H_
 #define _PDF_MEMORY_MANAGEMENT_H_
 
-#include "PdfDefines.h"
+// PdfMemoryManagement.h should not include PdfDefines.h, since it is included by it.
+// It should avoid depending on anything defined in PdfDefines.h .
+
+#include "podofoapi.h"
 #include <stdlib.h>
 
 namespace PoDoFo {
@@ -75,5 +78,5 @@
 
 };
 
-#endif // _PDF_XREF_STREAM_PARSER_OBJECT_H_
+#endif // _PDF_MEMORY_MANAGEMENT_H_
 
Index: src/base/PdfName.cpp
===================================================================
--- src/base/PdfName.cpp	(revision 1792)
+++ src/base/PdfName.cpp	(revision 1793)
@@ -176,7 +176,10 @@
 
 PdfName PdfName::FromEscaped( const char * pszName, pdf_long ilen )
 {
-    if( !ilen && pszName )
+    if( !pszName )
+        return PdfName();
+
+    if( !ilen )
         ilen = strlen( pszName );
 
     return PdfName(UnescapeName(pszName, ilen));
Index: src/base/PdfObject.cpp
===================================================================
--- src/base/PdfObject.cpp	(revision 1792)
+++ src/base/PdfObject.cpp	(revision 1793)
@@ -44,7 +44,6 @@
 
 #include <sstream>
 #include <fstream>
-#include <cassert>
 
 #include <string.h>
 
@@ -143,8 +142,8 @@
 
 #if defined(PODOFO_EXTRA_CHECKS)
     // Must've been demand loaded or already done
-    assert(DelayedLoadDone());
-    assert(DelayedStreamLoadDone());
+    PODOFO_ASSERT( DelayedLoadDone() );
+    PODOFO_ASSERT( DelayedStreamLoadDone() );
 #endif
 }
 
@@ -323,8 +322,8 @@
 
 #if defined(PODOFO_EXTRA_CHECKS)
     // Must've been demand loaded or already done
-    assert(DelayedLoadDone());
-    assert(DelayedStreamLoadDone());
+    PODOFO_ASSERT( DelayedLoadDone() );
+    PODOFO_ASSERT( DelayedStreamLoadDone() );
 #endif
 
     return *this;
Index: src/base/PdfObjectStreamParserObject.cpp
===================================================================
--- src/base/PdfObjectStreamParserObject.cpp	(revision 1792)
+++ src/base/PdfObjectStreamParserObject.cpp	(revision 1793)
@@ -76,7 +76,7 @@
         delete m_vecObjects->RemoveObject( m_pParser->Reference() );
         m_pParser = NULL;
 
-    } catch( const PdfError & rError ) {
+    } catch( PdfError & rError ) {
#         podofo_free( pBuffer );
         free( pBuffer );
         throw rError;
     }
Index: src/base/PdfOutputStream.cpp
===================================================================
--- src/base/PdfOutputStream.cpp	(revision 1792)
+++ src/base/PdfOutputStream.cpp	(revision 1793)
@@ -51,6 +51,11 @@
     }
 }
 
+PdfFileOutputStream::~PdfFileOutputStream()
+{
+    Close();
+}
+
 pdf_long PdfFileOutputStream::Write( const char* pBuffer, pdf_long lLen )
 {
     return fwrite( pBuffer, sizeof(char), lLen, m_hFile );
@@ -58,8 +63,11 @@
 
 void PdfFileOutputStream::Close() 
 {
-    if( m_hFile ) 
+    if( m_hFile )
+    {
         fclose( m_hFile );
+        m_hFile = NULL;
+    }
 }
 
 PdfMemoryOutputStream::PdfMemoryOutputStream( pdf_long lInitial )
Index: src/base/PdfOutputStream.h
===================================================================
--- src/base/PdfOutputStream.h	(revision 1792)
+++ src/base/PdfOutputStream.h	(revision 1793)
@@ -93,6 +93,8 @@
      */
     PdfFileOutputStream( const char* pszFilename );
 
+    virtual ~PdfFileOutputStream();
+
     /** Write data to the output stream
      *  
      *  \param pBuffer the data is read from this buffer
Index: src/base/PdfParser.cpp
===================================================================
--- src/base/PdfParser.cpp	(revision 1792)
+++ src/base/PdfParser.cpp	(revision 1793)
@@ -952,6 +952,9 @@
         {
             i = pEncrypt->GetReference().ObjectNumber();
             pObject = new PdfParserObject( m_vecObjects, m_device, m_buffer, m_offsets[i].lOffset );
+            if( !pObject )
+                PODOFO_RAISE_ERROR( ePdfError_OutOfMemory );
+
             pObject->SetLoadOnDemand( false ); // Never load this on demand, as we will use it immediately
             try {
                 pObject->ParseFile( NULL ); // The encryption dictionary is not encrypted :)
@@ -963,12 +966,9 @@
                 delete pObject;
             } catch( PdfError & e ) {
                 std::ostringstream oss;
-                if( pObject )
-                {
-                    oss << "Error while loading object " << pObject->Reference().ObjectNumber() << " " 
-                        << pObject->Reference().GenerationNumber() << std::endl;
-                    delete pObject;
-                }
+                oss << "Error while loading object " << pObject->Reference().ObjectNumber() << " " 
+                    << pObject->Reference().GenerationNumber() << std::endl;
+                delete pObject;
 
                 e.AddToCallstack( __FILE__, __LINE__, oss.str().c_str() );
                 throw e;
@@ -1024,6 +1024,9 @@
             //printf("Reading object %i 0 R from %li\n", i, m_offsets[i].lOffset );
             
             pObject = new PdfParserObject( m_vecObjects, m_device, m_buffer, m_offsets[i].lOffset );
+            if( !pObject )
+                PODOFO_RAISE_ERROR( ePdfError_OutOfMemory );
+
             pObject->SetLoadOnDemand( m_bLoadOnDemand );
             try {
# 				pObject->ParseFile( m_pEncrypt );
                 pObject->ParseFile( m_pEncrypt );
@@ -1062,14 +1065,11 @@
                     m_vecObjects->push_back( pObject );
             } catch( PdfError & e ) {
                 std::ostringstream oss;
-                if( pObject )
-                {
-                    oss << "Error while loading object " << pObject->Reference().ObjectNumber() 
-                        << " " << pObject->Reference().GenerationNumber() 
-                        << " Offset = " << m_offsets[i].lOffset
-                        << " Index = " << i << std::endl;
-                    delete pObject;
-                }
+                oss << "Error while loading object " << pObject->Reference().ObjectNumber() 
+                    << " " << pObject->Reference().GenerationNumber() 
+                    << " Offset = " << m_offsets[i].lOffset
+                    << " Index = " << i << std::endl;
+                delete pObject;
 
                 if( m_bIgnoreBrokenObjects ) 
                 {
Index: src/base/PdfParserObject.cpp
===================================================================
--- src/base/PdfParserObject.cpp	(revision 1792)
+++ src/base/PdfParserObject.cpp	(revision 1793)
@@ -43,7 +43,6 @@
 #include "PdfVariant.h"
 #include "PdfDefinesPrivate.h"
 
-#include <cassert>
 #include <iostream>
 #include <sstream>
 
@@ -177,8 +176,8 @@
 void PdfParserObject::ParseFileComplete( bool bIsTrailer )
 {
 #if defined(PODOFO_EXTRA_CHECKS)
-    assert(DelayedLoadInProgress());
-    assert(!DelayedLoadDone());
+    PODOFO_ASSERT( DelayedLoadInProgress() );
+    PODOFO_ASSERT( !DelayedLoadDone() );
 #endif
     const char* pszToken;
 
@@ -244,9 +243,9 @@
 void PdfParserObject::ParseStream()
 {
 #if defined(PODOFO_EXTRA_CHECKS)
-    assert(DelayedLoadDone());
-    assert(DelayedStreamLoadInProgress());
-    assert(!DelayedStreamLoadDone());
+    PODOFO_ASSERT( DelayedLoadDone() );
+    PODOFO_ASSERT( DelayedStreamLoadInProgress() );
+    PODOFO_ASSERT( !DelayedStreamLoadDone() );
 #endif
 
#     pdf_int64         lLen  = -1;
     long long         lLen  = -1;
@@ -365,8 +364,8 @@
 #if defined(PODOFO_EXTRA_CHECKS)
     // DelayedLoadImpl() should only ever be called via DelayedLoad(),
     // which ensures that it is never called repeatedly.
-    assert(!DelayedLoadDone());
-    assert(DelayedLoadInProgress());
+    PODOFO_ASSERT( !DelayedLoadDone() );
+    PODOFO_ASSERT( DelayedLoadInProgress() );
 #endif
 
     ParseFileComplete( m_bIsTrailer );
@@ -381,12 +380,12 @@
     // DelayedLoad() must've been called, either directly earlier
     // or via DelayedStreamLoad. DelayedLoad() will throw if the load
     // failed, so if we're being called this condition must be true.
-    assert(DelayedLoadDone());
+    PODOFO_ASSERT( DelayedLoadDone() );
 
     // Similarly, we should not be being called unless the stream isn't
     // already loaded.
-    assert(!DelayedStreamLoadDone());
-    assert(DelayedStreamLoadInProgress());
+    PODOFO_ASSERT( !DelayedStreamLoadDone() );
+    PODOFO_ASSERT( DelayedStreamLoadInProgress() );
 #endif
 
     // Note: we can't use HasStream() here because it'll call DelayedStreamLoad()
Index: src/base/PdfRefCountedInputDevice.cpp
===================================================================
--- src/base/PdfRefCountedInputDevice.cpp	(revision 1792)
+++ src/base/PdfRefCountedInputDevice.cpp	(revision 1793)
@@ -39,7 +39,7 @@
 
     try {
         m_pDevice->m_pDevice = new PdfInputDevice( pszFilename );
-    } catch( const PdfError & rError ) {
+    } catch( PdfError & rError ) {
         delete m_pDevice;
         throw rError;
     }
@@ -56,7 +56,7 @@
 
     try {
         m_pDevice->m_pDevice = new PdfInputDevice( pszFilename );
-    } catch( const PdfError & rError ) {
+    } catch( PdfError & rError ) {
         delete m_pDevice;
         throw rError;
     }
@@ -73,7 +73,7 @@
 
     try {
         m_pDevice->m_pDevice   = new PdfInputDevice( pBuffer, lLen );
-    } catch( const PdfError & rError ) {
+    } catch( PdfError & rError ) {
         delete m_pDevice;
         throw rError;
     }
Index: src/base/PdfStream.cpp
===================================================================
--- src/base/PdfStream.cpp	(revision 1792)
+++ src/base/PdfStream.cpp	(revision 1793)
@@ -71,7 +71,7 @@
             pDecodeStream->Write( const_cast<char*>(this->GetInternalBuffer()), this->GetInternalBufferSize() );
             pDecodeStream->Close();
         }
-        catch( const PdfError & e ) 
+        catch( PdfError & e ) 
         {
             delete pDecodeStream;
             throw e;
Index: src/base/PdfString.cpp
===================================================================
--- src/base/PdfString.cpp	(revision 1792)
+++ src/base/PdfString.cpp	(revision 1793)
@@ -1108,7 +1108,7 @@
             target += bytesToWrite;
         }
     }
-    catch( const PdfError & e ) 
+    catch( PdfError & e ) 
     {
         if( bOwnBuf )
             delete[] const_cast<pdf_utf16be *>(pszUtf16);
Index: src/base/PdfVariant.h
===================================================================
--- src/base/PdfVariant.h	(revision 1792)
+++ src/base/PdfVariant.h	(revision 1793)
@@ -1037,7 +1037,7 @@
 {
     if(m_bImmutable) 
     {
#-        throw PdfError( ePdfError_ChangeOnImmutable );
-        throw new PdfError( ePdfError_ChangeOnImmutable );
+        PODOFO_RAISE_ERROR( ePdfError_ChangeOnImmutable );
     }
 }
 
#Index: src/base/PdfWriter.cpp
#===================================================================
#--- src/base/PdfWriter.cpp	(revision 1792)
#+++ src/base/PdfWriter.cpp	(revision 1793)
#@@ -234,20 +234,36 @@
#     // is positioned at the end of the original file by the caller
#     if( pSourceInputDevice )
#     {
#-        #define BUFFER_SIZE 16384
#-
#         // copy the original file content first
#-        char pBuffer[ BUFFER_SIZE ];
#+        unsigned int uBufferLen = 65535;
#+        char *pBuffer;
# 
#-        pSourceInputDevice->Seek(0);
#-
#-        while( !pSourceInputDevice->Eof() )
#+        while( pBuffer = reinterpret_cast<char *>( podofo_malloc( sizeof( char ) * uBufferLen) ), !pBuffer )
#         {
#-            std::streamoff didRead;
#+            uBufferLen = uBufferLen / 2;
#+            if( !uBufferLen )
#+                break;
#+        }
# 
#-            didRead = pSourceInputDevice->Read( pBuffer, BUFFER_SIZE );
#-            if( didRead > 0)
#-                pDevice->Write( pBuffer, didRead );
#+        if( !pBuffer )
#+            PODOFO_RAISE_ERROR (ePdfError_OutOfMemory);
#+
#+        try {
#+            pSourceInputDevice->Seek(0);
#+
#+            while( !pSourceInputDevice->Eof() )
#+            {
#+                std::streamoff didRead;
#+
#+                didRead = pSourceInputDevice->Read( pBuffer, uBufferLen );
#+                if( didRead > 0)
#+                    pDevice->Write( pBuffer, didRead );
#+            }
#+
#+            podofo_free( pBuffer );
#+        } catch( PdfError & e ) {
#+            podofo_free( pBuffer );
#+            throw e;
#         }
#     }
# 
Index: src/base/PdfXRef.cpp
===================================================================
--- src/base/PdfXRef.cpp	(revision 1792)
+++ src/base/PdfXRef.cpp	(revision 1793)
@@ -92,7 +92,8 @@
     return false;
 }
 
-PdfXRef::PdfXRef() 
+PdfXRef::PdfXRef()
+    : m_offset( 0 )
 {
 
 }
Index: src/base/util/PdfMutexWrapper.h
===================================================================
--- src/base/util/PdfMutexWrapper.h	(revision 1792)
+++ src/base/util/PdfMutexWrapper.h	(revision 1793)
@@ -89,7 +89,7 @@
     try {
 	m_rMutex.UnLock();
     }
-    catch( const PdfError & rError ) 
+    catch( PdfError & rError ) 
     {
 	rError.PrintErrorMsg();
         throw rError;
Index: src/doc/PdfDocument.cpp
===================================================================
--- src/doc/PdfDocument.cpp	(revision 1792)
+++ src/doc/PdfDocument.cpp	(revision 1793)
@@ -544,7 +544,7 @@
                         }
                         else
                         {
-                            throw ePdfError_InvalidStream;
+                            PODOFO_RAISE_ERROR( ePdfError_InvalidStream );
                             break;
                         }
                     }
#Index: src/doc/PdfDocument.h
#===================================================================
#--- src/doc/PdfDocument.h	(revision 1792)
#+++ src/doc/PdfDocument.h	(revision 1793)
#@@ -694,8 +694,6 @@
## 
##     PdfOutlines*    m_pOutlines;
##     PdfNamesTree*   m_pNamesTree;
#     PdfNamesTree*   m_pNamesTree;
#     PdfPagesTree*   m_pPagesTree;
#     PdfAcroForm*    m_pAcroForms;
#-
#-    EPdfVersion     m_eVersion;
# };
# 
# // -----------------------------------------------------
Index: src/doc/PdfFontCID.cpp
===================================================================
--- src/doc/PdfFontCID.cpp	(revision 1792)
+++ src/doc/PdfFontCID.cpp	(revision 1793)
@@ -118,6 +118,7 @@
# PdfFontCID::PdfFontCID( PdfFontMetrics* pMetrics, const PdfEncoding* const pEncoding, PdfObject* pObject, bool PODOFO_UNUSED_PARAM(bEmbed) )
#     : PdfFont( pMetrics, pEncoding, pObject ), m_pDescendantFonts( NULL )
# {
                         PdfVecObjects* pParent, bool bEmbed )
     : PdfFont( pMetrics, pEncoding, pParent )
 {
+    m_pDescriptor = NULL;
#     /* this->Init( bEmbed, false ); No changes to dictionary */
#     m_bWasEmbedded = true; /* embedding on this path is not allowed at all, so
#                             pretend like it's already done */
     this->Init( bEmbed );
 }
 
@@ -127,6 +128,8 @@
#                         PdfVecObjects* pParent, bool bEmbed, bool bSubset )
#     : PdfFont( pMetrics, pEncoding, pParent ), m_pDescendantFonts( NULL )
# {
 PdfFontCID::PdfFontCID( PdfFontMetrics* pMetrics, const PdfEncoding* const pEncoding, PdfObject* pObject, bool )
     : PdfFont( pMetrics, pEncoding, pObject )
 {
+    m_pDescriptor = NULL;
+
#     this->Init( bEmbed, bSubset );
# }
# 
     /* this->Init( bEmbed ); */
 }
 
Index: src/doc/PdfFontConfigWrapper.cpp
===================================================================
--- src/doc/PdfFontConfigWrapper.cpp	(revision 1792)
+++ src/doc/PdfFontConfigWrapper.cpp	(revision 1793)
@@ -57,6 +57,7 @@
 }
 
 PdfFontConfigWrapper::PdfFontConfigWrapper(const PdfFontConfigWrapper & rhs)
+    : m_pFontConfig( NULL )
 {
     this->operator=(rhs);
 }
Index: src/doc/PdfFontMetricsBase14.cpp
===================================================================
--- src/doc/PdfFontMetricsBase14.cpp	(revision 1792)
+++ src/doc/PdfFontMetricsBase14.cpp	(revision 1793)
@@ -144,7 +144,7 @@
 const char* PdfFontMetricsBase14::GetFontname() const 
 {
 #ifdef MYASSERT
-    assert(font_name != NULL);
+    PODOFO_ASSERT(font_name != NULL);
 #endif
     return font_name;
 }
Index: src/doc/PdfFontMetricsObject.cpp
===================================================================
--- src/doc/PdfFontMetricsObject.cpp	(revision 1792)
+++ src/doc/PdfFontMetricsObject.cpp	(revision 1793)
@@ -46,6 +46,8 @@
     : PdfFontMetrics( ePdfFontType_Unknown, "", NULL ),
       m_pEncoding( pEncoding ), m_dDefWidth(0.0)
 {
+    m_missingWidth = NULL;
+
#     const PdfName & rSubType = pFont->GetDictionary().GetKey( PdfName::KeySubtype )->GetName();
# 
#     // OC 15.08.2010 BugFix: /FirstChar /LastChar /Widths are in the Font dictionary and not in the FontDescriptor
     if( !pDescriptor )
     {
         PODOFO_RAISE_ERROR( ePdfError_InvalidHandle );
@@ -85,8 +87,8 @@
#             if( widths == NULL ) 
#             {
#                 PODOFO_RAISE_ERROR_INFO( ePdfError_NoObject, "Font object defines neither Widths, nor MissingWidth values!" );
#-                m_missingWidth = widths;
#             }
#+            m_missingWidth = widths;
#         }
# 	} else if ( rSubType == PdfName("CIDFontType0") || rSubType == PdfName("CIDFontType2") ) {
# 		PdfObject *pObj = pDescriptor->GetIndirectKey( "FontName" );
         if( widths == NULL ) 
         {
             PODOFO_RAISE_ERROR_INFO( ePdfError_NoObject, "Font object defines neither Widths, nor MissingWidth values!" );
-            m_missingWidth = widths;
         }
+        m_missingWidth = widths;
     }
 	} else if ( rSubType == PdfName("CIDFontType0") || rSubType == PdfName("CIDFontType2") ) {
 		PdfObject *pObj = pDescriptor->GetIndirectKey( "FontName" );
Index: src/doc/PdfFontSimple.cpp
===================================================================
--- src/doc/PdfFontSimple.cpp	(revision 1792)
+++ src/doc/PdfFontSimple.cpp	(revision 1793)
@@ -56,6 +56,11 @@
 
 void PdfFontSimple::Init( bool bEmbed, const PdfName & rsSubType )
 {
+    if( !m_pEncoding )
+    {
+        PODOFO_RAISE_ERROR( ePdfError_InvalidHandle );
+    }
+
     PdfObject*    pWidth;
     PdfObject*    pDescriptor;
     PdfVariant    var;
#Index: src/doc/PdfFontTTFSubset.cpp
#===================================================================
#--- src/doc/PdfFontTTFSubset.cpp	(revision 1792)
#+++ src/doc/PdfFontTTFSubset.cpp	(revision 1793)
#@@ -173,7 +173,7 @@
#         if (it->tag == tag)
#             return it->offset;
#     }
#-    throw PdfError(ePdfError_InternalLogic, __FILE__, __LINE__, "table missing");
#+    PODOFO_RAISE_ERROR_INFO( ePdfError_InternalLogic, "table missing" );
# }
# 
# void PdfFontTTFSubset::GetNumberOfGlyphs()
#@@ -278,7 +278,7 @@
#     }
#     if ((tableMask & 0x3f )!= 0x3f) {
#         //std::cout << "ttfTables=" << std::hex << tableMask << std::dec << std::endl;
#-        throw PdfError(ePdfError_UnsupportedFontFormat, __FILE__, __LINE__, "Required TrueType table missing");
#+        PODOFO_RAISE_ERROR_INFO( ePdfError_UnsupportedFontFormat, "Required TrueType table missing" );
#     }
#     if ((tableMask & 0x0100 ) == 0x00) {
#         tbl.tag = TTAG_cmap;
#@@ -311,7 +311,7 @@
#         break;
#         case eFontFileType_Unknown:
#         default:
#-            throw PdfError(ePdfError_InternalLogic, __FILE__, __LINE__, "Invalid font type");
#+            PODOFO_RAISE_ERROR_INFO( ePdfError_InternalLogic, "Invalid font type" );
#     }
# }
# 
#@@ -407,7 +407,7 @@
#         }
#         return;
#     }
#-    throw PdfError(ePdfError_InternalLogic, __FILE__, __LINE__, "GID out of range");
#+    PODOFO_RAISE_ERROR_INFO( ePdfError_InternalLogic, "GID out of range" );
# }
# 
# void PdfFontTTFSubset::LoadCompound(GlyphContext& ctx, unsigned long offset)
#@@ -522,7 +522,7 @@
#     CodePointToGid::const_iterator it = usedCodes.lower_bound(gid);
#     do {
#         if (it == usedCodes.end()) {
#-            throw PdfError(ePdfError_InternalLogic, __FILE__, __LINE__, "Unexpected");
#+            PODOFO_RAISE_ERROR_INFO( ePdfError_InternalLogic, "Unexpected" );
#         }
#         m_sCMap.glyphArray.push_back(it->second);
#         ++it;
#@@ -811,8 +811,8 @@
#     //std::cout << " finalSize=" << tableOffset << " alloced=" << fontData.GetSize() << std::endl;
#     /* head table */
#     if (!headOffset) {
#-        throw PdfError(ePdfError_InternalLogic, __FILE__, __LINE__, "'head' table missing");
#-            }
#+        PODOFO_RAISE_ERROR_INFO( ePdfError_InternalLogic, "'head' table missing" );
#+    }
#     TTFWriteUInt32(bufp + headOffset + 8, TableCheksum(bufp, tableLength) - 0xB1B0AFBA);
# }
# 	    
Index: src/doc/PdfFontType1.cpp
===================================================================
--- src/doc/PdfFontType1.cpp	(revision 1792)
+++ src/doc/PdfFontType1.cpp	(revision 1793)
@@ -147,10 +147,25 @@
             PODOFO_RAISE_ERROR_INFO( ePdfError_FileNotFound, m_pMetrics->GetFilename() );
         }
 
-        fseek( hFile, 0L, SEEK_END );
-        lSize = ftell( hFile );
-        fseek( hFile, 0L, SEEK_SET );
+        if( fseeko( hFile, 0L, SEEK_END ) == -1 )
+        {
+            fclose( hFile );
+            PODOFO_RAISE_ERROR_INFO( ePdfError_InvalidDeviceOperation, "Failed to seek to the end of the file" );
+        }
 
+        lSize = ftello( hFile );
+        if( lSize == -1 )
+        {
+            fclose( hFile );
+            PODOFO_RAISE_ERROR_INFO( ePdfError_InvalidDeviceOperation, "Failed to read size of the file" );
+        }
+
+        if( fseeko( hFile, 0L, SEEK_SET ) == -1 )
+        {
+            fclose( hFile );
+            PODOFO_RAISE_ERROR_INFO( ePdfError_InvalidDeviceOperation, "Failed to seek to the beginning of the file" );
+        }
+
#         pAllocated = static_cast<char*>(podofo_calloc( lSize, sizeof(char) ));
         pAllocated = static_cast<char*>(malloc( sizeof(char) * lSize ));
         if( !pAllocated )
         {
@@ -158,7 +173,14 @@
             PODOFO_RAISE_ERROR( ePdfError_OutOfMemory );
         }
 
-        fread( pAllocated, sizeof(char), lSize, hFile );
+        if( static_cast<pdf_long>( fread( pAllocated, sizeof( char ), lSize, hFile ) ) != lSize )
+        {
+            podofo_free( pAllocated );
+            fclose( hFile );
+
+            PODOFO_RAISE_ERROR_INFO( ePdfError_InvalidDeviceOperation, "Failed to read whole file into the memory" );
+        }
+
         fclose( hFile );
 
         pBuffer = pAllocated;
@@ -437,10 +459,25 @@
             PODOFO_RAISE_ERROR_INFO( ePdfError_FileNotFound, m_pMetrics->GetFilename() );
         }
 
-        fseek( hFile, 0L, SEEK_END );
-        lSize = ftell( hFile );
-        fseek( hFile, 0L, SEEK_SET );
+        if( fseeko( hFile, 0L, SEEK_END ) == -1 )
+        {
+            fclose( hFile );
+            PODOFO_RAISE_ERROR_INFO( ePdfError_InvalidDeviceOperation, "Failed to seek to the end of the file" );
+        }
 
+        lSize = ftello( hFile );
+        if( lSize == -1 )
+        {
+            fclose( hFile );
+            PODOFO_RAISE_ERROR_INFO( ePdfError_InvalidDeviceOperation, "Failed to read size of the file" );
+        }
+
+        if( fseeko( hFile, 0L, SEEK_SET ) == -1 )
+        {
+            fclose( hFile );
+            PODOFO_RAISE_ERROR_INFO( ePdfError_InvalidDeviceOperation, "Failed to seek to the beginning of the file" );
+        }
+
#         pAllocated = static_cast<char*>(podofo_calloc( lSize, sizeof(char) ));
         pAllocated = static_cast<char*>(malloc( sizeof(char) * lSize ));
         if( !pAllocated )
         {
@@ -448,7 +485,14 @@
             PODOFO_RAISE_ERROR( ePdfError_OutOfMemory );
         }
 
-        fread( pAllocated, sizeof(char), lSize, hFile );
+        if( static_cast<pdf_long>( fread( pAllocated, sizeof( char ), lSize, hFile ) ) != lSize )
+        {
+            podofo_free( pAllocated );
+            fclose( hFile );
+
+            PODOFO_RAISE_ERROR_INFO( ePdfError_InvalidDeviceOperation, "Failed to read whole file into the memory" );
+        }
+
         fclose( hFile );
 
         pBuffer = pAllocated;
Index: src/doc/PdfFontType1Base14.cpp
===================================================================
--- src/doc/PdfFontType1Base14.cpp	(revision 1792)
+++ src/doc/PdfFontType1Base14.cpp	(revision 1793)
@@ -71,6 +71,11 @@
 {
     PdfVariant    var;
     
+    if( !m_pEncoding )
+    {
+        PODOFO_RAISE_ERROR( ePdfError_InvalidHandle );
+    }
+
     this->GetObject()->GetDictionary().AddKey( PdfName::KeySubtype, PdfName("Type1"));
#     this->GetObject()->GetDictionary().AddKey("BaseFont", PdfName( pMetrics->GetFontname() ) );
# 
     this->GetObject()->GetDictionary().AddKey("BaseFont", this->GetBaseFont() );
		 
#Index: src/doc/PdfIdentityEncoding.cpp
#===================================================================
#--- src/doc/PdfIdentityEncoding.cpp	(revision 1792)
#+++ src/doc/PdfIdentityEncoding.cpp	(revision 1793)
#@@ -127,8 +127,9 @@
#     else
#     {
#         PODOFO_RAISE_ERROR( ePdfError_InvalidHandle );
#-        return PdfRefCountedBuffer();
#     }
#+
#+    return PdfRefCountedBuffer();
# }
#     
# }; /* namespace PoDoFo */
Index: src/doc/PdfImage.cpp
===================================================================
--- src/doc/PdfImage.cpp	(revision 1792)
+++ src/doc/PdfImage.cpp	(revision 1793)
@@ -857,8 +857,8 @@
# {
#     FILE* hFile = pInStream->GetHandle();
#     png_byte header[8];
#-    fread(header, 1, 8, hFile);
#-    if( png_sig_cmp(header, 0, 8) )
#+    if( fread( header, 1, 8, hFile ) != 8 ||
#+        png_sig_cmp( header, 0, 8 ) )
#     {
#         PODOFO_RAISE_ERROR_INFO( ePdfError_UnsupportedImageFormat, "The file could not be recognized as a PNG file." );
#     }
     }
 
     png_byte header[8];
-    fread(header, 1, 8, hFile);
-    if( png_sig_cmp(header, 0, 8) )
+    if( fread( header, 1, 8, hFile ) != 8 ||
+        png_sig_cmp( header, 0, 8 ) )
     {
         fclose( hFile );
         PODOFO_RAISE_ERROR_INFO( ePdfError_UnsupportedImageFormat, "The file could not be recognized as a PNG file." );
Index: src/doc/PdfPagesTree.cpp
===================================================================
--- src/doc/PdfPagesTree.cpp	(revision 1792)
+++ src/doc/PdfPagesTree.cpp	(revision 1793)
@@ -836,7 +836,7 @@
     }
 
     // we should never exit from here - we should always have been able to return a page from above
-    // assert( false ) ;
+    // PODOFO_ASSERT( false ) ;
     return NULL;
 }
 */
Index: src/doc/PdfPainter.cpp
===================================================================
--- src/doc/PdfPainter.cpp	(revision 1792)
+++ src/doc/PdfPainter.cpp	(revision 1793)
@@ -146,7 +146,7 @@
         PdfError::LogMessage( eLogSeverity_Error, 
                               "PdfPainter::~PdfPainter(): FinishPage() has to be called after a page is completed!" );
 
-    assert(!m_pCanvas);
+    PODOFO_ASSERT( !m_pCanvas );
 }
 
 void PdfPainter::SetPage( PdfCanvas* pPage )
@@ -187,7 +187,7 @@
 	try { 
 		if( m_pCanvas )
 			m_pCanvas->EndAppend();
-	} catch( const PdfError & e ) {
+	} catch( PdfError & e ) {
 	    // clean up, even in case of error
 		m_pCanvas = NULL;
 		m_pPage   = NULL;
@@ -994,11 +994,11 @@
     // fast and easy individual characters access    
     const std::string& stringUtf8 = rsText.GetStringUtf8();
     std::vector<pdf_utf16be> stringUtf16(stringUtf8.length() + 1, 0);
-	assert(stringUtf16.size() > 0);	
+    PODOFO_ASSERT( stringUtf16.size() > 0 );
     const pdf_long converted = PdfString::ConvertUTF8toUTF16(
 	    reinterpret_cast<const pdf_utf8*>(stringUtf8.c_str()), &stringUtf16[0], stringUtf16.size());
 	//const pdf_long len = rsText.GetCharacterLength();
-    assert( converted == (rsText.GetCharacterLength() + 1) );
+    PODOFO_ASSERT( converted == (rsText.GetCharacterLength() + 1) );
 
 	const pdf_utf16be* const stringUtf16Begin = &stringUtf16[0];
     const pdf_utf16be* pszLineBegin = stringUtf16Begin;
Index: test/ContentParser/main.cpp
===================================================================
--- test/ContentParser/main.cpp	(revision 1792)
+++ test/ContentParser/main.cpp	(revision 1793)
@@ -173,7 +173,7 @@
             cout << " - page ok" << endl;
         }
     }
-    catch( const PdfError & e )
+    catch( PdfError & e )
     {
         e.PrintErrorMsg();
         return e.GetError();
Index: test/CreationTest/CreationTest.cpp
===================================================================
--- test/CreationTest/CreationTest.cpp	(revision 1792)
+++ test/CreationTest/CreationTest.cpp	(revision 1793)
@@ -20,8 +20,9 @@
 
 #include "../PdfTest.h"
 
-#include <stdlib.h>
+#include <cstdlib>
 #include <cstdio>
+#include <iostream>
 
 using namespace PoDoFo;
 
@@ -36,7 +37,7 @@
     pdf_long  lLen    = 0;
     char* pBuffer = NULL;
 
-    std::auto_ptr<PdfFilter> pFilter = PdfFilterFactory::Create( ePdfFilter_ASCIIHexDecode );    
+    std::auto_ptr<PdfFilter> pFilter = PdfFilterFactory::Create( ePdfFilter_ASCIIHexDecode );
     pFilter->Encode( buffer.GetBuffer(), buffer.GetSize(), &pBuffer, &lLen );
 
     oss << "<";
@@ -49,7 +50,7 @@
# void CreateUnicodeAnnotationText( PdfPage* pPage, PdfDocument* /*pDocument*/ )
 void CreateUnicodeAnnotationText( PdfPage* pPage, PdfDocument* pDocument )
 {
     PdfString sJap(reinterpret_cast<const pdf_utf8*>("「PoDoFo」は今から日本語も話せます。"));
-    PdfAnnotation* pAnnotation = 
+    PdfAnnotation* pAnnotation =
         pPage->CreateAnnotation( ePdfAnnotation_Text, PdfRect( 400.0, 200.0, 20.0, 20.0 ) );
 
     PdfString sGerman(reinterpret_cast<const pdf_utf8*>("Unicode Umlauts: ÄÖÜß"));
@@ -61,12 +62,12 @@
 void CreateUnicodeAnnotationFreeText( PdfPage* pPage, PdfDocument* pDocument )
 {
     PdfString sJap(reinterpret_cast<const pdf_utf8*>("「PoDoFo」は今から日本語も話せます。"));
#-    PdfFont* pFont = pDocument->CreateFont( "Arial Unicode MS", false, new PdfIdentityEncoding( 0, 0xffff, true ) ); 
-    PdfFont* pFont = pDocument->CreateFont( "Arial Unicode MS", new PdfIdentityEncoding( 0, 0xffff, true ) ); 
#+    PdfFont* pFont = pDocument->CreateFont( "Arial Unicode MS", false, new PdfIdentityEncoding( 0, 0xffff, true ) );
+    PdfFont* pFont = pDocument->CreateFont( "Arial Unicode MS", new PdfIdentityEncoding( 0, 0xffff, true ) );
 
     PdfRect rect( 200.0, 200.0, 200.0, 200.0 );
     /*
     PdfXObject xObj( rect, pDocument );
-    
+
     PdfPainter painter;
     painter.SetPage( &xObj );
     painter.SetFont( pFont );
@@ -90,7 +91,7 @@
     PdfDictionary resources;
     resources.AddKey( PdfName("Fonts"), fonts );
 
-    PdfAnnotation* pAnnotation = 
+    PdfAnnotation* pAnnotation =
         pPage->CreateAnnotation( ePdfAnnotation_FreeText, rect );
 
     PdfString sGerman(reinterpret_cast<const pdf_utf8*>("Unicode Umlauts: ÄÖÜß"));
@@ -99,8 +100,8 @@
     //pAnnotation->SetAppearanceStream( &xObj );
     pAnnotation->GetObject()->GetDictionary().AddKey( PdfName("DA"), PdfString(oss.str()) );
     pAnnotation->GetObject()->GetDictionary().AddKey( PdfName("DR"), resources );
-    
 
+
 }
 
 void LineTest( PdfPainter* pPainter, PdfPage* pPage, PdfDocument* pDocument )
@@ -265,10 +266,10 @@
 
     double dStroke = 0.01;
     double dLine   = pPainter->GetFont()->GetFontMetrics()->GetLineSpacing();
#-    for( i=0;i<23; i++ ) 
-    for( int i=0;i<23; i++ ) 
+    for( i=0;i<23; i++ )
     {
         sprintf( buffer, "Linewidth: %.3fpt", dStroke );
-        pPainter->DrawText( x, y, PdfString( buffer ) ); 
+        pPainter->DrawText( x, y, PdfString( buffer ) );
 
         pPainter->Save();
         pPainter->SetStrokeWidth( dStroke );
@@ -281,7 +282,7 @@
 
         pPainter->Restore();
         dStroke += 0.05;
- 
+
         y -= dLine*2.0;
     }
 }
@@ -400,7 +401,7 @@
 
     pPainter->SetColor( 0.0, 0.0, 0.0 );
     pPainter->DrawText( x, y, "Hallo Welt!" );
-    
+
     y -= pPainter->GetFont()->GetFontMetrics()->GetLineSpacing();
     pPainter->GetFont()->SetUnderlined( true );
     pPainter->SetStrokingColor( 1.0, 0.0, 0.0 );
@@ -410,10 +411,10 @@
     y -= pPainter->GetFont()->GetFontMetrics()->GetLineSpacing();
     pPainter->DrawText( x, y, "Disabled the underline again..." );
     y -= pPainter->GetFont()->GetFontMetrics()->GetLineSpacing();
-    
+
     PdfFont* pFont = pDocument->CreateFont( "Arial" );
     pFont->SetFontSize( 12.0 );
-    
+
     pPainter->SetFont( pFont );
 
     pPainter->DrawText( x, y, "Normal" );
@@ -427,7 +428,7 @@
     pFont->SetFontCharSpace( 100.0 );
     pPainter->DrawText( x, y, "Mormal+spaced" );
     y -= pPainter->GetFont()->GetFontMetrics()->GetLineSpacing();
-	
+
     pPainter->GetFont()->SetUnderlined( true );
     pPainter->DrawText( x, y, "Normal+underlined+spaced" );
     y -= pPainter->GetFont()->GetFontMetrics()->GetLineSpacing();
@@ -452,7 +453,7 @@
     pPainter->DrawText( x, y, "Condensed+spaced" );
     y -= pPainter->GetFont()->GetFontMetrics()->GetLineSpacing();
 
-    
+
     pPainter->GetFont()->SetUnderlined( true );
     pPainter->DrawText( x, y, "Condensed+underlined+spaced" );
     y -= pPainter->GetFont()->GetFontMetrics()->GetLineSpacing();
@@ -469,7 +470,7 @@
     pPainter->GetFont()->SetUnderlined( true );
     pPainter->DrawText( x, y, "Expanded+underlinded" );
     y -= pPainter->GetFont()->GetFontMetrics()->GetLineSpacing();
-    
+
     pPainter->GetFont()->SetUnderlined( false );
     pFont->SetFontCharSpace( 100.0 );
     pPainter->DrawText( x, y, "Expanded+spaced" );
@@ -529,7 +530,7 @@
     pnt.FinishPage();
 
     printf("Drawing on the page!\n");
-    // Draw onto the page 
+    // Draw onto the page
 
 #ifdef PODOFO_HAVE_JPEG_LIB
 	/*
#@@ -602,24 +603,24 @@
# 
#     pPainter->SetColor( 1.0, 0.8, 0.8 );
#     pPainter->Rectangle( x, y - dHeight, dWidth, dHeight );
#     pPainter->Fill();
#-    
#+
#     // Das funktioniert immer
#     PdfXObject xObj1( "resources/Illust.pdf", 0, pDocument );
#-    pPainter->DrawXObject( x + 90000 * CONVERSION_CONSTANT, 
#+    pPainter->DrawXObject( x + 90000 * CONVERSION_CONSTANT,
#                            y - dHeight,
# 						   &xObj1 );
#     pPainter->SetColor( 1.0, 0.0, 0.0 );
#-    pPainter->Rectangle( x + 90000 * CONVERSION_CONSTANT, 
#+    pPainter->Rectangle( x + 90000 * CONVERSION_CONSTANT,
#                         y - dHeight,
#                         1000 * CONVERSION_CONSTANT,
#                         1000 * CONVERSION_CONSTANT );
#     pPainter->Fill();
#-    
# 
#+
#     // Test XObject in XObject
#     PdfRect        rectX( 0, 0, 50000 * CONVERSION_CONSTANT, 50000 * CONVERSION_CONSTANT );
#     PdfXObject     xObj3( rectX, pDocument );
#     PdfXObject     xObj4( rectX, pDocument );
#-    
#+
#     // Draw text onto the XObject3
#     pPainter->SetPage( &xObj3 );
#     pPainter->SetColor( 0.0, 1.0, 0.0 );
@@ -630,7 +631,7 @@
     pPainter->SetColor( 0.0, 0.0, 0.0 );
     pPainter->DrawText( 0, 1000 * CONVERSION_CONSTANT, "I am XObject 3." );
     pPainter->FinishPage();
-    
+
     // Draw text and pdf onto the XObject4
     pPainter->SetPage( &xObj4 );
     pPainter->SetColor( 0.0, 1.0, 0.0 );
@@ -640,21 +641,21 @@
     pPainter->SetColor( 0.0, 0.0, 0.0 );
     pPainter->DrawText( 0, 1000 * CONVERSION_CONSTANT, "I am XObject 4." );
     PdfXObject xObj5( "resources/Illust.pdf", 0, pDocument );
-    pPainter->DrawXObject( 5000 * CONVERSION_CONSTANT, 
-                           5000 * CONVERSION_CONSTANT, 
-                           &xObj5, 
-                           0.1, 
+    pPainter->DrawXObject( 5000 * CONVERSION_CONSTANT,
+                           5000 * CONVERSION_CONSTANT,
+                           &xObj5,
+                           0.1,
                            0.1 );
     pPainter->FinishPage();
-    
-    
+
+
     // Switch back to page and draw Xobject 3+4
     pPainter->SetPage( pPage );
-    pPainter->DrawXObject( 20000 * CONVERSION_CONSTANT, 
-                           y - 60000 * CONVERSION_CONSTANT, 
+    pPainter->DrawXObject( 20000 * CONVERSION_CONSTANT,
+                           y - 60000 * CONVERSION_CONSTANT,
                            &xObj3 );
-    pPainter->DrawXObject( 120000 * CONVERSION_CONSTANT, 
-						   y - 60000 * CONVERSION_CONSTANT, 
+    pPainter->DrawXObject( 120000 * CONVERSION_CONSTANT,
+						   y - 60000 * CONVERSION_CONSTANT,
                            &xObj4 );
 }
 
@@ -706,7 +707,7 @@
     const int nRows = 10;
     PdfSimpleTableModel model( nCols, nRows );
     for(i=0;i<nCols;i++)
-        for(z=0;z<nRows;z++) 
+        for(z=0;z<nRows;z++)
         {
             std::ostringstream oss;
             oss << "Cell " << i << " " << z;
@@ -730,7 +731,7 @@
     model2.SetBackgroundColor( PdfColor( 0.3 ) );
     model2.SetBackgroundEnabled( true );
     for(i=0;i<nCols2;i++)
-        for(z=0;z<nRows2;z++) 
+        for(z=0;z<nRows2;z++)
         {
             std::ostringstream oss;
             oss << rand();
#@@ -739,7 +740,7 @@
# 
#     PdfTable table2( nCols2, nRows2 );
#     table2.SetModel( &model2 );
#-    table2.Draw( dX, dY, pPainter );    
#+    table2.Draw( dX, dY, pPainter );
# }
# 
# void LargeMultiLineTextTest( PdfPainter* pPainter, PdfPage* pPage, PdfDocument* pDocument )
#@@ -776,7 +777,7 @@
#     pPainter->Stroke();
# 
#     pFont->SetFontSize( 12.0 );
#-    pPainter->DrawMultiLineText( x, y, dWidth, dHeight, sMultiLine, ePdfAlignment_Left, ePdfVerticalAlignment_Top );   
#+    pPainter->DrawMultiLineText( x, y, dWidth, dHeight, sMultiLine, ePdfAlignment_Left, ePdfVerticalAlignment_Top );
# 
#     y = y - dHeight - dHeight / 2.0;
# 
#@@ -821,167 +822,173 @@
#     pFont->SetFontSize( 32.0 );
#     pPainter->DrawText(x, y, "Subsetting in action!");
# }
#-    
#-int main( int argc, char* argv[] ) 
#+
#+int main( int argc, char* argv[] )
# {
#-    PdfMemDocument  writer;
#-    //PdfStreamedDocument  writer ( argv[1], ePdfVersion_1_5, &PdfEncrypt( "dominik", "owner" ) );
#-    PdfPage*        pPage;
#-    PdfPainter      painter;
#-    PdfPainterMM    painterMM;
#-    PdfOutlines*    outlines;
#-    PdfOutlineItem* pRoot;
#-    if( argc != 2 )
#-    {
#-        printf("Usage: CreationTest [output_filename]\n");
#-        return 0;
#-    }
#+    try {
#+        PdfMemDocument  writer;
#+        //PdfStreamedDocument  writer ( argv[1], ePdfVersion_1_5, &PdfEncrypt( "dominik", "owner" ) );
#+        PdfPage*        pPage;
#+        PdfPainter      painter;
#+        PdfPainterMM    painterMM;
#+        PdfOutlines*    outlines;
#+        PdfOutlineItem* pRoot;
#+        if( argc != 2 )
#+        {
#+            printf("Usage: CreationTest [output_filename]\n");
#+            return 0;
#+        }
# 
#-    printf("This test tests the PdfWriter and PdfDocument classes.\n");
#-    printf("It creates a new PdfFile from scratch.\n");
#-    printf("---\n");
#+        printf("This test tests the PdfWriter and PdfDocument classes.\n");
#+        printf("It creates a new PdfFile from scratch.\n");
#+        printf("---\n");
# 
#-    printf("PoDoFo DataType Size Information:\n");
#-    printf("---\n");
#-    printf("sizeof variant=%lu\n", sizeof(PdfVariant) );
#-    printf("sizeof object=%lu\n", sizeof(PdfObject) );
#-    printf("sizeof reference=%lu\n", sizeof(PdfReference) );
#-    printf("---\n\n");
#- 
#-    outlines = writer.GetOutlines();
#-    pRoot = outlines->CreateRoot("PoDoFo Test Document" );
#+        printf("PoDoFo DataType Size Information:\n");
#+        printf("---\n");
#+        printf("sizeof variant=%lu\n", sizeof(PdfVariant) );
#+        printf("sizeof object=%lu\n", sizeof(PdfObject) );
#+        printf("sizeof reference=%lu\n", sizeof(PdfReference) );
#+        printf("---\n\n");
# 
#-    pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
#-    painter.SetPage( pPage );
#-    pRoot->CreateChild( "Line Test", PdfDestination( pPage ) );
#+        outlines = writer.GetOutlines();
#+        pRoot = outlines->CreateRoot("PoDoFo Test Document" );
# 
#-    printf("Drawing the first page with various lines.\n");
#-    TEST_SAFE_OP( LineTest( &painter, pPage, &writer ) );
#+        pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
#+        painter.SetPage( pPage );
#+        pRoot->CreateChild( "Line Test", PdfDestination( pPage ) );
# 
#-    pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_Letter ) );
#-    painter.SetPage( pPage );
#+        printf("Drawing the first page with various lines.\n");
#+        TEST_SAFE_OP( LineTest( &painter, pPage, &writer ) );
# 
#-    PdfString sLoremIpsum( pszLoremIpsum );
#+        pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_Letter ) );
#+        painter.SetPage( pPage );
# 
#-    painter.DrawMultiLineText( 50.0, 50.0,
#-                               pPage->GetMediaBox().GetWidth() - 100.0,
#-                               pPage->GetMediaBox().GetHeight() - 100.0, sLoremIpsum );
#-    painter.FinishPage();
#+        PdfString sLoremIpsum( pszLoremIpsum );
# 
#-    pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_Letter ) );
#-    painter.SetPage( pPage );
#-    pRoot->Last()->CreateNext( "Rectangles Test", PdfDestination( pPage ) );
#+        painter.DrawMultiLineText( 50.0, 50.0,
#+                                   pPage->GetMediaBox().GetWidth() - 100.0,
#+                                   pPage->GetMediaBox().GetHeight() - 100.0, sLoremIpsum );
#+        painter.FinishPage();
# 
#-    printf("Drawing the second page with various rectangle and triangles.\n");
#-    TEST_SAFE_OP( RectTest( &painter, pPage, &writer ) );
#+        pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_Letter ) );
#+        painter.SetPage( pPage );
#+        pRoot->Last()->CreateNext( "Rectangles Test", PdfDestination( pPage ) );
# 
#-    pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
#-    painter.SetPage( pPage );
#-    pRoot->Last()->CreateNext( "Text Test", PdfDestination( pPage ) );
#+        printf("Drawing the second page with various rectangle and triangles.\n");
#+        TEST_SAFE_OP( RectTest( &painter, pPage, &writer ) );
# 
#-    printf("Drawing some text.\n");
#-    TEST_SAFE_OP( TextTest( &painter, pPage, &writer ) );
#+        pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
#+        painter.SetPage( pPage );
#+        pRoot->Last()->CreateNext( "Text Test", PdfDestination( pPage ) );
# 
#-    pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
#-    painter.SetPage( pPage );
#-    pRoot->Last()->CreateNext( "Image Test", PdfDestination( pPage ) );
#+        printf("Drawing some text.\n");
#+        TEST_SAFE_OP( TextTest( &painter, pPage, &writer ) );
# 
#-    printf("Drawing some images.\n");
#-    TEST_SAFE_OP( ImageTest( &painter, pPage, &writer ) );
#+        pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
#+        painter.SetPage( pPage );
#+        pRoot->Last()->CreateNext( "Image Test", PdfDestination( pPage ) );
# 
#-    pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
#-    painter.SetPage( pPage );
#-    pRoot->Last()->CreateNext( "Circle Test", PdfDestination( pPage ) );
#+        printf("Drawing some images.\n");
#+        TEST_SAFE_OP( ImageTest( &painter, pPage, &writer ) );
# 
#-    printf("Drawing some circles and ellipsis.\n");
#-    TEST_SAFE_OP( EllipseTest( &painter, pPage, &writer ) );
#-    painter.FinishPage();
#+        pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
#+        painter.SetPage( pPage );
#+        pRoot->Last()->CreateNext( "Circle Test", PdfDestination( pPage ) );
# 
#-    printf("Drawing some XObject's.\n");
#-    pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
#-    painter.SetPage( pPage );
#-    TEST_SAFE_OP( XObjectTest( &painter, pPage, &writer ) );
#-    painter.FinishPage();
#+        printf("Drawing some circles and ellipsis.\n");
#+        TEST_SAFE_OP( EllipseTest( &painter, pPage, &writer ) );
#+        painter.FinishPage();
# 
#-    printf("Drawing using PdfTable.\n");
#-    pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
#-    painter.SetPage( pPage );
#-    pRoot->Last()->CreateNext( "PdfTable Test", PdfDestination( pPage ) );
#-    TEST_SAFE_OP( TableTest( &painter, pPage, &writer ) );
#-    painter.FinishPage();
#+        printf("Drawing some XObject's.\n");
#+        pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
#+        painter.SetPage( pPage );
#+        TEST_SAFE_OP( XObjectTest( &painter, pPage, &writer ) );
#+        painter.FinishPage();
# 
#-    printf("Drawing using PdfPainterMM.\n");
#-    pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
#-    painterMM.SetPage( pPage );
#-    pRoot->Last()->CreateNext( "MM Test", PdfDestination( pPage ) );
#-    TEST_SAFE_OP( MMTest( &painterMM, pPage, &writer ) );
#-    painterMM.FinishPage();
#+        printf("Drawing using PdfTable.\n");
#+        pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
#+        painter.SetPage( pPage );
#+        pRoot->Last()->CreateNext( "PdfTable Test", PdfDestination( pPage ) );
#+        TEST_SAFE_OP( TableTest( &painter, pPage, &writer ) );
#+        painter.FinishPage();
# 
#-    printf("Drawing using PdfPainter MultilineText.\n");
#-    pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
#-    painter.SetPage( pPage );
#-    pRoot->Last()->CreateNext( "Large MultilineText Test", PdfDestination( pPage ) );
#-    TEST_SAFE_OP( LargeMultiLineTextTest( &painter, pPage, &writer ) );
#-    painter.FinishPage();
#+        printf("Drawing using PdfPainterMM.\n");
#+        pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
#+        painterMM.SetPage( pPage );
#+        pRoot->Last()->CreateNext( "MM Test", PdfDestination( pPage ) );
#+        TEST_SAFE_OP( MMTest( &painterMM, pPage, &writer ) );
#+        painterMM.FinishPage();
# 
#-    printf("Drawing using Font Subset.\n");
#-    pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
#-    painter.SetPage( pPage );
#-    pRoot->Last()->CreateNext( "Font Subset Test", PdfDestination( pPage ) );
#-    TEST_SAFE_OP( FontSubsetTest( &painter, pPage, &writer ) );
#-    painter.FinishPage();
#-    
#+        printf("Drawing using PdfPainter MultilineText.\n");
#+        pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
#+        painter.SetPage( pPage );
#+        pRoot->Last()->CreateNext( "Large MultilineText Test", PdfDestination( pPage ) );
#+        TEST_SAFE_OP( LargeMultiLineTextTest( &painter, pPage, &writer ) );
#+        painter.FinishPage();
#+
#+        printf("Drawing using Font Subset.\n");
#+        pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
#+        painter.SetPage( pPage );
#+        pRoot->Last()->CreateNext( "Font Subset Test", PdfDestination( pPage ) );
#+        TEST_SAFE_OP( FontSubsetTest( &painter, pPage, &writer ) );
#+        painter.FinishPage();
#+
# #if 0
#-    /** Create a really large name tree to test the name tree implementation
#-     */
#-    for( int zz=1;zz<500;zz++ ) 
#-    {
#-        std::ostringstream oss;
#-        oss << "A" << zz;
#+        /** Create a really large name tree to test the name tree implementation
#+         */
#+        for( int zz=1;zz<500;zz++ )
#+        {
#+            std::ostringstream oss;
#+            oss << "A" << zz;
# 
#-        writer.GetNamesTree()->AddValue( "TestDict", PdfString( oss.str() ), PdfVariant( static_cast<long>(zz) )  );
#-    }
#+            writer.GetNamesTree()->AddValue( "TestDict", PdfString( oss.str() ), PdfVariant( static_cast<long>(zz) )  );
#+        }
# 
#-    writer.GetNamesTree()->AddValue( "TestDict", PdfString( "Berta" ), PdfVariant( 42L )  );
#+        writer.GetNamesTree()->AddValue( "TestDict", PdfString( "Berta" ), PdfVariant( 42L )  );
# #endif
# 
#-    printf("Setting document informations.\n\n");
#-    // Setup the document information dictionary
#-    TEST_SAFE_OP( writer.GetInfo()->SetCreator ( PdfString("CreationTest - A simple test application") ) );
#-    TEST_SAFE_OP( writer.GetInfo()->SetAuthor  ( PdfString("Dominik Seichter") ) );
#-    TEST_SAFE_OP( writer.GetInfo()->SetTitle   ( PdfString("Test Document") ) );
#-    //TEST_SAFE_OP( writer.GetInfo()->SetSubject ( PdfString("Testing the PDF Library") ) );
#-    TEST_SAFE_OP( writer.GetInfo()->SetSubject ( 
#-                      PdfString(reinterpret_cast<const pdf_utf8*>("「PoDoFo」は今から日本語も話せます。") ) ) );
#-    TEST_SAFE_OP( writer.GetInfo()->SetKeywords( PdfString("Test;PDF;") ) );
#+        printf("Setting document informations.\n\n");
#+        // Setup the document information dictionary
#+        TEST_SAFE_OP( writer.GetInfo()->SetCreator ( PdfString("CreationTest - A simple test application") ) );
#+        TEST_SAFE_OP( writer.GetInfo()->SetAuthor  ( PdfString("Dominik Seichter") ) );
#+        TEST_SAFE_OP( writer.GetInfo()->SetTitle   ( PdfString("Test Document") ) );
#+        //TEST_SAFE_OP( writer.GetInfo()->SetSubject ( PdfString("Testing the PDF Library") ) );
#+        TEST_SAFE_OP( writer.GetInfo()->SetSubject (
#+                          PdfString(reinterpret_cast<const pdf_utf8*>("「PoDoFo」は今から日本語も話せます。") ) ) );
#+        TEST_SAFE_OP( writer.GetInfo()->SetKeywords( PdfString("Test;PDF;") ) );
# 
#-    //xTEST_SAFE_OP( writer.AttachFile( PdfFileSpec("../../../podofo/test/CreationTest/CreationTest.cpp", true, &writer ) ) );
#+        //xTEST_SAFE_OP( writer.AttachFile( PdfFileSpec("../../../podofo/test/CreationTest/CreationTest.cpp", true, &writer ) ) );
# 
#-    TEST_SAFE_OP( writer.Write( argv[1] ) );
#-    //TEST_SAFE_OP( writer.Close() );
#+        TEST_SAFE_OP( writer.Write( argv[1] ) );
#+        //TEST_SAFE_OP( writer.Close() );
# 
# #ifdef TEST_MEM_BUFFER
#-    // ---
#-    const char*   pszMemFile = "./mem_out.pdf";
#-    FILE*         hFile;
#+        // ---
#+        const char*   pszMemFile = "./mem_out.pdf";
#+        FILE*         hFile;
# 
#-    PdfRefCountedBuffer buffer;
#-    PdfOutputDevice device( &buffer );
#-    printf("Writing document from a memory buffer to: %s\n", pszMemFile );
#-    TEST_SAFE_OP( writer.Write( &device ) );
#+        PdfRefCountedBuffer buffer;
#+        PdfOutputDevice device( &buffer );
#+        printf("Writing document from a memory buffer to: %s\n", pszMemFile );
#+        TEST_SAFE_OP( writer.Write( &device ) );
# 
#-    hFile = fopen( pszMemFile, "wb" );
#-    if( !hFile )
#-    {
#-        fprintf( stderr, "Cannot open file %s for writing.\n", pszMemFile );
#-        return ePdfError_InvalidHandle;
#-    }
#+        hFile = fopen( pszMemFile, "wb" );
#+        if( !hFile )
#+        {
#+            fprintf( stderr, "Cannot open file %s for writing.\n", pszMemFile );
#+            return ePdfError_InvalidHandle;
#+        }
# 
#-    long lBufferLen = device.GetLength();
#-    printf("lBufferLen=%li\n", lBufferLen );
#-    printf("Wrote=%i\n", static_cast<int>(fwrite( buffer.GetBuffer(), lBufferLen, sizeof( char ), hFile )) );
#-    fclose( hFile );
#+        long lBufferLen = device.GetLength();
#+        printf("lBufferLen=%li\n", lBufferLen );
#+        printf("Wrote=%i\n", static_cast<int>(fwrite( buffer.GetBuffer(), lBufferLen, sizeof( char ), hFile )) );
#+        fclose( hFile );
# #endif
#+    } catch( PdfError & e ) {
#+        std::cerr << "Error: An error " << e.GetError() << " ocurred." << std::endl;
#+        e.PrintErrorMsg();
#+        return e.GetError();
#+    }
# 
#     return 0;
# }
Index: test/FilterTest/FilterTest.cpp
===================================================================
--- test/FilterTest/FilterTest.cpp	(revision 1792)
+++ test/FilterTest/FilterTest.cpp	(revision 1793)
@@ -34,7 +34,7 @@
 // We treat the buffer as _excluding_ the trailing \0
 const pdf_long lTestLength1 = strlen(pTestBuffer1);
 
-const char pTestBuffer2[]  = { 
+const char pTestBuffer2[]  = {
     0x01, 0x64, 0x65, static_cast<char>(0xFE), 0x6B, static_cast<char>(0x80), 0x45, 0x32,
     static_cast<char>(0x88), 0x12, static_cast<char>(0x71), static_cast<char>(0xEA), 0x01,
     0x01, 0x64, 0x65, static_cast<char>(0xFE), 0x6B, static_cast<char>(0x80), 0x45, 0x32,
#     0x01, 0x64, 0x65, 0xFE, 0x6B, 0x80, 0x45, 0x32, 0x88, 0x12, 0x71, 0xEA, 0x01,
#     0x01, 0x64, 0x65, 0xFE, 0x6B, 0x80, 0x45, 0x32, 0x88, 0x12, 0x71, 0xEA, 0x03,
#     0x01, 0x64, 0x65, 0xFE, 0x6B, 0x80, 0x45, 0x32, 0x88, 0x12, 0x71, 0xEA, 0x02,
@@ -56,7 +56,7 @@
     char*      pDecoded;
     pdf_long   lEncoded;
     pdf_long   lDecoded;
-   
+
     std::auto_ptr<PdfFilter> pFilter = PdfFilterFactory::Create( eFilter );
     if( !pFilter.get() )
     {
@@ -69,7 +69,7 @@
     try {
         pFilter->Encode( pTestBuffer, lTestLength, &pEncoded, &lEncoded );
     } catch( PdfError & e ) {
-        if( e == ePdfError_UnsupportedFilter ) 
+        if( e == ePdfError_UnsupportedFilter )
         {
             printf("\t-> Encoding not supported for filter %i.\n", eFilter );
             return;
@@ -85,7 +85,7 @@
     try {
         pFilter->Decode( pEncoded, lEncoded, &pDecoded, &lDecoded );
     } catch( PdfError & e ) {
-        if( e == ePdfError_UnsupportedFilter ) 
+        if( e == ePdfError_UnsupportedFilter )
         {
             printf("\t-> Decoding not supported for filter %i.\n", eFilter);
             return;
@@ -101,7 +101,7 @@
     printf("\t-> Encoded  Data Length: %li\n", lEncoded );
     printf("\t-> Decoded  Data Length: %li\n", lDecoded );
 
-    if( static_cast<pdf_long>(lTestLength) != lDecoded ) 
+    if( static_cast<pdf_long>(lTestLength) != lDecoded )
     {
         fprintf( stderr, "Error: Decoded Length != Original Length\n");
 
@@ -147,7 +147,7 @@
 
     PdfMemoryOutputStream  stream;
     PdfOutputStream*       pEncode = PdfFilterFactory::CreateEncodeStream( filters, &stream );
-    
+
     pEncode->Write( pBuffer, lLen );
     pEncode->Close();
 
@@ -158,10 +158,10 @@
 
     PdfMemoryOutputStream stream2;
     PdfOutputStream* pDecode = PdfFilterFactory::CreateDecodeStream( filters, &stream2 );
-    
+
     pDecode->Write( pEncoded, lEncoded );
     pDecode->Close();
-    
+
     delete pDecode;
 
     lDecoded = stream2.GetLength();
@@ -171,7 +171,7 @@
     printf("\t-> Encoded  Data Length: %li\n", lEncoded );
     printf("\t-> Decoded  Data Length: %li\n", lDecoded );
 
-    if( lDecoded != lLen ) 
+    if( lDecoded != lLen )
     {
         fprintf( stderr, "Error: Decoded data length does not match original data length.\n");
         PODOFO_RAISE_ERROR( ePdfError_TestFailed );
@@ -209,7 +209,7 @@
     printf("\t-> Encoded  Data Length: %lu\n", stream.GetLength() );
     printf("\t-> Decoded  Data Length: %li\n", lDecoded );
 
-    if( lDecoded != lLen ) 
+    if( lDecoded != lLen )
     {
         fprintf( stderr, "Error: Decoded data length does not match original data length.\n");
         PODOFO_RAISE_ERROR( ePdfError_TestFailed );
@@ -225,13 +225,13 @@
     }
 
     free( pDecoded );
-    
-    
+
+
 }
 
 } // end anon namespace
 
-int main() 
+int main()
 {
     printf("This test tests all filters of PoDoFo\n");
     printf("---\n");
@@ -247,7 +247,7 @@
     printf("ePdfFilter_JPXDecode          = 8\n");
     printf("ePdfFilter_Crypt              = 9\n");
 
-    // Data from stream  of obj 9 0 R 
+    // Data from stream  of obj 9 0 R
     const char pszInputAscii85Lzw[] = "J..)6T`?q0\"W37&!thJ^C,m/iL/?:-g&uFOK1b,*F;>>qM[VuU#oJ230p2o6!o^dK\r=tpu7Tr'VZ1gWb9&Im[N#Q~>";
 
     pdf_long lLargeBufer1  = strlen(pszInputAscii85Lzw) * 6;
@@ -255,35 +255,35 @@
     char*    pLargeBuffer1 = static_cast<char*>(malloc( strlen(pszInputAscii85Lzw) * 6 ));
     char*    pLargeBuffer2 = static_cast<char*>(malloc( strlen(pszInputAscii85Lzw) * 6 ));
 
-    std::auto_ptr<PdfFilter> pFilter = PdfFilterFactory::Create( ePdfFilter_ASCII85Decode );
-    pFilter->Decode( pszInputAscii85Lzw, strlen(pszInputAscii85Lzw),
-                     &pLargeBuffer1, &lLargeBufer1 );
-    pFilter->Encode( pLargeBuffer1, lLargeBufer1,
-                     &pLargeBuffer2, &lLargeBufer2 );
+    try {
+        std::auto_ptr<PdfFilter> pFilter = PdfFilterFactory::Create( ePdfFilter_ASCII85Decode );
+        pFilter->Decode( pszInputAscii85Lzw, strlen(pszInputAscii85Lzw),
+                         &pLargeBuffer1, &lLargeBufer1 );
+        pFilter->Encode( pLargeBuffer1, lLargeBufer1,
+                         &pLargeBuffer2, &lLargeBufer2 );
 
-    if( memcmp( pszInputAscii85Lzw, pLargeBuffer2, lLargeBufer2 ) != 0 )
-    {
-        printf("\tROACH -> Original Data: <%s>\n", pszInputAscii85Lzw );
-        printf("\tROACH -> Encoded  Data: <%s>\n", pLargeBuffer1 );
-        printf("\tROACH -> Decoded  Data: <%s>\n", pLargeBuffer2 );
+        if( memcmp( pszInputAscii85Lzw, pLargeBuffer2, lLargeBufer2 ) != 0 )
+        {
+            printf("\tROACH -> Original Data: <%s>\n", pszInputAscii85Lzw );
+            printf("\tROACH -> Encoded  Data: <%s>\n", pLargeBuffer1 );
+            printf("\tROACH -> Decoded  Data: <%s>\n", pLargeBuffer2 );
 
-        fprintf( stderr, "Error: Decoded Data does not match original data.\n");
-        PODOFO_RAISE_ERROR( ePdfError_TestFailed );
-    }
+            fprintf( stderr, "Error: Decoded Data does not match original data.\n");
+            PODOFO_RAISE_ERROR( ePdfError_TestFailed );
+        }
 
-    if( static_cast<pdf_long>(strlen(pszInputAscii85Lzw)) != lLargeBufer2 ) 
-    {
-        fprintf( stderr, "ROACH Error: Decoded Length != Original Length\n");
-        fprintf( stderr, "ROACH Original: %li\n", strlen(pszInputAscii85Lzw) );
-        fprintf( stderr, "ROACH Encode: %li\n", lLargeBufer2 );
-        PODOFO_RAISE_ERROR( ePdfError_TestFailed );
-    }
+        if( static_cast<pdf_long>(strlen(pszInputAscii85Lzw)) != lLargeBufer2 )
+        {
+            fprintf( stderr, "ROACH Error: Decoded Length != Original Length\n");
+            fprintf( stderr, "ROACH Original: %li\n", strlen(pszInputAscii85Lzw) );
+            fprintf( stderr, "ROACH Encode: %li\n", lLargeBufer2 );
+            PODOFO_RAISE_ERROR( ePdfError_TestFailed );
+        }
 
 
-    // ASCII 85 decode and re-encode delivers same results
-    printf("ROACH ASCII encode/decode OK\n");
+        // ASCII 85 decode and re-encode delivers same results
+        printf("ROACH ASCII encode/decode OK\n");
 
-    try {
         for( int i =0; i<=ePdfFilter_Crypt; i++ )
         {
             test_filter( static_cast<EPdfFilter>(i), pTestBuffer1, lTestLength1 );
@@ -293,7 +293,7 @@
 
         test_filter_queque( pTestBuffer1, lTestLength1 );
         test_filter_queque( pTestBuffer2, lTestLength2 );
-        
+
         test_stream( pTestBuffer1, lTestLength1 );
         test_stream( pTestBuffer2, lTestLength2 );
 
Index: test/FormTest/FormTest.cpp
===================================================================
--- test/FormTest/FormTest.cpp	(revision 1792)
+++ test/FormTest/FormTest.cpp	(revision 1793)
@@ -55,7 +55,7 @@
     // Name
     y -= 10000.0 * CONVERSION_CONSTANT;
     painter.DrawText( x, y, "Your Name:" );
-    PdfTextField textName( pPage, PdfRect( 80000.0 * CONVERSION_CONSTANT, y - 2500.0 * CONVERSION_CONSTANT, 
+    PdfTextField textName( pPage, PdfRect( 80000.0 * CONVERSION_CONSTANT, y - 2500.0 * CONVERSION_CONSTANT,
                                            80000.0 * CONVERSION_CONSTANT, h ), pDoc );
     textName.SetFieldName("field_name");
     textName.SetBorderColor( 1.0 );
@@ -63,16 +63,16 @@
     // E-Mail
     y -= 10000.0 * CONVERSION_CONSTANT;
     painter.DrawText( x, y, "E-Mail Address:" );
-    PdfTextField textMail( pPage, PdfRect( 80000.0 * CONVERSION_CONSTANT, y - 2500.0 * CONVERSION_CONSTANT, 
+    PdfTextField textMail( pPage, PdfRect( 80000.0 * CONVERSION_CONSTANT, y - 2500.0 * CONVERSION_CONSTANT,
                                            80000.0 * CONVERSION_CONSTANT, h ), pDoc );
     textMail.SetFieldName("field_mail");
     textMail.SetBorderColor( 1.0 );
-    
+
     // Interest
     y -= 10000.0 * CONVERSION_CONSTANT;
     painter.DrawText( x, y, "Job:" );
 
-    PdfComboBox comboJob( pPage, PdfRect( 80000.0 * CONVERSION_CONSTANT, y - 2500.0 * CONVERSION_CONSTANT, 
+    PdfComboBox comboJob( pPage, PdfRect( 80000.0 * CONVERSION_CONSTANT, y - 2500.0 * CONVERSION_CONSTANT,
                                           80000.0 * CONVERSION_CONSTANT, h ), pDoc );
     comboJob.SetFieldName("field_combo");
     comboJob.SetBorderColor( 1.0 );
@@ -85,7 +85,7 @@
     // Open Source
     y -= 11000.0 * CONVERSION_CONSTANT;
     painter.DrawText( x, y, "I wan't to use PoDoFo in an Open Source application" );
-    PdfCheckBox checkOpenSource( pPage, PdfRect( 120000.0 * CONVERSION_CONSTANT, y - 2500.0 * CONVERSION_CONSTANT, 
+    PdfCheckBox checkOpenSource( pPage, PdfRect( 120000.0 * CONVERSION_CONSTANT, y - 2500.0 * CONVERSION_CONSTANT,
                                                  h, h ), pDoc );
     checkOpenSource.SetFieldName("field_check_oss");
 
@@ -92,7 +92,7 @@
     // Commercial
     y -= 11000.0 * CONVERSION_CONSTANT;
     painter.DrawText( x, y, "I wan't to use PoDoFo in a commercial application" );
-    PdfCheckBox checkCom( pPage, PdfRect( 120000.0 * CONVERSION_CONSTANT, y - 2500.0 * CONVERSION_CONSTANT, 
+    PdfCheckBox checkCom( pPage, PdfRect( 120000.0 * CONVERSION_CONSTANT, y - 2500.0 * CONVERSION_CONSTANT,
                                           h, h ), pDoc );
     checkCom.SetFieldName("field_check_com");
 
@@ -118,10 +118,10 @@
     buttonClear.SetBackgroundColor( 0.5 );
 
     PdfAction actionClear( ePdfAction_JavaScript, pDoc );
-    actionClear.SetScript( 
+    actionClear.SetScript(
         PdfString("this.getField(\"field_name\").value = \"\";" \
                   "this.getField(\"field_mail\").value = \"\";" \
-                  "this.getField(\"field_combo\").value = \"\";" 
+                  "this.getField(\"field_combo\").value = \"\";"
                   "this.getField(\"field_check_oss.\").checkThisBox( 0, false );" \
                   "this.getField(\"field_check_com.\").checkThisBox( 0, false );" \
                   "this.getField(\"field_comment\").value = \"\";" ) );
@@ -128,11 +128,11 @@
 
 
     buttonClear.SetMouseDownAction( actionClear );
-                  
+
     PdfAction actionSubmit( ePdfAction_SubmitForm, pDoc );
 
     buttonSend.SetMouseDownAction( actionSubmit );
-    
+
     painter.FinishPage();
 }
 
@@ -156,7 +156,7 @@
 
 
     PdfAction action( ePdfAction_JavaScript, pDoc );
-    action.SetScript( 
+    action.SetScript(
         PdfString("var str = this.getField(\"TextFieldName\").value;" \
                   "var j = 4*5;" \
                   "app.alert(\"Hello World! 4 * 5 = \" + j + \" Text Field: \" + str );") );
@@ -201,7 +201,7 @@
     listBox.SetSelectedItem( 2 );
 }
 
-void FillTextField( PdfTextField & rField ) 
+void FillTextField( PdfTextField & rField )
 {
     const char* pszCur = rField.GetText().GetString();
     std::cout << "  Current value:" << (pszCur ? pszCur : "") << std::endl;
@@ -224,13 +224,13 @@
     }
 }
 
-void FillListField( PdfListField & rField ) 
+void FillListField( PdfListField & rField )
 {
-    const char* pszCur = ( rField.GetSelectedItem() == -1 ? NULL : 
+    const char* pszCur = ( rField.GetSelectedItem() == -1 ? NULL :
                            rField.GetItemDisplayText( rField.GetSelectedItem() ).GetString() );
     std::cout << "  Current value:" << (pszCur ? pszCur : "") << std::endl;
     std::cout << "  Values:" << std::endl;
-    
+
     for( int i=0;i<static_cast<int>(rField.GetItemCount());i++ )
     {
         pszCur = rField.GetItemDisplayText( i ).GetString();
@@ -245,7 +245,7 @@
         rField.SetSelectedItem( nValue );
 }
 
-void FillForm( const char* pszFilename, const char* pszOutput ) 
+void FillForm( const char* pszFilename, const char* pszOutput )
 {
     PdfMemDocument doc( pszFilename );
     PdfPage*       pPage;
@@ -281,7 +281,7 @@
                 case ePdfField_TextField:
                 {
                     std::cout << "TextField" << std::endl;
-                    PdfTextField text( field ); 
+                    PdfTextField text( field );
                     FillTextField( text );
                     break;
                 }
@@ -289,7 +289,7 @@
                 {
                     std::cout << "ComboBox" << std::endl;
                     PdfListField lst( field );
-                    FillListField( lst ); 
+                    FillListField( lst );
                     break;
                 }
                 case ePdfField_ListBox:
@@ -296,7 +296,7 @@
                 {
                     std::cout << "ListBox" << std::endl;
                     PdfListField lst( field );
-                    FillListField( lst ); 
+                    FillListField( lst );
                     break;
                 }
                 case ePdfField_Signature:
@@ -315,7 +315,7 @@
     doc.Write( pszOutput );
 }
 
-int main( int argc, char* argv[] ) 
+int main( int argc, char* argv[] )
 {
     PdfPage*            pPage;
 
@@ -323,26 +323,32 @@
     {
         printf("Usage: FormTest [output_filename]\n");
         printf("       - Create a new example PDF form\n");
-        printf("       Formtest [input_filename] [output_filename]\n"); 
+        printf("       Formtest [input_filename] [output_filename]\n");
         printf("       - Fill out an existing form and save it to a PDF file\n");
         return 0;
     }
 
-    if( argc == 3 )
-    {
-        TEST_SAFE_OP( FillForm( argv[1], argv[2] ) );
-    }
-    else
-    {
-        PdfStreamedDocument writer( argv[1] );
+    try {
+        if( argc == 3 )
+        {
+            TEST_SAFE_OP( FillForm( argv[1], argv[2] ) );
+        }
+        else
+        {
+            PdfStreamedDocument writer( argv[1] );
 
-        pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
-        TEST_SAFE_OP( CreateComplexForm( pPage, &writer ) );
+            pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
+            TEST_SAFE_OP( CreateComplexForm( pPage, &writer ) );
 
-        pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
-        TEST_SAFE_OP( CreateSimpleForm( pPage, &writer ) );
+            pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
+            TEST_SAFE_OP( CreateSimpleForm( pPage, &writer ) );
 
-        TEST_SAFE_OP( writer.Close() );
+            TEST_SAFE_OP( writer.Close() );
+        }
+    } catch( PdfError & e ) {
+        std::cerr << "Error: An error " << e.GetError() << " ocurred." << std::endl;
+        e.PrintErrorMsg();
+        return e.GetError();
     }
 
     return 0;
Index: test/LargeTest/LargeTest.cpp
===================================================================
--- test/LargeTest/LargeTest.cpp	(revision 1792)
+++ test/LargeTest/LargeTest.cpp	(revision 1793)
@@ -39,7 +39,7 @@
  
     try {
         pFont  = pDoc->CreateFont( pszFontName );
-    } catch ( const PdfError & e ) {
+    } catch ( PdfError & e ) {
         e.PrintErrorMsg();
         return;
     }
@@ -86,7 +86,7 @@
     try {
         pImage->LoadFromFile( pszImagePath );
     }
-    catch( const PdfError & e ) 
+    catch( PdfError & e ) 
     {
         e.PrintErrorMsg();
     }
Index: test/ObjectParserTest/ObjectParserTest.cpp
===================================================================
--- test/ObjectParserTest/ObjectParserTest.cpp	(revision 1792)
+++ test/ObjectParserTest/ObjectParserTest.cpp	(revision 1793)
@@ -206,7 +206,7 @@
 
         cerr << "  -> Has Stream, loading ... " << flush;
         PdfMemStream * const ps = dynamic_cast<PdfMemStream*>(obj.GetStream());
-        assert(ps);
+        PODOFO_ASSERT(ps);
         cerr << " ok, length: " << ps->GetLength() << endl;
 
         ps->GetFilteredCopy( &pBuffer, &lLen );
@@ -214,6 +214,8 @@
         cerr << "Data:\n" << endl;
         cerr.write( pBuffer, lLen );
         cerr << "\n====\n" << endl;
+
+        podofo_free( pBuffer );
     }
 
     string str;
@@ -297,7 +299,7 @@
 // This may only be used for objects without associated streams.
 void TestObject_String( const string & sData, long lObjNo, long lGenNo, const char * expectedData )
 {
-    TestObject_String(sData, lObjNo, lGenNo, expectedData != NULL, string(expectedData), false);
+    TestObject_String(sData, lObjNo, lGenNo, expectedData != NULL, string( expectedData ? expectedData : "" ), false);
 }
 
 // Test an object stored in a file against the expected value, also a file (if provided).
@@ -404,7 +406,7 @@
         "endobj\n";
 
 // Comment tokenizer test adapted from PDF Reference, section 3.1.2 . Should parse as [ /abc 123 ] .
-const char* pszCommentObject       = "91 0 obj\n[/abc\% comment {/%) blah blah blah\n123]\nendobj\n";
+const char* pszCommentObject       = "91 0 obj\n[/abc% comment {/%) blah blah blah\n123]\nendobj\n";
 
 // Use a FULL statement in this macro, it will not add any trailing
 // semicolons etc.
Index: test/ParserTest/ParserTest.cpp
===================================================================
--- test/ParserTest/ParserTest.cpp	(revision 1792)
+++ test/ParserTest/ParserTest.cpp	(revision 1793)
@@ -205,7 +205,7 @@
                     parser.SetPassword( pw );
                 
                 bIncorrectPw = false;
-            } catch( const PdfError & e ) {
+            } catch( PdfError & e ) {
                 if( e.GetError() == ePdfError_InvalidPassword ) 
                 {
                     cout << endl << "Password :";
Index: test/SignTest/SignTest.cpp
===================================================================
--- test/SignTest/SignTest.cpp	(revision 1792)
+++ test/SignTest/SignTest.cpp	(revision 1793)
@@ -51,7 +51,7 @@
 }
 
 
-int main( int argc, char* argv[] ) 
+int main( int argc, char* argv[] )
 {
     PdfPage*            pPage;
 
@@ -62,42 +62,47 @@
         return 0;
     }
 
-    PdfSignOutputDevice signer(argv[1]);
-	// Reserve space for signature
-    signer.SetSignatureSize(1024);
+    try {
+        PdfSignOutputDevice signer(argv[1]);
+        // Reserve space for signature
+        signer.SetSignatureSize(1024);
 
-	PdfStreamedDocument writer( &signer, PoDoFo::ePdfVersion_1_5 );
-    // Disable default appearance
-    writer.GetAcroForm(ePdfCreateObject, PdfAcroForm::ePdfAcroFormDefaultAppearance_None);
+        PdfStreamedDocument writer( &signer, PoDoFo::ePdfVersion_1_5 );
+        // Disable default appearance
+        writer.GetAcroForm(ePdfCreateObject, PdfAcroForm::ePdfAcroFormDefaultAppearance_None);
 
-    pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
-    TEST_SAFE_OP( CreateSimpleForm( pPage, &writer, *signer.GetSignatureBeacon() ) );
+        pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
+        TEST_SAFE_OP( CreateSimpleForm( pPage, &writer, *signer.GetSignatureBeacon() ) );
 
-    TEST_SAFE_OP( writer.Close() );
+        TEST_SAFE_OP( writer.Close() );
 
-    // Adjust ByteRange for signature
-    if(signer.HasSignaturePosition()) {
-        signer.AdjustByteRange();
-		
-		// read data for signature and count it
-		signer.Seek(0);
+        // Adjust ByteRange for signature
+        if(signer.HasSignaturePosition()) {
+            signer.AdjustByteRange();
 
-		// generate digest and count signature
-		// use NSS, MS Crypto API or OpenSSL 
-		// to generate signature in DER format
-		char buff[65536];
-		size_t len;
-		while( (len = signer.ReadForSignature(buff, 65536))>0 )
-		{
-		}
+            // read data for signature and count it
+            signer.Seek(0);
 
-		// Paste signature to the file
-        PdfData sigData("my-real-signature");
-        signer.SetSignature(sigData);
-    }
+            // generate digest and count signature
+            // use NSS, MS Crypto API or OpenSSL
+            // to generate signature in DER format
+            char buff[65536];
+            size_t len;
+            while( (len = signer.ReadForSignature(buff, 65536))>0 )
+            {
+            }
 
-	signer.Flush();
+            // Paste signature to the file
+            PdfData sigData("my-real-signature");
+            signer.SetSignature(sigData);
+        }
 
+        signer.Flush();
+    } catch( PdfError & e ) {
+        std::cerr << "Error: An error " << e.GetError() << " ocurred." << std::endl;
+        e.PrintErrorMsg();
+        return e.GetError();
+    }
 
     return 0;
 }
Index: test/SignatureTest/SignTest.cpp
===================================================================
--- test/SignatureTest/SignTest.cpp	(revision 1792)
+++ test/SignatureTest/SignTest.cpp	(revision 1793)
@@ -79,7 +79,7 @@
 }
 
 
-int main( int argc, char* argv[] ) 
+int main( int argc, char* argv[] )
 {
     PdfPage*            pPage;
 
#@@ -90,75 +90,80 @@
#         return 0;
#     }
# 
#-    PdfSignOutputDevice signer(argv[1]);
#-	// Reserve space for signature
#-    signer.SetSignatureSize(1024);
#+    try {
#+        PdfSignOutputDevice signer(argv[1]);
#+        // Reserve space for signature
#+        signer.SetSignatureSize(1024);
# 
#-	PdfStreamedDocument writer( &signer, PoDoFo::ePdfVersion_1_5 );
#-    // Disable default appearance
#-    writer.GetAcroForm(ePdfCreateObject, ePdfAcroFormDefaultAppearance_None);
#+        PdfStreamedDocument writer( &signer, PoDoFo::ePdfVersion_1_5 );
#+        // Disable default appearance
#+        writer.GetAcroForm(ePdfCreateObject, ePdfAcroFormDefaultAppearance_None);
# 
#-    pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
#-    TEST_SAFE_OP( CreateSimpleForm( pPage, &writer, *signer.GetSignatureBeacon() ) );
#+        pPage = writer.CreatePage( PdfPage::CreateStandardPageSize( ePdfPageSize_A4 ) );
#+        TEST_SAFE_OP( CreateSimpleForm( pPage, &writer, *signer.GetSignatureBeacon() ) );
# 
#-    TEST_SAFE_OP( writer.Close() );
#+        TEST_SAFE_OP( writer.Close() );
# 
#-    // Check if position of signature was found
#-    if(signer.HasSignaturePosition()) {
#-		// Adjust ByteRange for signature
#-        signer.AdjustByteRange();
#-		
#-		// Read data for signature and count it
#-		// We have to seek at the beginning of the file
#-		signer.Seek(0);
#+        // Check if position of signature was found
#+        if(signer.HasSignaturePosition()) {
#+            // Adjust ByteRange for signature
#+            signer.AdjustByteRange();
# 
#-		// Generate digest and count signature
#-		// use NSS, MS Crypto API or OpenSSL 
#-		// to generate signature in DER format
#+            // Read data for signature and count it
#+            // We have to seek at the beginning of the file
#+            signer.Seek(0);
# 
#-		// This is example of generation process
#-		// with dummy generator. Check example for 
#-		// NSS generator
#-		/*
#-        SimpleSignatureGenerator sg;
#+            // Generate digest and count signature
#+            // use NSS, MS Crypto API or OpenSSL
#+            // to generate signature in DER format
# 
#-		// Read data to be signed and send them to the
#-		// signature generator
#-		char buff[65536];
#-		size_t len;
#-		while( (len = signer.ReadForSignature(buff, 65536))>0 )
#-		{
#-			sg.appendData(buff, len);
#-		}
#-		sg.finishData();		
#+            // This is example of generation process
#+            // with dummy generator. Check example for
#+            // NSS generator
#+            /*
#+            SimpleSignatureGenerator sg;
# 
#-		// Paste signature to the file
#-		const PdfData *pSignature = sg.getSignature();
#-        */
#-        /*
#-        CERTCertificate* pCert = read_cert();        
#-        NSSSignatureGenerator ng(pCert);
#-		char buff[65536];
#-		size_t len;
#-		while( (len = signer.ReadForSignature(buff, 65536))>0 )
#-		{
#-			ng.appendData(buff, len);
#-		}
#-		ng.finishData();		
#+            // Read data to be signed and send them to the
#+            // signature generator
#+            char buff[65536];
#+            size_t len;
#+            while( (len = signer.ReadForSignature(buff, 65536))>0 )
#+            {
#+                sg.appendData(buff, len);
#+            }
#+            sg.finishData();
# 
#-		// Paste signature to the file
#-		const PdfData *pSignature = ng.getSignature();
#+            // Paste signature to the file
#+            const PdfData *pSignature = sg.getSignature();
#+            */
#+            /*
#+            CERTCertificate* pCert = read_cert();
#+            NSSSignatureGenerator ng(pCert);
#+            char buff[65536];
#+            size_t len;
#+            while( (len = signer.ReadForSignature(buff, 65536))>0 )
#+            {
#+                ng.appendData(buff, len);
#+            }
#+            ng.finishData();
# 
#-        CERT_DestroyCertificate(pCert);
#+            // Paste signature to the file
#+            const PdfData *pSignature = ng.getSignature();
# 
#-		if(pSignature!=NULL) {
#-			signer.SetSignature(*pSignature);
#-		}
#-        */
#-    }
#+            CERT_DestroyCertificate(pCert);
# 
#-	signer.Flush();
#+            if(pSignature!=NULL) {
#+                signer.SetSignature(*pSignature);
#+            }
#+            */
#+        }
# 
#+        signer.Flush();
#+    } catch( PdfError & e ) {
#+        std::cerr << "Error: An error " << e.GetError() << " ocurred." << std::endl;
#+        e.PrintErrorMsg();
#+        return e.GetError();
#+    }
# 
#     return 0;
# }
Index: test/TokenizerTest/TokenizerTest.cpp
===================================================================
--- test/TokenizerTest/TokenizerTest.cpp	(revision 1792)
+++ test/TokenizerTest/TokenizerTest.cpp	(revision 1793)
@@ -48,7 +48,7 @@
             printf("Got token: %s\n", pszToken );
         }
 
-    } catch( const PdfError & e ) {
+    } catch( PdfError & e ) {
         e.PrintErrorMsg();
         return e.GetError();
     }
Index: test/WatermarkTest/WatermarkTest.cpp
===================================================================
--- test/WatermarkTest/WatermarkTest.cpp	(revision 1792)
+++ test/WatermarkTest/WatermarkTest.cpp	(revision 1793)
@@ -72,7 +72,7 @@
     try {
         WatermarkFile( argv[1], argv[2] );
     } 
-    catch( const PdfError & e ) 
+    catch( PdfError & e ) 
     {
         e.PrintErrorMsg();
         return e.GetError();
Index: test/unit/EncodingTest.cpp
===================================================================
--- test/unit/EncodingTest.cpp	(revision 1792)
+++ test/unit/EncodingTest.cpp	(revision 1793)
@@ -332,7 +332,7 @@
     try {
 	pEncoding->GetCharCode( pEncoding->GetFirstChar() );
     } 
-    catch( const PdfError & rError ) 
+    catch( PdfError & rError ) 
     {
 	// This may not throw!
 	rMsg = "pEncoding->GetCharCode( pEncoding->GetFirstChar() ) failed";
@@ -342,7 +342,7 @@
     try {
 	pEncoding->GetCharCode( pEncoding->GetFirstChar() - 1 );
     } 
-    catch( const PdfError & rError ) 
+    catch( PdfError & rError ) 
     {
 	// This has to throw!
 	exception = true;
@@ -357,7 +357,7 @@
     try {
 	pEncoding->GetCharCode( pEncoding->GetLastChar() );
     } 
-    catch( const PdfError & rError ) 
+    catch( PdfError & rError ) 
     {
 	// This may not throw!
 	rMsg = "pEncoding->GetCharCode( pEncoding->GetLastChar()  ); failed";
@@ -368,7 +368,7 @@
     try {
 	pEncoding->GetCharCode( pEncoding->GetLastChar() + 1 );
     } 
-    catch( const PdfError & rError ) 
+    catch( PdfError & rError ) 
     {
 	// This has to throw!
 	exception = true;
Index: test/unit/EncryptTest.cpp
===================================================================
--- test/unit/EncryptTest.cpp	(revision 1792)
+++ test/unit/EncryptTest.cpp	(revision 1793)
@@ -238,7 +238,7 @@
 
             // Must throw an exception
             CPPUNIT_FAIL("Encrypted file not recognized!");
-        } catch( const PdfError & e ) {
+        } catch( PdfError & e ) {
             if( e.GetError() != ePdfError_InvalidPassword ) 
             {
                 CPPUNIT_FAIL("Invalid encryption exception thrown!");
@@ -272,7 +272,7 @@
 
             // Must throw an exception
             CPPUNIT_FAIL("Encrypted file not recognized!");
-        } catch( const PdfError & e ) {
+        } catch( PdfError & e ) {
             if( e.GetError() != ePdfError_InvalidPassword ) 
             {
                 CPPUNIT_FAIL("Invalid encryption exception thrown!");
Index: tools/podofocrop/podofocrop.cpp
===================================================================
--- tools/podofocrop/podofocrop.cpp	(revision 1792)
+++ tools/podofocrop/podofocrop.cpp	(revision 1793)
@@ -161,7 +161,11 @@
         if( strncmp( "%%BoundingBox: ", sLine.c_str(), 15 ) == 0 )
         {
             int x, y, w, h;
-            sscanf(sLine.c_str()+15, "%i %i %i %i\n", &x, &y, &w, &h);
+            if( sscanf( sLine.c_str() + 15, "%i %i %i %i\n", &x, &y, &w, &h ) != 4 )
+            {
+                printf( "Failed to read bounding box's four numbers from '%s'\n", sLine.c_str() + 15 );
+                exit( 1 );
+            }
             curRect = PdfRect( static_cast<double>(x), 
                                static_cast<double>(y),
                                static_cast<double>(w-x),
Index: tools/podofogc/podofogc.cpp
===================================================================
--- tools/podofogc/podofogc.cpp	(revision 1792)
+++ tools/podofogc/podofogc.cpp	(revision 1793)
@@ -61,7 +61,7 @@
                     parser.SetPassword( pw );
                 
                 bIncorrectPw = false;
-            } catch( const PdfError & e ) {
+            } catch( PdfError & e ) {
                 if( e.GetError() == ePdfError_InvalidPassword ) 
                 {
                     cout << endl << "Password :";
Index: tools/podofoimpose/impositionplan.cpp
===================================================================
--- tools/podofoimpose/impositionplan.cpp	(revision 1792)
+++ tools/podofoimpose/impositionplan.cpp	(revision 1793)
@@ -57,7 +57,8 @@
 		destPage ( 0 ),
 		rotate ( 0 ),
 		transX ( 0 ),
-		transY ( 0 )
+		transY ( 0 ),
+		duplicateOf( 0 )
 {};
 
 void PageRecord::load ( const std::string& buffer, const std::map<std::string, std::string>& vars )
Index: tools/podofoimpose/impositionplan.h
===================================================================
--- tools/podofoimpose/impositionplan.h	(revision 1792)
+++ tools/podofoimpose/impositionplan.h	(revision 1793)
@@ -85,7 +85,6 @@
 		PageRecord( );
 		~PageRecord() {};
 		int sourcePage;
-		int xobjIndex;
 		int destPage;
 		double rotate;
 		double transX;
Index: tools/podofoimpose/pdftranslator.cpp
===================================================================
--- tools/podofoimpose/pdftranslator.cpp	(revision 1792)
+++ tools/podofoimpose/pdftranslator.cpp	(revision 1793)
@@ -74,10 +74,17 @@
 		PdfTranslator::PdfTranslator ( )
 		{
 			std::cerr<<"PdfTranslator::PdfTranslator"<<std::endl;
-			sourceDoc = 0;
-			targetDoc = 0;
+			sourceDoc = NULL;
+			targetDoc = NULL;
+			planImposition = NULL;
+			duplicate = 0;
 			extraSpace = 0;
 			scaleFactor = 1.0;
+			pcount = 0;
+			sourceWidth = 0.0;
+			sourceHeight = 0.0;
+			destWidth = 0.0;
+			destHeight = 0.0;
 		}
 
 		void PdfTranslator::setSource ( const std::string & source )
@@ -111,7 +118,7 @@
 				}
 				while ( !in.eof() );
 				in.close();
-				delete filenameBuffer;
+				delete [] filenameBuffer;
 			}
 			std::cerr<< ++dbg <<std::endl;
 
Index: tools/podofopages/podofopages.cpp
===================================================================
--- tools/podofopages/podofopages.cpp	(revision 1792)
+++ tools/podofopages/podofopages.cpp	(revision 1793)
@@ -49,14 +49,14 @@
   printf("Usage: podofopages [inputfile] [outputfile]\n");
   printf("Options:\n");
   printf("\t--delete NUMBER\n");
-  printf("\tDeletes the page NUMBER (number is 0-based)\n"); 
+  printf("\tDeletes the page NUMBER (number is 0-based)\n");
   printf("\tThe page will not really be deleted from the PDF.\n");
   printf("\tIt is only removed from the so called pagestree and\n");
   printf("\ttherefore invisible. The content of the page can still\n");
   printf("\tbe retrieved from the document though.\n\n");
   printf("\t--move FROM TO\n");
-  printf("\tMoves a page FROM TO in the document (FROM and TO are 0-based)\n\n"); 
-  printf("\nPoDoFo Version: %s\n\n", PODOFO_VERSION_STRING);  
+  printf("\tMoves a page FROM TO in the document (FROM and TO are 0-based)\n\n");
+  printf("\nPoDoFo Version: %s\n\n", PODOFO_VERSION_STRING);
 }
 
 void work(const char* pszInput, const char* pszOutput, std::vector<Operation*> & rvecOperations)
@@ -63,13 +63,13 @@
 {
     std::cout << "Input file: " << pszInput << std::endl;
     std::cout << "Output file: " << pszOutput << std::endl;
-    
+
     PdfMemDocument doc(pszInput);
 
     int total = rvecOperations.size();
     int i = 1;
     std::vector<Operation*>::iterator it = rvecOperations.begin();
-    while( it != rvecOperations.end() ) 
+    while( it != rvecOperations.end() )
     {
         std::string msg = (*it)->ToString();
         std::cout << "Operation " << i << " of " << total << ": " << msg;
@@ -109,30 +109,30 @@
 
   // Fill operations vector
   std::vector<Operation*> vecOperations;
-  for( int i=1; i < argc; i++ ) 
+  for( int i=1; i < argc; i++ )
   {
       std::string argument = argv[i];
-      if( argument == "--delete" || argument == "-delete" ) 
+      if( argument == "--delete" || argument == "-delete" )
       {
           int page = static_cast<int>(convertToInt( std::string(argv[i+1]) ));
           vecOperations.push_back( new DeleteOperation( page ) );
           ++i;
       }
-      else if( argument == "--move" || argument == "-move" ) 
+      else if( argument == "--move" || argument == "-move" )
       {
           int from = static_cast<int>(convertToInt( std::string(argv[i+1]) ));
           int to = static_cast<int>(convertToInt( std::string(argv[i+2]) ));
           vecOperations.push_back( new MoveOperation( from, to ) );
           ++i;
-          ++i;          
+          ++i;
       }
       else
       {
-          if( pszInput == NULL ) 
+          if( pszInput == NULL )
           {
               pszInput = argv[i];
           }
-          else if( pszOutput == NULL ) 
+          else if( pszOutput == NULL )
           {
               pszOutput = argv[i];
           }
@@ -143,19 +143,19 @@
       }
   }
 
-  if( !pszInput ) 
+  if( !pszInput )
   {
       std::cerr << "Please specify an input file." << std::endl;
       exit( -2 );
   }
 
-  if( !pszOutput ) 
+  if( !pszOutput )
   {
       std::cerr << "Please specify an output file." << std::endl;
       exit( -3 );
   }
 
-  if( std::string(pszInput) == std::string(pszOutput) ) 
+  if( std::string(pszInput) == std::string(pszOutput) )
   {
       std::cerr << "Input and outpuf file must point to different files." << std::endl;
       exit( -4 );
@@ -167,11 +167,14 @@
       std::cerr << "Error: An error " << e.GetError() << " ocurred." << std::endl;
       e.PrintErrorMsg();
       return e.GetError();
+  } catch( std::runtime_error & re ) {
+      std::cerr << "Error: An error " << re.what() << " ocurred." << std::endl;
+      return -1;
   }
 
   // Delete operations vectore
   std::vector<Operation*>::iterator it = vecOperations.begin();
-  while( it != vecOperations.end() ) 
+  while( it != vecOperations.end() )
   {
       delete (*it);
       ++it;
#Index: tools/podofosign/podofosign.cpp
#===================================================================
#--- tools/podofosign/podofosign.cpp	(revision 1792)
#+++ tools/podofosign/podofosign.cpp	(revision 1793)
#@@ -180,17 +180,17 @@
#     if( !pkey )
#         PODOFO_RAISE_ERROR_INFO( ePdfError_InvalidHandle, "pkey == NULL" );
# 
#-    unsigned int buffLen = 65535, len;
#-    char *buff;
#+    unsigned int uBufferLen = 65535, len;
#+    char *pBuffer;
# 
#-    while( buff = reinterpret_cast<char *>( malloc( sizeof( char ) * buffLen) ), !buff )
#+    while( pBuffer = reinterpret_cast<char *>( podofo_malloc( sizeof( char ) * uBufferLen) ), !pBuffer )
#     {
#-        buffLen = buffLen / 2;
#-        if( !buffLen )
#+        uBufferLen = uBufferLen / 2;
#+        if( !uBufferLen )
#             break;
#     }
# 
#-    if( !buff )
#+    if( !pBuffer )
#         PODOFO_RAISE_ERROR (ePdfError_OutOfMemory);
# 
#     int rc;
#@@ -197,7 +197,7 @@
#     BIO *mem = BIO_new( BIO_s_mem() );
#     if( !mem )
#     {
#-        free( buff );
#+        podofo_free( pBuffer );
#         raise_podofo_error_with_opensslerror( "Failed to create input BIO" );
#     }
# 
#@@ -206,23 +206,23 @@
#     if( !pkcs7 )
#     {
#         BIO_free( mem );
#-        free( buff );
#+        podofo_free( pBuffer );
#         raise_podofo_error_with_opensslerror( "PKCS7_sign failed" );
#     }
# 
#-    while( len = signer.ReadForSignature( buff, buffLen ), len > 0 )
#+    while( len = signer.ReadForSignature( pBuffer, uBufferLen ), len > 0 )
#     {
#-        rc = BIO_write( mem, buff, len );
#+        rc = BIO_write( mem, pBuffer, len );
#         if( static_cast<unsigned int>( rc ) != len )
#         {
#             PKCS7_free( pkcs7 );
#             BIO_free( mem );
#-            free( buff );
#+            podofo_free( pBuffer );
#             raise_podofo_error_with_opensslerror( "BIO_write failed" );
#         }
#     }
# 
#-    free( buff );
#+    podofo_free( pBuffer );
# 
#     if( PKCS7_final( pkcs7, mem, flags ) <= 0 )
#     {
#@@ -714,8 +714,14 @@
#                 return -5;
#             }
# 
#-            if( *value == annot_position && !parse_annot_position( annot_position, annot_units, annot_page, annot_left, annot_top, annot_width, annot_height ) )
#-            {
#+            try {
#+                if( *value == annot_position && !parse_annot_position( annot_position, annot_units, annot_page, annot_left, annot_top, annot_width, annot_height ) )
#+                {
#+                    std::cerr << "Invalid -annot-position value '" << *value << "', expected format \"page,left,top,width,height\"" << std::endl;
#+
#+                    return -6;
#+                }
#+            } catch( PdfError & e ) {
#                 std::cerr << "Invalid -annot-position value '" << *value << "', expected format \"page,left,top,width,height\"" << std::endl;
# 
#                 return -6;
Index: tools/podofotxt2pdf/podofotxt2pdf.cpp
===================================================================
--- tools/podofotxt2pdf/podofotxt2pdf.cpp	(revision 1792)
+++ tools/podofotxt2pdf/podofotxt2pdf.cpp	(revision 1793)
@@ -117,8 +117,8 @@
 
     PdfStreamedDocument doc( pszOutput );
 
-    char*  pszBuf;
-    size_t lSize;
+    char* pszBuf;
+    long lSize;
 
     hFile = fopen( pszInput, "rb" );	// read it as binary if we are going to compare sizes!
     if( !hFile )
@@ -126,13 +126,24 @@
         PODOFO_RAISE_ERROR( ePdfError_InvalidHandle );
     }
 
-    fseek( hFile, 0x00, SEEK_END );
+    if( fseek( hFile, 0x00, SEEK_END ) == -1 )
+    {
+        fclose( hFile );
+        PODOFO_RAISE_ERROR_INFO( ePdfError_InvalidDeviceOperation, "Failed to seek to the end of the file" );
+    }
+
     lSize  = ftell( hFile );
+    if( lSize == -1 )
+    {
+        fclose( hFile );
+        PODOFO_RAISE_ERROR_INFO( ePdfError_InvalidDeviceOperation, "Failed to read size of the file" );
+    }
 
     pszBuf = static_cast<char*>(malloc( sizeof( char ) * (lSize+1) ));
     fseek( hFile, 0x00, SEEK_SET );
     if( !pszBuf )
     {
+        fclose( hFile );
         PODOFO_RAISE_ERROR( ePdfError_OutOfMemory );
     }
 
@@ -140,9 +151,10 @@
     // this not very efficient, but as this is 
     // a library demonstration I do not care.
     // If anyone wants to improve this: Go for it!
-    if( fread( pszBuf, sizeof(char), lSize, hFile ) != lSize )
+    if( static_cast<long>( fread( pszBuf, sizeof(char), lSize, hFile ) ) != lSize )
     {
         free( pszBuf );
+        fclose( hFile );
         PODOFO_RAISE_ERROR( ePdfError_UnexpectedEOF );
     }
 
Index: tools/podofouncompress/Uncompress.cpp
===================================================================
--- tools/podofouncompress/Uncompress.cpp	(revision 1792)
+++ tools/podofouncompress/Uncompress.cpp	(revision 1793)
@@ -61,11 +61,13 @@
                 printf("-> Uncompressing object %i %i\n", 
                        (*it)->Reference().ObjectNumber(), (*it)->Reference().GenerationNumber() );
                 PdfMemStream* pStream = dynamic_cast<PdfMemStream*>((*it)->GetStream());
+                if( !pStream )
+                    PODOFO_RAISE_ERROR( ePdfError_InvalidHandle );
#                 printf("-> Original Length: %" PDF_FORMAT_INT64 "\n", 
                 printf("-> Original Length: %"PDF_FORMAT_INT64"\n", 
                        static_cast<pdf_int64>(pStream->GetLength()) );
                 try {
                     pStream->Uncompress();
-                } catch( const PdfError & e ) {
+                } catch( PdfError & e ) {
                     if( e.GetError() == ePdfError_Flate )
                     {
                         // Ignore ZLib errors
@@ -76,7 +78,7 @@
                 }
#                 printf("-> Uncompressed Length: %" PDF_FORMAT_INT64 "\n", 
                 printf("-> Uncompressed Length: %"PDF_FORMAT_INT64"\n", 
                        static_cast<pdf_int64>(pStream->GetLength()) );
-            } catch( const PdfError & e ) {
+            } catch( PdfError & e ) {
                 e.PrintErrorMsg();
                 if( e.GetError() != ePdfError_UnsupportedFilter )
                     throw e;
Index: tools/podofoxmp/podofoxmp.cpp
===================================================================
--- tools/podofoxmp/podofoxmp.cpp	(revision 1792)
+++ tools/podofoxmp/podofoxmp.cpp	(revision 1793)
@@ -25,8 +25,8 @@
 #include <cstdio>
 
 #ifdef _MSC_VER
-	#include <io.h>
-	#include <fcntl.h>
+    #include <io.h>
+    #include <fcntl.h>
 #endif
 
 #include <podofo.h>
@@ -35,93 +35,132 @@
 
 int main (int argc, char *argv[])
 {
-	PoDoFo::PdfError::EnableDebug(false);
-	if (argc != 2 && argc != 4)
-    {
-		cout << "Syntax" << endl;
-		cout << "  " << argv[0] << " <pdf file> - display the XMP in a file (use \"-\" to specify stdin)" << endl;
-		cout << "or" << endl;
-		cout << "  " << argv[0] << " <src pdf file> <xmp file> <new pdf file> - create a new PDF with the XMP in" << endl;
-		return EXIT_FAILURE;
-    }
+    using namespace PoDoFo;
+    PoDoFo::PdfMemDocument *doc = NULL;
+    int result = 0;
 
-	PoDoFo::PdfMemDocument *doc;
+    try {
+        PoDoFo::PdfError::EnableDebug(false);
+        if (argc != 2 && argc != 4)
+        {
+            cout << "Syntax" << endl;
+            cout << "  " << argv[0] << " <pdf file> - display the XMP in a file (use \"-\" to specify stdin)" << endl;
+            cout << "or" << endl;
+            cout << "  " << argv[0] << " <src pdf file> <xmp file> <new pdf file> - create a new PDF with the XMP in" << endl;
+            return EXIT_FAILURE;
+        }
 
-	if ( string("-") == argv[1] )
-	{
-		cin >> std::noskipws;
-		#ifdef _MSC_VER
-			_setmode(_fileno(stdin), _O_BINARY); // @TODO: MSVC specific binary setmode -- not sure if other platforms need it
-			cin.sync_with_stdio();
-		#endif
-		istream_iterator<char> it(std::cin);
-		istream_iterator<char> end;
-		string buffer(it, end);
-		doc = new PoDoFo::PdfMemDocument();
-		doc->Load( buffer.c_str(), (long)buffer.size() );
-	} 
-	else 
-	{
-		doc = new PoDoFo::PdfMemDocument(argv[1]);
-	}
+        if ( string("-") == argv[1] )
+        {
+            cin >> std::noskipws;
+            #ifdef _MSC_VER
+                _setmode(_fileno(stdin), _O_BINARY); // @TODO: MSVC specific binary setmode -- not sure if other platforms need it
+                cin.sync_with_stdio();
+            #endif
+            istream_iterator<char> it(std::cin);
+            istream_iterator<char> end;
+            string buffer(it, end);
+            doc = new PoDoFo::PdfMemDocument();
+            doc->Load( buffer.c_str(), (long)buffer.size() );
+        }
+        else
+        {
+            doc = new PoDoFo::PdfMemDocument(argv[1]);
+        }
 
 
-	if (argc == 2)
-    {
-		PoDoFo::PdfObject *metadata;
-		if ((metadata = doc->GetMetadata()) == NULL)
-			cout << "No metadata" << endl;
-		else
+        if (argc == 2)
         {
-			PoDoFo::PdfStream *str = metadata->GetStream();
-			if (str != NULL)
+            PoDoFo::PdfObject *metadata;
+            if ((metadata = doc->GetMetadata()) == NULL)
+                cout << "No metadata" << endl;
+            else
             {
-				char *buf;
-				PoDoFo::pdf_long len;
-	
-				str->GetFilteredCopy(&buf, &len);
-				for (PoDoFo::pdf_long i = 0; i < len; ++i)
-					printf("%c", buf[i]);
-				printf("\n");
-				fflush(stdout);
-				free(buf);
+                PoDoFo::PdfStream *str = metadata->GetStream();
+                if (str != NULL)
+                {
+                    char *buf;
+                    PoDoFo::pdf_long len;
+
+                    str->GetFilteredCopy(&buf, &len);
+                    for (PoDoFo::pdf_long i = 0; i < len; ++i)
+                        printf("%c", buf[i]);
+                    printf("\n");
+                    fflush(stdout);
+                    free(buf);
+                }
             }
         }
-    }
 
-	if (argc == 4)
-    {
-		char *xmpBuf;
-		FILE *fp;
-
-		if ((fp = fopen(argv[2], "rb")) == NULL)
-			cout << "Cannot open " << argv[2] << endl;
-		else
+        if (argc == 4)
         {
-			fseek(fp, 0, SEEK_END);
-			long xmpLen = ftell(fp);
-			xmpBuf = new char[xmpLen];
-			fseek(fp, 0, SEEK_SET);
-			fread(xmpBuf, 1, xmpLen, fp);
-			fclose(fp);
+            char *xmpBuf;
+            FILE *fp;
 
-			PoDoFo::PdfObject *metadata;
-			if ((metadata = doc->GetMetadata()) != NULL)
-				metadata->GetStream()->Set(xmpBuf, xmpLen, PoDoFo::TVecFilters());
-			else
+            if ((fp = fopen(argv[2], "rb")) == NULL)
+                cout << "Cannot open " << argv[2] << endl;
+            else
             {
-				metadata = doc->GetObjects().CreateObject("Metadata");
-				metadata->GetDictionary().AddKey(PoDoFo::PdfName("Subtype"), PoDoFo::PdfName("XML"));
-				metadata->GetStream()->Set(xmpBuf, xmpLen, PoDoFo::TVecFilters());
-				doc->GetCatalog()->GetDictionary().AddKey(PoDoFo::PdfName("Metadata"), metadata->Reference());
+                if( fseek( fp, 0, SEEK_END ) == -1 )
+                {
+                    fclose( fp );
+                    PODOFO_RAISE_ERROR_INFO( ePdfError_InvalidDeviceOperation, "Failed to seek to the end of the file" );
+                }
+
+                long xmpLen = ftell(fp);
+                if( xmpLen == -1 )
+                {
+                    fclose( fp );
+                    PODOFO_RAISE_ERROR_INFO( ePdfError_InvalidDeviceOperation, "Failed to read size of the file" );
+                }
+
+                xmpBuf = new char[xmpLen];
+                if( !xmpBuf )
+                {
+                    fclose( fp );
+                    PODOFO_RAISE_ERROR( ePdfError_OutOfMemory );
+                }
+
+                if( fseek( fp, 0, SEEK_SET ) == -1 )
+                {
+                    delete [] xmpBuf;
+                    fclose( fp );
+
+                    PODOFO_RAISE_ERROR_INFO( ePdfError_InvalidDeviceOperation, "Failed to seek to the beginning of the file" );
+                }
+
+                if( static_cast<long>( fread( xmpBuf, 1, xmpLen, fp ) ) != xmpLen )
+                {
+                    delete [] xmpBuf;
+                    fclose( fp );
+
+                    PODOFO_RAISE_ERROR_INFO( ePdfError_InvalidDeviceOperation, "Failed to read whole file into the memory" );
+                }
+
+                PoDoFo::PdfObject *metadata;
+                if ((metadata = doc->GetMetadata()) != NULL)
+                    metadata->GetStream()->Set(xmpBuf, xmpLen, PoDoFo::TVecFilters());
+                else
+                {
+                    metadata = doc->GetObjects().CreateObject("Metadata");
+                    metadata->GetDictionary().AddKey(PoDoFo::PdfName("Subtype"), PoDoFo::PdfName("XML"));
+                    metadata->GetStream()->Set(xmpBuf, xmpLen, PoDoFo::TVecFilters());
+                    doc->GetCatalog()->GetDictionary().AddKey(PoDoFo::PdfName("Metadata"), metadata->Reference());
+                }
+                delete[] xmpBuf;
+
+                doc->Write(argv[3]);
             }
-			delete[] xmpBuf;
+        }
+    } catch( PdfError & e ) {
+        std::cerr << "Error: An error " << e.GetError() << " occurred during the sign of the pdf file:" << std::endl;
+        e.PrintErrorMsg();
 
-			doc->Write(argv[3]);
-        }
+        result = e.GetError();
     }
 
-	delete doc;
+    if( doc )
+        delete doc;
 
-	return EXIT_SUCCESS;
+    return result;
 }

------------------------------------------------------------------------
