/********************************************************************************
    LibVideoGfx - video processing library
    Copyright (C) 2002  Dirk Farin

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 ********************************************************************************/

template <class T> Array2<T>::Array2()
{
  d_width = d_height = 0;
  d_array = NULL;
}


template <class T> Array2<T>::Array2(int width,int height,int xbase,int ybase)
  : d_array(NULL)
{
  Create(width,height,xbase,ybase);
}


template <class T> void Array2<T>::Create(int width,int height,int xbase,int ybase)
{
  if (d_array)
    {
      if (d_width == width && d_height == height)
	return;

      delete[] d_array[0];
      delete[] d_array;
    }

  d_width  = width;
  d_height = height; 

  d_xbase = xbase;
  d_ybase = ybase;

  T* bitmap = new T[d_width * d_height];
  d_array   = new T* [d_height];

  {for (int y=0;y<d_height;y++)
    d_array[y]= &bitmap[y*d_width];}
}


template <class T> void Array2<T>::Resize(int newwidth,int newheight)
{
  // No old array -> simply create new one.

  if (!d_array)
    {
       Create(newwidth,newheight,0,0);
       return;
    }


  // same size as before -> do nothing

  if (d_width == newwidth && d_height == newheight)
    return;


  // hide (but remember) old array

  T** old_row_array = d_array;
  int old_width     = d_width;
  int old_height    = d_height;
  d_array = NULL;


  // create new array

  Create(newwidth,newheight, d_xbase,d_ybase);


  // copy old content to new array

  int copywidth  = std::min(old_width ,newwidth);
  int copyheight = std::min(old_height,newheight);

  for (int y=0;y<copyheight;y++)
    for (int x=0;x<copywidth;x++)
      d_array[y][x] = old_row_array[y][x];


  // delete old array

  delete[] old_row_array[0];
  delete[] old_row_array;  
}


template <class T> Array2<T>::~Array2()
{
  if (d_array)
    {
      delete[] d_array[0];
      delete[] d_array;
    }
}

