#include <iostream>
#include <fstream>
#include "connected.hpp"
#include "afmm/include/field.h"
#include "messages.h"

using namespace std;


bool initialized = false;
ofstream file;

/* Initialize the image statistics variables.
 * Call this before calling any other functions, to open
 * the output-stream.
 */
void IS_init(const char *filename){
    if(initialized){    return; }
    char fn[256];
    int i=1;
    while(*(filename+i)!='.' && *(filename+i)!='\0')++i;
    memcpy(fn,filename,i*sizeof(char));
    fn[i]='\0';
    strcat(fn, "_stat.m");
    PRINT(MSG_VERBOSE, "Writing statistics to: %s.\n", fn);
    file.open(fn, ios_base::trunc | ios::out);

    file << "clear all; close all;" << endl;
    initialized = true;
}

/* Some things cannot be done in this statistics file, pass the stream handler
 * to external functions when necessary
 */
ofstream* IS_get_statistics_ofstream(){
    return &file;
}

/*
 * Analyse a layer - The number of objects, and number of pixels.
 */
void IS_analyseLayer(string postid, FIELD<float> *im, int intensity) {
    ConnectedComponents *CC = new ConnectedComponents(255);
    int nPix = im->dimX() * im->dimY();
    int *ccaOut = new int[nPix];
    intensity += 1;

    /* Number of objects */
    int highestLabel = CC->connected(im->data(), ccaOut, im->dimX(), im->dimY(), std::equal_to<float>(), true);
    file << "number_of_objects_" << postid << "(" << intensity << ")=" << highestLabel << ";" << endl;

    /* Number of pixels  */
    int notZero = 0;
    for (int i = 0; i < im->dimX() * im->dimY(); ++i) {
        if (*(im->data() + i) > 0.0001) {
            notZero++;
        }
    }
    file << "number_of_on_pixels_" << postid << "(" << intensity << ")=" << notZero << ";" << endl;
    
    delete CC;
    delete [] ccaOut;
}

/* Analyse an image. The image dimensions, its histogram, and include a full
 * copy of the image in matlab format.
 */
void IS_analyseImage(string postid, FIELD<float> *im){
    int *hist = new int[256];
    
    /* Image dimensions */
    file << "IMAGE_WIDTH_" << postid << "=" << im->dimX() << endl;
    file << "IMAGE_HEIGHT_" << postid << "=" << im->dimY()<< endl;
    
    /* Histogram */
    for(int i=0; i<256;++i){  hist[i]=0;  }
    
    for(int i=0; i< im->dimX()* im->dimY(); ++i){
        hist[(int) *( im->data() + i )]++;
    }
    
    file << "IMhistogram_" << postid << "=[";
    for(int i=0; i<256;++i){
        if(i != 0) file << ", ";
        file << hist[i];
    }
    file << "];";
    
    /* Entire Image */
    file << "IMimg_" << postid << " = [";
    for(int y=0; y<im->dimY(); ++y){
        for(int x=0; x<im->dimX(); ++x){
            file << im->fvalue(x,y);
            if(x <im->dimX()-1) file << ", ";
        }
        file << ";\n";
    }
    file << "];" << endl;
    delete [] hist;
}

void IS_stop(){
    if(!initialized){ return; }
    initialized = false;

    ifstream ifs;
    ifs.open("_STATISTICS_APPEND", ios::in);
    if(!ifs){ PRINT(MSG_ERROR, "Could not open statistics file, data is written, but no statistics will be generated.\n"); }
    else{
        file << ifs.rdbuf();
        file << flush;
    }

    file.close();
}
