
#include "removecard.hpp"

#include "fitsfiles.hpp"
#include "io.hpp"

#include <fstream>

using namespace std;

/* useful when card is misplaced in header: deletes card from current position and
 * adds card to new position (decided by cfitsio fits_add_card) */
void remove_raw_card(const std::string pathname, /*unsigned int hdunum,*/ std::string keyname)
{
   LOG_trace(__func__);

   /* fitsfiles::reinsert_card(pathname, hdunum, keyname); */

   const long HDU_BEGIN = 0;

   char card[81];
   int ii;
   for(ii=0;ii<81;ii++) card[ii] = 0;

   vector<string> cards;

   cout << "keyname: "  << keyname << endl;

   keyname += string(8-keyname.size() ,' ');

   fstream fileBuffer(pathname, ios::in|ios::out|ios::binary);// in out = update file record (not truncate)
   if (fileBuffer.is_open())
   {
      fileBuffer.seekg(HDU_BEGIN, ios::beg);
      fileBuffer.read(card, 80);

      string cardstr(card);
      cards.push_back(cardstr);

      cout << cards.size() << " " << cardstr << endl;

      ii = 1;
      while(cardstr.substr(0,8).compare("END     ") != 0)
      {
         cout << ii << " : " << cardstr << "<" << endl;
         fileBuffer.read(card, 80);
         cardstr = string(card);
         ii++;

         if(cardstr.substr(0,8).compare(keyname) == 0)
            continue;
         else
            cards.push_back(cardstr);

         cout << cards.size() << " " << cardstr << endl;
      }
      cout << ii << " : " << cardstr << "<" << endl;
      cards.push_back(cardstr);
   }

   cout << cards.size() << endl;

   fileBuffer.seekg(HDU_BEGIN, ios::beg);
   for(string crd : cards)
   {
      cout << crd << endl;
      fileBuffer.write(crd.c_str(), 80);
      if(crd.substr(0,8).compare("END     ") == 0) break;
   }

   // add padding up to next 2880 border (and delete eventual duplicate END cards)

   long fpos{fileBuffer.tellp()};

   long block_fill = fpos % 2880;

   cout << fpos << " " << block_fill << endl;

   if(block_fill != 0)
   {
      long padding_len = 2880-block_fill;
      cout << padding_len << endl;
      string padding(padding_len, ' ');
      cout <<'>' <<  padding << '<' <<  endl;
      fileBuffer.write(padding.c_str(), padding_len);
   }

   fileBuffer.close();
}

