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

  File        : wavelet_atrous.cpp

  Description : Performs a 2D or 3D 'a trous' wavelet transform 
                (using a cubic spline) on an image or a video sequence.

  Reference :   Starck, J.-L., Murtagh, F. and Bijaoui, A.,
                Image Processing and Data Analysis: The Multiscale Approach,
                Cambridge University Press, 1998.
               (Hardback and softback, ISBN 0-521-59084-1 and 0-521-59914-8.)

  Author      : Renaud Péteri  - Renaud.Peteri '@' mines-paris.org

  Institution : CWI, Amsterdam

  Date        : February 2005
  
  This software is governed by the CeCILL  license under French law and
  abiding by the rules of distribution of free software.  You can  use, 
  modify and/ or redistribute the software under the terms of the CeCILL
  license as circulated by CEA, CNRS and INRIA at the following URL
  "http://www.cecill.info". 
  
  As a counterpart to the access to the source code and  rights to copy,
  modify and redistribute granted by the license, users are provided only
  with a limited warranty  and the software's author,  the holder of the
  economic rights,  and the successive licensors  have only  limited
  liability. 
  
  In this respect, the user's attention is drawn to the risks associated
  with loading,  using,  modifying and/or developing or reproducing the
  software by the user in light of its specific status of free software,
  that may mean  that it is complicated to manipulate,  and  that  also
  therefore means  that it is reserved for developers  and  experienced
  professionals having in-depth computer knowledge. Users are therefore
  encouraged to load and test the software's suitability as regards their
  requirements in conditions enabling the security of their systems and/or 
  data to be ensured and,  more generally, to use and operate it in the 
  same conditions as regards security. 
  
  The fact that you are presently reading this means that you have had
  knowledge of the CeCILL license and that you accept its terms.
  
  ---------------------------------------------------------------------------------------*/

#include <iostream>
#include <fstream>
#include "../CImg.h"
using namespace std;
using namespace cimg_library;

CImg<float> mask_x(const unsigned char scale) { 
  unsigned char d1 = (unsigned char) pow( 2.0, (double)(scale-1));
  unsigned char d2 = (unsigned char) pow( 2.0, (double)(scale));
  unsigned char cx = (unsigned char) pow( 2.0, (double)(scale));
  unsigned char res = (unsigned char) pow( 2.0, (double)scale); 
  CImg<float> m(2*res +1,1,1);m.fill(0);
  m(cx) = 6.0;
  m(cx-d1) =  m(cx+d1) =4.0;
  m(cx-d2) =  m(cx+d2) =1.0;
  m /= 16.0;
  return m;
}

CImg<float> mask_y(const unsigned char scale) { 
  unsigned char d1 = (unsigned char) pow( 2.0, (double)(scale-1));
  unsigned char d2 = (unsigned char) pow( 2.0, (double)(scale));
  unsigned char cy = (unsigned char) pow( 2.0, (double)(scale));
  unsigned char res = (unsigned char) pow( 2.0, (double)scale); 
  CImg<float> m(1,2*res +1);m.fill(0);
  m(0,cy) = 6.0;
  m(0,cy-d1) =  m(0,cy+d1) =4.0;
  m(0,cy-d2) =  m(0,cy+d2) =1.0;
  m /= 16.0;
  return m;
}

CImg<float> mask_t(const unsigned char scale) { 
  unsigned char d1 = (unsigned char) pow( 2.0, (double)(scale-1));
  unsigned char d2 = (unsigned char) pow( 2.0, (double)(scale));
  unsigned char ct = (unsigned char) pow( 2.0, (double)(scale));
  unsigned char res = (unsigned char) pow( 2.0, (double)scale); 
  CImg<float> m(1,1,2*res +1);m.fill(0);
  m(0,0,ct) = 6.0;
  m(0,0,ct-d1) =  m(0,0,ct+d1) =4.0;
  m(0,0,ct-d2) =  m(0,0,ct+d2) =1.0;
  m /= 16.0;
  return m;
}

/*------------------
  Main procedure
  ----------------*/
int main(int argc,char **argv) {
  
  cimg_usage("Perform an 'a trous' wavelet transform (using a cubic spline) on an image or on a video sequence.\n"
	     "This wavelet transform is undecimated and produces 2 images/videos at each scale. For an example of\n"
	     "decomposition on a video, try -i /usr/local/share/examples/cimg/img/trees.inr (sequence from the MIT).\n"
	     "\t(Type -h for help)");

  // Read command line parameters
  const char
    *name_i  = cimg_option("-i","/usr/local/share/examples/cimg/img/lena.pgm","Input image or video"),
    *name_o  = cimg_option("-o","","Name of the multiscale analysis output"),
    *axe_dec = cimg_option("-axe",(char*)NULL,"Perform the multiscale decomposition in just one direction ('x', 'y' or 't')");
  const unsigned int
    s = cimg_option("-s",3,"Scale of decomposition");

  const bool help = cimg_option("-h",false,"Display Help");
  if(help) exit(0);

  // Initialize Image Data
  cout << " - Load image sequence " << name_i << "...\n";
  const CImg<float> texture_in(name_i);
  CImg<float> mask_conv_x, mask_conv_y, mask_conv_t;
  CImgl<float> res(s, texture_in.dimx(),texture_in.dimy(),texture_in.dimz());
  CImgl<float> wav(s,texture_in.dimx(), texture_in.dimy(), texture_in.dimz());
  cimgl_map(res,l){res(l).fill(0.0); wav(l).fill(0.0);}
  unsigned int i;

  if (!axe_dec){
    // Perform the multiscale decomposition in all directions
    for(i=0;i<s;i++){
      cout << " - Performing scale "<< i+1 <<" ... \n";
      if(i==0){ res(i) =  texture_in;} else {  res(i) = res(i-1);}
      mask_conv_x = mask_x(i+1);
      res(i) = res(i).get_convolve(mask_conv_x);
      mask_conv_y = mask_y(i+1);
      res(i) = res(i).get_convolve(mask_conv_y);
      mask_conv_t = mask_t(i+1);
      res(i) = res(i).get_convolve(mask_conv_t);
      if(i==0){wav(i) = texture_in - res(i);}  // res(0) and wav(0) are the 1st scale of decompostion  
      else {wav(i) = res(i-1) - res(i);} 
    } }

  if (axe_dec) {
    // Perform the multiscale decomposition in just one direction
    char c;
    c = cimg::uncase(axe_dec[0]);
    fprintf(stderr," - Decompose the image along axe '%c'\n",c); fflush(stdout);

    switch(c) {
    case 'x': { 
      for(i=0;i<s;i++){
	cout << " - Performing scale "<< i+1 <<" ... \n";
	if(i==0){ res(i) =  texture_in;} else {  res(i) = res(i-1);}
	mask_conv_x = mask_x(i+1);
	res(i) = res(i).get_convolve(mask_conv_x);
	if(i==0){wav(i) = texture_in - res(i);}  
	else {wav(i) = res(i-1) - res(i);}}}
      break;
      
    case 'y': {
      for(i=0;i<s;i++){
	cout << " - Performing scale "<< i+1 <<" ... \n";
	if(i==0){ res(i) =  texture_in;} else {  res(i) = res(i-1);}
	mask_conv_y = mask_y(i+1);
	res(i) = res(i).get_convolve(mask_conv_y);
	if(i==0){wav(i) = texture_in - res(i);}  
	else {wav(i) = res(i-1) - res(i);}}}
      break;
      
    case 't': {
      for(i=0;i<s;i++){
	cout << " - Performing scale "<< i+1 <<" ... \n";
	if(i==0){ res(i) =  texture_in;} else {  res(i) = res(i-1);}
	mask_conv_t = mask_t(i+1);
	res(i) = res(i).get_convolve(mask_conv_t);
	if(i==0){wav(i) = texture_in - res(i);}  
	else {wav(i) = res(i-1) - res(i);}}}
      break;
      
    default: throw CImgException("Error, unknow decompostion axe '%c', try 'x', 'y' or 't'",c);
    }
    fputc('\n',stderr);
  }
    
  if (*name_o){
    // Save the Multi-Scale Analysis
    cout << " - Saving of all output sequences: "<< name_o <<" in the msa/ directory... \n"; 
    int count = 1; // res0 = original image
    char filename[256] = "", filename_wav[256] = "";
    char STmp[3] = "";
    system("mkdir msa");
    for(i=0;i<s;i++){   
      strcpy( filename, "msa/res" );
      strcpy( filename_wav, "msa/wav" );
      if( count < 10 )
	{ strcat( filename, "0" );strcat( filename_wav, "0" );}
      sprintf( STmp, "%d_", count );
      strcat( filename, STmp ); strcat( filename_wav, STmp );
      strcat( filename,name_o);strcat( filename_wav,name_o);
      res(i).save(filename);
      wav(i).save(filename_wav);
      count++;
    }
  }
  
  // Result visualization
  const float value = 255;
  for(i=0;i<s;i++) {
    res[i].normalize(0,255).draw_text(2,2,&value,NULL,1,"Scale %d",i);
    wav[i].normalize(0,255).draw_text(2,2,&value,NULL,1,"Scale %d",i);
  }
  
  CImgDisplay disp(res,"Approximations levels by increasing scale",0);
  CImgDisplay disp2(wav,"Wavelet coefficients by increasing scale",0);
  while ( !disp.closed && disp.key!=cimg::keyQ && disp.key!=cimg::keyESC &&
	  !disp2.closed && disp2.key!=cimg::keyQ && disp2.key!=cimg::keyESC ) {
    if (disp.resized) disp.resize().display(res);
    if (disp2.resized) disp2.resize().display(wav);
    cimg::wait(20);
  }
  
  return 0;
}
