/*
    libmaus2
    Copyright (C) 2019 German Tischler-Höhle

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#if ! defined(LIBMAUS2_GTF_BAMGTFMAP_HPP)
#define LIBMAUS2_GTF_BAMGTFMAP_HPP

#include <libmaus2/bambam/BamHeader.hpp>
#include <libmaus2/gtf/GTFData.hpp>

namespace libmaus2
{
	namespace gtf
	{
		struct BAMGTFMap
		{
			std::vector<int64_t> Vmap;
			std::vector<int64_t> Vrmap;

			void setup(libmaus2::bambam::BamHeader const & bamheader, std::vector<std::string> const & Vchr)
			{
				Vmap = std::vector<int64_t>(bamheader.getNumRef(),-1);
				Vrmap = std::vector<int64_t>(Vchr.size(),-1);

				/* compute mapping between ids in BAM header and in GTF data */
				for ( uint64_t i = 0; i < bamheader.getNumRef(); ++i )
				{
					std::string const srefname = bamheader.getRefIDName(i);
					typedef std::vector<std::string>::const_iterator it;
					std::pair<it,it> const P = std::equal_range(Vchr.begin(),Vchr.end(),srefname);
					if ( P.second != P.first )
					{
						assert ( P.second - P.first == 1 );
						uint64_t const chrid = P.first - Vchr.begin();
						// std::cerr << srefname << "\t" << chrid << std::endl;

						Vmap.at(i) = chrid;
						Vrmap.at(chrid) = i;
					}
					#if 0
					else
					{
						std::cerr << "[V] " << srefname << " not found in annotation file" << std::endl;
					}
					#endif
				}

			}

			BAMGTFMap(libmaus2::bambam::BamHeader const & bamheader, libmaus2::gtf::GTFData const & gtfdata)
			{
				setup(bamheader,gtfdata.Vchr);
			}

			BAMGTFMap(libmaus2::bambam::BamHeader const & bamheader, std::vector<std::string> const & Vchr)
			{
				setup(bamheader,Vchr);
			}
		};
	}
}
#endif
