/* -*- 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
 * @author Mahmoud Ghoniem 
 * @date 2007-02-08
 *
 */

/*
 * @file fatom1.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 fftw1d{
#include "fftw1d.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 fftw1d{
#include "fftw1d.cpp"
}
namespace arithmetic{
#include "arithmetic/pmultcst.cpp"
#include "arithmetic/pdivcst.cpp"
}

#endif

// modulus function
float modulo(float w, float p){ 
  return p!=0 ? w-p*floor(w/p):w;
}

// Extract from a complex image the real parts in a separate images
Img1dsf real(const Img1dC& c){
  int w = c.Width();
  Img1dsf res(w);

  for (int i=0; i<w; i++)
    res[i]=real(c[i]);
  return res;
}

// Extract from a complex image the imaginary parts in a separate images
Img1dsf imag(const Img1dC& c){
  int w = c.Width();
  Img1dsf res(w);

  for (int i=0; i<w; i++)
    res[i]=imag(c[i]);
  return res;
}

// Create a complex image from real images (real and imaginary parts)
Img1dC join (const Img1dsf& re, const Img1dsf& im){
  int w = re.Width();
  Img1dC res(w);

  for (int k=0; k<w; k++)
    res[k] = Complexe(re[k], im[k]);
  return res;
}

/**
 * Function Fatom1
 *
 * @input x : the input image
 * @output c : cell array of wave atom coefficients

 * @param pat : type of frequency partition which satsifies parabolic scaling relationship
 * @apram tp : type of tranform
 *         1: standard version
 *        -1: Hilbert transformed version
 *         [default set to 1]
 * 
 */
Errc Fatom1(Img1dsf& x, Collection& c, char pat, Short tp=1) {
   double A,B,D;
   double Ict, Ifm, Ito,IdxSize;
   int N,H,resWidth;

   Img1dsf *empty =new Img1dsf;

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

   Img1dsf *imd_re =new Img1dsf;
   Img1dsf *imd_im =new Img1dsf;

   Img1dsf *res_re =new Img1dsf;
   Img1dsf *res_im =new Img1dsf;

   Img1dsf *ires_im =new Img1dsf;
   Img1dsf *ires_re =new Img1dsf;

   Img1dC Icf, res,ires, xft;

   //Collection lst;
   Img1duc* lst;
   Ulong nb_scales; // the collections number
   Ulong size; // the total packets number
   Ulong nw; // the packets number
 
   size = 0;

   /******************************/
   N = x.Width();
   H = N/2;
   freq_pat::Freq_pat(lst,H,pat);
   /******************************/

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

   imd_re->New(N);
   imd_im->New(N);
   xft.New(N);
   fftw1d::FFTW(x,*empty,*imd_re,*imd_im,1);
   arithmetic::PDivCst(*imd_re, *imd_re, sqrt(N));
   arithmetic::PDivCst(*imd_im, *imd_im, sqrt(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
      Img1dsf* index = new Img1dsf (nw);
      (*index) = 0;

      // wave atoms coefficients computation
      for(unsigned int i=0; i<nw; i++){    
	 nb_packets++; //packets number per collection

	 if(lst[s-1][i]==0){ // leaf
	 }
	 else {
	    (*index)[i]=1;

	    B = 1<<(s-1);// 2^(s-1);
	    D = 2*B;

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

	    Ict = i*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;
	    }

	    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);
	       }
	       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);
	       }

	       for (int k=0; k<Icf.Width(); k++){
		  Icf[k] = conj(Icf[k]);
	       }

	       for (int k=0; k<IdxSize; k++){
		  int modD,modA;
		  modD = (int)modulo((*Idx)[k],D);
		  modA = (int)modulo((*Idx)[k],A);
		  res[modD] += Icf[k] * xft[modA];
	       }
	    }

	    resWidth=res.Width();

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

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

	    fftw1d::FFTW(*res_re,*res_im, *ires_re,*ires_im,-1); // (-1) -> ifft
	    arithmetic::PMultCst(*ires_re, *ires_re, sqrt(resWidth));

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

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

	    size+=resWidth;// packets counter
	 }
      } // 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", Img1dsf, (Img1dsf*)(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(1 or -1) [im_in|-] [im_out|-]"
#define PARC    2
#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_Img1dsf :{
      Img1dsf* const ims=(Img1dsf*)objs[0];
      objd[0] = new Collection();
      Collection* imd = (Collection*) objd[0];

      result=Fatom1(*ims, *imd, parv[0][0], atoi(parv[1]));
   }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
