/*
 * helpers.h
 *
 *  Created on: Jul 3, 2014
 *      Author: Daniel Wesierski
 */

#ifndef HELPERS_H_
#define HELPERS_H_

#include <opencv2/highgui.hpp>
#include <iostream>
#include <fstream>
#include <sstream>

inline void show_img(const cv::Mat &image, bool inVideo=false) {
	cv::namedWindow("Window", CV_WINDOW_AUTOSIZE);
	cv::imshow("Window", image);

	if (inVideo) cv::waitKey(2.3);
	else cv::waitKey(0);
}

inline const cv::Scalar color(unsigned int which=0)
{
	cv::Scalar color;
	switch(which%6)
	{		
		case 0: color = cv::Scalar(0,255,0);     break;
		case 1: color = cv::Scalar(0,0,255);     break;
		case 2: color = cv::Scalar(0,255,255);   break;
		case 3: color = cv::Scalar(255,0,0);     break;
		case 4: color = cv::Scalar(255,0,255);   break;
		case 5: color = cv::Scalar(255,255,0);   break;		
	}

	return color;
}

inline double deg()
{
	return 180./CV_PI;
}

inline int sgn(double a)
{
	return (a>=0) ? 1 : -1;
}

inline double start_clock()
{
	return (double)cv::getTickCount();  // start tick counter
}

inline double stop_clock(double starting_tick)
{
	return 1000.0*((double)cv::getTickCount() - starting_tick)/cv::getTickFrequency(); // in [ms]
}

template <class T>
inline void cvmat2file(const cv::Mat& m, const char* filename) {
    std::ofstream f(filename);

    if(!f) {
        std::cout <<"File Not Opened"<< std::endl;
    	return;
    }

    for(int i=0; i<m.rows; ++i) {
        for(int j=0; j<m.cols; ++j)
            f << m.at<T>(i,j) << ",";

        f << std::endl;
    }

    f.close();
}

inline void parseconfigfile(const char* filename, std::string& pathtovideo, std::vector<cv::Rect>& BBoxes, std::vector<std::vector<unsigned int> >& partsIdx) {
	std::ifstream f(filename);

	if (!f) {
		std::cout << "File Not Opened" << std::endl;
		return;
	}
	
	std::getline(f, pathtovideo);        // get path to video
	std::string str;
	unsigned int c = 0;
	while (std::getline(f,str)) { // get bbox annotations
				
		std::vector<unsigned int> idx;
		std::vector<int> vec;
		std::stringstream s(str);

		int i;
		while (s >> i)
		{
			vec.push_back(i);
			if (s.peek()==',' || s.peek()==' ')
				s.ignore();
		}
		
		for (int j = 0; j != vec.size() / 4; ++j) {
			BBoxes.push_back(cv::Rect(vec[4*j], vec[4*j+1], vec[4*j+2], vec[4*j+3]));
			idx.push_back(c++);
		}
		idx.push_back(c); // 'joint/anchor part' is shared by neighbor segments of parts
		partsIdx.push_back(idx);			
	}
	partsIdx[partsIdx.size()-1].pop_back();
	f.close();
}


#endif /* HELPERS_H_ */
