/*

File: index_record.c
Author: Neil Cafferkey
Copyright (C) 2000 Neil Cafferkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA.

*/

#include "viewer.h"
#include <exec/memory.h>

#include "index_record_protos.h"
#include "reference_protos.h"
#include "general_protos.h"
#include <clib/exec_protos.h>


/* Function: CreateIndexRecord
 * ===========================
 * Creates an index record.
 */

IndexRecord CreateIndexRecord(UBYTE *data)
{
   IndexRecord index_rec;
   BOOL success=TRUE;
   UBYTE *p;
   UWORD i;
   Reference ref;

   index_rec=AllocMem(sizeof(IndexRecord_imp),MEMF_CLEAR|MEMF_PUBLIC);

   if(index_rec)
   {
      index_rec->data_length=GetLittleEndianUWord(data);
      index_rec->ref_count=*(data+5);

      NewList((struct List *)&index_rec->ref_list);

      index_rec->data=AllocMem(index_rec->data_length,MEMF_PUBLIC);

      if(index_rec->data)
      {

         /* Copy record data and store parameters */

         CopyMem(data,index_rec->data,index_rec->data_length);

         p=index_rec->data+10;
         index_rec->keywords=p;
         p+=strlen(p)+1;
         index_rec->title=p;
         index_rec->node.ln_Name=p;
         p+=strlen(p)+1;

         /* Create references from raw data */

         for(i=0;i<index_rec->ref_count;i++)
         {
            ref=CreateReference(p);
            if(ref!=NULL)
               AddTail((struct List *)&index_rec->ref_list,&ref->node);
            else
               success=FALSE;
            p+=10;
            while(*(p++)!='\0');
         }

      }
      else
      {
         ReportError(NULL,ERROR_REPORT_MEM,NULL,0);
         success=FALSE;
      }

      if(!success)
      {
         KillIndexRecord(index_rec);
         index_rec=NULL;
      }
   }
   else
   {
      ReportError(NULL,ERROR_REPORT_MEM,NULL,0);
   }

/*printf("index_rec->title=%s\n",index_rec->title);*/
   return index_rec;
}



/* Function: KillIndexRecord
 * =========================
 * Destroys an index record.
 */

VOID KillIndexRecord(IndexRecord index_rec)
{
   Reference ref;

   while(ref=(Reference)RemHead((struct List *)&index_rec->ref_list))
      KillReference(ref);

   if(index_rec->data)
      FreeMem(index_rec->data,index_rec->data_length);

   FreeMem(index_rec,sizeof(IndexRecord_imp));

   return;
}



