/*
 * Tools related to the MitoPacq, the CBIA time-lapse cell observation simulator.
 *
 * Copyright (C) 2005-2013   Centre for Biomedical Image Analysis (CBIA)
 *
 * This library-related tools is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <i3d/image3d.h>
#include <i3d/basic.h>
#include <fstream>

using namespace i3d;
using namespace std;

template <class VOXELIN> void DoVTKlegacyFile(Image3d<VOXELIN> & inImg, char *nameFrom, char *nameTo, char VOXEL)
{
    fstream filestr;
    const size_t xIndMax = inImg.GetSizeX();
    const size_t yIndMax = inImg.GetSizeY();
    const size_t zIndMax = inImg.GetSizeZ();

    filestr.open(nameTo, std::ios::out);

    filestr << "# vtk DataFile Version 3.0\n";
    filestr << "Image converted from " << nameFrom << endl;
    filestr << "ASCII\n";

    filestr << "DATASET STRUCTURED_POINTS\n";
    filestr << "DIMENSIONS " << xIndMax << " " << yIndMax << " " << zIndMax << endl;
    //GetOffset() returns origin position in micrometers
    filestr << "ORIGIN " << inImg.GetOffset().x << " " \
    			 << inImg.GetOffset().y << " " \
    			 << inImg.GetOffset().z << endl;
    //GetResolution() returns pixels per micron, we assume that SPACING should hold
    //the size of voxel along given axis (since documentation says "SPACING sx sy sz").
    //sx=1 should be interpreted as the size of 1um.
    filestr << "SPACING " << 1.0f/inImg.GetResolution().GetX() << " " \
    			  << 1.0f/inImg.GetResolution().GetY() << " " \
			  << 1.0f/inImg.GetResolution().GetZ() << endl;

    filestr << "POINT_DATA " << xIndMax*yIndMax*zIndMax << endl;

    if (VOXEL < 3) {
    	//GRAY8 or GRAY16 input image
	filestr << "SCALARS voxel_values " << ((VOXEL==1)?"unsigned_char":"unsigned_short") << " 1\n";
	//filestr << "SCALARS voxel_values " << ((VOXEL==1)?"unsigned_char":"unsigned_short") << " 3\n";

	//filestr << "LOOKUP_TABLE default\n";
	filestr << "LOOKUP_TABLE intensity_colors\n";

	//now, the list of voxel values with x-axis first, then y-axis and z-axis as the latest
	VOXELIN *p=inImg.GetFirstVoxelAddr();
	for (size_t z = 0; z < zIndMax; ++z) {
	  for (size_t y = 0; y < yIndMax; ++y)
	    for (size_t x = 0; x < xIndMax; ++x, ++p)
		filestr << (int)*p << " ";
		//filestr << (int)*p << " " << (int)*p << " " << (int)*p << " ";
	  filestr << endl;
	}

	filestr << "\nLOOKUP_TABLE intensity_colors 256\n";
	filestr << "0 0 0 0\n";  //black, the color of background, is the only transparent color
	for (int i=1; i < 256; ++i)
		filestr << i << " " << i << " " << i << " 1\n";

/*
	filestr << "\nCOLOR_SCALARS voxel_colors 1\n";
	float brightest_color=255;

	//now, the list of voxel values with x-axis first, then y-axis and z-axis as the latest
	p=inImg.GetFirstVoxelAddr();
	for (size_t z = 0; z < zIndMax; ++z) {
	  for (size_t y = 0; y < yIndMax; ++y)
	    for (size_t x = 0; x < xIndMax; ++x, ++p)
		filestr << ((float)*p)/brightest_color << " ";
	  filestr << endl;
	}
*/

    } else if (VOXEL == 3) {
    	//float input image
	filestr << "SCALARS voxel_values float 1\n";
	filestr << "LOOKUP_TABLE default\n";

	//now, the list of voxel values with x-axis first, then y-axis and z-axis as the latest
	VOXELIN *p=inImg.GetFirstVoxelAddr();
	for (size_t z = 0; z < zIndMax; ++z) {
	  for (size_t y = 0; y < yIndMax; ++y)
	    for (size_t x = 0; x < xIndMax; ++x, ++p)
		filestr << *p << " ";
	  filestr << endl;
	}

    } else {
    	cerr << "Unsupported VOXEL type in input image! Bailing out...\n";
	return;
    }

    filestr.close();
}


int main(int argc, char **argv)
{
    cout << argv[0] << " - part of the tools set of the OpticalFlow library \n"
         "Copyright (C) 2005-2013 Centre for Biomedical Image Analysis (CBIA)\n"
         "This is free software; see the source for copying conditions. "
         "There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR "
         "A PARTICULAR PURPOSE.\n\n";


    Image3d <i3d::GRAY8> g8Img;
    Image3d <i3d::GRAY16> g16Img;
    Image3d <float> fImg;

    if (argc < 3)
    {
        cout << "Bad number of parameters\nUsage: " << argv[0] << " input output\nexample: " << argv[0] << " image.tif image.vtk\n" ;
        return -2;
    }
        // zjisteni typu vstupniho souboru
        // !!! Nefunguje zjisteni souboru z regularniho vyrazu !!!
        cerr << "Reading image Type" << endl;
        ImgVoxelType vt = ReadImageType(argv[1]);
        cerr << "Voxel=" << VoxelTypeToString(vt) << endl;

    try
    {
	switch (vt)
	{
	    case Gray8Voxel:
		g8Img.ReadImage(argv[1]);
		DoVTKlegacyFile(g8Img, argv[1], argv[2], 1);
		break;
	    case Gray16Voxel:
		g16Img.ReadImage(argv[1]);
		DoVTKlegacyFile(g16Img, argv[1], argv[2], 2);
		break;
	    case FloatVoxel:
		fImg.ReadImage(argv[1]);
		DoVTKlegacyFile(fImg, argv[1], argv[2], 3);
		break;

	    default:
		cerr << "Other voxel types not supported!\n";
		break;

	}
    }
    catch(IOException & e)
    {
        cerr << e << endl;
        exit(1);
    }
    catch(InternalException & e)
    {
        cerr << e << endl;
        exit(1);
    }
    catch(bad_alloc &)
    {
        cerr << "Not enough memory." << endl;
        exit(1);
    }
    catch(...)
    {
        cerr << argv[0] << "Unknown exception." << endl;
        exit(1);
    }
    return 0;
}
