/*

File: sequence.c
Author: Neil Cafferkey
Copyright (C) 1999-2001 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 "sequence_protos.h"
#include "memory_protos.h"
#include <stdio.h>


/* Function: CreateSequence
 * ========================
 */

Sequence CreateSequence(ULONG length,UBYTE *data)
{
   Sequence sequence=Malloc(sizeof(Sequence_imp));

   sequence->length=length;
   sequence->data=data;

   return sequence;
}


/* Function: ReadSequence
 * ======================
 * Makes a sequence from the contents of a file.
 */

Sequence ReadSequence(TEXT *file_name)
{
   UBYTE *buffer;
   FILE *file;
   ULONG length;
   Sequence sequence;

   if((file=fopen(file_name,"rb"))==NULL)
   {
      NoMoreMem();
      printf("Couldn't open \"%s\" for reading. Exiting...\n",file_name);
      exit(20);
   }

   fseek(file,0,SEEK_END);
   length=ftell(file);
   rewind(file);

   buffer=Malloc(length*sizeof(UBYTE));

   fread(buffer,sizeof(UBYTE),length,file);
   fclose(file);

   sequence=CreateSequence(length,buffer);

   return sequence;
}


/* Function: GetSequenceLength
 * ===========================
 */

ULONG GetSequenceLength(Sequence sequence)
{
   return sequence->length;
}


/* Function: GetSequenceContents
 * =============================
 */

UBYTE *GetSequenceContents(Sequence sequence,ULONG offset)
{
   return sequence->data+offset;
}


/* Function: IsSubsequence
 * =======================
 */

BOOL IsSubsequence(Sequence sub_seq,UBYTE *main_data)
{
   ULONG i,length=GetSequenceLength(sub_seq);
   UBYTE *sub_data=sub_seq->data;

   for(i=0;(i<length)&&(*(sub_data++)==*(main_data++));i++);

   return (i==length);
}


/* Function: KillSequence
 * ======================
 */

VOID KillSequence(Sequence sequence)
{
   Free(sequence->data,sequence->length);
   Free(sequence,sizeof(Sequence_imp));

   return;
}


#ifndef NDEBUG

/* Function: ShowSequence
 * ======================
 */

VOID ShowSequence(Sequence sequence)
{
   ULONG i;

   for(i=0;i<sequence->length;i++)
      printf("%x",sequence->data[i]);
   printf("\n");

   return;
}

#endif

