// Copyright 1994, 1995 by Jon Dart

#include "stdafx.h"
#include "epdrec.h"
#include "chessio.h"
#include "strpair.h"

EPD_Record::EPD_Record()
{
}

EPD_Record::~EPD_Record()
{
   const int n = getSize();
   for (int i = 0; i < n; i++)
   {
      StringPair *p = (StringPair*)cmds[i];
      delete p;
   }
}

BOOL EPD_Record::has_val(LPCSTR key) const
{
   const int n = getSize();
   for (int i = 0; i < n; i++)
   {
      StringPair *cmd = (StringPair*)cmds[i];
      if (strcmp(cmd->tag,key)==0)
      {
          return TRUE;
      }
   }
   return FALSE;
}

BOOL EPD_Record::get_val(LPCSTR key, CString &val) const
{
   const int n = getSize();
   for (int i = 0; i < n; i++)
   {
      StringPair *cmd = (StringPair*)cmds[i];
      if (strcmp(cmd->tag,key)==0)
      {
          val = cmd->val;
          return TRUE;
      }
   }
   return FALSE;
}

void EPD_Record::getData(int i,CString &key,CString &val) const
{
    StringPair *h = (StringPair*)cmds[i];
    val = h->val;
    key = h->tag;
}

void EPD_Record::add(LPCSTR key, LPCSTR val)
{
   const int n = getSize();
   for (int i = 0; i < n; i++)
   {
      StringPair *cmd = (StringPair*)cmds[i];
      if (strcmp(cmd->tag,key)==0)
      {
          StringPair* tmp = (StringPair*)cmds[i];
          cmds.RemoveAt(i);
          delete tmp;
          break;
      }
   }
   StringPair *newEntry = new StringPair(key,val);
   cmds.Add(newEntry);
}

void EPD_Record::sort()
{
    // uses Shell sort

    int gap, i, j, tj;
    StringPair *t;

    const int n = cmds.GetSize();
    gap = n / 2;
    while (gap)
    {
        for (i = gap; i < n; i++)
        {
            j = i - gap;
            while (j >= 0)
            {
                tj = j + gap;
                StringPair *pj = (StringPair*)cmds[j];
                StringPair *ptj = (StringPair*)cmds[tj];
                if (strcmp(pj->tag,ptj->tag) > 0)
                {
                    t = pj;
                    cmds.SetAt(j,ptj);
                    cmds.SetAt(tj,t);
                } else
                    break;
                if (j >= gap)
                    j -= gap;
                else
                    break;
            }
        }
        gap /= 2;
    }
}