/******************************************************************************
 * program:     cp-lib							      *
 * function:    support file for codepage based character conversion          *
 * modul:       cptran.cc 						      *
 * description: This file should be linked with final code together with trn  *
 *              output files from cpbldr code.				      *
 ******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <stringa.h>

#if defined(__BORLANDC__) && !defined(__WIN32__)
 #include "cp_lib/cptran.h"
#else
 #include "cptran.h"
#endif


CpTranslator *CpTranslator::First=NULL;
CpTranslator Dummy("dummy");

CpTranslator::CpTranslator(const char *name)
{
 Name = name;

 Next = First;
 Previous = NULL;
 First = this;
 if(Next!=NULL) Next->Previous=this;
}


CpTranslator::~CpTranslator(void)
{
 if(First==this)
	{
	First=Next;
	if(Next!=NULL) Next->Previous=NULL;
	return;
	}
 if(Next!=NULL) Next->Previous=Previous;
 if(Previous==NULL) return; //Error
 Previous->Next=Next;
}

//---------------

WCpTranslator::WCpTranslator(const char *name, uint16_t number, const uint16_t *trn): CpTranslator(name)
{
 Number=number;
 Trn=trn;
}


BCpTranslator::BCpTranslator(const char *name, uint16_t number, const uint8_t *trn): CpTranslator(name)
{
 Number = number;
 Trn = trn;
}


WSparseCpTranslator::WSparseCpTranslator(const char *name, uint8_t banks, const uint16_t *const*trn_bank): CpTranslator(name)
{
 Banks = banks;
 Trn_bank = trn_bank;
}


uint16_t WSparseCpTranslator::operator[](const uint16_t n) const
{
uint8_t b=n>>8;
 if(b>=Banks) return(0);
 if(Trn_bank[b]==NULL) return(0);
 return(Trn_bank[b][n & 0xFF]);
}


BSparseCpTranslator::BSparseCpTranslator(const char *name, uint8_t banks, const uint8_t *const*trn_bank): CpTranslator(name)
{
 Banks = banks;
 Trn_bank = trn_bank;
}


uint16_t BSparseCpTranslator::operator[](const uint16_t n) const
{
uint8_t b = n>>8;
 if(b>=Banks) return(0);
 if(Trn_bank[b]==NULL) return(0);
 return(Trn_bank[b][n & 0xFF]);
}


//---------------

CpTranslator *GetTranslator(const char *Name)
{
CpTranslator *Ptrn;

Ptrn = CpTranslator::First;
if(Name!=NULL)
  while(Ptrn!=NULL)
	{
	if(!StrCmp(Name,Ptrn->Name)) return(Ptrn);
	Ptrn=Ptrn->Next;
	}
return(&Dummy);
}


#if defined(__BORLANDC__) && !defined(__WIN32__)
  #include "cp_lib/out_dir/trn.trn"
#else
  #include "out_dir/trn.trn"
#endif




//The main function for testing purpose only.
#if 0
void main(void)
{
CpTranslator *x;

x=GetTranslator("Dummy");
x=GetTranslator("wp6TOwp5");

}
#endif
