// fgdyymmdd.cc

#include "fgdyymmddcomp.h"

#ifndef _FGSTRING_H
#include "fgstring.h"
#endif

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

FGDateYYMMDDComponent::FGDateYYMMDDComponent()
{
}

FGDateYYMMDDComponent::~FGDateYYMMDDComponent()
{
}

bool
FGDateYYMMDDComponent::MatchAndRankComponent(FGString& fnameRemainder,
                                             int* pMatchVal) const
{
  // Initialize to be safe
  *pMatchVal = -1;

  // Need 6 characters!
  if (fnameRemainder.GetLength() < 6) {
    return false;
  }

  FGString dateBit = fnameRemainder.Left(6);

  // Must be all digits
  if (!isdigit(dateBit[0]) || !isdigit(dateBit[1]) ||
      !isdigit(dateBit[2]) || !isdigit(dateBit[3]) ||
      !isdigit(dateBit[4]) || !isdigit(dateBit[5])) {
    return false;
  }

  // OK so its all digits
  // From here it will always be a match, we don't validate the month/day
  // values are valid (e.g. 17th Month of the year?)

  FGString yearStr = dateBit.Left(2);
  int year = atoi(yearStr);
  // Year 00 (2000) must have greater value than, e.g., 99 (1999)
  if (year < 50) {
    year += 50;
  } else {
    year -= 50;
  }

  // Build the final value string
  char yearBuf[3];
  sprintf(yearBuf, "%d", year);
  FGString theVal(yearBuf);
  theVal += dateBit[2];
  theVal += dateBit[3];
  theVal += dateBit[4];
  theVal += dateBit[5];

  *pMatchVal = atoi(theVal);

  // Consume the 6 digits we matched
  int charsLeft = fnameRemainder.GetLength() - 6;
  FGString bitLeft = fnameRemainder.Right(charsLeft);

  fnameRemainder = bitLeft;

  return true;
}
