/*****************************************************************
* unit:    doublelists             release 0.3                   *
* purpose: general manipulation with array of couples of strings *
******************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#include<dbllist.h>
#include <std_str.h>


#ifndef ERROR_HANDLER
  #define RaiseError(ErrNo,Instance)	{}; 
#else
  void RaiseError(int ErrNo,void *Instance);
#endif


/*This method adds two strings into one double list record*/
void doublelist::Add(const char *str1,const char *str2)
{
char*str;
int SLen1,SLen2;

 if(str1==NULL) {SLen1=0;str1="";}
	  else SLen1=strlen(str1);
 if(str2==NULL) {SLen2=0;str2="";}
	  else SLen2=strlen(str2)+0;

 if( (str=(char*)malloc(SLen1+SLen2+2))==NULL)
	{
	RaiseError(ListsId|No_Memory,this);	//Memory Exhausted
	return;
	}
 memmove(str,str1,SLen1+1);
 memmove(str+SLen1+1,str2,SLen2+1);
 if(flipped) str[SLen1]=1;
 MoveSTR(*this,str);
}


char *doublelist::Member(const int i,const int j)
{
char *str;

str=(*this)[i];
if(str==NULL) return(str);

switch(j)
   {
   case 0:return(str);
   case 1:if(flipped)
		{
		str=strstr(str,"\1");
		}
	   else {
		str+=strlen(str);
		}
	   if(str!=NULL) str++;
	   return(str);
   default:return(NULL);
   }
}


void doublelist::Flip(int FlipMode)
{
int i;
char *s;
  if(FlipMode==flipped) return;
  if(flipped)
    {
    for(i=0;i<length();i++)
      {
      s=(*this)[i];
      if(s!=NULL)
        {
        s=strchr(s,1);
        if(s!=NULL) *s=0;
        }
      }
    flipped=0;
    }
  else
    {
    for(i=0;i<length();i++)
      {
      s=(*this)[i];
      if(s!=NULL)
        {
        s+=strlen(s);
        if(*s==0) *s=1;
        }
      }
    flipped=1;
    }
}


doublelist::doublelist(const doublelist &dl): flipped(0), list()
{
  *this=dl;
}


doublelist &doublelist::operator=(const doublelist &dl)
{
char *s;
char **cpstr1, **cpstr2;
int i, len;

  erase();
  
  flipped=dl.flipped;
  
  if( (cpstr1=pstr=(char **)calloc(sizeof(char *),dl.number))==NULL)
	{
	numalloc=number=0;
	RaiseError(ListsId|No_Memory,this);	//Memory Exhausted
	return(*this);
	}
  number=numalloc=dl.number;
  cpstr2=dl.pstr;
  for(i=0;i<dl.number;i++)
	{
	if(flipped)  // stringA\1stringB
	    *cpstr1++ = StrDup(*cpstr2++);
	else	     // stringA\0stringB
	    {
	    s=dl[i];
	    if(s==NULL)
	      *cpstr1++ = NULL;
	    else
              {
	      len=strlen(s)+1;
	      len+=strlen(s+len) + 1;
	      *cpstr1 = (char *)malloc(len);
	      memcpy(*cpstr1, s, len);
	      cpstr1++;
              }
	     
	    }
	}
  

return(*this);
}


#if 0
void main(void)
{
doublelist ll;

cout<<ll;

ll.Add("Ahoj","Svete");
ll.Add("Abbb","Ssss");
ll.Add("Abream","Abraham");

printf("\n[%s %s]\n",ll.Member(0,0),ll.Member(0,1));

cout<<ll;

}
#endif
