]> rtime.felk.cvut.cz Git - opencv.git/blobdiff - opencv/src/cxcore/cxarray.cpp
fixed other 2 bugs in documentation and cvReleaseMat()
[opencv.git] / opencv / src / cxcore / cxarray.cpp
index c994d9af94ddf3649a9fac0f2c325b6bdcab8ceb..7d0ef6762da12478c150ce3b4f63bce0abb83ecf 100644 (file)
@@ -48,6 +48,7 @@
 
 #include "_cxcore.h"
 
+
 static struct
 {
     Cv_iplCreateImageHeader  createHeader;
@@ -66,24 +67,18 @@ cvSetIPLAllocators( Cv_iplCreateImageHeader createHeader,
                     Cv_iplCreateROI createROI,
                     Cv_iplCloneImage cloneImage )
 {
-    CV_FUNCNAME( "cvSetIPLAllocators" );
-
-    __BEGIN__;
-
-    if( !createHeader || !allocateData || !deallocate || !createROI || !cloneImage )
-    {
-        if( createHeader || allocateData || deallocate || createROI || cloneImage )
-            CV_ERROR( CV_StsBadArg, "Either all the pointers should be null or "
-                                    "they all should be non-null" );
-    }
+    int count = (createHeader != 0) + (allocateData != 0) + (deallocate != 0) +
+        (createROI != 0) + (cloneImage != 0);
+    
+    if( count != 0 && count != 5 )
+        CV_Error( CV_StsBadArg, "Either all the pointers should be null or "
+                                 "they all should be non-null" );
 
     CvIPL.createHeader = createHeader;
     CvIPL.allocateData = allocateData;
     CvIPL.deallocate = deallocate;
     CvIPL.createROI = createROI;
     CvIPL.cloneImage = cloneImage;
-
-    __END__;
 }
 
 
@@ -95,19 +90,8 @@ cvSetIPLAllocators( Cv_iplCreateImageHeader createHeader,
 CV_IMPL CvMat*
 cvCreateMat( int height, int width, int type )
 {
-    CvMat* arr = 0;
-
-    CV_FUNCNAME( "cvCreateMat" );
-    
-    __BEGIN__;
-
-    CV_CALL( arr = cvCreateMatHeader( height, width, type ));
-    CV_CALL( cvCreateData( arr ));
-
-    __END__;
-
-    if( cvGetErrStatus() < 0 )
-        cvReleaseMat( &arr );
+    CvMat* arr = cvCreateMatHeader( height, width, type );
+    cvCreateData( arr );
 
     return arr;
 }
@@ -123,27 +107,19 @@ static void icvCheckHuge( CvMat* arr )
 CV_IMPL CvMat*
 cvCreateMatHeader( int rows, int cols, int type )
 {
-    CvMat* arr = 0;
-    
-    CV_FUNCNAME( "cvCreateMatHeader" );
-
-    __BEGIN__;
-
-    int min_step;
     type = CV_MAT_TYPE(type);
 
     if( rows <= 0 || cols <= 0 )
-        CV_ERROR( CV_StsBadSize, "Non-positive width or height" );
+        CV_Error( CV_StsBadSize, "Non-positive width or height" );
 
-    min_step = CV_ELEM_SIZE(type)*cols;
+    int min_step = CV_ELEM_SIZE(type)*cols;
     if( min_step <= 0 )
-        CV_ERROR( CV_StsUnsupportedFormat, "Invalid matrix type" );
+        CV_Error( CV_StsUnsupportedFormat, "Invalid matrix type" );
 
-    CV_CALL( arr = (CvMat*)cvAlloc( sizeof(*arr)));
+    CvMat* arr = (CvMat*)cvAlloc( sizeof(*arr));
 
-    arr->step = rows == 1 ? 0 : cvAlign(min_step, CV_DEFAULT_MAT_ROW_ALIGN);
-    arr->type = CV_MAT_MAGIC_VAL | type |
-                (arr->step == 0 || arr->step == min_step ? CV_MAT_CONT_FLAG : 0);
+    arr->step = min_step;
+    arr->type = CV_MAT_MAGIC_VAL | type | CV_MAT_CONT_FLAG;
     arr->rows = rows;
     arr->cols = cols;
     arr->data.ptr = 0;
@@ -151,12 +127,6 @@ cvCreateMatHeader( int rows, int cols, int type )
     arr->hdr_refcount = 1;
 
     icvCheckHuge( arr );
-
-    __END__;
-
-    if( cvGetErrStatus() < 0 )
-        cvReleaseMat( &arr );
-
     return arr;
 }
 
@@ -166,20 +136,14 @@ CV_IMPL CvMat*
 cvInitMatHeader( CvMat* arr, int rows, int cols,
                  int type, void* data, int step )
 {
-    CV_FUNCNAME( "cvInitMatHeader" );
-    
-    __BEGIN__;
-
-    int mask, pix_size, min_step;
-
     if( !arr )
-        CV_ERROR_FROM_CODE( CV_StsNullPtr );
+        CV_Error( CV_StsNullPtr, "" );
 
     if( (unsigned)CV_MAT_DEPTH(type) > CV_DEPTH_MAX )
-        CV_ERROR_FROM_CODE( CV_BadNumChannels );
+        CV_Error( CV_BadNumChannels, "" );
 
     if( rows <= 0 || cols <= 0 )
-        CV_ERROR( CV_StsBadSize, "Non-positive cols or rows" );
+        CV_Error( CV_StsBadSize, "Non-positive cols or rows" );
  
     type = CV_MAT_TYPE( type );
     arr->type = type | CV_MAT_MAGIC_VAL;
@@ -189,15 +153,14 @@ cvInitMatHeader( CvMat* arr, int rows, int cols,
     arr->refcount = 0;
     arr->hdr_refcount = 0;
 
-    mask = (arr->rows <= 1) - 1;
-    pix_size = CV_ELEM_SIZE(type);
-    min_step = arr->cols*pix_size & mask;
+    int pix_size = CV_ELEM_SIZE(type);
+    int min_step = arr->cols*pix_size;
 
     if( step != CV_AUTOSTEP && step != 0 )
     {
         if( step < min_step )
-            CV_ERROR_FROM_CODE( CV_BadStep );
-        arr->step = step & mask;
+            CV_Error( CV_BadStep, "" );
+        arr->step = step;
     }
     else
     {
@@ -205,41 +168,38 @@ cvInitMatHeader( CvMat* arr, int rows, int cols,
     }
 
     arr->type = CV_MAT_MAGIC_VAL | type |
-                (arr->step == min_step ? CV_MAT_CONT_FLAG : 0);
+        (arr->rows == 1 || arr->step == min_step ? CV_MAT_CONT_FLAG : 0);
 
     icvCheckHuge( arr );
-
-    __END__;
-
     return arr;
 }
 
 
+#undef CV_IS_MAT_HDR_Z
+#define CV_IS_MAT_HDR_Z(mat) \
+    ((mat) != NULL && \
+    (((const CvMat*)(mat))->type & CV_MAGIC_MASK) == CV_MAT_MAGIC_VAL && \
+    ((const CvMat*)(mat))->cols >= 0 && ((const CvMat*)(mat))->rows >= 0)
+
 // Deallocates the CvMat structure and underlying data
 CV_IMPL void
 cvReleaseMat( CvMat** array )
 {
-    CV_FUNCNAME( "cvReleaseMat" );
-    
-    __BEGIN__;
-
     if( !array )
-        CV_ERROR_FROM_CODE( CV_HeaderIsNull );
+        CV_Error( CV_HeaderIsNull, "" );
 
     if( *array )
     {
         CvMat* arr = *array;
         
-        if( !CV_IS_MAT_HDR(arr) && !CV_IS_MATND_HDR(arr) )
-            CV_ERROR_FROM_CODE( CV_StsBadFlag );
+        if( !CV_IS_MAT_HDR_Z(arr) && !CV_IS_MATND_HDR(arr) )
+            CV_Error( CV_StsBadFlag, "" );
 
         *array = 0;
 
         cvDecRefData( arr );
         cvFree( &arr );
     }
-
-    __END__;
 }
 
 
@@ -247,24 +207,17 @@ cvReleaseMat( CvMat** array )
 CV_IMPL CvMat*
 cvCloneMat( const CvMat* src )
 {
-    CvMat* dst = 0;
-    CV_FUNCNAME( "cvCloneMat" );
-
-    __BEGIN__;
-
     if( !CV_IS_MAT_HDR( src ))
-        CV_ERROR( CV_StsBadArg, "Bad CvMat header" );
+        CV_Error( CV_StsBadArg, "Bad CvMat header" );
 
-    CV_CALL( dst = cvCreateMatHeader( src->rows, src->cols, src->type ));
+    CvMat* dst = cvCreateMatHeader( src->rows, src->cols, src->type );
 
     if( src->data.ptr )
     {
-        CV_CALL( cvCreateData( dst ));
-        CV_CALL( cvCopy( src, dst ));
+        cvCreateData( dst );
+        cvCopy( src, dst );
     }
 
-    __END__;
-
     return dst;
 }
 
@@ -275,38 +228,31 @@ cvCloneMat( const CvMat* src )
 
 CV_IMPL CvMatND*
 cvInitMatNDHeader( CvMatND* mat, int dims, const int* sizes,
-                    int type, void* data )
+                   int type, void* data )
 {
-    CvMatND* result = 0;
-
-    CV_FUNCNAME( "cvInitMatNDHeader" );
-
-    __BEGIN__;
-
     type = CV_MAT_TYPE(type);
-    int i;
     int64 step = CV_ELEM_SIZE(type);
 
     if( !mat )
-        CV_ERROR( CV_StsNullPtr, "NULL matrix header pointer" );
+        CV_Error( CV_StsNullPtr, "NULL matrix header pointer" );
 
     if( step == 0 )
-        CV_ERROR( CV_StsUnsupportedFormat, "invalid array data type" );
+        CV_Error( CV_StsUnsupportedFormat, "invalid array data type" );
 
     if( !sizes )
-        CV_ERROR( CV_StsNullPtr, "NULL <sizes> pointer" );
+        CV_Error( CV_StsNullPtr, "NULL <sizes> pointer" );
 
     if( dims <= 0 || dims > CV_MAX_DIM )
-        CV_ERROR( CV_StsOutOfRange,
+        CV_Error( CV_StsOutOfRange,
         "non-positive or too large number of dimensions" );
 
-    for( i = dims - 1; i >= 0; i-- )
+    for( int i = dims - 1; i >= 0; i-- )
     {
         if( sizes[i] <= 0 )
-            CV_ERROR( CV_StsBadSize, "one of dimesion sizes is non-positive" );
+            CV_Error( CV_StsBadSize, "one of dimesion sizes is non-positive" );
         mat->dim[i].size = sizes[i];
         if( step > INT_MAX )
-            CV_ERROR( CV_StsOutOfRange, "The array is too big" );
+            CV_Error( CV_StsOutOfRange, "The array is too big" );
         mat->dim[i].step = (int)step;
         step *= sizes[i];
     }
@@ -315,17 +261,8 @@ cvInitMatNDHeader( CvMatND* mat, int dims, const int* sizes,
     mat->dims = dims;
     mat->data.ptr = (uchar*)data;
     mat->refcount = 0;
-    result = mat;
-
-    __END__;
-
-    if( cvGetErrStatus() < 0 && mat )
-    {
-        mat->type = 0;
-        mat->data.ptr = 0;
-    }
-
-    return result;
+    mat->hdr_refcount = 0;
+    return mat;
 }
 
 
@@ -333,19 +270,8 @@ cvInitMatNDHeader( CvMatND* mat, int dims, const int* sizes,
 CV_IMPL CvMatND*
 cvCreateMatND( int dims, const int* sizes, int type )
 {
-    CvMatND* arr = 0;
-
-    CV_FUNCNAME( "cvCreateMatND" );
-    
-    __BEGIN__;
-
-    CV_CALL( arr = cvCreateMatNDHeader( dims, sizes, type ));
-    CV_CALL( cvCreateData( arr ));
-
-    __END__;
-
-    if( cvGetErrStatus() < 0 )
-        cvReleaseMatND( &arr );
+    CvMatND* arr = cvCreateMatNDHeader( dims, sizes, type );
+    cvCreateData( arr );
 
     return arr;
 }
@@ -355,26 +281,14 @@ cvCreateMatND( int dims, const int* sizes, int type )
 CV_IMPL CvMatND*
 cvCreateMatNDHeader( int dims, const int* sizes, int type )
 {
-    CvMatND* arr = 0;
-    
-    CV_FUNCNAME( "cvCreateMatNDHeader" );
-
-    __BEGIN__;
-
     if( dims <= 0 || dims > CV_MAX_DIM )
-        CV_ERROR( CV_StsOutOfRange,
+        CV_Error( CV_StsOutOfRange,
         "non-positive or too large number of dimensions" );
 
-    CV_CALL( arr = (CvMatND*)cvAlloc( sizeof(*arr) ));
+    CvMatND* arr = (CvMatND*)cvAlloc( sizeof(*arr) );
     
-    CV_CALL( cvInitMatNDHeader( arr, dims, sizes, type, 0 ));
+    cvInitMatNDHeader( arr, dims, sizes, type, 0 );
     arr->hdr_refcount = 1;
-
-    __END__;
-
-    if( cvGetErrStatus() < 0 )
-        cvReleaseMatND( &arr );
-
     return arr;
 }
 
@@ -383,31 +297,22 @@ cvCreateMatNDHeader( int dims, const int* sizes, int type )
 CV_IMPL CvMatND*
 cvCloneMatND( const CvMatND* src )
 {
-    CvMatND* dst = 0;
-    CV_FUNCNAME( "cvCloneMatND" );
-
-    __BEGIN__;
-
-    int i, *sizes;
-
     if( !CV_IS_MATND_HDR( src ))
-        CV_ERROR( CV_StsBadArg, "Bad CvMatND header" );
+        CV_Error( CV_StsBadArg, "Bad CvMatND header" );
 
-    sizes = (int*)alloca( src->dims*sizeof(sizes[0]) );
+    int* sizes = (int*)cvStackAlloc( src->dims*sizeof(sizes[0]) );
 
-    for( i = 0; i < src->dims; i++ )
+    for( int i = 0; i < src->dims; i++ )
         sizes[i] = src->dim[i].size;
 
-    CV_CALL( dst = cvCreateMatNDHeader( src->dims, sizes, src->type ));
+    CvMatND* dst = cvCreateMatNDHeader( src->dims, sizes, src->type );
 
     if( src->data.ptr )
     {
-        CV_CALL( cvCreateData( dst ));
-        CV_CALL( cvCopy( src, dst ));
+        cvCreateData( dst );
+        cvCopy( src, dst );
     }
 
-    __END__;
-
     return dst;
 }
 
@@ -416,21 +321,17 @@ static CvMatND*
 cvGetMatND( const CvArr* arr, CvMatND* matnd, int* coi )
 {
     CvMatND* result = 0;
-    
-    CV_FUNCNAME( "cvGetMat" );
-
-    __BEGIN__;
 
     if( coi )
         *coi = 0;
 
     if( !matnd || !arr )
-        CV_ERROR( CV_StsNullPtr, "NULL array pointer is passed" );
+        CV_Error( CV_StsNullPtr, "NULL array pointer is passed" );
 
     if( CV_IS_MATND_HDR(arr))
     {
         if( !((CvMatND*)arr)->data.ptr )
-            CV_ERROR( CV_StsNullPtr, "The matrix has NULL data pointer" );
+            CV_Error( CV_StsNullPtr, "The matrix has NULL data pointer" );
         
         result = (CvMatND*)arr;
     }
@@ -439,13 +340,13 @@ cvGetMatND( const CvArr* arr, CvMatND* matnd, int* coi )
         CvMat stub, *mat = (CvMat*)arr;
         
         if( CV_IS_IMAGE_HDR( mat ))
-            CV_CALL( mat = cvGetMat( mat, &stub, coi ));
+            mat = cvGetMat( mat, &stub, coi );
 
         if( !CV_IS_MAT_HDR( mat ))
-            CV_ERROR( CV_StsBadArg, "Unrecognized or unsupported array type" );
+            CV_Error( CV_StsBadArg, "Unrecognized or unsupported array type" );
         
         if( !mat->data.ptr )
-            CV_ERROR( CV_StsNullPtr, "Input array has NULL data pointer" );
+            CV_Error( CV_StsNullPtr, "Input array has NULL data pointer" );
 
         matnd->data.ptr = mat->data.ptr;
         matnd->refcount = 0;
@@ -459,8 +360,6 @@ cvGetMatND( const CvArr* arr, CvMatND* matnd, int* coi )
         result = matnd;
     }
 
-    __END__;
-
     return result;
 }
 
@@ -480,23 +379,18 @@ cvInitNArrayIterator( int count, CvArr** arrs,
                       CvNArrayIterator* iterator, int flags )
 {
     int dims = -1;
-
-    CV_FUNCNAME( "cvInitArrayOp" );
-    
-    __BEGIN__;
-
     int i, j, size, dim0 = -1;
     int64 step;
     CvMatND* hdr0 = 0;
 
     if( count < 1 || count > CV_MAX_ARR )
-        CV_ERROR( CV_StsOutOfRange, "Incorrect number of arrays" );
+        CV_Error( CV_StsOutOfRange, "Incorrect number of arrays" );
 
     if( !arrs || !stubs )
-        CV_ERROR( CV_StsNullPtr, "Some of required array pointers is NULL" );
+        CV_Error( CV_StsNullPtr, "Some of required array pointers is NULL" );
 
     if( !iterator )
-        CV_ERROR( CV_StsNullPtr, "Iterator pointer is NULL" );
+        CV_Error( CV_StsNullPtr, "Iterator pointer is NULL" );
 
     for( i = 0; i <= count; i++ )
     {
@@ -506,7 +400,7 @@ cvInitNArrayIterator( int count, CvArr** arrs,
         if( !arr )
         {
             if( i < count )
-                CV_ERROR( CV_StsNullPtr, "Some of required array pointers is NULL" );
+                CV_Error( CV_StsNullPtr, "Some of required array pointers is NULL" );
             break;
         }
 
@@ -515,9 +409,9 @@ cvInitNArrayIterator( int count, CvArr** arrs,
         else
         {
             int coi = 0;
-            CV_CALL( hdr = cvGetMatND( arr, stubs + i, &coi ));
+            hdr = cvGetMatND( arr, stubs + i, &coi );
             if( coi != 0 )
-                CV_ERROR( CV_BadCOI, "COI set is not allowed here" );
+                CV_Error( CV_BadCOI, "COI set is not allowed here" );
         }
 
         iterator->hdr[i] = hdr;
@@ -525,7 +419,7 @@ cvInitNArrayIterator( int count, CvArr** arrs,
         if( i > 0 )
         {
             if( hdr->dims != hdr0->dims )
-                CV_ERROR( CV_StsUnmatchedSizes,
+                CV_Error( CV_StsUnmatchedSizes,
                           "Number of dimensions is the same for all arrays" );
             
             if( i < count )
@@ -534,17 +428,17 @@ cvInitNArrayIterator( int count, CvArr** arrs,
                 {
                 case 0:
                     if( !CV_ARE_TYPES_EQ( hdr, hdr0 ))
-                        CV_ERROR( CV_StsUnmatchedFormats,
+                        CV_Error( CV_StsUnmatchedFormats,
                                   "Data type is not the same for all arrays" );
                     break;
                 case CV_NO_DEPTH_CHECK:
                     if( !CV_ARE_CNS_EQ( hdr, hdr0 ))
-                        CV_ERROR( CV_StsUnmatchedFormats,
+                        CV_Error( CV_StsUnmatchedFormats,
                                   "Number of channels is not the same for all arrays" );
                     break;
                 case CV_NO_CN_CHECK:
                     if( !CV_ARE_CNS_EQ( hdr, hdr0 ))
-                        CV_ERROR( CV_StsUnmatchedFormats,
+                        CV_Error( CV_StsUnmatchedFormats,
                                   "Depth is not the same for all arrays" );
                     break;
                 }
@@ -552,14 +446,14 @@ cvInitNArrayIterator( int count, CvArr** arrs,
             else
             {
                 if( !CV_IS_MASK_ARR( hdr ))
-                    CV_ERROR( CV_StsBadMask, "Mask should have 8uC1 or 8sC1 data type" );
+                    CV_Error( CV_StsBadMask, "Mask should have 8uC1 or 8sC1 data type" );
             }
 
             if( !(flags & CV_NO_SIZE_CHECK) )
             {
                 for( j = 0; j < hdr->dims; j++ )
                     if( hdr->dim[j].size != hdr0->dim[j].size )
-                        CV_ERROR( CV_StsUnmatchedSizes,
+                        CV_Error( CV_StsUnmatchedSizes,
                                   "Dimension sizes are the same for all arrays" );
             }
         }
@@ -596,14 +490,12 @@ cvInitNArrayIterator( int count, CvArr** arrs,
     for( i = 0; i < dims; i++ )
         iterator->stack[i] = hdr0->dim[i].size;
 
-    __END__;
-
     return dims;
 }
 
 
 // returns zero value if iteration is finished, non-zero otherwise
-CV_IMPL  int  cvNextNArraySlice( CvNArrayIterator* iterator )
+CV_IMPL int cvNextNArraySlice( CvNArrayIterator* iterator )
 {
     assert( iterator != 0 );
     int i, dims, size = 0;
@@ -637,12 +529,6 @@ CV_IMPL  int  cvNextNArraySlice( CvNArrayIterator* iterator )
 CV_IMPL CvSparseMat*
 cvCreateSparseMat( int dims, const int* sizes, int type )
 {
-    CvSparseMat* arr = 0;
-
-    CV_FUNCNAME( "cvCreateSparseMat" );
-    
-    __BEGIN__;
-
     type = CV_MAT_TYPE( type );
     int pix_size1 = CV_ELEM_SIZE1(type);
     int pix_size = pix_size1*CV_MAT_CN(type);
@@ -650,21 +536,21 @@ cvCreateSparseMat( int dims, const int* sizes, int type )
     CvMemStorage* storage;
 
     if( pix_size == 0 )
-        CV_ERROR( CV_StsUnsupportedFormat, "invalid array data type" );
+        CV_Error( CV_StsUnsupportedFormat, "invalid array data type" );
 
     if( dims <= 0 || dims > CV_MAX_DIM_HEAP )
-        CV_ERROR( CV_StsOutOfRange, "bad number of dimensions" );
+        CV_Error( CV_StsOutOfRange, "bad number of dimensions" );
 
     if( !sizes )
-        CV_ERROR( CV_StsNullPtr, "NULL <sizes> pointer" );
+        CV_Error( CV_StsNullPtr, "NULL <sizes> pointer" );
 
     for( i = 0; i < dims; i++ )
     {
         if( sizes[i] <= 0 )
-            CV_ERROR( CV_StsBadSize, "one of dimesion sizes is non-positive" );
+            CV_Error( CV_StsBadSize, "one of dimesion sizes is non-positive" );
     }
 
-    CV_CALL( arr = (CvSparseMat*)cvAlloc(sizeof(*arr)+MAX(0,dims-CV_MAX_DIM)*sizeof(arr->size[0])));
+    CvSparseMat* arr = (CvSparseMat*)cvAlloc(sizeof(*arr)+MAX(0,dims-CV_MAX_DIM)*sizeof(arr->size[0]));
 
     arr->type = CV_SPARSE_MAT_MAGIC_VAL | type;
     arr->dims = dims;
@@ -676,20 +562,15 @@ cvCreateSparseMat( int dims, const int* sizes, int type )
     arr->idxoffset = (int)cvAlign(arr->valoffset + pix_size, sizeof(int));
     size = (int)cvAlign(arr->idxoffset + dims*sizeof(int), sizeof(CvSetElem));
 
-    CV_CALL( storage = cvCreateMemStorage( CV_SPARSE_MAT_BLOCK ));
-    CV_CALL( arr->heap = cvCreateSet( 0, sizeof(CvSet), size, storage ));
+    storage = cvCreateMemStorage( CV_SPARSE_MAT_BLOCK );
+    arr->heap = cvCreateSet( 0, sizeof(CvSet), size, storage );
 
     arr->hashsize = CV_SPARSE_HASH_SIZE0;
     size = arr->hashsize*sizeof(arr->hashtable[0]);
     
-    CV_CALL( arr->hashtable = (void**)cvAlloc( size ));
+    arr->hashtable = (void**)cvAlloc( size );
     memset( arr->hashtable, 0, size );
 
-    __END__;
-
-    if( cvGetErrStatus() < 0 )
-        cvReleaseSparseMat( &arr );
-
     return arr;
 }
 
@@ -698,28 +579,23 @@ cvCreateSparseMat( int dims, const int* sizes, int type )
 CV_IMPL void
 cvReleaseSparseMat( CvSparseMat** array )
 {
-    CV_FUNCNAME( "cvReleaseSparseMat" );
-    
-    __BEGIN__;
-
     if( !array )
-        CV_ERROR_FROM_CODE( CV_HeaderIsNull );
+        CV_Error( CV_HeaderIsNull, "" );
 
     if( *array )
     {
         CvSparseMat* arr = *array;
         
         if( !CV_IS_SPARSE_MAT_HDR(arr) )
-            CV_ERROR_FROM_CODE( CV_StsBadFlag );
+            CV_Error( CV_StsBadFlag, "" );
 
         *array = 0;
 
-        cvReleaseMemStorage( &arr->heap->storage );
+        CvMemStorage* storage = arr->heap->storage;
+        cvReleaseMemStorage( &storage );
         cvFree( &arr->hashtable );
         cvFree( &arr );
     }
-
-    __END__;
 }
 
 
@@ -727,23 +603,11 @@ cvReleaseSparseMat( CvSparseMat** array )
 CV_IMPL CvSparseMat*
 cvCloneSparseMat( const CvSparseMat* src )
 {
-    CvSparseMat* dst = 0;
-    
-    CV_FUNCNAME( "cvCloneSparseMat" );
-    
-    __BEGIN__;
-
     if( !CV_IS_SPARSE_MAT_HDR(src) )
-        CV_ERROR( CV_StsBadArg, "Invalid sparse array header" );
+        CV_Error( CV_StsBadArg, "Invalid sparse array header" );
 
-    CV_CALL( dst = cvCreateSparseMat( src->dims, src->size, src->type ));
-    CV_CALL( cvCopy( src, dst )); 
-
-    __END__;
-
-    if( cvGetErrStatus() < 0 )
-        cvReleaseSparseMat( &dst );
-    
+    CvSparseMat* dst = cvCreateSparseMat( src->dims, src->size, src->type );
+    cvCopy( src, dst ); 
     return dst;
 }
 
@@ -752,18 +616,13 @@ CvSparseNode*
 cvInitSparseMatIterator( const CvSparseMat* mat, CvSparseMatIterator* iterator )
 {
     CvSparseNode* node = 0;
-    
-    CV_FUNCNAME( "cvInitSparseMatIterator" );
-
-    __BEGIN__;
-
     int idx;
 
     if( !CV_IS_SPARSE_MAT( mat ))
-        CV_ERROR( CV_StsBadArg, "Invalid sparse matrix header" );
+        CV_Error( CV_StsBadArg, "Invalid sparse matrix header" );
 
     if( !iterator )
-        CV_ERROR( CV_StsNullPtr, "NULL iterator pointer" );
+        CV_Error( CV_StsNullPtr, "NULL iterator pointer" );
 
     iterator->mat = (CvSparseMat*)mat;
     iterator->node = 0;
@@ -776,24 +635,16 @@ cvInitSparseMatIterator( const CvSparseMat* mat, CvSparseMatIterator* iterator )
         }
 
     iterator->curidx = idx;
-
-    __END__;
-
     return node;
 }
 
-#define ICV_SPARSE_MAT_HASH_MULTIPLIER  33
+#define ICV_SPARSE_MAT_HASH_MULTIPLIER  cv::SparseMat::HASH_SCALE
 
 static uchar*
-icvGetNodePtr( CvSparseMat* mat, int* idx, int* _type,
+icvGetNodePtr( CvSparseMat* mat, const int* idx, int* _type,
                int create_node, unsigned* precalc_hashval )
 {
     uchar* ptr = 0;
-    
-    CV_FUNCNAME( "icvGetNodePtr" );
-
-    __BEGIN__;
-
     int i, tabidx;
     unsigned hashval = 0;
     CvSparseNode *node;
@@ -805,7 +656,7 @@ icvGetNodePtr( CvSparseMat* mat, int* idx, int* _type,
         {
             int t = idx[i];
             if( (unsigned)t >= (unsigned)mat->size[i] )
-                CV_ERROR( CV_StsOutOfRange, "One of indices is out of range" );
+                CV_Error( CV_StsOutOfRange, "One of indices is out of range" );
             hashval = hashval*ICV_SPARSE_MAT_HASH_MULTIPLIER + t;
         }
     }
@@ -817,19 +668,22 @@ icvGetNodePtr( CvSparseMat* mat, int* idx, int* _type,
     tabidx = hashval & (mat->hashsize - 1);
     hashval &= INT_MAX;
 
-    for( node = (CvSparseNode*)mat->hashtable[tabidx];
-         node != 0; node = node->next )
+    if( create_node >= -1 )
     {
-        if( node->hashval == hashval )
+        for( node = (CvSparseNode*)mat->hashtable[tabidx];
+             node != 0; node = node->next )
         {
-            int* nodeidx = CV_NODE_IDX(mat,node);
-            for( i = 0; i < mat->dims; i++ )
-                if( idx[i] != nodeidx[i] )
-                    break;
-            if( i == mat->dims )
+            if( node->hashval == hashval )
             {
-                ptr = (uchar*)CV_NODE_VAL(mat,node);
-                break;
+                int* nodeidx = CV_NODE_IDX(mat,node);
+                for( i = 0; i < mat->dims; i++ )
+                    if( idx[i] != nodeidx[i] )
+                        break;
+                if( i == mat->dims )
+                {
+                    ptr = (uchar*)CV_NODE_VAL(mat,node);
+                    break;
+                }
             }
         }
     }
@@ -846,7 +700,7 @@ icvGetNodePtr( CvSparseMat* mat, int* idx, int* _type,
             assert( (newsize & (newsize - 1)) == 0 );
 
             // resize hash table
-            CV_CALL( newtable = (void**)cvAlloc( newrawsize ));
+            newtable = (void**)cvAlloc( newrawsize );
             memset( newtable, 0, newrawsize );
 
             node = cvInitSparseMatIterator( mat, &iterator );
@@ -878,19 +732,13 @@ icvGetNodePtr( CvSparseMat* mat, int* idx, int* _type,
     if( _type )
         *_type = CV_MAT_TYPE(mat->type);
 
-    __END__;
-
     return ptr;
 }
 
 
 static void
-icvDeleteNode( CvSparseMat* mat, int* idx, unsigned* precalc_hashval )
+icvDeleteNode( CvSparseMat* mat, const int* idx, unsigned* precalc_hashval )
 {
-    CV_FUNCNAME( "icvDeleteNode" );
-
-    __BEGIN__;
-
     int i, tabidx;
     unsigned hashval = 0;
     CvSparseNode *node, *prev = 0;
@@ -902,7 +750,7 @@ icvDeleteNode( CvSparseMat* mat, int* idx, unsigned* precalc_hashval )
         {
             int t = idx[i];
             if( (unsigned)t >= (unsigned)mat->size[i] )
-                CV_ERROR( CV_StsOutOfRange, "One of indices is out of range" );
+                CV_Error( CV_StsOutOfRange, "One of indices is out of range" );
             hashval = hashval*ICV_SPARSE_MAT_HASH_MULTIPLIER + t;
         }
     }
@@ -936,12 +784,9 @@ icvDeleteNode( CvSparseMat* mat, int* idx, unsigned* precalc_hashval )
             mat->hashtable[tabidx] = node->next;
         cvSetRemoveByPtr( mat->heap, node );
     }
-
-    __END__;
 }
 
 
-
 /****************************************************************************************\
 *                          Common for multiple array types operations                    *
 \****************************************************************************************/
@@ -950,10 +795,6 @@ icvDeleteNode( CvSparseMat* mat, int* idx, unsigned* precalc_hashval )
 CV_IMPL void
 cvCreateData( CvArr* arr )
 {
-    CV_FUNCNAME( "cvCreateData" );
-    
-    __BEGIN__;
-
     if( CV_IS_MAT_HDR( arr ))
     {
         size_t step, total_size;
@@ -961,13 +802,16 @@ cvCreateData( CvArr* arr )
         step = mat->step;
 
         if( mat->data.ptr != 0 )
-            CV_ERROR( CV_StsError, "Data is already allocated" );
+            CV_Error( CV_StsError, "Data is already allocated" );
 
         if( step == 0 )
             step = CV_ELEM_SIZE(mat->type)*mat->cols;
 
-        total_size = step*mat->rows + sizeof(int) + CV_MALLOC_ALIGN;
-        CV_CALL( mat->refcount = (int*)cvAlloc( (size_t)total_size ));
+        int64 _total_size = (int64)step*mat->rows + sizeof(int) + CV_MALLOC_ALIGN;
+        total_size = (size_t)_total_size;
+        if(_total_size != (int64)total_size)
+            CV_Error(CV_StsNoMem, "Too big buffer is allocated" );
+        mat->refcount = (int*)cvAlloc( (size_t)total_size );
         mat->data.ptr = (uchar*)cvAlignPtr( mat->refcount + 1, CV_MALLOC_ALIGN );
         *mat->refcount = 1;
     }
@@ -976,19 +820,19 @@ cvCreateData( CvArr* arr )
         IplImage* img = (IplImage*)arr;
 
         if( img->imageData != 0 )
-            CV_ERROR( CV_StsError, "Data is already allocated" );
+            CV_Error( CV_StsError, "Data is already allocated" );
 
         if( !CvIPL.allocateData )
         {
-            CV_CALL( img->imageData = img->imageDataOrigin = 
-                        (char*)cvAlloc( (size_t)img->imageSize ));
+            img->imageData = img->imageDataOrigin = 
+                        (char*)cvAlloc( (size_t)img->imageSize );
         }
         else
         {
             int depth = img->depth;
             int width = img->width;
 
-            if( img->depth == IPL_DEPTH_32F || img->nChannels == 64 )
+            if( img->depth == IPL_DEPTH_32F || img->depth == IPL_DEPTH_64F )
             {
                 img->width *= img->depth == IPL_DEPTH_32F ? sizeof(float) : sizeof(double);
                 img->depth = IPL_DEPTH_8U;
@@ -1007,7 +851,7 @@ cvCreateData( CvArr* arr )
         size_t total_size = CV_ELEM_SIZE(mat->type);
 
         if( mat->data.ptr != 0 )
-            CV_ERROR( CV_StsError, "Data is already allocated" );
+            CV_Error( CV_StsError, "Data is already allocated" );
 
         if( CV_IS_MAT_CONT( mat->type ))
         {
@@ -1025,17 +869,13 @@ cvCreateData( CvArr* arr )
             }
         }
         
-        CV_CALL( mat->refcount = (int*)cvAlloc( total_size +
-                                        sizeof(int) + CV_MALLOC_ALIGN ));
+        mat->refcount = (int*)cvAlloc( total_size +
+                                        sizeof(int) + CV_MALLOC_ALIGN );
         mat->data.ptr = (uchar*)cvAlignPtr( mat->refcount + 1, CV_MALLOC_ALIGN );
         *mat->refcount = 1;
     }
     else
-    {
-        CV_ERROR( CV_StsBadArg, "unrecognized or unsupported array type" );
-    }
-
-    __END__;
+        CV_Error( CV_StsBadArg, "unrecognized or unsupported array type" );
 }
 
 
@@ -1043,100 +883,83 @@ cvCreateData( CvArr* arr )
 CV_IMPL void
 cvSetData( CvArr* arr, void* data, int step )
 {
-    CV_FUNCNAME( "cvSetData" );
-
-    __BEGIN__;
-
     int pix_size, min_step;
 
     if( CV_IS_MAT_HDR(arr) || CV_IS_MATND_HDR(arr) )
         cvReleaseData( arr );
 
-    if( data )
+    if( CV_IS_MAT_HDR( arr ))
     {
-        if( CV_IS_MAT_HDR( arr ))
-        {
-            CvMat* mat = (CvMat*)arr;
-        
-            int type = CV_MAT_TYPE(mat->type);
-            pix_size = CV_ELEM_SIZE(type);
-            min_step = mat->cols*pix_size & ((mat->rows <= 1) - 1);
-
-            if( step != CV_AUTOSTEP )
-            {
-                if( step < min_step && data != 0 )
-                    CV_ERROR_FROM_CODE( CV_BadStep );
-                mat->step = step & ((mat->rows <= 1) - 1);
-            }
-            else
-            {
-                mat->step = min_step;
-            }
+        CvMat* mat = (CvMat*)arr;
     
-            mat->data.ptr = (uchar*)data;
-            mat->type = CV_MAT_MAGIC_VAL | type |
-                        (mat->step==min_step ? CV_MAT_CONT_FLAG : 0);
-            icvCheckHuge( mat );
-        }
-        else if( CV_IS_IMAGE_HDR( arr ))
-        {
-            IplImage* img = (IplImage*)arr;
-        
-            pix_size = ((img->depth & 255) >> 3)*img->nChannels;
-            min_step = img->width*pix_size;
+        int type = CV_MAT_TYPE(mat->type);
+        pix_size = CV_ELEM_SIZE(type);
+        min_step = mat->cols*pix_size;
 
-            if( step != CV_AUTOSTEP && img->height > 1 )
-            {
-                if( step < min_step && data != 0 )
-                    CV_ERROR_FROM_CODE( CV_BadStep );
-                img->widthStep = step;
-            }
-            else
-            {
-                img->widthStep = min_step;
-            }
+        if( step != CV_AUTOSTEP && step != 0 )
+        {
+            if( step < min_step && data != 0 )
+                CV_Error( CV_BadStep, "" );
+            mat->step = step;
+        }
+        else
+            mat->step = min_step;
 
-            img->imageSize = img->widthStep * img->height;
-            img->imageData = img->imageDataOrigin = (char*)data;
+        mat->data.ptr = (uchar*)data;
+        mat->type = CV_MAT_MAGIC_VAL | type |
+                    (mat->rows == 1 || mat->step == min_step ? CV_MAT_CONT_FLAG : 0);
+        icvCheckHuge( mat );
+    }
+    else if( CV_IS_IMAGE_HDR( arr ))
+    {
+        IplImage* img = (IplImage*)arr;
+    
+        pix_size = ((img->depth & 255) >> 3)*img->nChannels;
+        min_step = img->width*pix_size;
 
-            if( (((int)(size_t)data | step) & 7) == 0 &&
-                cvAlign(img->width * pix_size, 8) == step )
-            {
-                img->align = 8;
-            }
-            else
-            {
-                img->align = 4;
-            }
+        if( step != CV_AUTOSTEP && img->height > 1 )
+        {
+            if( step < min_step && data != 0 )
+                CV_Error( CV_BadStep, "" );
+            img->widthStep = step;
         }
-        else if( CV_IS_MATND_HDR( arr ))
+        else
         {
-            CvMatND* mat = (CvMatND*)arr;
-            int i;
-            int64 cur_step;
-        
-            if( step != CV_AUTOSTEP )
-                CV_ERROR( CV_BadStep,
-                "For multidimensional array only CV_AUTOSTEP is allowed here" );
+            img->widthStep = min_step;
+        }
 
-            mat->data.ptr = (uchar*)data;
-            cur_step = CV_ELEM_SIZE(mat->type);
+        img->imageSize = img->widthStep * img->height;
+        img->imageData = img->imageDataOrigin = (char*)data;
 
-            for( i = mat->dims - 1; i >= 0; i-- )
-            {
-                if( cur_step > INT_MAX )
-                    CV_ERROR( CV_StsOutOfRange, "The array is too big" );
-                mat->dim[i].step = (int)cur_step;
-                cur_step *= mat->dim[i].size;
-            }
-        }
+        if( (((int)(size_t)data | step) & 7) == 0 &&
+            cvAlign(img->width * pix_size, 8) == step )
+            img->align = 8;
         else
+            img->align = 4;
+    }
+    else if( CV_IS_MATND_HDR( arr ))
+    {
+        CvMatND* mat = (CvMatND*)arr;
+        int i;
+        int64 cur_step;
+    
+        if( step != CV_AUTOSTEP )
+            CV_Error( CV_BadStep,
+            "For multidimensional array only CV_AUTOSTEP is allowed here" );
+
+        mat->data.ptr = (uchar*)data;
+        cur_step = CV_ELEM_SIZE(mat->type);
+
+        for( i = mat->dims - 1; i >= 0; i-- )
         {
-            CV_ERROR( CV_StsBadArg, "unrecognized or unsupported array type" );
+            if( cur_step > INT_MAX )
+                CV_Error( CV_StsOutOfRange, "The array is too big" );
+            mat->dim[i].step = (int)cur_step;
+            cur_step *= mat->dim[i].size;
         }
     }
-
-    __END__;
+    else
+        CV_Error( CV_StsBadArg, "unrecognized or unsupported array type" );
 }
 
 
@@ -1144,10 +967,6 @@ cvSetData( CvArr* arr, void* data, int step )
 CV_IMPL void
 cvReleaseData( CvArr* arr )
 {
-    CV_FUNCNAME( "cvReleaseData" );
-    
-    __BEGIN__;
-
     if( CV_IS_MAT_HDR( arr ) || CV_IS_MATND_HDR( arr ))
     {
         CvMat* mat = (CvMat*)arr;
@@ -1169,11 +988,7 @@ cvReleaseData( CvArr* arr )
         }
     }
     else
-    {
-        CV_ERROR( CV_StsBadArg, "unrecognized or unsupported array type" );
-    }
-
-    __END__;
+        CV_Error( CV_StsBadArg, "unrecognized or unsupported array type" );
 }
 
 
@@ -1181,10 +996,6 @@ cvReleaseData( CvArr* arr )
 CV_IMPL void
 cvGetRawData( const CvArr* arr, uchar** data, int* step, CvSize* roi_size )
 {
-    CV_FUNCNAME( "cvGetRawData" );
-
-    __BEGIN__;
-
     if( CV_IS_MAT( arr ))
     {
         CvMat *mat = (CvMat*)arr;
@@ -1206,7 +1017,7 @@ cvGetRawData( const CvArr* arr, uchar** data, int* step, CvSize* roi_size )
             *step = img->widthStep;
 
         if( data )
-            CV_CALL( *data = cvPtr2D( img, 0, 0 ));
+            *data = cvPtr2D( img, 0, 0 );
 
         if( roi_size )
         {
@@ -1225,7 +1036,7 @@ cvGetRawData( const CvArr* arr, uchar** data, int* step, CvSize* roi_size )
         CvMatND* mat = (CvMatND*)arr;
 
         if( !CV_IS_MAT_CONT( mat->type ))
-            CV_ERROR( CV_StsBadArg, "Only continuous nD arrays are supported here" );
+            CV_Error( CV_StsBadArg, "Only continuous nD arrays are supported here" );
 
         if( data )
             *data = mat->data.ptr;
@@ -1247,15 +1058,11 @@ cvGetRawData( const CvArr* arr, uchar** data, int* step, CvSize* roi_size )
             }
 
             if( step )
-                *step = size1 == 1 ? 0 : mat->dim[0].step;
+                *step = mat->dim[0].step;
         }
     }
     else
-    {
-        CV_ERROR( CV_StsBadArg, "unrecognized or unsupported array type" );
-    }
-
-    __END__;
+        CV_Error( CV_StsBadArg, "unrecognized or unsupported array type" );
 }
 
 
@@ -1263,24 +1070,15 @@ CV_IMPL int
 cvGetElemType( const CvArr* arr )
 {
     int type = -1;
-
-    CV_FUNCNAME( "cvGetElemType" );
-
-    __BEGIN__;
-
     if( CV_IS_MAT_HDR(arr) || CV_IS_MATND_HDR(arr) || CV_IS_SPARSE_MAT_HDR(arr))
-    {
         type = CV_MAT_TYPE( ((CvMat*)arr)->type );
-    }
     else if( CV_IS_IMAGE(arr))
     {
         IplImage* img = (IplImage*)arr;
-        type = CV_MAKETYPE( icvIplToCvDepth(img->depth), img->nChannels );
+        type = CV_MAKETYPE( IPL2CV_DEPTH(img->depth), img->nChannels );
     }
     else
-        CV_ERROR( CV_StsBadArg, "unrecognized or unsupported array type" );
-
-    __END__;
+        CV_Error( CV_StsBadArg, "unrecognized or unsupported array type" );
 
     return type;
 }
@@ -1291,10 +1089,6 @@ CV_IMPL int
 cvGetDims( const CvArr* arr, int* sizes )
 {
     int dims = -1;
-    CV_FUNCNAME( "cvGetDims" );
-
-    __BEGIN__;
-
     if( CV_IS_MAT_HDR( arr ))
     {
         CvMat* mat = (CvMat*)arr;
@@ -1338,11 +1132,7 @@ cvGetDims( const CvArr* arr, int* sizes )
             memcpy( sizes, mat->size, dims*sizeof(sizes[0]));
     }
     else
-    {
-        CV_ERROR( CV_StsBadArg, "unrecognized or unsupported array type" );
-    }
-
-    __END__;
+        CV_Error( CV_StsBadArg, "unrecognized or unsupported array type" );
 
     return dims;
 }
@@ -1353,9 +1143,6 @@ CV_IMPL int
 cvGetDimSize( const CvArr* arr, int index )
 {
     int size = -1;
-    CV_FUNCNAME( "cvGetDimSize" );
-
-    __BEGIN__;
 
     if( CV_IS_MAT( arr ))
     {
@@ -1370,7 +1157,7 @@ cvGetDimSize( const CvArr* arr, int index )
             size = mat->cols;
             break;
         default:
-            CV_ERROR( CV_StsOutOfRange, "bad dimension index" );
+            CV_Error( CV_StsOutOfRange, "bad dimension index" );
         }
     }
     else if( CV_IS_IMAGE( arr ))
@@ -1386,7 +1173,7 @@ cvGetDimSize( const CvArr* arr, int index )
             size = !img->roi ? img->width : img->roi->width;
             break;
         default:
-            CV_ERROR( CV_StsOutOfRange, "bad dimension index" );
+            CV_Error( CV_StsOutOfRange, "bad dimension index" );
         }
     }
     else if( CV_IS_MATND_HDR( arr ))
@@ -1394,7 +1181,7 @@ cvGetDimSize( const CvArr* arr, int index )
         CvMatND* mat = (CvMatND*)arr;
         
         if( (unsigned)index >= (unsigned)mat->dims )
-            CV_ERROR( CV_StsOutOfRange, "bad dimension index" );
+            CV_Error( CV_StsOutOfRange, "bad dimension index" );
 
         size = mat->dim[index].size;
     }
@@ -1403,16 +1190,12 @@ cvGetDimSize( const CvArr* arr, int index )
         CvSparseMat* mat = (CvSparseMat*)arr;
         
         if( (unsigned)index >= (unsigned)mat->dims )
-            CV_ERROR( CV_StsOutOfRange, "bad dimension index" );
+            CV_Error( CV_StsOutOfRange, "bad dimension index" );
 
         size = mat->size[index];
     }
     else
-    {
-        CV_ERROR( CV_StsBadArg, "unrecognized or unsupported array type" );
-    }
-
-    __END__;
+        CV_Error( CV_StsBadArg, "unrecognized or unsupported array type" );
 
     return size;
 }
@@ -1424,10 +1207,6 @@ cvGetSize( const CvArr* arr )
 {
     CvSize size = { 0, 0 };
 
-    CV_FUNCNAME( "cvGetSize" );
-
-    __BEGIN__;
-
     if( CV_IS_MAT_HDR( arr ))
     {
         CvMat *mat = (CvMat*)arr;
@@ -1451,11 +1230,7 @@ cvGetSize( const CvArr* arr )
         }
     }
     else
-    {
-        CV_ERROR( CV_StsBadArg, "Array should be CvMat or IplImage" );
-    }
-
-    __END__;
+        CV_Error( CV_StsBadArg, "Array should be CvMat or IplImage" );
 
     return size;
 }
@@ -1466,25 +1241,20 @@ CV_IMPL  CvMat*
 cvGetSubRect( const CvArr* arr, CvMat* submat, CvRect rect )
 {
     CvMat* res = 0;
-    
-    CV_FUNCNAME( "cvGetRect" );
-
-    __BEGIN__;
-
     CvMat stub, *mat = (CvMat*)arr;
 
     if( !CV_IS_MAT( mat ))
-        CV_CALL( mat = cvGetMat( mat, &stub ));
+        mat = cvGetMat( mat, &stub );
 
     if( !submat )
-        CV_ERROR( CV_StsNullPtr, "" );
+        CV_Error( CV_StsNullPtr, "" );
 
     if( (rect.x|rect.y|rect.width|rect.height) < 0 )
-        CV_ERROR( CV_StsBadSize, "" );
+        CV_Error( CV_StsBadSize, "" );
 
     if( rect.x + rect.width > mat->cols ||
         rect.y + rect.height > mat->rows )
-        CV_ERROR( CV_StsBadSize, "" );
+        CV_Error( CV_StsBadSize, "" );
 
     {
     /*
@@ -1497,16 +1267,14 @@ cvGetSubRect( const CvArr* arr, CvMat* submat, CvRect rect )
     */
     submat->data.ptr = mat->data.ptr + (size_t)rect.y*mat->step +
                        rect.x*CV_ELEM_SIZE(mat->type);
-    submat->step = mat->step & (rect.height > 1 ? -1 : 0);
+    submat->step = mat->step;
     submat->type = (mat->type & (rect.width < mat->cols ? ~CV_MAT_CONT_FLAG : -1)) |
-                   (submat->step == 0 ? CV_MAT_CONT_FLAG : 0);
+                   (rect.height <= 1 ? CV_MAT_CONT_FLAG : 0);
     submat->rows = rect.height;
     submat->cols = rect.width;
     submat->refcount = 0;
     res = submat;
     }
-    
-    __END__;
 
     return res;
 }
@@ -1518,22 +1286,17 @@ cvGetRows( const CvArr* arr, CvMat* submat,
            int start_row, int end_row, int delta_row )
 {
     CvMat* res = 0;
-    
-    CV_FUNCNAME( "cvGetRows" );
-
-    __BEGIN__;
-
     CvMat stub, *mat = (CvMat*)arr;
 
     if( !CV_IS_MAT( mat ))
-        CV_CALL( mat = cvGetMat( mat, &stub ));
+        mat = cvGetMat( mat, &stub );
 
     if( !submat )
-        CV_ERROR( CV_StsNullPtr, "" );
+        CV_Error( CV_StsNullPtr, "" );
 
     if( (unsigned)start_row >= (unsigned)mat->rows ||
         (unsigned)end_row > (unsigned)mat->rows || delta_row <= 0 )
-        CV_ERROR( CV_StsOutOfRange, "" );
+        CV_Error( CV_StsOutOfRange, "" );
 
     {
     /*
@@ -1547,7 +1310,7 @@ cvGetRows( const CvArr* arr, CvMat* submat,
     if( delta_row == 1 )
     {
         submat->rows = end_row - start_row;
-        submat->step = mat->step & (submat->rows > 1 ? -1 : 0);
+        submat->step = mat->step;
     }
     else
     {
@@ -1558,14 +1321,12 @@ cvGetRows( const CvArr* arr, CvMat* submat,
     submat->cols = mat->cols;
     submat->step &= submat->rows > 1 ? -1 : 0;
     submat->data.ptr = mat->data.ptr + (size_t)start_row*mat->step;
-    submat->type = (mat->type | (submat->step == 0 ? CV_MAT_CONT_FLAG : 0)) &
-                   (delta_row != 1 ? ~CV_MAT_CONT_FLAG : -1);
+    submat->type = (mat->type | (submat->rows == 1 ? CV_MAT_CONT_FLAG : 0)) &
+                   (delta_row != 1 && submat->rows > 1 ? ~CV_MAT_CONT_FLAG : -1);
     submat->refcount = 0;
     submat->hdr_refcount = 0;
     res = submat;
     }
-    
-    __END__;
 
     return res;
 }
@@ -1576,22 +1337,19 @@ CV_IMPL  CvMat*
 cvGetCols( const CvArr* arr, CvMat* submat, int start_col, int end_col )
 {
     CvMat* res = 0;
-    
-    CV_FUNCNAME( "cvGetCols" );
-
-    __BEGIN__;
-
     CvMat stub, *mat = (CvMat*)arr;
+    int cols;
 
     if( !CV_IS_MAT( mat ))
-        CV_CALL( mat = cvGetMat( mat, &stub ));
+        mat = cvGetMat( mat, &stub );
 
     if( !submat )
-        CV_ERROR( CV_StsNullPtr, "" );
-
-    if( (unsigned)start_col >= (unsigned)mat->cols ||
-        (unsigned)end_col > (unsigned)mat->cols )
-        CV_ERROR( CV_StsOutOfRange, "" );
+        CV_Error( CV_StsNullPtr, "" );
+    
+    cols = mat->cols;
+    if( (unsigned)start_col >= (unsigned)cols ||
+        (unsigned)end_col > (unsigned)cols )
+        CV_Error( CV_StsOutOfRange, "" );
 
     {
     /*
@@ -1604,16 +1362,13 @@ cvGetCols( const CvArr* arr, CvMat* submat, int start_col, int end_col )
     */
     submat->rows = mat->rows;
     submat->cols = end_col - start_col;
-    submat->step = mat->step & (submat->rows > 1 ? -1 : 0);
+    submat->step = mat->step;
     submat->data.ptr = mat->data.ptr + (size_t)start_col*CV_ELEM_SIZE(mat->type);
-    submat->type = mat->type & (submat->step && submat->cols < mat->cols ?
-                                ~CV_MAT_CONT_FLAG : -1);
+    submat->type = mat->type & (submat->rows > 1 && submat->cols < cols ? ~CV_MAT_CONT_FLAG : -1);
     submat->refcount = 0;
     submat->hdr_refcount = 0;
     res = submat;
     }
-    
-    __END__;
 
     return res;
 }
@@ -1624,19 +1379,14 @@ CV_IMPL  CvMat*
 cvGetDiag( const CvArr* arr, CvMat* submat, int diag )
 {
     CvMat* res = 0;
-    
-    CV_FUNCNAME( "cvGetDiag" );
-
-    __BEGIN__;
-
     CvMat stub, *mat = (CvMat*)arr;
     int len, pix_size; 
 
     if( !CV_IS_MAT( mat ))
-        CV_CALL( mat = cvGetMat( mat, &stub ));
+        mat = cvGetMat( mat, &stub );
 
     if( !submat )
-        CV_ERROR( CV_StsNullPtr, "" );
+        CV_Error( CV_StsNullPtr, "" );
 
     pix_size = CV_ELEM_SIZE(mat->type);
 
@@ -1654,7 +1404,7 @@ cvGetDiag( const CvArr* arr, CvMat* submat, int diag )
         len = mat->cols - diag;
         
         if( len <= 0 )
-            CV_ERROR( CV_StsOutOfRange, "" );
+            CV_Error( CV_StsOutOfRange, "" );
 
         len = CV_IMIN( len, mat->rows );
         submat->data.ptr = mat->data.ptr + diag*pix_size;
@@ -1664,7 +1414,7 @@ cvGetDiag( const CvArr* arr, CvMat* submat, int diag )
         len = mat->rows + diag;
         
         if( len <= 0 )
-            CV_ERROR( CV_StsOutOfRange, "" );
+            CV_Error( CV_StsOutOfRange, "" );
 
         len = CV_IMIN( len, mat->cols );
         submat->data.ptr = mat->data.ptr - diag*mat->step;
@@ -1672,17 +1422,15 @@ cvGetDiag( const CvArr* arr, CvMat* submat, int diag )
 
     submat->rows = len;
     submat->cols = 1;
-    submat->step = (mat->step + pix_size) & (submat->rows > 1 ? -1 : 0);
+    submat->step = mat->step + (submat->rows > 1 ? pix_size : 0);
     submat->type = mat->type;
-    if( submat->step )
+    if( submat->rows > 1 )
         submat->type &= ~CV_MAT_CONT_FLAG;
     else
         submat->type |= CV_MAT_CONT_FLAG;
     submat->refcount = 0;
     submat->hdr_refcount = 0;
     res = submat;
-    
-    __END__;
 
     return res;
 }
@@ -1696,18 +1444,13 @@ cvGetDiag( const CvArr* arr, CvMat* submat, int diag )
 CV_IMPL void
 cvScalarToRawData( const CvScalar* scalar, void* data, int type, int extend_to_12 )
 {
-    CV_FUNCNAME( "cvScalarToRawData" );
-
     type = CV_MAT_TYPE(type);
-    
-    __BEGIN__;
-
     int cn = CV_MAT_CN( type );
     int depth = type & CV_MAT_DEPTH_MASK;
 
     assert( scalar && data );
     if( (unsigned)(cn - 1) >= 4 )
-        CV_ERROR( CV_StsOutOfRange, "The number of channels must be 1, 2, 3 or 4" );
+        CV_Error( CV_StsOutOfRange, "The number of channels must be 1, 2, 3 or 4" );
 
     switch( depth )
     {
@@ -1753,7 +1496,7 @@ cvScalarToRawData( const CvScalar* scalar, void* data, int type, int extend_to_1
         break;
     default:
         assert(0);
-        CV_ERROR_FROM_CODE( CV_BadDepth );
+        CV_Error( CV_BadDepth, "" );
     }
 
     if( extend_to_12 )
@@ -1768,8 +1511,6 @@ cvScalarToRawData( const CvScalar* scalar, void* data, int type, int extend_to_1
         }
         while( offset > pix_size );
     }
-
-    __END__;
 }
 
 
@@ -1777,16 +1518,12 @@ cvScalarToRawData( const CvScalar* scalar, void* data, int type, int extend_to_1
 CV_IMPL void
 cvRawDataToScalar( const void* data, int flags, CvScalar* scalar )
 {
-    CV_FUNCNAME( "cvRawDataToScalar" );
-    
-    __BEGIN__;
-
     int cn = CV_MAT_CN( flags );
 
     assert( scalar && data );
     
     if( (unsigned)(cn - 1) >= 4 )
-        CV_ERROR( CV_StsOutOfRange, "The number of channels must be 1, 2, 3 or 4" );
+        CV_Error( CV_StsOutOfRange, "The number of channels must be 1, 2, 3 or 4" );
 
     memset( scalar->val, 0, sizeof(scalar->val));
 
@@ -1822,10 +1559,8 @@ cvRawDataToScalar( const void* data, int flags, CvScalar* scalar )
         break;
     default:
         assert(0);
-        CV_ERROR_FROM_CODE( CV_BadDepth );
+        CV_Error( CV_BadDepth, "" );
     }
-
-    __END__;
 }
 
 
@@ -1897,11 +1632,6 @@ CV_IMPL  uchar*
 cvPtr1D( const CvArr* arr, int idx, int* _type )
 {
     uchar* ptr = 0;
-    
-    CV_FUNCNAME( "cvPtr1D" );
-
-    __BEGIN__;
-
     if( CV_IS_MAT( arr ))
     {
         CvMat* mat = (CvMat*)arr;
@@ -1916,7 +1646,7 @@ cvPtr1D( const CvArr* arr, int idx, int* _type )
         // that the index is within the matrix
         if( (unsigned)idx >= (unsigned)(mat->rows + mat->cols - 1) &&
             (unsigned)idx >= (unsigned)(mat->rows*mat->cols))
-            CV_ERROR( CV_StsOutOfRange, "index is out of range" );
+            CV_Error( CV_StsOutOfRange, "index is out of range" );
 
         if( CV_IS_MAT_CONT(mat->type))
         {
@@ -1953,7 +1683,7 @@ cvPtr1D( const CvArr* arr, int idx, int* _type )
             size *= mat->dim[j].size;
 
         if((unsigned)idx >= (unsigned)size )
-            CV_ERROR( CV_StsOutOfRange, "index is out of range" );
+            CV_Error( CV_StsOutOfRange, "index is out of range" );
 
         if( CV_IS_MAT_CONT(mat->type))
         {
@@ -1996,11 +1726,9 @@ cvPtr1D( const CvArr* arr, int idx, int* _type )
     }
     else
     {
-        CV_ERROR( CV_StsBadArg, "unrecognized or unsupported array type" );
+        CV_Error( CV_StsBadArg, "unrecognized or unsupported array type" );
     }
 
-    __END__;
-
     return ptr;
 }
 
@@ -2010,11 +1738,6 @@ CV_IMPL  uchar*
 cvPtr2D( const CvArr* arr, int y, int x, int* _type )
 {
     uchar* ptr = 0;
-    
-    CV_FUNCNAME( "cvPtr2D" );
-
-    __BEGIN__;
-
     if( CV_IS_MAT( arr ))
     {
         CvMat* mat = (CvMat*)arr;
@@ -2022,7 +1745,7 @@ cvPtr2D( const CvArr* arr, int y, int x, int* _type )
 
         if( (unsigned)y >= (unsigned)(mat->rows) ||
             (unsigned)x >= (unsigned)(mat->cols) )
-            CV_ERROR( CV_StsOutOfRange, "index is out of range" );
+            CV_Error( CV_StsOutOfRange, "index is out of range" );
 
         type = CV_MAT_TYPE(mat->type);
         if( _type )
@@ -2052,7 +1775,7 @@ cvPtr2D( const CvArr* arr, int y, int x, int* _type )
             {
                 int coi = img->roi->coi;
                 if( !coi )
-                    CV_ERROR( CV_BadCOI,
+                    CV_Error( CV_BadCOI,
                         "COI must be non-null in case of planar images" );
                 ptr += (coi - 1)*img->imageSize;
             }
@@ -2065,15 +1788,15 @@ cvPtr2D( const CvArr* arr, int y, int x, int* _type )
 
         if( (unsigned)y >= (unsigned)height ||
             (unsigned)x >= (unsigned)width )
-            CV_ERROR( CV_StsOutOfRange, "index is out of range" );
+            CV_Error( CV_StsOutOfRange, "index is out of range" );
 
         ptr += y*img->widthStep + x*pix_size;
 
         if( _type )
         {
-            int type = icvIplToCvDepth(img->depth);
+            int type = IPL2CV_DEPTH(img->depth);
             if( type < 0 || (unsigned)(img->nChannels - 1) > 3 )
-                CV_ERROR( CV_StsUnsupportedFormat, "" );
+                CV_Error( CV_StsUnsupportedFormat, "" );
 
             *_type = CV_MAKETYPE( type, img->nChannels );
         }
@@ -2085,7 +1808,7 @@ cvPtr2D( const CvArr* arr, int y, int x, int* _type )
         if( mat->dims != 2 || 
             (unsigned)y >= (unsigned)(mat->dim[0].size) ||
             (unsigned)x >= (unsigned)(mat->dim[1].size) )
-            CV_ERROR( CV_StsOutOfRange, "index is out of range" );
+            CV_Error( CV_StsOutOfRange, "index is out of range" );
 
         ptr = mat->data.ptr + (size_t)y*mat->dim[0].step + x*mat->dim[1].step;
         if( _type )
@@ -2098,11 +1821,9 @@ cvPtr2D( const CvArr* arr, int y, int x, int* _type )
     }
     else
     {
-        CV_ERROR( CV_StsBadArg, "unrecognized or unsupported array type" );
+        CV_Error( CV_StsBadArg, "unrecognized or unsupported array type" );
     }
 
-    __END__;
-
     return ptr;
 }
 
@@ -2112,11 +1833,6 @@ CV_IMPL  uchar*
 cvPtr3D( const CvArr* arr, int z, int y, int x, int* _type )
 {
     uchar* ptr = 0;
-    
-    CV_FUNCNAME( "cvPtr3D" );
-
-    __BEGIN__;
-
     if( CV_IS_MATND( arr ))
     {
         CvMatND* mat = (CvMatND*)arr;
@@ -2125,7 +1841,7 @@ cvPtr3D( const CvArr* arr, int z, int y, int x, int* _type )
             (unsigned)z >= (unsigned)(mat->dim[0].size) ||
             (unsigned)y >= (unsigned)(mat->dim[1].size) ||
             (unsigned)x >= (unsigned)(mat->dim[2].size) )
-            CV_ERROR( CV_StsOutOfRange, "index is out of range" );
+            CV_Error( CV_StsOutOfRange, "index is out of range" );
 
         ptr = mat->data.ptr + (size_t)z*mat->dim[0].step +
               (size_t)y*mat->dim[1].step + x*mat->dim[2].step;
@@ -2140,27 +1856,21 @@ cvPtr3D( const CvArr* arr, int z, int y, int x, int* _type )
     }
     else
     {
-        CV_ERROR( CV_StsBadArg, "unrecognized or unsupported array type" );
+        CV_Error( CV_StsBadArg, "unrecognized or unsupported array type" );
     }
 
-    __END__;
-
     return ptr;
 }
 
 
 // Returns pointer to specified element of n-d array
 CV_IMPL  uchar*
-cvPtrND( const CvArr* arr, int* idx, int* _type,
+cvPtrND( const CvArr* arr, const int* idx, int* _type,
          int create_node, unsigned* precalc_hashval )
 {
     uchar* ptr = 0;
-    CV_FUNCNAME( "cvPtrND" );
-
-    __BEGIN__;
-
     if( !idx )
-        CV_ERROR( CV_StsNullPtr, "NULL pointer to indices" );
+        CV_Error( CV_StsNullPtr, "NULL pointer to indices" );
 
     if( CV_IS_SPARSE_MAT( arr ))
         ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, 
@@ -2174,7 +1884,7 @@ cvPtrND( const CvArr* arr, int* idx, int* _type,
         for( i = 0; i < mat->dims; i++ )
         {
             if( (unsigned)idx[i] >= (unsigned)(mat->dim[i].size) )
-                CV_ERROR( CV_StsOutOfRange, "index is out of range" );
+                CV_Error( CV_StsOutOfRange, "index is out of range" );
             ptr += (size_t)idx[i]*mat->dim[i].step;
         }
 
@@ -2184,9 +1894,7 @@ cvPtrND( const CvArr* arr, int* idx, int* _type,
     else if( CV_IS_MAT_HDR(arr) || CV_IS_IMAGE_HDR(arr) )
         ptr = cvPtr2D( arr, idx[0], idx[1], _type );
     else
-        CV_ERROR( CV_StsBadArg, "unrecognized or unsupported array type" );
-
-    __END__;
+        CV_Error( CV_StsBadArg, "unrecognized or unsupported array type" );
 
     return ptr;
 }
@@ -2197,11 +1905,6 @@ CV_IMPL  CvScalar
 cvGet1D( const CvArr* arr, int idx )
 {
     CvScalar scalar = {{0,0,0,0}};
-
-    CV_FUNCNAME( "cvGet1D" );
-
-    __BEGIN__;
-
     int type = 0;
     uchar* ptr;
     
@@ -2216,7 +1919,7 @@ cvGet1D( const CvArr* arr, int idx )
         // that the index is within the matrix
         if( (unsigned)idx >= (unsigned)(mat->rows + mat->cols - 1) &&
             (unsigned)idx >= (unsigned)(mat->rows*mat->cols))
-            CV_ERROR( CV_StsOutOfRange, "index is out of range" );
+            CV_Error( CV_StsOutOfRange, "index is out of range" );
 
         ptr = mat->data.ptr + (size_t)idx*pix_size;
     }
@@ -2225,9 +1928,8 @@ cvGet1D( const CvArr* arr, int idx )
     else
         ptr = icvGetNodePtr( (CvSparseMat*)arr, &idx, &type, 0, 0 );
 
-    cvRawDataToScalar( ptr, type, &scalar );
-
-    __END__;
+    if( ptr )
+        cvRawDataToScalar( ptr, type, &scalar );
 
     return scalar;
 }
@@ -2238,11 +1940,6 @@ CV_IMPL  CvScalar
 cvGet2D( const CvArr* arr, int y, int x )
 {
     CvScalar scalar = {{0,0,0,0}};
-
-    CV_FUNCNAME( "cvGet2D" );
-
-    __BEGIN__;
-
     int type = 0;
     uchar* ptr;
 
@@ -2252,7 +1949,7 @@ cvGet2D( const CvArr* arr, int y, int x )
 
         if( (unsigned)y >= (unsigned)(mat->rows) ||
             (unsigned)x >= (unsigned)(mat->cols) )
-            CV_ERROR( CV_StsOutOfRange, "index is out of range" );
+            CV_Error( CV_StsOutOfRange, "index is out of range" );
 
         type = CV_MAT_TYPE(mat->type);
         ptr = mat->data.ptr + (size_t)y*mat->step + x*CV_ELEM_SIZE(type);
@@ -2265,9 +1962,8 @@ cvGet2D( const CvArr* arr, int y, int x )
         ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, &type, 0, 0 );
     }
 
-    cvRawDataToScalar( ptr, type, &scalar );
-
-    __END__;
+    if( ptr )
+        cvRawDataToScalar( ptr, type, &scalar );
 
     return scalar;
 }
@@ -2278,11 +1974,6 @@ CV_IMPL  CvScalar
 cvGet3D( const CvArr* arr, int z, int y, int x )
 {
     CvScalar scalar = {{0,0,0,0}};
-
-    /*CV_FUNCNAME( "cvGet3D" );*/
-
-    __BEGIN__;
-
     int type = 0;
     uchar* ptr;
 
@@ -2293,25 +1984,18 @@ cvGet3D( const CvArr* arr, int z, int y, int x )
         int idx[] = { z, y, x };
         ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, &type, 0, 0 );
     }
-
-    cvRawDataToScalar( ptr, type, &scalar );
-
-    __END__;
-
+    
+    if( ptr )
+        cvRawDataToScalar( ptr, type, &scalar );
     return scalar;
 }
 
 
 // Returns specifed element of nD array
 CV_IMPL  CvScalar
-cvGetND( const CvArr* arr, int* idx )
+cvGetND( const CvArr* arr, const int* idx )
 {
     CvScalar scalar = {{0,0,0,0}};
-
-    /*CV_FUNCNAME( "cvGetND" );*/
-
-    __BEGIN__;
-
     int type = 0;
     uchar* ptr;
 
@@ -2320,9 +2004,8 @@ cvGetND( const CvArr* arr, int* idx )
     else
         ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, &type, 0, 0 );
 
-    cvRawDataToScalar( ptr, type, &scalar );
-
-    __END__;
+    if( ptr )
+        cvRawDataToScalar( ptr, type, &scalar );
 
     return scalar;
 }
@@ -2333,11 +2016,6 @@ CV_IMPL  double
 cvGetReal1D( const CvArr* arr, int idx )
 {
     double value = 0;
-
-    CV_FUNCNAME( "cvGetReal1D" );
-
-    __BEGIN__;
-
     int type = 0;
     uchar* ptr;
 
@@ -2352,7 +2030,7 @@ cvGetReal1D( const CvArr* arr, int idx )
         // that the index is within the matrix
         if( (unsigned)idx >= (unsigned)(mat->rows + mat->cols - 1) &&
             (unsigned)idx >= (unsigned)(mat->rows*mat->cols))
-            CV_ERROR( CV_StsOutOfRange, "index is out of range" );
+            CV_Error( CV_StsOutOfRange, "index is out of range" );
 
         ptr = mat->data.ptr + (size_t)idx*pix_size;
     }
@@ -2364,13 +2042,10 @@ cvGetReal1D( const CvArr* arr, int idx )
     if( ptr )
     {
         if( CV_MAT_CN( type ) > 1 )
-            CV_ERROR( CV_BadNumChannels, "cvGetReal* support only single-channel arrays" );
+            CV_Error( CV_BadNumChannels, "cvGetReal* support only single-channel arrays" );
 
         value = icvGetReal( ptr, type );
     }
-
-    __END__;
-
     return value;
 }
 
@@ -2380,11 +2055,6 @@ CV_IMPL  double
 cvGetReal2D( const CvArr* arr, int y, int x )
 {
     double value = 0;
-
-    CV_FUNCNAME( "cvGetReal2D" );
-
-    __BEGIN__;
-
     int type = 0;
     uchar* ptr;
     
@@ -2394,7 +2064,7 @@ cvGetReal2D( const CvArr* arr, int y, int x )
 
         if( (unsigned)y >= (unsigned)(mat->rows) ||
             (unsigned)x >= (unsigned)(mat->cols) )
-            CV_ERROR( CV_StsOutOfRange, "index is out of range" );
+            CV_Error( CV_StsOutOfRange, "index is out of range" );
 
         type = CV_MAT_TYPE(mat->type);
         ptr = mat->data.ptr + (size_t)y*mat->step + x*CV_ELEM_SIZE(type);
@@ -2410,13 +2080,11 @@ cvGetReal2D( const CvArr* arr, int y, int x )
     if( ptr )
     {
         if( CV_MAT_CN( type ) > 1 )
-            CV_ERROR( CV_BadNumChannels, "cvGetReal* support only single-channel arrays" );
+            CV_Error( CV_BadNumChannels, "cvGetReal* support only single-channel arrays" );
 
         value = icvGetReal( ptr, type );
     }
 
-    __END__;
-
     return value;
 }
 
@@ -2426,11 +2094,6 @@ CV_IMPL  double
 cvGetReal3D( const CvArr* arr, int z, int y, int x )
 {
     double value = 0;
-
-    CV_FUNCNAME( "cvGetReal3D" );
-
-    __BEGIN__;
-
     int type = 0;
     uchar* ptr;
 
@@ -2445,27 +2108,20 @@ cvGetReal3D( const CvArr* arr, int z, int y, int x )
     if( ptr )
     {
         if( CV_MAT_CN( type ) > 1 )
-            CV_ERROR( CV_BadNumChannels, "cvGetReal* support only single-channel arrays" );
+            CV_Error( CV_BadNumChannels, "cvGetReal* support only single-channel arrays" );
 
         value = icvGetReal( ptr, type );
     }
 
-    __END__;
-
     return value;
 }
 
 
 // Returns specifed element of nD array
 CV_IMPL  double
-cvGetRealND( const CvArr* arr, int* idx )
+cvGetRealND( const CvArr* arr, const int* idx )
 {
     double value = 0;
-
-    CV_FUNCNAME( "cvGetRealND" );
-
-    __BEGIN__;
-
     int type = 0;
     uchar* ptr;
     
@@ -2477,13 +2133,11 @@ cvGetRealND( const CvArr* arr, int* idx )
     if( ptr )
     {
         if( CV_MAT_CN( type ) > 1 )
-            CV_ERROR( CV_BadNumChannels, "cvGetReal* support only single-channel arrays" );
+            CV_Error( CV_BadNumChannels, "cvGetReal* support only single-channel arrays" );
 
         value = icvGetReal( ptr, type );
     }
 
-    __END__;
-
     return value;
 }
 
@@ -2492,10 +2146,6 @@ cvGetRealND( const CvArr* arr, int* idx )
 CV_IMPL  void
 cvSet1D( CvArr* arr, int idx, CvScalar scalar )
 {
-    CV_FUNCNAME( "cvSet1D" );
-
-    __BEGIN__;
-
     int type = 0;
     uchar* ptr;
     
@@ -2510,7 +2160,7 @@ cvSet1D( CvArr* arr, int idx, CvScalar scalar )
         // that the index is within the matrix
         if( (unsigned)idx >= (unsigned)(mat->rows + mat->cols - 1) &&
             (unsigned)idx >= (unsigned)(mat->rows*mat->cols))
-            CV_ERROR( CV_StsOutOfRange, "index is out of range" );
+            CV_Error( CV_StsOutOfRange, "index is out of range" );
 
         ptr = mat->data.ptr + (size_t)idx*pix_size;
     }
@@ -2520,8 +2170,6 @@ cvSet1D( CvArr* arr, int idx, CvScalar scalar )
         ptr = icvGetNodePtr( (CvSparseMat*)arr, &idx, &type, -1, 0 );
 
     cvScalarToRawData( &scalar, ptr, type );
-
-    __END__;
 }
 
 
@@ -2529,10 +2177,6 @@ cvSet1D( CvArr* arr, int idx, CvScalar scalar )
 CV_IMPL  void
 cvSet2D( CvArr* arr, int y, int x, CvScalar scalar )
 {
-    CV_FUNCNAME( "cvSet2D" );
-
-    __BEGIN__;
-
     int type = 0;
     uchar* ptr;
     
@@ -2542,7 +2186,7 @@ cvSet2D( CvArr* arr, int y, int x, CvScalar scalar )
 
         if( (unsigned)y >= (unsigned)(mat->rows) ||
             (unsigned)x >= (unsigned)(mat->cols) )
-            CV_ERROR( CV_StsOutOfRange, "index is out of range" );
+            CV_Error( CV_StsOutOfRange, "index is out of range" );
 
         type = CV_MAT_TYPE(mat->type);
         ptr = mat->data.ptr + (size_t)y*mat->step + x*CV_ELEM_SIZE(type);
@@ -2555,8 +2199,6 @@ cvSet2D( CvArr* arr, int y, int x, CvScalar scalar )
         ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, &type, -1, 0 );
     }
     cvScalarToRawData( &scalar, ptr, type );
-
-    __END__;
 }
 
 
@@ -2564,10 +2206,6 @@ cvSet2D( CvArr* arr, int y, int x, CvScalar scalar )
 CV_IMPL  void
 cvSet3D( CvArr* arr, int z, int y, int x, CvScalar scalar )
 {
-    /*CV_FUNCNAME( "cvSet3D" );*/
-
-    __BEGIN__;
-
     int type = 0;
     uchar* ptr;
     
@@ -2579,19 +2217,13 @@ cvSet3D( CvArr* arr, int z, int y, int x, CvScalar scalar )
         ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, &type, -1, 0 );
     }
     cvScalarToRawData( &scalar, ptr, type );
-
-    __END__;
 }
 
 
 // Assigns new value to specifed element of nD array
 CV_IMPL  void
-cvSetND( CvArr* arr, int* idx, CvScalar scalar )
+cvSetND( CvArr* arr, const int* idx, CvScalar scalar )
 {
-    /*CV_FUNCNAME( "cvSetND" );*/
-
-    __BEGIN__;
-
     int type = 0;
     uchar* ptr;
     
@@ -2600,18 +2232,12 @@ cvSetND( CvArr* arr, int* idx, CvScalar scalar )
     else
         ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, &type, -1, 0 );
     cvScalarToRawData( &scalar, ptr, type );
-
-    __END__;
 }
 
 
 CV_IMPL  void
 cvSetReal1D( CvArr* arr, int idx, double value )
 {
-    CV_FUNCNAME( "cvSetReal1D" );
-
-    __BEGIN__;
-
     int type = 0;
     uchar* ptr;
     
@@ -2626,7 +2252,7 @@ cvSetReal1D( CvArr* arr, int idx, double value )
         // that the index is within the matrix
         if( (unsigned)idx >= (unsigned)(mat->rows + mat->cols - 1) &&
             (unsigned)idx >= (unsigned)(mat->rows*mat->cols))
-            CV_ERROR( CV_StsOutOfRange, "index is out of range" );
+            CV_Error( CV_StsOutOfRange, "index is out of range" );
 
         ptr = mat->data.ptr + (size_t)idx*pix_size;
     }
@@ -2636,22 +2262,16 @@ cvSetReal1D( CvArr* arr, int idx, double value )
         ptr = icvGetNodePtr( (CvSparseMat*)arr, &idx, &type, -1, 0 );
 
     if( CV_MAT_CN( type ) > 1 )
-        CV_ERROR( CV_BadNumChannels, "cvSetReal* support only single-channel arrays" );
+        CV_Error( CV_BadNumChannels, "cvSetReal* support only single-channel arrays" );
 
     if( ptr )
         icvSetReal( value, ptr, type );
-
-    __END__;
 }
 
 
 CV_IMPL  void
 cvSetReal2D( CvArr* arr, int y, int x, double value )
 {
-    CV_FUNCNAME( "cvSetReal2D" );
-
-    __BEGIN__;
-
     int type = 0;
     uchar* ptr;
     
@@ -2661,7 +2281,7 @@ cvSetReal2D( CvArr* arr, int y, int x, double value )
 
         if( (unsigned)y >= (unsigned)(mat->rows) ||
             (unsigned)x >= (unsigned)(mat->cols) )
-            CV_ERROR( CV_StsOutOfRange, "index is out of range" );
+            CV_Error( CV_StsOutOfRange, "index is out of range" );
 
         type = CV_MAT_TYPE(mat->type);
         ptr = mat->data.ptr + (size_t)y*mat->step + x*CV_ELEM_SIZE(type);
@@ -2676,22 +2296,16 @@ cvSetReal2D( CvArr* arr, int y, int x, double value )
         ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, &type, -1, 0 );
     }
     if( CV_MAT_CN( type ) > 1 )
-        CV_ERROR( CV_BadNumChannels, "cvSetReal* support only single-channel arrays" );
+        CV_Error( CV_BadNumChannels, "cvSetReal* support only single-channel arrays" );
 
     if( ptr )
         icvSetReal( value, ptr, type );
-
-    __END__;
 }
 
 
 CV_IMPL  void
 cvSetReal3D( CvArr* arr, int z, int y, int x, double value )
 {
-    CV_FUNCNAME( "cvSetReal3D" );
-
-    __BEGIN__;
-
     int type = 0;
     uchar* ptr;
     
@@ -2703,22 +2317,16 @@ cvSetReal3D( CvArr* arr, int z, int y, int x, double value )
         ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, &type, -1, 0 );
     }
     if( CV_MAT_CN( type ) > 1 )
-        CV_ERROR( CV_BadNumChannels, "cvSetReal* support only single-channel arrays" );
+        CV_Error( CV_BadNumChannels, "cvSetReal* support only single-channel arrays" );
 
     if( ptr )
         icvSetReal( value, ptr, type );
-
-    __END__;
 }
 
 
 CV_IMPL  void
-cvSetRealND( CvArr* arr, int* idx, double value )
+cvSetRealND( CvArr* arr, const int* idx, double value )
 {
-    CV_FUNCNAME( "cvSetRealND" );
-
-    __BEGIN__;
-
     int type = 0;
     uchar* ptr;
     
@@ -2728,22 +2336,16 @@ cvSetRealND( CvArr* arr, int* idx, double value )
         ptr = icvGetNodePtr( (CvSparseMat*)arr, idx, &type, -1, 0 );
 
     if( CV_MAT_CN( type ) > 1 )
-        CV_ERROR( CV_BadNumChannels, "cvSetReal* support only single-channel arrays" );
+        CV_Error( CV_BadNumChannels, "cvSetReal* support only single-channel arrays" );
 
     if( ptr )
         icvSetReal( value, ptr, type );
-
-    __END__;
 }
 
 
 CV_IMPL void
-cvClearND( CvArr* arr, int* idx )
+cvClearND( CvArr* arr, const int* idx )
 {
-    /*CV_FUNCNAME( "cvClearND" );*/
-
-    __BEGIN__;
-
     if( !CV_IS_SPARSE_MAT( arr ))
     {
         int type;
@@ -2753,11 +2355,7 @@ cvClearND( CvArr* arr, int* idx )
             CV_ZERO_CHAR( ptr, CV_ELEM_SIZE(type) );
     }
     else
-    {
         icvDeleteNode( (CvSparseMat*)arr, idx, 0 );
-    }
-
-    __END__;
 }
 
 
@@ -2773,18 +2371,14 @@ cvGetMat( const CvArr* array, CvMat* mat,
     CvMat* result = 0;
     CvMat* src = (CvMat*)array;
     int coi = 0;
-    
-    CV_FUNCNAME( "cvGetMat" );
-
-    __BEGIN__;
 
     if( !mat || !src )
-        CV_ERROR( CV_StsNullPtr, "NULL array pointer is passed" );
+        CV_Error( CV_StsNullPtr, "NULL array pointer is passed" );
 
     if( CV_IS_MAT_HDR(src))
     {
         if( !src->data.ptr )
-            CV_ERROR( CV_StsNullPtr, "The matrix has NULL data pointer" );
+            CV_Error( CV_StsNullPtr, "The matrix has NULL data pointer" );
         
         result = (CvMat*)src;
     }
@@ -2794,11 +2388,11 @@ cvGetMat( const CvArr* array, CvMat* mat,
         int depth, order;
 
         if( img->imageData == 0 )
-            CV_ERROR( CV_StsNullPtr, "The image has NULL data pointer" );
+            CV_Error( CV_StsNullPtr, "The image has NULL data pointer" );
 
-        depth = icvIplToCvDepth( img->depth );
+        depth = IPL2CV_DEPTH( img->depth );
         if( depth < 0 )
-            CV_ERROR_FROM_CODE( CV_BadDepth );
+            CV_Error( CV_BadDepth, "" );
 
         order = img->dataOrder & (img->nChannels > 1 ? -1 : 0);
 
@@ -2809,15 +2403,15 @@ cvGetMat( const CvArr* array, CvMat* mat,
                 int type = depth;
 
                 if( img->roi->coi == 0 )
-                    CV_ERROR( CV_StsBadFlag,
+                    CV_Error( CV_StsBadFlag,
                     "Images with planar data layout should be used with COI selected" );
 
-                CV_CALL( cvInitMatHeader( mat, img->roi->height,
-                                   img->roi->width, type,
-                                   img->imageData + (img->roi->coi-1)*img->imageSize +
-                                   img->roi->yOffset*img->widthStep +
-                                   img->roi->xOffset*CV_ELEM_SIZE(type),
-                                   img->widthStep ));
+                cvInitMatHeader( mat, img->roi->height,
+                                img->roi->width, type,
+                                img->imageData + (img->roi->coi-1)*img->imageSize +
+                                img->roi->yOffset*img->widthStep +
+                                img->roi->xOffset*CV_ELEM_SIZE(type),
+                                img->widthStep );
             }
             else /* pixel order */
             {
@@ -2825,14 +2419,14 @@ cvGetMat( const CvArr* array, CvMat* mat,
                 coi = img->roi->coi;
 
                 if( img->nChannels > CV_CN_MAX )
-                    CV_ERROR( CV_BadNumChannels,
+                    CV_Error( CV_BadNumChannels,
                         "The image is interleaved and has over CV_CN_MAX channels" );
 
-                CV_CALL( cvInitMatHeader( mat, img->roi->height, img->roi->width,
-                                          type, img->imageData +
-                                          img->roi->yOffset*img->widthStep +
-                                          img->roi->xOffset*CV_ELEM_SIZE(type),
-                                          img->widthStep ));
+                cvInitMatHeader( mat, img->roi->height, img->roi->width,
+                                 type, img->imageData +
+                                 img->roi->yOffset*img->widthStep +
+                                 img->roi->xOffset*CV_ELEM_SIZE(type),
+                                 img->widthStep );
             }
         }
         else
@@ -2840,10 +2434,10 @@ cvGetMat( const CvArr* array, CvMat* mat,
             int type = CV_MAKETYPE( depth, img->nChannels );
 
             if( order != IPL_DATA_ORDER_PIXEL )
-                CV_ERROR( CV_StsBadFlag, "Pixel order should be used with coi == 0" );
+                CV_Error( CV_StsBadFlag, "Pixel order should be used with coi == 0" );
 
-            CV_CALL( cvInitMatHeader( mat, img->height, img->width, type,
-                                      img->imageData, img->widthStep ));
+            cvInitMatHeader( mat, img->height, img->width, type,
+                             img->imageData, img->widthStep );
         }
 
         result = mat;
@@ -2855,10 +2449,10 @@ cvGetMat( const CvArr* array, CvMat* mat,
         int size1 = matnd->dim[0].size, size2 = 1;
         
         if( !src->data.ptr )
-            CV_ERROR( CV_StsNullPtr, "Input array has NULL data pointer" );
+            CV_Error( CV_StsNullPtr, "Input array has NULL data pointer" );
 
         if( !CV_IS_MAT_CONT( matnd->type ))
-            CV_ERROR( CV_StsBadArg, "Only continuous nD arrays are supported here" );
+            CV_Error( CV_StsBadArg, "Only continuous nD arrays are supported here" );
 
         if( matnd->dims > 2 )
             for( i = 1; i < matnd->dims; i++ )
@@ -2879,11 +2473,7 @@ cvGetMat( const CvArr* array, CvMat* mat,
         result = mat;
     }
     else
-    {
-        CV_ERROR( CV_StsBadFlag, "Unrecognized or unsupported array type" );
-    }
-
-    __END__;
+        CV_Error( CV_StsBadFlag, "Unrecognized or unsupported array type" );
 
     if( pCOI )
         *pCOI = coi;
@@ -2898,19 +2488,15 @@ cvReshapeMatND( const CvArr* arr,
                 int new_cn, int new_dims, int* new_sizes )
 {
     CvArr* result = 0;
-    CV_FUNCNAME( "cvReshapeMatND" );
-
-    __BEGIN__;
-
     int dims, coi = 0;
 
     if( !arr || !_header )
-        CV_ERROR( CV_StsNullPtr, "NULL pointer to array or destination header" );
+        CV_Error( CV_StsNullPtr, "NULL pointer to array or destination header" );
 
     if( new_cn == 0 && new_dims == 0 )
-        CV_ERROR( CV_StsBadArg, "None of array parameters is changed: dummy call?" );
+        CV_Error( CV_StsBadArg, "None of array parameters is changed: dummy call?" );
 
-    CV_CALL( dims = cvGetDims( arr ));
+    dims = cvGetDims( arr );
 
     if( new_dims == 0 )
     {
@@ -2924,29 +2510,30 @@ cvReshapeMatND( const CvArr* arr,
     else
     {
         if( new_dims <= 0 || new_dims > CV_MAX_DIM )
-            CV_ERROR( CV_StsOutOfRange, "Non-positive or too large number of dimensions" );
+            CV_Error( CV_StsOutOfRange, "Non-positive or too large number of dimensions" );
         if( !new_sizes )
-            CV_ERROR( CV_StsNullPtr, "New dimension sizes are not specified" );
+            CV_Error( CV_StsNullPtr, "New dimension sizes are not specified" );
     }
 
     if( new_dims <= 2 )
     {
         CvMat* mat = (CvMat*)arr;
-        CvMat* header = (CvMat*)_header;
+        CvMat header;
         int* refcount = 0;
         int  hdr_refcount = 0;
         int  total_width, new_rows, cn;
 
-        if( sizeof_header != sizeof(CvMat))
-            CV_ERROR( CV_StsBadArg, "The header should be CvMat" );
+        if( sizeof_header != sizeof(CvMat) && sizeof_header != sizeof(CvMatND) )
+            CV_Error( CV_StsBadArg, "The output header should be CvMat or CvMatND" );
 
-        if( mat == header )
+        if( mat == (CvMat*)_header )
         {
             refcount = mat->refcount;
             hdr_refcount = mat->hdr_refcount;
         }
-        else if( !CV_IS_MAT( mat ))
-            CV_CALL( mat = cvGetMat( mat, header, &coi, 1 ));
+        
+        if( !CV_IS_MAT( mat ))
+            mat = cvGetMat( mat, &header, &coi, 1 );
 
         cn = CV_MAT_CN( mat->type );
         total_width = mat->cols * cn;
@@ -2970,41 +2557,51 @@ cvReshapeMatND( const CvArr* arr,
             int total_size = total_width * mat->rows;
 
             if( !CV_IS_MAT_CONT( mat->type ))
-                CV_ERROR( CV_BadStep,
+                CV_Error( CV_BadStep,
                 "The matrix is not continuous so the number of rows can not be changed" );
 
             total_width = total_size / new_rows;
 
             if( total_width * new_rows != total_size )
-                CV_ERROR( CV_StsBadArg, "The total number of matrix elements "
+                CV_Error( CV_StsBadArg, "The total number of matrix elements "
                                         "is not divisible by the new number of rows" );
         }
 
-        header->rows = new_rows;
-        header->cols = total_width / new_cn;
+        header.rows = new_rows;
+        header.cols = total_width / new_cn;
 
-        if( header->cols * new_cn != total_width ||
-            new_sizes && header->cols != new_sizes[1] )
-            CV_ERROR( CV_StsBadArg, "The total matrix width is not "
+        if( header.cols * new_cn != total_width ||
+            (new_sizes && header.cols != new_sizes[1]) )
+            CV_Error( CV_StsBadArg, "The total matrix width is not "
                             "divisible by the new number of columns" );
 
-        header->type = CV_MAKETYPE( mat->type & ~CV_MAT_CN_MASK, new_cn );
-        header->step = header->cols * CV_ELEM_SIZE(mat->type);
-        header->step &= new_rows > 1 ? -1 : 0;
-        header->refcount = refcount;
-        header->hdr_refcount = hdr_refcount;
+        header.type = (mat->type & ~CV_MAT_TYPE_MASK) | CV_MAKETYPE(mat->type, new_cn);
+        header.step = header.cols * CV_ELEM_SIZE(mat->type);
+        header.step &= new_rows > 1 ? -1 : 0;
+        header.refcount = refcount;
+        header.hdr_refcount = hdr_refcount;
+        
+        if( sizeof_header == sizeof(CvMat) )
+            *(CvMat*)_header = header;
+        else
+        {
+            CvMatND* __header = (CvMatND*)_header;
+            cvGetMatND(&header, __header, 0);
+            if( new_dims > 0 )
+                __header->dims = new_dims;
+        }
     }
     else
     {
         CvMatND* header = (CvMatND*)_header;
 
         if( sizeof_header != sizeof(CvMatND))
-            CV_ERROR( CV_StsBadSize, "The header should be CvMatND" );
+            CV_Error( CV_StsBadSize, "The output header should be CvMatND" );
         
         if( !new_sizes )
         {
             if( !CV_IS_MATND( arr ))
-                CV_ERROR( CV_StsBadArg, "The source array must be CvMatND" );
+                CV_Error( CV_StsBadArg, "The input array must be CvMatND" );
 
             {
             CvMatND* mat = (CvMatND*)arr;
@@ -3013,7 +2610,7 @@ cvReshapeMatND( const CvArr* arr,
             int new_size = last_dim_size/new_cn;
 
             if( new_size*new_cn != last_dim_size )
-                CV_ERROR( CV_StsBadArg,
+                CV_Error( CV_StsBadArg,
                 "The last dimension full size is not divisible by new number of channels");
 
             if( mat != header )
@@ -3024,7 +2621,7 @@ cvReshapeMatND( const CvArr* arr,
             }
 
             header->dim[header->dims-1].size = new_size;
-            header->type = CV_MAKETYPE( header->type & ~CV_MAT_CN_MASK, new_cn );
+            header->type = (header->type & ~CV_MAT_TYPE_MASK) | CV_MAKETYPE(header->type, new_cn);
             }
         }
         else
@@ -3035,18 +2632,18 @@ cvReshapeMatND( const CvArr* arr,
             int step;
             
             if( new_cn != 0 )
-                CV_ERROR( CV_StsBadArg,
+                CV_Error( CV_StsBadArg,
                 "Simultaneous change of shape and number of channels is not supported. "
                 "Do it by 2 separate calls" );
             
             if( !CV_IS_MATND( mat ))
             {
-                CV_CALL( cvGetMatND( mat, &stub, &coi ));
+                cvGetMatND( mat, &stub, &coi );
                 mat = &stub;
             }
 
             if( CV_IS_MAT_CONT( mat->type ))
-                CV_ERROR( CV_StsBadArg, "Non-continuous nD arrays are not supported" );
+                CV_Error( CV_StsBadArg, "Non-continuous nD arrays are not supported" );
 
             size1 = mat->dim[0].size;
             for( i = 1; i < dims; i++ )
@@ -3056,13 +2653,13 @@ cvReshapeMatND( const CvArr* arr,
             for( i = 0; i < new_dims; i++ )
             {
                 if( new_sizes[i] <= 0 )
-                    CV_ERROR( CV_StsBadSize,
+                    CV_Error( CV_StsBadSize,
                     "One of new dimension sizes is non-positive" );
                 size2 *= new_sizes[i];
             }
 
             if( size1 != size2 )
-                CV_ERROR( CV_StsBadSize,
+                CV_Error( CV_StsBadSize,
                 "Number of elements in the original and reshaped array is different" );
 
             if( header != mat )
@@ -3085,13 +2682,10 @@ cvReshapeMatND( const CvArr* arr,
         }
     }
 
-    if( !coi )
-        CV_ERROR( CV_BadCOI, "COI is not supported by this operation" );
+    if( coi )
+        CV_Error( CV_BadCOI, "COI is not supported by this operation" );
 
     result = _header;
-    
-    __END__;
-
     return result;
 }
 
@@ -3101,34 +2695,31 @@ cvReshape( const CvArr* array, CvMat* header,
            int new_cn, int new_rows )
 {
     CvMat* result = 0;
-    CV_FUNCNAME( "cvReshape" );
-
-    __BEGIN__;
-
     CvMat *mat = (CvMat*)array;
     int total_width, new_width;
 
     if( !header )
-        CV_ERROR( CV_StsNullPtr, "" );
+        CV_Error( CV_StsNullPtr, "" );
 
     if( !CV_IS_MAT( mat ))
     {
         int coi = 0;
-        CV_CALL( mat = cvGetMat( mat, header, &coi, 1 ));
+        mat = cvGetMat( mat, header, &coi, 1 );
         if( coi )
-            CV_ERROR( CV_BadCOI, "COI is not supported" );
+            CV_Error( CV_BadCOI, "COI is not supported" );
     }
 
     if( new_cn == 0 )
         new_cn = CV_MAT_CN(mat->type);
     else if( (unsigned)(new_cn - 1) > 3 )
-        CV_ERROR( CV_BadNumChannels, "" );
+        CV_Error( CV_BadNumChannels, "" );
 
     if( mat != header )
     {
+        int hdr_refcount = header->hdr_refcount;
         *header = *mat;
         header->refcount = 0;
-        header->hdr_refcount = 0;
+        header->hdr_refcount = hdr_refcount;
     }
 
     total_width = mat->cols * CV_MAT_CN( mat->type );
@@ -3145,16 +2736,16 @@ cvReshape( const CvArr* array, CvMat* header,
     {
         int total_size = total_width * mat->rows;
         if( !CV_IS_MAT_CONT( mat->type ))
-            CV_ERROR( CV_BadStep,
+            CV_Error( CV_BadStep,
             "The matrix is not continuous, thus its number of rows can not be changed" );
 
         if( (unsigned)new_rows > (unsigned)total_size )
-            CV_ERROR( CV_StsOutOfRange, "Bad new number of rows" );
+            CV_Error( CV_StsOutOfRange, "Bad new number of rows" );
 
         total_width = total_size / new_rows;
 
         if( total_width * new_rows != total_size )
-            CV_ERROR( CV_StsBadArg, "The total number of matrix elements "
+            CV_Error( CV_StsBadArg, "The total number of matrix elements "
                                     "is not divisible by the new number of rows" );
 
         header->rows = new_rows;
@@ -3164,16 +2755,13 @@ cvReshape( const CvArr* array, CvMat* header,
     new_width = total_width / new_cn;
 
     if( new_width * new_cn != total_width )
-        CV_ERROR( CV_BadNumChannels,
+        CV_Error( CV_BadNumChannels,
         "The total width is not divisible by the new number of channels" );
 
     header->cols = new_width;
-    header->type = CV_MAKETYPE( mat->type & ~CV_MAT_CN_MASK, new_cn );
+    header->type = (mat->type  & ~CV_MAT_TYPE_MASK) | CV_MAKETYPE(mat->type, new_cn);
 
     result = header;
-
-    __END__;
-
     return  result;
 }
 
@@ -3184,27 +2772,22 @@ cvGetImage( const CvArr* array, IplImage* img )
 {
     IplImage* result = 0;
     const IplImage* src = (const IplImage*)array;
-    
-    CV_FUNCNAME( "cvGetImage" );
-
-    __BEGIN__;
-
     int depth;
 
     if( !img )
-        CV_ERROR_FROM_CODE( CV_StsNullPtr );
+        CV_Error( CV_StsNullPtr, "" );
 
     if( !CV_IS_IMAGE_HDR(src) )
     {
         const CvMat* mat = (const CvMat*)src;
         
         if( !CV_IS_MAT_HDR(mat))
-            CV_ERROR_FROM_CODE( CV_StsBadFlag );
+            CV_Error( CV_StsBadFlag, "" );
 
         if( mat->data.ptr == 0 )
-            CV_ERROR_FROM_CODE( CV_StsNullPtr );
+            CV_Error( CV_StsNullPtr, "" );
 
-        depth = cvCvToIplDepth(mat->type);
+        depth = cvIplDepth(mat->type);
 
         cvInitImageHeader( img, cvSize(mat->cols, mat->rows),
                            depth, CV_MAT_CN(mat->type) );
@@ -3217,8 +2800,6 @@ cvGetImage( const CvArr* array, IplImage* img )
         result = (IplImage*)src;
     }
 
-    __END__;
-
     return result;
 }
 
@@ -3230,14 +2811,9 @@ cvGetImage( const CvArr* array, IplImage* img )
 static IplROI* icvCreateROI( int coi, int xOffset, int yOffset, int width, int height )
 {
     IplROI *roi = 0;
-
-    CV_FUNCNAME( "icvCreateROI" );
-
-    __BEGIN__;
-
     if( !CvIPL.createROI )
     {
-        CV_CALL( roi = (IplROI*)cvAlloc( sizeof(*roi)));
+        roi = (IplROI*)cvAlloc( sizeof(*roi));
 
         roi->coi = coi;
         roi->xOffset = xOffset;
@@ -3250,15 +2826,13 @@ static IplROI* icvCreateROI( int coi, int xOffset, int yOffset, int width, int h
         roi = CvIPL.createROI( coi, xOffset, yOffset, width, height );
     }
 
-    __END__;
-
     return roi;
 }
 
 static  void
-icvGetColorModel( int nchannels, char** colorModel, char** channelSeq )
+icvGetColorModel( int nchannels, const char** colorModel, const char** channelSeq )
 {
-    static char* tab[][2] =
+    static const char* tab[][2] =
     {
         {"GRAY", "GRAY"},
         {"",""},
@@ -3283,34 +2857,24 @@ cvCreateImageHeader( CvSize size, int depth, int channels )
 {
     IplImage *img = 0;
 
-    CV_FUNCNAME( "cvCreateImageHeader" );
-
-    __BEGIN__;
-
     if( !CvIPL.createHeader )
     {
-        CV_CALL( img = (IplImage *)cvAlloc( sizeof( *img )));
-        CV_CALL( cvInitImageHeader( img, size, depth, channels, IPL_ORIGIN_TL,
-                                    CV_DEFAULT_IMAGE_ROW_ALIGN ));
+        img = (IplImage *)cvAlloc( sizeof( *img ));
+        cvInitImageHeader( img, size, depth, channels, IPL_ORIGIN_TL,
+                                    CV_DEFAULT_IMAGE_ROW_ALIGN );
     }
     else
     {
-        char *colorModel;
-        char *channelSeq;
+        const char *colorModel, *channelSeq;
 
         icvGetColorModel( channels, &colorModel, &channelSeq );
 
-        img = CvIPL.createHeader( channels, 0, depth, colorModel, channelSeq,
+        img = CvIPL.createHeader( channels, 0, depth, (char*)colorModel, (char*)channelSeq,
                                   IPL_DATA_ORDER_PIXEL, IPL_ORIGIN_TL,
                                   CV_DEFAULT_IMAGE_ROW_ALIGN,
                                   size.width, size.height, 0, 0, 0, 0 );
     }
 
-    __END__;
-
-    if( cvGetErrStatus() < 0 && img )
-        cvReleaseImageHeader( &img );
-
     return img;
 }
 
@@ -3319,20 +2883,9 @@ cvCreateImageHeader( CvSize size, int depth, int channels )
 CV_IMPL IplImage *
 cvCreateImage( CvSize size, int depth, int channels )
 {
-    IplImage *img = 0;
-
-    CV_FUNCNAME( "cvCreateImage" );
-
-    __BEGIN__;
-
-    CV_CALL( img = cvCreateImageHeader( size, depth, channels ));
+    IplImage *img = cvCreateImageHeader( size, depth, channels );
     assert( img );
-    CV_CALL( cvCreateData( img ));
-
-    __END__;
-
-    if( cvGetErrStatus() < 0 )
-        cvReleaseImage( &img );
+    cvCreateData( img );
 
     return img;
 }
@@ -3343,38 +2896,32 @@ CV_IMPL IplImage*
 cvInitImageHeader( IplImage * image, CvSize size, int depth,
                    int channels, int origin, int align )
 {
-    IplImage* result = 0;
-
-    CV_FUNCNAME( "cvInitImageHeader" );
-
-    __BEGIN__;
-
-    char *colorModel, *channelSeq;
+    const char *colorModel, *channelSeq;
 
     if( !image )
-        CV_ERROR( CV_HeaderIsNull, "null pointer to header" );
+        CV_Error( CV_HeaderIsNull, "null pointer to header" );
 
     memset( image, 0, sizeof( *image ));
     image->nSize = sizeof( *image );
 
-    CV_CALL( icvGetColorModel( channels, &colorModel, &channelSeq ));
+    icvGetColorModel( channels, &colorModel, &channelSeq );
     strncpy( image->colorModel, colorModel, 4 );
     strncpy( image->channelSeq, channelSeq, 4 );
 
     if( size.width < 0 || size.height < 0 )
-        CV_ERROR( CV_BadROISize, "Bad input roi" );
+        CV_Error( CV_BadROISize, "Bad input roi" );
 
     if( (depth != (int)IPL_DEPTH_1U && depth != (int)IPL_DEPTH_8U &&
          depth != (int)IPL_DEPTH_8S && depth != (int)IPL_DEPTH_16U &&
          depth != (int)IPL_DEPTH_16S && depth != (int)IPL_DEPTH_32S &&
          depth != (int)IPL_DEPTH_32F && depth != (int)IPL_DEPTH_64F) ||
          channels < 0 )
-        CV_ERROR( CV_BadDepth, "Unsupported format" );
+        CV_Error( CV_BadDepth, "Unsupported format" );
     if( origin != CV_ORIGIN_BL && origin != CV_ORIGIN_TL )
-        CV_ERROR( CV_BadOrigin, "Bad input origin" );
+        CV_Error( CV_BadOrigin, "Bad input origin" );
 
     if( align != 4 && align != 8 )
-        CV_ERROR( CV_BadAlign, "Bad input align" );
+        CV_Error( CV_BadAlign, "Bad input align" );
 
     image->width = size.width;
     image->height = size.height;
@@ -3395,23 +2942,15 @@ cvInitImageHeader( IplImage * image, CvSize size, int depth,
     image->origin = origin;
     image->imageSize = image->widthStep * image->height;
 
-    result = image;
-
-    __END__;
-
-    return result;
+    return image;
 }
 
 
 CV_IMPL void
 cvReleaseImageHeader( IplImage** image )
 {
-    CV_FUNCNAME( "cvReleaseImageHeader" );
-
-    __BEGIN__;
-
     if( !image )
-        CV_ERROR( CV_StsNullPtr, "" );
+        CV_Error( CV_StsNullPtr, "" );
 
     if( *image )
     {
@@ -3428,19 +2967,14 @@ cvReleaseImageHeader( IplImage** image )
             CvIPL.deallocate( img, IPL_IMAGE_HEADER | IPL_IMAGE_ROI );
         }
     }
-    __END__;
 }
 
 
 CV_IMPL void
 cvReleaseImage( IplImage ** image )
 {
-    CV_FUNCNAME( "cvReleaseImage" );
-
-    __BEGIN__
-
     if( !image )
-        CV_ERROR( CV_StsNullPtr, "" );
+        CV_Error( CV_StsNullPtr, "" );
 
     if( *image )
     {
@@ -3450,44 +2984,31 @@ cvReleaseImage( IplImage ** image )
         cvReleaseData( img );
         cvReleaseImageHeader( &img );
     }
-
-    __END__;
 }
 
 
 CV_IMPL void
 cvSetImageROI( IplImage* image, CvRect rect )
 {
-    CV_FUNCNAME( "cvSetImageROI" );
-
-    __BEGIN__;
-
     if( !image )
-        CV_ERROR( CV_HeaderIsNull, "" );
+        CV_Error( CV_HeaderIsNull, "" );
 
-    if( rect.x > image->width || rect.y > image->height )
-        CV_ERROR( CV_BadROISize, "" );
-
-    if( rect.x + rect.width < 0 || rect.y + rect.height < 0 )
-        CV_ERROR( CV_BadROISize, "" );
-
-    if( rect.x < 0 )
-    {
-        rect.width += rect.x;
-        rect.x = 0;
-    }
-
-    if( rect.y < 0 )
-    {
-        rect.height += rect.y;
-        rect.y = 0;
-    }
-
-    if( rect.x + rect.width > image->width )
-        rect.width = image->width - rect.x;
-
-    if( rect.y + rect.height > image->height )
-        rect.height = image->height - rect.y;
+    // allow zero ROI width or height
+    CV_Assert( rect.width >= 0 && rect.height >= 0 &&
+               rect.x < image->width && rect.y < image->height &&
+               rect.x + rect.width >= (int)(rect.width > 0) &&
+               rect.y + rect.height >= (int)(rect.height > 0) );
+    
+    rect.width += rect.x;
+    rect.height += rect.y;
+    
+    rect.x = std::max(rect.x, 0);
+    rect.y = std::max(rect.y, 0);
+    rect.width = std::min(rect.width, image->width);
+    rect.height = std::min(rect.height, image->height);
+    
+    rect.width -= rect.x;
+    rect.height -= rect.y;
 
     if( image->roi )
     {
@@ -3497,23 +3018,15 @@ cvSetImageROI( IplImage* image, CvRect rect )
         image->roi->height = rect.height;
     }
     else
-    {
-        CV_CALL( image->roi = icvCreateROI( 0, rect.x, rect.y, rect.width, rect.height ));
-    }
-
-    __END__;
+        image->roi = icvCreateROI( 0, rect.x, rect.y, rect.width, rect.height );
 }
 
 
 CV_IMPL void
 cvResetImageROI( IplImage* image )
 {
-    CV_FUNCNAME( "cvResetImageROI" );
-
-    __BEGIN__;
-
     if( !image )
-        CV_ERROR( CV_HeaderIsNull, "" );
+        CV_Error( CV_HeaderIsNull, "" );
 
     if( image->roi )
     {
@@ -3527,8 +3040,6 @@ cvResetImageROI( IplImage* image )
             image->roi = 0;
         }
     }
-
-    __END__;
 }
 
 
@@ -3536,21 +3047,14 @@ CV_IMPL CvRect
 cvGetImageROI( const IplImage* img )
 {
     CvRect rect = { 0, 0, 0, 0 };
-    
-    CV_FUNCNAME( "cvGetImageROI" );
-
-    __BEGIN__;
-
     if( !img )
-        CV_ERROR( CV_StsNullPtr, "Null pointer to image" );
+        CV_Error( CV_StsNullPtr, "Null pointer to image" );
 
     if( img->roi )
         rect = cvRect( img->roi->xOffset, img->roi->yOffset,
                        img->roi->width, img->roi->height );
     else
         rect = cvRect( 0, 0, img->width, img->height );
-
-    __END__;
     
     return rect;
 }
@@ -3559,15 +3063,11 @@ cvGetImageROI( const IplImage* img )
 CV_IMPL void
 cvSetImageCOI( IplImage* image, int coi )
 {
-    CV_FUNCNAME( "cvSetImageCOI" );
-
-    __BEGIN__;
-
     if( !image )
-        CV_ERROR( CV_HeaderIsNull, "" );
+        CV_Error( CV_HeaderIsNull, "" );
 
     if( (unsigned)coi > (unsigned)(image->nChannels) )
-        CV_ERROR( CV_BadCOI, "" );
+        CV_Error( CV_BadCOI, "" );
 
     if( image->roi || coi != 0 )
     {
@@ -3577,30 +3077,19 @@ cvSetImageCOI( IplImage* image, int coi )
         }
         else
         {
-            CV_CALL( image->roi = icvCreateROI( coi, 0, 0, image->width, image->height ));
+            image->roi = icvCreateROI( coi, 0, 0, image->width, image->height );
         }
     }
-
-    __END__;
 }
 
 
 CV_IMPL int
 cvGetImageCOI( const IplImage* image )
 {
-    int coi = -1;
-    CV_FUNCNAME( "cvGetImageCOI" );
-
-    __BEGIN__;
-
     if( !image )
-        CV_ERROR( CV_HeaderIsNull, "" );
+        CV_Error( CV_HeaderIsNull, "" );
 
-    coi = image->roi ? image->roi->coi : 0;
-
-    __END__;
-
-    return coi;
+    return image->roi ? image->roi->coi : 0;
 }
 
 
@@ -3608,16 +3097,13 @@ CV_IMPL IplImage*
 cvCloneImage( const IplImage* src )
 {
     IplImage* dst = 0;
-    CV_FUNCNAME( "cvCloneImage" );
-
-    __BEGIN__;
 
     if( !CV_IS_IMAGE_HDR( src ))
-        CV_ERROR( CV_StsBadArg, "Bad image header" );
+        CV_Error( CV_StsBadArg, "Bad image header" );
 
     if( !CvIPL.cloneImage )
     {
-        CV_CALL( dst = (IplImage*)cvAlloc( sizeof(*dst)));
+        dst = (IplImage*)cvAlloc( sizeof(*dst));
 
         memcpy( dst, src, sizeof(*src));
         dst->imageData = dst->imageDataOrigin = 0;
@@ -3637,11 +3123,7 @@ cvCloneImage( const IplImage* src )
         }
     }
     else
-    {
         dst = CvIPL.cloneImage( src );
-    }
-
-    __END__;
 
     return dst;
 }
@@ -3655,24 +3137,20 @@ CV_IMPL CvTermCriteria
 cvCheckTermCriteria( CvTermCriteria criteria, double default_eps,
                      int default_max_iters )
 {
-    CV_FUNCNAME( "cvCheckTermCriteria" );
-
     CvTermCriteria crit;
 
     crit.type = CV_TERMCRIT_ITER|CV_TERMCRIT_EPS;
     crit.max_iter = default_max_iters;
     crit.epsilon = (float)default_eps;
-    
-    __BEGIN__;
 
     if( (criteria.type & ~(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER)) != 0 )
-        CV_ERROR( CV_StsBadArg,
+        CV_Error( CV_StsBadArg,
                   "Unknown type of term criteria" );
 
     if( (criteria.type & CV_TERMCRIT_ITER) != 0 )
     {
         if( criteria.max_iter <= 0 )
-            CV_ERROR( CV_StsBadArg,
+            CV_Error( CV_StsBadArg,
                   "Iterations flag is set and maximum number of iterations is <= 0" );
         crit.max_iter = criteria.max_iter;
     }
@@ -3680,18 +3158,16 @@ cvCheckTermCriteria( CvTermCriteria criteria, double default_eps,
     if( (criteria.type & CV_TERMCRIT_EPS) != 0 )
     {
         if( criteria.epsilon < 0 )
-            CV_ERROR( CV_StsBadArg, "Accuracy flag is set and epsilon is < 0" );
+            CV_Error( CV_StsBadArg, "Accuracy flag is set and epsilon is < 0" );
 
         crit.epsilon = criteria.epsilon;
     }
 
     if( (criteria.type & (CV_TERMCRIT_EPS | CV_TERMCRIT_ITER)) == 0 )
-        CV_ERROR( CV_StsBadArg,
+        CV_Error( CV_StsBadArg,
                   "Neither accuracy nor maximum iterations "
                   "number flags are set in criteria type" );
 
-    __END__;
-
     crit.epsilon = (float)MAX( 0, crit.epsilon );
     crit.max_iter = MAX( 1, crit.max_iter );