#include <iostream>

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <dmtx.h>

using namespace cv;
using namespace std;


int main()
{
   size_t          width, height, bytesPerPixel;
   unsigned char   str[] = "111222";
   DmtxImage      *img;
   DmtxDecode     *dec;
   DmtxRegion     *reg;
   DmtxMessage    *msg;
   

//    Mat cv_img = imread("/home/luis/Documentos/Dissertação/Codigo/Leitura de DataMatrix/Imagens/wikidmtx_dmg2.jpg",CV_LOAD_IMAGE_GRAYSCALE);
//    Mat cv_img = imread("/home/luis/Documentos/Dissertação/Codigo/Leitura de DataMatrix/minhadmtx_dmg6.jpg",CV_LOAD_IMAGE_GRAYSCALE);
//    Mat cv_img = imread("/home/luis/Documentos/Dissertação/Codigo/Leitura de DataMatrix/Imagens/mydmtx.png",CV_LOAD_IMAGE_GRAYSCALE);
   Mat cv_img = imread("/home/luis/Documentos/Dissertação/Codigo/Aquisição de Imagem/Imagens/Imagem2.jpeg",CV_LOAD_IMAGE_GRAYSCALE);
   
   int type = cv_img.type();
   int depth = cv_img.depth();
   int chan = cv_img.channels();
   cout << "Tipo: " << type << ", Depth: " << depth << ", channels: " << chan << endl;
   
   imshow("DataMatrix",cv_img);
//    Size size = cv_img.size();
//    cout << " width: " << size << endl;

   img = dmtxImageCreate(cv_img.data, cv_img.cols, cv_img.rows, DmtxPack24bppRGB);
   assert(img != NULL);

   dec = dmtxDecodeCreate(img, 1);
   assert(dec != NULL);

   reg = dmtxRegionFindNext(dec, NULL);
   while(reg != NULL) {
      msg = dmtxDecodeMatrixRegion(dec, reg, DmtxUndefined);
      if(msg != NULL) {
         fputs("output: \"", stdout);
         fwrite(msg->output, sizeof(unsigned char), msg->outputIdx, stdout);
// 	 cout << "output: " << msg->output << endl;
// 	 cout << "Código completo: " << msg->codeSize << endl;
         fputs("\"\n", stdout);
         dmtxMessageDestroy(&msg);
      }else{
	cout << "Matrix detectada. Mensagem não descodificada" << endl;
      }
      
//    }else{
//      cout << "Matrix não detectada" << endl;
   }

   
   waitKey(0);
   dmtxRegionDestroy(&reg);
   dmtxDecodeDestroy(&dec);
   dmtxImageDestroy(&img);
   exit(0);

}
