
#include "vlkb_dropdegen.hpp"

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

#include <fitsio.h>

#include <string.h>
#include <stdio.h>

using namespace std;

void dropdegen(fitsfile *fptr)
{
    LOG_trace(__func__);

    FILE* lferr = stderr;

    int status = 0;

    // DBG print key statistics Before eventual modifications
    int keysexist = 0;
    int morekeys  = 0;
    if(fits_get_hdrspace(fptr,&keysexist,&morekeys,&status))
        fits_report_error(lferr, status);
//    else
        // FIXME fprintf(lferr,"BEFORE keysexist:%d morekeys:%d\n",keysexist,morekeys);

    int naxis = 0;
    if(fits_read_key(fptr,TINT,"NAXIS",&naxis,NULL,&status))
        fits_report_error(lferr, status);
//    else
        //fprintf(lfout, "%s: NAXIS  %d\n",__func__,naxis);

    // Note: string lengths:
    // char keyname[FLEN_KEYWORD], colname[FLEN_VALUE], coltype[FLEN_VALUE];

    LOG_STREAM << "NAXIS: " << to_string(naxis) << endl;

    int i;
    int orignaxis = naxis;
    for (i=0; (i<orignaxis) && (!status); i++) {

        int axislen = 0;
        char key[FLEN_KEYWORD] = {"\0"};
        int kix = i+1; // keyindex (starts from 1)
        sprintf(key,"NAXIS%d",kix);
        // FIXME fprintf(lfout,"%s: start for %s\n",__func__,key);
        if(fits_read_key(fptr,TINT,key,&axislen,NULL,&status))
            fits_report_error(lferr, status);
//        else
            // FIXME fprintf(lfout, "%s: %s %d\n",__func__,key,axislen);

        if(axislen != 1)
            continue;

        // found degen axis NAXISi = 1 -> remove it
        // FIXME fprintf(lfout,"%s: degen axis %s\n",__func__,key);

        // adjust NAXIS
        int newvalue = --naxis;
        // FIXME fprintf(lfout,"%s: new value NAXIS %d\n",__func__,newvalue);
        if(fits_update_key(fptr,TINT,"NAXIS",&newvalue,NULL,&status))
            fits_report_error(lferr, status);

        // delete NAXISi ...
        // FIXME fprintf(lfout,"%s: delete key %s\n",__func__,key);
        if(fits_delete_key(fptr,key,&status))
            fits_report_error(lferr, status);

        // ... and all keys which end with kix and are 5 chars: CTYPE CRVAL CRPIX ...
        // FIXME is this correct ? Other keys longer then 5 chars and
        // alternative encodings (one letter after axis number)??
        // How to define what keys to remove ?
        char keys[FLEN_KEYWORD] = {"\0"};
        sprintf(keys,"?????%d",kix);
        // FIXME fprintf(lfout,"%s: delete keys %s ",__func__,keys);
        while(fits_delete_key(fptr,keys,&status) != KEY_NO_EXIST){
            ;// FIXME fprintf(lfout,".");
        }
        // FIXME fprintf(lfout,"\n");
        if(status==KEY_NO_EXIST){
            status = 0; // Reset after expected error in while()
        } else {
            fits_report_error(lferr, status);
        }
    }

    // DBG print key statistics After eventual modifications
    if(fits_get_hdrspace(fptr,&keysexist,&morekeys,&status))
        fits_report_error(lferr, status);
//    else
        // FIXME fprintf(lferr,"AFTER  keysexist:%d morekeys:%d\n",keysexist,morekeys);
}




/*
 * Filename is <somename>.fits -> try to read it as fits file.
 */
int vlkb_dropdegen(const char * fitsfname)
{
	LOG_trace(__func__);

	fitsfile *fptr;
	int status=0;
	int rc=0;
	int hdupos;

	int iomode = READWRITE;

	LOG_STREAM << "fits_open_file" << endl;

	if (fits_open_file(&fptr, fitsfname, iomode, &status))
	{
		LOG_STREAM << "fitsfname: " << fitsfname << endl;
		LOG_STREAM << fitsfiles::cfitsio_errmsg(__FILE__,__LINE__,status) << endl;
		rc = 0;
		goto f_end;
	}
	fits_get_hdu_num(fptr, &hdupos);  /* Get the current HDU position */

	LOG_STREAM << "hdupos: " << to_string(hdupos) << endl;

	for (; !status; hdupos++)  /* Main loop through each HDU/extension */
	{
		LOG_STREAM << "hdupos: " << to_string(hdupos) << endl;

		// drop degenerate axis in current HDU
		dropdegen(fptr);

		// take next HDU
		fits_movrel_hdu(fptr, 1, NULL, &status);  /* try to move to next HDU */
	}

	if (status == END_OF_FILE){
		status = 0; // Reset after expected error in for
	} else {
		rc = -1;
	}

	fits_close_file(fptr, &status);

f_end:
	//printf("%s: rc = %d\n",__func__,rc);
	return rc;
}




