// DSDib.cpp: implementation of the CDSDib class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
//#include "SideScan.h"
#include "DSDib.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CDSDib::CDSDib()
{
   m_pBitmapBits = 0;
   m_hDib =        0;
   m_nWidth =      0;
   m_nHeight =     0;
   m_nBytes =      0;
   m_nHdrBytes =   0;
}

CDSDib::CDSDib(UINT nWidth, UINT nHeight, EDibColorMode mode)
{
   Create(nWidth, nHeight, mode);
}

CDSDib::~CDSDib()
{

}

// returns 0 - ok
BOOL  CDSDib::Create(UINT nWidth, UINT nHeight, EDibColorMode mode)
{
   ASSERT(nWidth);
   ASSERT(nHeight);

   // we don't support this mode yet
   if (mode == dcm2) return true;

   // if exists
   if (m_hDib) {
      // check for same size

      if (nWidth == m_nWidth && nHeight == m_nHeight) {
          return false;
      }

      // clear memory if already allocated
      delete [] m_hDib;
	  m_hDib = NULL;
   }

   // set width and height
   m_nWidth =  nWidth;
   m_nHeight = nHeight;

   // calc size of bitmap
   m_nInternalWidth = UPTO_DWORD(nWidth * (int)mode);
   m_nBytes =         m_nInternalWidth * nHeight;

   // calc header size
   m_nHdrBytes = sizeof(BITMAPINFOHEADER);

   // add palette size
   m_nHdrBytes += this->PaletteSize(mode);

   // add to total size
   m_nBytes += m_nHdrBytes;

   // allocate
   m_hDib = new BYTE[m_nBytes+10000];

   if (!m_hDib) {
      return true;   // couldn't allocate memory
   }
   ZeroMemory(m_hDib, m_nBytes);

   // set bit pointer
   m_pBitmapBits = m_hDib + m_nHdrBytes;

   // initialize header
   BITMAPINFOHEADER  *pInfo = (BITMAPINFOHEADER *)m_hDib;
   pInfo->biSize =          sizeof(BITMAPINFOHEADER);
   pInfo->biWidth =         nWidth;
   pInfo->biHeight =        (int)nHeight;
   pInfo->biPlanes =        1;
   pInfo->biBitCount =      (int)mode * 8;
   pInfo->biCompression =   BI_RGB;
   pInfo->biSizeImage =     0;
   pInfo->biXPelsPerMeter = 0;
   pInfo->biYPelsPerMeter = 0;
   pInfo->biClrUsed =       0;
   pInfo->biClrImportant =  0;

   // what about the color table

   return false;
}

int  CDSDib::PaletteSize(EDibColorMode mode)
{
   BITMAPINFOHEADER  *pInfo = (BITMAPINFOHEADER *)m_hDib;

   if (mode == dcmNoParm) {
      if (pInfo->biClrUsed != 0) {
         return pInfo->biClrUsed;
      }

      if (pInfo->biBitCount == 8) {
         return (256 * sizeof(RGBQUAD));
      } else {
         return 0;
      }
   }

   switch((int)mode)
   {
   case dcm8:  return (256 * sizeof(RGBQUAD));
   case dcm16: 
   case dcm24:
   case dcm32: return 0;
   }

   return 0;
}