// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// Mobius Forensic Toolkit
// Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016,2017 Eduardo Aguiar
//
// 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 2, 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/>.
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include <mobius/partition/partition_system_impl_base.h>
#include <algorithm>

namespace mobius
{
namespace partition
{
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//! \brief add freespaces between non-contiguous entries
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void
partition_system_impl_base::_add_freespaces (mobius::io::sector_reader_adaptor reader)
{
  // sort entries
  std::sort (entries_.begin (), entries_.end ());

  // fill in freespace where it is necessary
  sector_type pos = 0;
      
  auto entries = entries_;
  entries_.clear ();

  for (auto e : entries)
    {
      if (pos < e.starting_sector)
        {
          entry f_entry;
          f_entry.starting_sector = pos;
          f_entry.ending_sector = e.starting_sector - 1;
          f_entry.sectors = f_entry.ending_sector - f_entry.starting_sector + 1;
          f_entry.type = "freespace";
          f_entry.description = "Freespace";
          entries_.push_back (f_entry);
        }

      entries_.push_back (e);
      pos = e.ending_sector + 1;
    }
        
  auto ending_sector = reader.get_sectors () - 1;

  if (pos < ending_sector)
    {
      entry f_entry;
      f_entry.starting_sector = pos;
      f_entry.ending_sector = ending_sector;
      f_entry.sectors = f_entry.ending_sector - f_entry.starting_sector + 1;
      f_entry.type = "freespace";
      f_entry.description = "Freespace";
      entries_.push_back (f_entry);
    }
}
        
} // namespace partition
} // namespace mobius
