/* -*- mode: c++; c-basic-offset: 3 -*-
 *
 * PANTHEON Project
 *
 * GREYC IMAGE
 * 6 Boulevard Maréchal Juin
 * F-14050 Caen Cedex France
 *
 * This file is free software. You can use it, distribute it
 * and/or modify it. However, the entire risk to the quality
 * and performance of this program is with you.
 *
 * Please email any bugs, comments, and/or additions to this file to:
 * pandore@greyc.ensicaen.fr
 * http://www.greyc.ensicaen.fr/EquipeImage/Pandore/
 */

/**
 * Projet 3A : WAVEATOM transform
 * @authors
 *  Jalal Fadili
 *  Mahmoud Ghoniem 
 * @date 2007-02-11
 *
 */

/*
 * @file fatom2.cpp
 * @brief Forward transform of wave atom orthonormal basis
 */

#include <math.h>
#include <complex>
#include <iostream>
using namespace std;
#include "complexe.h"
using namespace pandore;



#ifdef MAIN
#undef MAIN

namespace freq_pat{
#include "freq_pat.cpp"
}
namespace kf_lf{
#include "kf_lf.cpp"
}
namespace kf_rt{
#include "kf_rt.cpp"
}
namespace fftw{
#include "fftw.cpp"
}
namespace arithmetic{
#include "arithmetic/pmultcst.cpp"
#include "arithmetic/pdivcst.cpp"
}

#define MAIN
#else
namespace freq_pat{
#include "freq_pat.cpp"
}
namespace kf_lf{
#include "kf_lf.cpp"
}
namespace kf_rt{
#include "kf_rt.cpp"
}
namespace fftw{
#include "fftw.cpp"
}
namespace arithmetic{
#include "arithmetic/pmultcst.cpp"
#include "arithmetic/pdivcst.cpp"
}

#endif


// Fonction modulo pour des parametres de type float
float modulo(float w, float p){ 
  return p!=0 ? w-p*floor(w/p):w;
}

// Fonction retournant l'image des parties reelles d'une image complexe
Img2dsf real(const Img2dC& c){

  Img2dsf res(c.Size());

  for (int i=0; i<c.Height(); i++)
  for (int j=0; j<c.Width(); j++)
    res[i][j] = real(c[i][j]);
  return res;
}

// Fonction retournant l'image des parties reelles d'une image complexe
Img2dsf imag(const Img2dC& c){
  Img2dsf res(c.Size());

  for (int i=0; i<c.Height(); i++)
  for (int j=0; j<c.Width(); j++)
    res[i][j] = imag(c[i][j]);
  return res;
}
// Fonction construisant une image complexe a partir de 2 images reelles
Img2dC join (const Img2dsf& re, const Img2dsf& im){
  Img2dC res( re.Size());

  for (int k=0; k<re.Height(); k++)
  for (int l=0; l<re.Width(); l++)
    res[k][l] = Complexe(re[k][l], im[k][l]);
  return res;
}

/**
 * Function fatom2.m - forward transform of wave atom orthnormal basis
 *
 * input x:  the input N-by-N image
 * output c:    cell array of wave atom coefficients
 *
 * @param pat : type of frequency partition which satsifies parabolic scaling relationship
 *         equal to 'p' or 'q'
 *   tp:   1-by-2, tp(1) and tp(2) denote the type of transform to use in x and y dimension respectively
 *         1: standard version
 *         -1: Hilbert transformed version
 *         [default set to [1 1]]
 */
Errc Fatom2(Img2dsf& x, Collection& c, char pat, Short tp[2]) {
   float B;
   float Ict, Ifm, Ito, Jct, Jfm, Jto, IdxSize, JdxSize;
   int A, D, N, H;
   Dimension2d resSize;

   // 1D
   Img1dC Icf, Jcf;

   Img1dsf* Idx = new Img1dsf;
   Img1dsf* Idx2 = new Img1dsf;

   Img1dsf* Jdx = new Img1dsf;
   Img1dsf* Jdx2 = new Img1dsf;

   //2D
   Img2dsf* empty = new Img2dsf;

   Img2dsf* res_re = new Img2dsf;
   Img2dsf* res_im = new Img2dsf;

   Img2dsf* ires_re = new Img2dsf;
   Img2dsf* ires_im = new Img2dsf;

   Img2dsf* imd_re = new Img2dsf;
   Img2dsf* imd_im = new Img2dsf;

   Img2dC res, ires, xft;

   //Collection lst;
   Img1duc* lst;
   Ulong nb_scales; // the collections number
   Ulong size = 0; // the total packets number
   Ulong nw; // the packets number
 
   
   /******************************/
   N = x.Width();
   H = N/2;
   freq_pat::Freq_pat(lst,H,pat);
   /******************************/

   empty->New(N,N);
   (*empty) = 0; // empty image for the fftw

   imd_re->New(N,N);
   imd_im->New(N,N);
   xft.New(N,N);
   fftw::FFTWNORM(x,*empty,*imd_re,*imd_im,1);
   arithmetic::PDivCst(*imd_re, *imd_re, N);
   arithmetic::PDivCst(*imd_im, *imd_im, N);

   xft = join (*imd_re, *imd_im);
 
   A = N;

   // Get the number of scales
   //nb_scales = lst.GETVALUE("nb_scales",Ulong);
   nb_scales = (pat=='p' ? (int) ceil(log2((double)H)/2)+1:(int) floor(log2((double)H)/2)+1);

   //char str[100];
   char colname[100];
   char tabname[100];

   // Allocate c as a collection of collections of arrays.

   // Parse the collection c
   // The packets numbering starts at 1 to nb_scales
   for(unsigned int s=1; s<nb_scales+1; s++){
      int nb_packets =0;

      // Create a collection at each iteration
      Collection *col= new Collection;

      //sprintf(str, "packets%d", s);

      //Img1dsl* tab_lst;
      //tab_lst = (Img1dsl *)(lst.GETPOBJECT(str, Img1dsl));
      //nw = tab_lst->Width();
      nw = lst[s-1].Width();

      //index the unempty packets
      Img2dsf* index = new Img2dsf (nw,nw);
      (*index) = 0;
      
      B = 1<<(s-1); // 2^(s-1);
      D = (int)(2*B);
      
      res.New((int)D, (int)D);

      // wave atoms coefficients computation
      for(unsigned int i=0; i<nw; i++){
	 for(unsigned int j=0; j<nw; j++){

	    nb_packets++;
	    if(lst[s-1][i]==0 && lst[s-1][j]==0){ // leaf 
	    }
	    else {

	       (*index)[i][j]=1;

	       for (int k=0; k<D; k++)
		  for (int l=0; l<D; l++)
		     res[k][l]=0;

	       Ict = i*B;
	       Jct = j*B;

	       if(i%2==0){
		  Ifm = Ict - 2.0F/3*B;
		  Ito = Ict + 4.0F/3*B;
	       }
	       else{
		  Ifm = Ict - 1.0F/3*B;
		  Ito = Ict + 5.0F/3*B;
	       }

	       if(j%2==0){
		  Jfm = Jct - 2.0F/3*B;
		  Jto = Jct + 4.0F/3*B;
	       }
	       else{
		  Jfm = Jct - 1.0F/3*B;
		  Jto = Jct + 5.0F/3*B;
	       }

	       for(int id=0; id<2; id++){
		  if(id==0){
		     IdxSize = floor(Ito)-ceil(Ifm)+1;

		     Idx->New((int)IdxSize);
		     Idx2->New((int)IdxSize);

		     for(int k=0; k<IdxSize; k++){
			(*Idx)[k] = ceil(Ifm) + k;
			(*Idx2)[k] = (*Idx)[k] / B * M_PI;
		     }
		     Icf = kf_rt::kf_rt(*Idx2, i, tp[0]);
		  }
		  else{
		     IdxSize = floor(-Ifm)-ceil(-Ito)+1;

		     Idx->New((int)IdxSize);
		     Idx2->New((int)IdxSize);

		     for(int k=0; k<IdxSize; k++){
			(*Idx)[k] = ceil(-Ito) + k;
			(*Idx2)[k] = (*Idx)[k] / B * M_PI;
		     }
		     Icf = kf_lf::kf_lf(*Idx2, i, tp[0]);
		  }

		  for(int jd=0; jd<2; jd++){
		     if(jd==0){
			JdxSize = floor(Jto)-ceil(Jfm)+1;

			Jdx->New((int)JdxSize);
			Jdx2->New((int)JdxSize);

			for(int k=0; k<JdxSize; k++){
			   (*Jdx)[k] = ceil(Jfm) + k;
			   (*Jdx2)[k] = (*Jdx)[k] / B * M_PI;
			}
			Jcf = kf_rt::kf_rt(*Jdx2, j, tp[1]);
		     }
		     else{
			JdxSize = floor(-Jfm)-ceil(-Jto)+1;

			Jdx->New((int)JdxSize);
			Jdx2->New((int)JdxSize);

			for(int k=0; k<JdxSize; k++){
			   (*Jdx)[k] = ceil(-Jto) + k;
			   (*Jdx2)[k] = (*Jdx)[k] / B * M_PI;
			}
			Jcf = kf_lf::kf_lf(*Jdx2, j, tp[1]);
		     }

		     for (int k=0; k<IdxSize; k++)
			for (int l=0; l<JdxSize; l++){
			   int modDI, modDJ, modAI, modAJ;
			   modDI = (int)modulo((*Idx)[k],D);
			   modDJ = (int)modulo((*Jdx)[l],D);
			   modAI = (int)modulo((*Idx)[k],A);
			   modAJ = (int)modulo((*Jdx)[l],A);
			   res[modDI][modDJ] += conj(Icf[k] * Jcf[l]) * xft[modAI][modAJ];
			}
		  }
	       }

	       resSize=res.Size();

	       res_re->New(resSize);
	       res_im->New(resSize);
	       ires_re->New(resSize);
	       ires_im->New(resSize);

	       (*res_re) = real(res);
	       (*res_im) = imag(res);

	       fftw::FFTWNORM(*res_re,*res_im, *ires_re,*ires_im,-1); // (-1) -> ifft
	       arithmetic::PMultCst(*ires_re, *ires_re, sqrt((double)(resSize.w*resSize.h)));

	       sprintf(tabname, "packets%d_%d_%d", s,i,j);

	       col->SETPOBJECT(tabname,Img2dsf, (Img2dsf*)(ires_re->Clone()));

	       size += resSize.w*resSize.h;
	    }
	 } // end of the nw loop.
      }
      // Set the packets number and the index of unempty packets in the collection
      col->SETVALUE("nb_packets", Ulong, (Ulong)nb_packets);
      col->SETPOBJECT("index_packets", Img2dsf, (Img2dsf*)(index->Clone()));

      // Set the collections in the main collection c
      sprintf(colname, "collections%d", s);
      c.SETPOBJECT(colname, Collection, col);
   }
   c.SETVALUE("size", Ulong, (Ulong)size);
   return SUCCESS;
}


#ifdef MAIN
#define USAGE   "usage: %s pat(p or q) tp[0](1 or -1) tp[1](1 or -1) [-m mask] [im_in|-] [im_out|-]"
#define PARC    3
#define FINC    1
#define FOUTC   1
#define MASK    0

int main(int argc,char* argv[]) {
   Errc result;			// The result code of the execution.
   Pobject *mask;		// The mask.
   Pobject *objin[FINC+1];	// The input objects;
   Pobject *objs[FINC+1];	// The source objects masked by mask.
   Pobject *objout[FOUTC+1];	// The output object unmasked by mask.
   Pobject *objd[FOUTC+1];	// The result object.
   char *parv[PARC+1];		// The input parameters.
  
   ReadArgs(argc,argv,PARC,FINC,FOUTC,&mask,objin,objs,objout,objd,parv,USAGE,MASK);

   switch(objs[0]->Type()){
   case Po_Img2dsf :{
      Img2dsf* const ims=(Img2dsf*)objs[0];
      objd[0] = new Collection();
      Collection* imd = (Collection*) objd[0];

      Short tp[2];
      tp[0] = atoi(parv[1]);
      tp[1] = atoi(parv[2]);

      result=Fatom2(*ims, *imd, parv[0][0], tp);
   }break;
   default :
      PrintErrorFormat(objin,FINC);
      result =FAILURE;
   }
  
   if (result)
      WriteArgs(argc,argv,PARC,FINC,FOUTC,&mask,objin,objs,objout,objd,MASK);
   Exit(result);
   return 0;
}

#endif
