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

/*
  Every program which uses the CFITSIO interface must include the
  the fitsio.h header file.  This contains the prototypes for all
  the routines and defines the error status values and other symbolic
  constants used in the interface.  
*/
#include "fitsio.h"
int main( int argc, char *argv[]);
void modifyheader( char *hdunum, char *keyname, char *value, char *comment );


 fitsfile *fptr;       /* pointer to the FITS file, defined in fitsio.h */

 int status=0, nkeys, keypos, hdutype, ii, jj;
 char filename[80];     /* name of existing FITS file   */
 char card[FLEN_CARD];   /* standard string lengths defined in fitsioc.h */




int main(int argc, char *argv[])
{
/*************************************************************************
   This is a simple main program that calls the following routines:

   
    readheader    - read and print the header keywords in every extension
   

**************************************************************************/
  int i ;

  if(argc != 6)
    {
       printf("report_error_status:102\n") ;
       exit(0) ;
     } 
 
 
  strcpy(filename, argv[1]) ;
  fits_open_file(&fptr, filename, READWRITE, &status) ;
  if(status)
   {
      printf("1.report_error_status:%d\n", status) ;
      exit(0) ; 
   }
   modifyheader(argv[2], argv[3], argv[4], argv[5]);     
   fits_close_file(fptr, &status) ;
   if(status)
   {
        printf("2.report_error_status:%d\n", status) ;
        exit(0) ; 
   }  
  
    printf("\n\n");
    return(0);
}

void modifyheader ( char *hdunum, char *keyname, char *value, char *comment )
{
  char card[80] ;
  int i ; 
  ii = (int)atoi(hdunum) ;
  

  /*Replace the ampersands with spaces. In jsp, spaces were replaced by ampersand to tackle the command line problem*/
  i=0 ;
  while(keyname[i] != '\0')
    {
      if(keyname[i] == '&')
	keyname[i] = (char)32 ; 
      i++ ; 
    } 

   i=0; 
   while(value[i] != '\0')
    {
      if(value[i] == '&')
	value[i] = (char)32 ; 
      i++ ; 
    } 

    i=0; 
    while(comment[i] != '\0')
    {
      if(comment[i] == '&')
        comment[i] = (char)32 ; 
      i++ ; 
    } 

  if( strstr(keyname, "HISTORY") == 0) 
    {
      strcpy(card, keyname) ;
      strcat(card , " = ") ;
      strcat(card, value) ; 
      strcat(card , " / ") ;
      strcat(card, comment) ;
    }
  else
    {
      strcpy(card, keyname) ;
      strcat(card , " = ") ;
      strcat(card, value) ; 
      strcat(card , " / ") ;
      strcat(card, comment) ;

    } 
  printf("\n%s", card) ;
    /* attempt to move to next HDU, until we get an EOF error */
    if ( !(fits_movabs_hdu(fptr, ii, &hdutype, &status))) 
    {
      fits_update_card(fptr, keyname, card, &status) ;
      if(status)
       {
          printf("3.report_error_status:%d\n", status) ;
          exit(0) ;
       }
    }
    else
      {
         printf("4.report_error_status:%d\n", status) ;
         exit(0) ; 
      }
    return;
}

