# include <ohana.h>
# include <gfitsio.h>

/*********************** fits header field ****************************/
char *gfits_header_field (Header *header, char *field, int N) {

  char *buf;
  int i, Nwant, Nfound;
  char keyword[10];

  /* create a blank-padded keyword with exactly 8 characters */
  strcpy (keyword, field);
  for (i = strlen(field); i < 8; i++) keyword[i] = ' ';
  keyword[8] = 0;

  buf = header[0].buffer;

  if (N > 0) {
    /* find the Nth entry */
    Nfound = 0;
    for (i = 0; i < header[0].size; i+= FT_LINE_LENGTH, buf += FT_LINE_LENGTH) {
      if (!strncmp (keyword, buf, 8)) {
	Nfound ++;
	if (Nfound == N) return (buf);
      }
    }
  }

  if (N < 0) {
    /* count the entries */
    Nfound = 0;
    for (i = 0; i < header[0].size; i+= FT_LINE_LENGTH, buf += FT_LINE_LENGTH) {
      if (!strncmp (keyword, buf, 8)) {
	Nfound ++;
      }
    }

    Nwant = Nfound + N + 1;
    buf = header[0].buffer;

    /* find the Nwant entry */
    Nfound = 0;
    for (i = 0; i < header[0].size; i+= FT_LINE_LENGTH, buf += FT_LINE_LENGTH) {
      if (!strncmp (keyword, buf, 8)) {
	Nfound ++;
	if (Nwant == Nfound) return (buf);
      }
    }

  }

  return ((char *) NULL);

}

/* 

   find the Nth entry of this keyword.
   if N < 0, find the last - N - 1 word (ie, -1 = last)

*/
