/*
 * Utility for creating 2D arrays of any type. 
 * Note: Use a vector instead if you can, it's much safer. 
 *
 * Author: Samuel A. Inverso 
 *
 * License:
 * Use this code freely, it is distributed without warranty express or 
 * implied.
 */


#include <iostream>
#include "MultiArrayUtilities.h"

// Don't use this create3DArray
#if 0
template <class T>
T *** MultiArrayUtilities<T>::create3DArray( int rows, int cols, int depth, T initial )
{
    T *** result = new T**[rows];

    for( int i = 0; i < rows; ++i )
    {
        result[i] = create2DArray( cols, depth, initial );
    }

    return result;
}
#endif

template <class T>
T ** MultiArrayUtilities<T>::create2DArray( int rows, int cols, T initial )
{
    T **result = new T*[rows];  // first create an array of pointers ints

    for( int i=0; i < rows; ++i )
    {
        result[i] = new T[cols];  // second point every pointer to an array of
                                    // ints

        for( int j = 0 ; j < cols ; ++j )
        {
            result[i][j] = initial; 
        }
    }

    return result;
}

template <class T>
void MultiArrayUtilities<T>::delete2DArray( T** ary, int rows )
{
    while( rows-- )
    {
        delete [] ary[rows];
    }
    delete[] ary;
}

int main( int argc, char** argv)
{
    int rows = 7;
    int cols = 5;
    int depth = 2;

    float **ary = MultiArrayUtilities<float>::create2DArray( rows , cols, 4.2 );

    for( int i= 0; i < rows ; ++i )
    {
        for( int j=0; j < cols ; ++j )
        {
            std::cout << ary[i][j] << " ";              
        }
        std::cout << "\n";
    }

    MultiArrayUtilities<float>::delete2DArray( ary, rows );

    #if 0
    int ***ary = MultiArrayUtilities<int>::create3DArray( rows, cols, depth, 1 );
    
    for( int k = 0; k < depth; ++k )
    {
        std::cout << std::endl <<  "Depth: " << k << std::endl;
        for( int i= 0; i < rows ; ++i )
        {
            for( int j=0; j < cols ; ++j )
            {
                std::cout << ary[i][j][k] << " ";              
            }
            std::cout << "\n";
        }
    }
    #endif
}

