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

  File        : image2ascii.cpp

  Description : An image to ASCII-art converter

  Copyright  : David Tschumperle - http://www.greyc.ensicaen.fr/~dtschump/
  
  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.
  
  ------------------------------------------------------------------------------*/

// Tell CImg not to use display capabilities.
#define cimg_display_type 0
#include "../CImg.h"
using namespace cimg_library;

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

  Main procedure

  --------------------------*/
int main(int argc,char **argv) {
  cimg_usage("An image to ASCII-art converter.\n\nUsage : image2ascii [options] image");

  // Read command line parameters
  const char *file_i = NULL;
  for (int i=1; i<argc; i++) if (argv[i][0]!='-') file_i = argv[i];
  const char *geom    = cimg_option("-g","80x40","Output size");
  const int alphabet  = cimg_option("-a",0,"Alphabet type (0=full, 1=numbers, 2=letters, 3=signs, 4=minimal");
  const bool invert   = cimg_option("-invert",false,"Invert image intensities");
  const float contour = cimg_option("-contour",0.0,"Use image contours higher than specified threshold");
  const float blur    = cimg_option("-blur",0.8,"Image pre-blur");
  const float sigma   = cimg_option("-sigma",1.5,"Font pre-blur");
  int w,h;
  std::sscanf(geom,"%d%*c%d",&w,&h);

  // Init fonts
  const CImgl<> font_full = CImgl<>::get_font(11,false);
  const int fw = font_full['A'].dimx(), fh = font_full['A'].dimy();
  CImgl<> font, font_blur;
  CImgl<unsigned char> font_code;

  switch (alphabet) {
  case 1: { 
    font_code.insert(CImg<unsigned char>::vector(' '));
    for (unsigned int l='0'; l<='9'; l++) font_code.insert(CImg<unsigned char>::vector(l)); 
  } break;
  case 2: {
    font_code.insert(CImg<unsigned char>::vector(' '));
    for (unsigned int l='A'; l<='Z'; l++) font_code.insert(CImg<unsigned char>::vector(l)); 
  } break;
  case 3: {
    font_code.insert(CImg<unsigned char>::vector(' '));
    font_code.insert(CImg<unsigned char>::vector('-'));
    font_code.insert(CImg<unsigned char>::vector('_'));
    font_code.insert(CImg<unsigned char>::vector('|'));
    font_code.insert(CImg<unsigned char>::vector('/'));
    font_code.insert(CImg<unsigned char>::vector('\\'));
    font_code.insert(CImg<unsigned char>::vector('+'));
    font_code.insert(CImg<unsigned char>::vector('.'));
    font_code.insert(CImg<unsigned char>::vector('*'));
    font_code.insert(CImg<unsigned char>::vector('='));
    font_code.insert(CImg<unsigned char>::vector(']'));
    font_code.insert(CImg<unsigned char>::vector('['));
    font_code.insert(CImg<unsigned char>::vector('('));
    font_code.insert(CImg<unsigned char>::vector(')'));
    font_code.insert(CImg<unsigned char>::vector('{'));
    font_code.insert(CImg<unsigned char>::vector('}'));
    font_code.insert(CImg<unsigned char>::vector('"'));
    font_code.insert(CImg<unsigned char>::vector('!'));
    font_code.insert(CImg<unsigned char>::vector('$'));
    } break;
  case 4: {
    font_code.insert(CImg<unsigned char>::vector(' '));
    font_code.insert(CImg<unsigned char>::vector('.'));
    font_code.insert(CImg<unsigned char>::vector('/'));
    font_code.insert(CImg<unsigned char>::vector('\\'));
    font_code.insert(CImg<unsigned char>::vector('_'));
    font_code.insert(CImg<unsigned char>::vector('_'));
    font_code.insert(CImg<unsigned char>::vector('|'));
    } break;
  default: { for (unsigned int l=' '; l<='~'; l++) font_code.insert(CImg<unsigned char>::vector(l)); } break;
  }
  cimgl_map(font_code,l) {
    font.insert(font_full(font_code[l](0)));
    font_blur.insert(font[l].get_resize(fw,fh,1,1).blur(sigma).normalize(0,255));
  }
  
  // Init images
  if (!file_i) { std::fprintf(stderr,"You must specify an input image (try '%s -h').\n\n",argv[0]); std::exit(0); }
  CImg<> img = CImg<>(file_i).norm_pointwise().resize(fw*w,fh*h);
  if (blur) img.blur(blur);
  if (contour>0) {
    CImgl<> grad = img.get_gradientXY(4);
    img = (grad[0].pow(2) + grad[1].pow(2)).sqrt().normalize(0,100).threshold(contour);
  }
  img.normalize(0,255);
  if (invert) img = 255.0f-img;
  CImg<unsigned char> dest(w,h,1,1,0);

  // Render ASCII-art image, using a simple correlation method.
  CImg<> neigh;
  cimg_mapY(dest,y) { cimg_mapX(dest,x) {
    neigh = img.get_crop(x*fw,y*fh,(x+1)*fw,(y+1)*fh);
    float scoremin = 2e28;
    unsigned int best = 0;
    cimgl_map(font_code,l) {
      const CImg<>& letter = font_blur[l];
      const float score = (letter-neigh).pow(2).sum();
      if (score<scoremin) { scoremin = score; best = l; }
    }
    dest(x,y) = best;
    std::fprintf(stdout,"%c",font_code[dest(x,y)](0));
  }
  std::fprintf(stdout,"\n");
  }
  
  std::exit(0);
  return 0;
}
