/******************************************************************************
 * program:     rasimg library 0.23                                           *
 * function:    Miscellaneous utilities for manipulation with images.         *
 * modul:       rasterut.cc                                                   *
 * licency:     GPL or LGPL                                                   *
 * Copyright: (c) 1998-2023 Jaroslav Fojtik                                   *
 ******************************************************************************/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

#include "typedfs.h"
#include "common.h"

#include "raster.h"
#include "vecimage.h"
#include "ras_prot.h"

#ifdef _MSC_VER  
  #pragma warning(disable: 4244)
  #pragma warning(disable: 4250)	// Inheriting via dominance, standard C++ feature.
#endif


void SetValue2(BYTE *b, unsigned x, BYTE NewValue)
{
BYTE v;
 v = NewValue;
 if(NewValue>3) v=3;
 b+= x >> 2;
 switch(x & 3)
   {
   case 0:v=v << 6; *b=*b & 0x3F;	break;
   case 1:v=v << 4; *b=*b & 0xCF;	break;
   case	2:v=v << 2; *b=*b & 0xF3;	break;
   case	3:*b=*b & 0xFC;
   }
 *b = *b | v;
}


BYTE GetValue2(const BYTE *b, unsigned x)
{
 if(b==NULL) return 0;
 b+= x >> 2;
 switch(x & 3)
   {
   case 0:return( (*b >> 6)&3 );
   case 1:return( (*b >> 4)&3 );
   case	2:return( (*b >> 2)&3 );
   case	3:return( *b & 3 );
   }
return 0;
}


void Flip2(BYTE *b, unsigned len)
{
  unsigned x1 = 0;
  unsigned x2 = len - 1;
  
  while(x1<x2)
  {
    BYTE tmp = GetValue2(b,x1);
    SetValue2(b, x1, GetValue2(b,x2));
    SetValue2(b, x2, tmp);
    x1++;
    x2--;
  }
}


/* ------------ Properties ---------------*/

PropertyItem::~PropertyItem()
{
  if(Data)
  {
    free(Data);
    Data=NULL;DataSize=0;
  }
}


PropertyList::~PropertyList()
{
  if(pProperties != NULL)
  {
    for(int i=0; i<PropCount; i++)
    {
      if(pProperties[i] != NULL)
      {
        if(pProperties[i]->UsageCount--<=1) delete pProperties[i];
        pProperties[i] = NULL;
      }
    }
    free(pProperties);
    pProperties = NULL;
  }
}


void PropertyList::AddProp(PropertyItem *NewProp)
{
int i;
  if(NewProp==NULL) return;
	// Method 1: list ie empty.
  if(pProperties == NULL)
  {
    pProperties = (PropertyItem**)malloc(sizeof(PropertyItem*));
    if(pProperties==NULL)
    {	// report memory error
      return;
    }
    pProperties[0] = NewProp;
    PropCount=1;
    NewProp->UsageCount++;
    return;
  }
	// Method 2: list has a free slot.
  for(i=0; i<PropCount; i++)
  {
    if(pProperties[i]==NULL)
    {
      pProperties[i] = NewProp;
      NewProp->UsageCount++;
      return;
    }
  }
	// Method 3: list must be reallocated.
  PropertyItem **NewList = (PropertyItem**)realloc(pProperties, sizeof(PropertyItem*)*(PropCount+1));
  if(NewList==NULL)
  {
    return;
  }
  pProperties = NewList;
  pProperties[PropCount++] = NewProp;
  NewProp->UsageCount++;
}


/* ---------- Global class Image --------- */
void Image::Create(unsigned SizeX, unsigned SizeY, int Planes)
{
  if(Raster)
    {
    if(Raster->GetSize1D()==SizeX && Raster->Size2D==SizeY &&
       Raster->GetPlanes()==(Planes & 0xFF) && 
       Raster->UsageCount==1)		// only this object owns raster
		return;

    Erase();
    }

if(Planes & ImageTrueColor)
  {
  if( (Raster=CreateRaster2DRGB(SizeX, SizeY, Planes&0xFF)) != NULL)
	Raster->UsageCount++;
  }
else
  {
  if( (Raster=CreateRaster2D(SizeX,SizeY,Planes&0xFF))!=NULL)
	Raster->UsageCount++;
  }
}


Image::Image(const Image & I, bool AllFrames)
{
 if((Raster=I.Raster)!=NULL) Raster->UsageCount++;
 if((Palette=I.Palette)!=NULL) Palette->UsageCount++;
 if((VecImage=I.VecImage)!=NULL) VecImage->UsageCount++;

 if(!I.Properties.isEmpty())
 {
    for(int i=0; i<I.Properties.PropCount; i++)
      Properties.AddProp(I.Properties.pProperties[i]);
 }

 x=I.x; y=I.y; dx=I.dx; dy=I.dy; RotAngle=I.RotAngle;
 Next = NULL;  

 if(AllFrames)
 {
   Image *PImg, *CurrImg;
   PImg = this;
   CurrImg = I.Next;
   while(CurrImg!=NULL)	//Multiple images
	{
	PImg->Next = new Image(*CurrImg,false);
	if(PImg->Next==NULL) break;	/*Allocation error*/
	PImg = PImg->Next;
	CurrImg = CurrImg->Next;
	}
 }
}


Raster2DAbstract *Image::operator=(Raster2DAbstract *NewRaster)
{
 x=y=dx=dy=0; 
 if(Raster==NewRaster) return(Raster);		//Identical assignment
 if(Raster!=NULL) Erase();
 if((Raster=NewRaster)!=NULL ) Raster->UsageCount++;
 return(Raster);
}


Image &Image::operator=(const Image &I)
{
Image *PImg;
const Image *CurrImg;
 Erase();

 PImg = this;
 CurrImg = &I;
 goto CopyImg;

 while(CurrImg!=NULL)	//Multiple images
	{
	PImg->Next = new Image;
	if(PImg->Next==NULL) return(*this);
	PImg = PImg->Next;

CopyImg:if((PImg->Raster=CurrImg->Raster)!=NULL)
		CurrImg->Raster->UsageCount++;
	if((PImg->Palette=CurrImg->Palette)!=NULL)
		CurrImg->Palette->UsageCount++;
	PImg->x=CurrImg->x;PImg->y=CurrImg->y;
	PImg->dx=CurrImg->dx;PImg->dy=CurrImg->dy;
	PImg->RotAngle=CurrImg->RotAngle;
        if((PImg->VecImage=CurrImg->VecImage)!=NULL)
                CurrImg->VecImage->UsageCount++;
        if(!CurrImg->Properties.isEmpty())
	  {
          for(int i=0; i<CurrImg->Properties.PropCount; i++)
            PImg->Properties.AddProp(CurrImg->Properties.pProperties[i]);
          }
	CurrImg = CurrImg->Next;
	}
 return(*this);
}


void Image::Erase(void)
{
Image *I,*OldI;

 I = this;
 while(I!=NULL)
   {
   if(I->Raster!=NULL)
      {
      if(I->Raster->UsageCount--<=1) delete I->Raster;
      I->Raster = NULL;
      }
   if(I->Palette!=NULL)
      {
      if(I->Palette->UsageCount--<=1) delete I->Palette;
      I->Palette = NULL;
      }
   if(I->VecImage!=NULL)
      {
      if(I->VecImage->UsageCount--<=1) delete I->VecImage;
      I->VecImage = NULL;
      }
   OldI = I;
   I = I->Next;
   OldI->Next = NULL;
   if(OldI!=this) delete(OldI);
   }
}


/** 0-none (ImageNone), 1-gray (ImageGray), 2-palette (ImagePalette), 3-true color (ImageTrueColor). */
IMAGE_TYPE Image::ImageType(void) const
{
  if(Raster==NULL) return ImageNone;
  if(Raster->Size1D==0 || Raster->Size2D==0) return ImageNone;
  if(Raster->Channels()>=3) return ImageTrueColor;
  if(Palette!=NULL)
    {
    if(GrayPalette(Palette,Raster->GetPlanes())) return ImageGray;
    if(Raster->GetPlanes()==24) return ImageTrueColor;
    return ImagePalette;
    }
  if(Raster->GetPlanes()==24) return ImageTrueColor;
  return ImageGray;
}


DWORD Image::GetPixelRGB(unsigned Offset1D, unsigned Offset2D) const
{
  if(Raster==NULL) return 0;
  switch(ImageType() & 0xFF00)
    {
    case ImageTrueColor:
	     return Raster->GetValue2D(Offset1D,Offset2D);
    case ImagePalette:
	     {
	     const DWORD b = Raster->GetValue2D(Offset1D,Offset2D);
	     return Palette->GetValue1D(b);
	     }
    default: {
	     DWORD b = Raster->GetValue2D(Offset1D,Offset2D);
	     switch(Raster->GetPlanes())
	     {
	       case   1: b *= 0xFF; break;
	       case   2: b *= 85; break;		// 255/3 = 85  -> 85*3=0xFF
	       case   4: b *= 17; break;		// 255/15=17   -> 17*15=0xFF
	       case  16: b >>= 8; break;
	       case  24: b >>= 16; break;
	       case  32:
	       case -32:				// floats are normalised to the full range 0 ... 0xFFFFFFFF.
	       case -64: b>>=24; break;
	     }
	     return b | 0x100*b | 0x10000*b;
	     }
    }
  return 0;
}


void Image::AttachRaster(Raster2DAbstract *NewRaster)
{
  if(Raster==NewRaster) return;		// Raster is already attached
  if(Raster!=NULL)			// Detach previously attached raster
   {
   if(Raster->UsageCount--<=1) delete Raster;
   Raster=NULL;
   }
  if(NewRaster!=NULL)			// Attach raster now
   {
   Raster=NewRaster; Raster->UsageCount++;
   }
}


void Image::AttachPalette(APalette *NewPalette)
{
  if(Palette==NewPalette) return;		// Raster is already attached
  if(Palette!=NULL)			// Detach previously attached raster
   {
   if(Palette->UsageCount--<=1) delete Palette;
   Palette = NULL;
   }
  if(NewPalette!=NULL)			// Attach raster now
   {
   Palette=NewPalette; Palette->UsageCount++;
   }
}


void Image::AttachVecImg(VectorImage *NewVecImg)
{
  if(VecImage==NewVecImg) return;		// Raster is already attached
  if(VecImage!=NULL)			// Detach previously attached raster
  {
    if(VecImage->UsageCount--<=1) delete VecImage;
    VecImage = NULL;
  }
  if(NewVecImg!=NULL)			// Attach raster now
  {
    VecImage=NewVecImg; VecImage->UsageCount++;
  }
}


void Image::AttachProperty(PropertyItem *NewProp)
{
  Properties.AddProp(NewProp);
}


/* ---------------------------- */


void Flip1D(Raster1DAbstract *r1D)
{
  if(r1D==NULL) return;
  if(r1D->Data1D==NULL) return;
  const int p = labs(r1D->GetPlanes());

  switch(p)
  {
    case 1:  Flip1((BYTE*)r1D->GetRow(), r1D->GetSize1D());
	     return;
    case 2:  Flip2((BYTE*)r1D->GetRow(), r1D->GetSize1D());
	     return;
    case 4:  Flip4((BYTE*)r1D->GetRow(), r1D->GetSize1D());
	     return;
    case 8:  Flip8((BYTE*)r1D->GetRow(), r1D->GetSize1D());
	     return;
    case 16: Flip16((WORD*)r1D->GetRow(), r1D->GetSize1D());
	     return;
    case 24: Flip24((BYTE*)r1D->GetRow(), r1D->GetSize1D());
	     return;
    case 32: Flip32((DWORD*)r1D->GetRow(), r1D->GetSize1D());
	     return;
#ifdef QWORD
    case 64: Flip64((QWORD*)r1D->GetRow(), r1D->GetSize1D());
	     return;
#endif
  }
/*
  unsigned x1 = 0;
  unsigned x2 = r1D->Size1D - 1;
  if(p>32)
  {    
    while(x1<x2)
    {
      double tmp = r1D->GetValue1Dd(x1);
      r1D->SetValue1Dd(x1, r1D->GetValue1Dd(x2));
      r1D->SetValue1Dd(x2, tmp);
      x1++;
      x2--;
    }
  }
  else
  {
    while(x1<x2)
    {
      DWORD tmp = r1D->GetValue1D(x1);
      r1D->SetValue1D(x1, r1D->GetValue1D(x2));
      r1D->SetValue1D(x2, tmp);
      x1++;
      x2--;
    }
  }
*/
}


/** This procedure provides vertical flipping of the raster. */
void Flip2D(Raster2DAbstract *r2D)
{
 if(r2D==NULL) return;
 if(r2D->Data2D==NULL) return;

#if defined(POINTER_SIZE) && POINTER_SIZE==32
  Flip32((DWORD*)r2D->Data2D, r2D->GetSize2D());
#else
 #if defined(POINTER_SIZE) && POINTER_SIZE==64 && defined(QWORD)
  Flip64((QWORD*)r2D->Data2D, r2D->GetSize2D());
 #else
  void *ptr, **P1, **P2;
  P1 = r2D->Data2D;
  P2 = P1 + (r2D->Size2D-1); 
  while(P2>P1)
    {
    ptr = *P1;
    *P1 = *P2;
    *P2 = ptr;
    P1++; P2--;
    }
 #endif
#endif
}


/** This procedure provides flipping along 1st dimension (usually horizontal)
 * of the raster. */
void Flip1D(Raster2DAbstract *r2D)
{
unsigned y;

  if(r2D==NULL) return;
  if(r2D->Data2D==NULL) return;

  const int p = labs(r2D->GetPlanes());
  const unsigned Size1D = r2D->GetSize1D();

/*
  if(p<8 && p!=4)	// Speedup for <4 bits
    {
    Raster1D_8Bit Buff;
    Buff.Allocate1D(r2D->GetSize1D());
    if(Buff.Data1D==NULL) return;	// Report error here.

    for(y=0; y<r2D->Size2D; y++)
      {
      r2D->GetRowRaster(y)->Get(Buff);
      Flip8((BYTE*)Buff.Data1D, r2D->GetSize1D());
      r2D->GetRowRaster(y)->Set(Buff);
      }
    Buff.Erase();
    return;
    }
*/

  for(y=0; y<r2D->Size2D; y++)
    {
    switch(p)
      {
      case 1:  Flip1((BYTE*)r2D->GetRow(y), Size1D);
	       break;
      case 2:  Flip2((BYTE*)r2D->GetRow(y), Size1D);
	       break;
      case 4:  Flip4((BYTE*)r2D->GetRow(y), Size1D);
	       break;
      case 8:  Flip8((BYTE*)r2D->GetRow(y), Size1D);
	       break;
      case 16: Flip16((WORD*)r2D->GetRow(y), Size1D);
	       break;
      case 24: Flip24((BYTE*)r2D->GetRow(y), Size1D);
	       break;
      case 32: Flip32((DWORD*)r2D->GetRow(y), Size1D);
	       break;
#ifdef QWORD
      case 64: Flip64((QWORD*)r2D->GetRow(y), Size1D);
	       break;
#endif
/*
      default: {
                 unsigned x1 = 0;
	         unsigned x2 = r2D->Size1D - 1;
	         while(x1<x2)
		 {
		   double tmp = r2D->GetValue2Dd(x1,y);
		   r2D->SetValue2Dd(x1,y, r2D->GetValue2Dd(x2,y));
		   r2D->SetValue2Dd(x2,y, tmp);
		   x1++;
		   x2--;
		 }
               }
*/
      }
   }
}


#if defined(RASTER_3D)

/** This procedure provides flipping along 1st dimension of the raster. */
void Flip1D(Raster3DAbstract *r3D)
{
unsigned y, z;

  if(r3D==NULL) return;
  if(r3D->Size1D<=1 || r3D->Data3D==NULL) return;

  const int p = labs(r3D->GetPlanes());
  const unsigned Size1D = r3D->GetSize1D();

/*
  if(p<8 && p!=4)	// Speedup for less than 8 bits
    {
    Raster1D_8Bit Buff;
    Buff.Allocate1D(r3D->GetSize1D());
    if(Buff.Data1D==NULL) return;

    for(z=0; z<r3D->Size3D; z++)
      for(y=0; y<r3D->Size2D; y++)
	{
	r3D->GetRowRaster(y,z)->Get(Buff);
	Flip8((BYTE*)Buff.Data1D, r3D->GetSize1D());
	r3D->GetRowRaster(y,z)->Set(Buff);
	}
    Buff.Erase();
    return;
    }
*/

  for(z=0; z<r3D->Size3D; z++)
  {
    void **Row2D = r3D->GetRow(z);
    for(y=0; y<r3D->Size2D; y++)
    {
    switch(p)
      {
      case 1:  Flip1((BYTE*)Row2D[y], Size1D);
	       break;
      case 2:  Flip2((BYTE*)Row2D[y], Size1D);
	       break;
      case 4:  Flip4((BYTE*)Row2D[y], Size1D);
	       break;
      case 8:  Flip8((BYTE*)Row2D[y], Size1D);
	       break;
      case 16: Flip16((WORD*)Row2D[y], Size1D);
	       break;
      case 24: Flip24((BYTE*)Row2D[y], Size1D);
	       break;
      case 32: Flip32((DWORD*)Row2D[y], Size1D);
	       break;
#ifdef QWORD
      case 64: Flip64((QWORD*)Row2D[y], Size1D);
	       break;
#endif
/*
      default: unsigned x1 = 0;
	       unsigned x2 = r3D->Size1D - 1;
               
	       while(x1<x2)
		 {
		 double tmp = r3D->GetValue3Dd(x1,y,z);
		 r3D->SetValue3Dd(x1,y,z, r3D->GetValue3Dd(x2,y,z));
		 r3D->SetValue3Dd(x2,y,z, tmp);
		 x1++;
		 x2--;
		 }
*/               
       }
    }
 }
}


/** This procedure provides flipping along 2nd dimension of the raster. */
void Flip2D(Raster3DAbstract *r3D)
{
 if(r3D==NULL) return;
 if(r3D->Size2D==0 || r3D->Data3D==NULL) return;

 for(unsigned z=0; z<r3D->Size3D; z++)
 {
#if defined(POINTER_SIZE) && POINTER_SIZE==32
   Flip32((DWORD*)r3D->Data3D[z], r3D->GetSize2D());
#else
 #if defined(POINTER_SIZE) && POINTER_SIZE==64 && defined(QWORD)
   Flip64((QWORD*)r3D->Data3D[z], r3D->GetSize2D());
 #else
   void *ptr, **P1, **P2;
   P1 = r3D->Data3D[z];
   P2 = r3D->Data3D[z] + (r3D->Size2D-1);
   while(P2>P1)
     {
     ptr = *P1;
     *P1 = *P2;
     *P2 = ptr;
     P1++; P2--;
     }
 #endif
#endif
 }
}


/** This procedure provides flipping along 3rd dimension of the raster. */
void Flip3D(Raster3DAbstract *r3D)
{
  if(r3D==NULL) return;
  if(r3D->Size3D==0 || r3D->Data3D==NULL) return;

#if defined(POINTER_SIZE) && POINTER_SIZE==32
  Flip32((DWORD*)r3D->Data3D, r3D->GetSize3D());
#else
 #if defined(POINTER_SIZE) && POINTER_SIZE==64 && defined(QWORD)
  Flip64((QWORD*)r3D->Data3D, r3D->GetSize3D());
 #else
  void **ptr, ***P1, ***P2;
  P1 = r3D->Data3D;
  P2 = r3D->Data3D + (r3D->Size3D-1);
  while(P2>P1)
    {
    ptr = *P1;
    *P1 = *P2;
    *P2 = ptr;
    P1++; P2--;
    }
 #endif
#endif
}

#endif

//////////////////////////////////////////////////////////


class Palette_8bit: virtual public APalette, virtual public Raster1D_8BitRGB
	{
public:	Palette_8bit(int Indices): Raster1D_8BitRGB(Indices) {};
	Palette_8bit(void): Raster1D_8BitRGB() {};
	};

class Palette_16bit: virtual public APalette, virtual public Raster1D_16BitRGB
	{
public:	Palette_16bit(int Indices): Raster1D_16BitRGB(Indices) {};
	Palette_16bit(void) {};
	};


APalette *BuildPalette(unsigned Indices, char type)
{
APalette *pal=NULL;

 switch(type)
	{
	case 0:
	case 8: pal = new Palette_8bit(Indices);  break;
	case 16:pal = new Palette_16bit(Indices); break;
	}
 if(pal)
   if(pal->GetSize1D()<Indices)
	{
	delete pal;
	return(NULL);
	}

return(pal);
}


/** Is this Gray scale palette? */
int GrayPalette(APalette *Palette, int Planes)
{
unsigned i;
unsigned PalItems;

 if(Palette==NULL) return(1);
 if(Palette->Data1D==NULL ||
    Palette->Size1D==0) return(1);	//consider invalid palette to be gray

 if(Planes==0) Planes = Palette->GetPlanes() / Palette->Channels();
 if(Planes >= sizeof(PalItems)*8) return 0; // Shift operation will overflow, consider image to be color.
 PalItems = (1<<Planes);
 if(Planes!=0)
   if(PalItems > Palette->GetSize1D())
	{
	//PalItems=Palette->Size1D/3;
	return(0);	//insufficient palette size, ?? non gray ??
	}

 const unsigned divider = (PalItems>1) ? (PalItems - 1) : 1;
 const unsigned multiplayer = (Planes>8) ? 65535 : 255;
 for(i=0; i<PalItems; i++)
	{
	const unsigned color = i*multiplayer / divider;
        RGBQuad RGB;
        Palette->Get(i,&RGB);
	if((RGB.R!=color) ||
	   (RGB.G!=color) ||
	   (RGB.B!=color) )
			return(0);
	}
 return(1);
}


/** Make this palette gray.
 * @param[in,out]	Palette	Palette to be set as gray.
 * @param[in]		Planes	If nonzeto, check for real planes per channel. */
int FillGray(Raster1DAbstractRGB *Palette, int Planes)
{
unsigned i;

 if(Palette==NULL) return(1);
 if(Palette->Data1D==NULL) return(0);

 if(Planes!=0)
   if(3*Planes != Palette->GetPlanes()) return(0);

 unsigned Divider = (Palette->Size1D-1);
 if(Divider==0) Divider=1;

 unsigned Multiplier = (Palette->GetPlanes()/Palette->Channels()<=8) ? 255 : 65535;

 for(i=0; i<Palette->Size1D; i++)
   {
   const unsigned color = i*Multiplier / Divider;
   Palette->R(i,color);
   Palette->G(i,color);
   Palette->B(i,color);
   }
 return(1);
}


/** This fuction is intended to schrink image colors.
 * It can work in two modes: 
 *       1, 256 colors to 16 colors.
 *       2, True color to 256 colors.
 * @param[in,out]	Img	Image to be processed.
 * @param[in]		maxColors  Maximal color table size for true color images.
 * @return	0 - image was not changed; ColorCount - image has been reordered. */
int ReducePalette(Image *Img, unsigned maxColors)
{
unsigned x,y;
Raster1DAbstract *RowRas,*RowRas2;
APalette *paletettebuff;
unsigned CurrentColors = 0;
DWORD RGBval, RGBval2;
unsigned i;
Raster2DAbstract *Raster2;

  if(Img==NULL || maxColors<=0) return 0;
  if(Img->Raster==NULL) return 0;
  if(Img->ImageType()!=ImageTrueColor)
    {
    BYTE *Reindex;

    if(Img->Palette==NULL || 
       Img->Raster->GetPlanes()>8 || Img->Raster->GetPlanes()<=4) return 0;

    Reindex = (BYTE *)calloc(256,sizeof(BYTE));
    if(Reindex==NULL) return 0;

	/* Calculate a histogram */
    for(y=Img->Raster->Size2D; y>0; y--)
    {
      RowRas = Img->Raster->GetRowRaster(y-1);
      if(RowRas==NULL) continue;

      for(x=0; x<RowRas->GetSize1D(); x++)
        {
        Reindex[RowRas->GetValue1D(x)] = 1;
        }
    }

	/* Create remapping matrix. */
    y = 0;
    for(x=0; x<((unsigned)1<<labs(Img->Raster->GetPlanes())); x++)
      {
      if(Reindex[x])
        {
        Reindex[x] = y++;
        }
      }
    
    if(y<=16)		// We can schring 256 to 16 levels
      {
	/* Remap a raster. */
      Raster2 = CreateRaster2D(Img->Raster->Size1D,Img->Raster->Size2D,4);

      for(y=Img->Raster->Size2D;y>0;y--)   //fix for 32 bit planes
        {
        RowRas = Img->Raster->GetRowRaster(y-1);
        RowRas2 = Raster2->GetRowRaster(y-1);
        if(RowRas==NULL || RowRas2==NULL) continue;

        for(x=0;x<RowRas->GetSize1D();x++)
	  {
          RowRas2->SetValue1D(x, Reindex[RowRas->GetValue1D(x)]);
	  }
        }

      if(--Img->Raster->UsageCount <= 0)
	delete Img->Raster;
      Img->Raster = Raster2;
      Img->Raster->UsageCount++;
      

	/* Remap a palette. */
      if((paletettebuff=BuildPalette(maxColors,8))!=NULL)
        {
        for(x=0;x<Img->Palette->GetSize1D();x++)
          {
          if(x==0 || Reindex[x])
            {
            paletettebuff->SetValue1D(Reindex[x], Img->Palette->GetValue1D(x));
            }
          }
        
          Img->AttachPalette(paletettebuff);
          paletettebuff = NULL;
        }
      }  

    free(Reindex);
    return 0;
    }

	/* True color reduction process. */
  //printf("\n---- Image check starts %d ------", maxColors);

  if((paletettebuff=BuildPalette(maxColors,8))==NULL) return 0;

  for(y=Img->Raster->Size2D;y>0;y--)   //fix for 32 bit planes
    {
    RowRas = Img->Raster->GetRowRaster(y-1);
    if(RowRas==NULL) continue;
    for(x=0;x<RowRas->GetSize1D();x++)
      {
      RGBval = RowRas->GetValue1D(x);

      i=0;
      while(i<CurrentColors)
	{
	RGBval2 = paletettebuff->GetValue1D(i);
	if(RGBval2 == RGBval) goto Found;

	if(RGBval2>RGBval)		// keep palette sorted
	  {
	  while(i<CurrentColors)
	    {
	    paletettebuff->SetValue1D(i,RGBval);
	    RGBval = RGBval2;
	    i++;
	    RGBval2 = paletettebuff->GetValue1D(i);
	    }
	  break;
	  }

	i++;
	}
	// Insert last value and extend palette
      paletettebuff->SetValue1D(CurrentColors++,RGBval);
      if(CurrentColors>=maxColors) goto Finish;
Found: {}
      }
    }

  if(CurrentColors<=256)
    {
    if(CurrentColors<=16)
      Raster2 = CreateRaster2D(Img->Raster->Size1D,Img->Raster->Size2D,4);
    else
      Raster2 = CreateRaster2D(Img->Raster->Size1D,Img->Raster->Size2D,8);
    if(Raster2->Data1D==NULL) goto Finish;

      {
      APalette *paletettebuff2 = BuildPalette(1<<Raster2->GetPlanes());
      if(paletettebuff2==NULL) goto Finish;
      Img->AttachPalette(paletettebuff2);
      }

    for(i=0; i<Img->Palette->GetSize1D(); i++)
      {
	Img->Palette->SetValue1D(i, paletettebuff->GetValue1D(i));
      }

    for(y=Img->Raster->Size2D;y>0;y--)   //fix for 32 bit planes
      {
      RowRas = Img->Raster->GetRowRaster(y-1);
      RowRas2 = Raster2->GetRowRaster(y-1);
      if(RowRas==NULL || RowRas2==NULL) continue;

      for(x=0;x<RowRas->GetSize1D();x++)
	{
	RGBval = RowRas->GetValue1D(x);

	for(i=0; i<CurrentColors; i++)
	  {
	  if(paletettebuff->GetValue1D(i) == RGBval)
	    {
	    RowRas2->SetValue1D(x,i);	// index has been found
	    break;
	    }
	  }
	}
      }

    Img->AttachRaster(Raster2);
    //printf("---- Image reduced %d ------", CurrentColors);
    }

Finish:
  if(paletettebuff) {delete paletettebuff;paletettebuff=NULL;}
  //printf("---- Image check ended<<<");

return CurrentColors;
}
