/***************************************************************************
                          cencrypt.cpp  -  description
                             -------------------
    begin                : Sat Sep 29 2001
    copyright            : (C) 2001-2003 by Mathias Küster
    email                : mathen@users.berlios.de
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

#include "cencrypt.h"

CEncrypt::CEncrypt()
{
}

CEncrypt::~CEncrypt()
{
}

/** */
void CEncrypt::Encrypt( CString s, CString & d )
{
	int v;
	int i;
	unsigned char u,l,o;

	d.Empty();

	if ( s.Length() <= 3 )
	{
		return;
	}

	u = s.Data()[0];
	l = s.Data()[s.Length()-1];
	o = s.Data()[s.Length()-2];

	u = (char)(u ^ l ^ o ^ 0x05);

	v = ((u<<4)|(u>>4))&0xFF;

	Encode(v,d);

	for(i=1;i<s.Length();i++)
	{
		u = s.Data()[i];
		l = s.Data()[i-1];

		u = (char)(u^l);

		v = ((u<<4)|(u>>4))&0xFF;

		Encode(v,d);
	}
}

/** */
void CEncrypt::Encode( int c, CString & d )
{
	// convert direct connect numerics
	switch(c&0xFF)
	{
		case 126:
			d.Append("/%DCN126%/");
			break;
		case 124:
			d.Append("/%DCN124%/");
			break;
		case 96:
			d.Append("/%DCN096%/");
			break;
		case 36:
			d.Append("/%DCN036%/");
			break;
		case 5:
			d.Append("/%DCN005%/");
			break;
		case 0:
			d.Append("/%DCN000%/");
			break;
		default:
			d.Append((char)c);
			break;
	}
}

/** */
CString CEncrypt::Encode( CString s )
{
	long i;
	CString tmp;

	for(i=0;i<s.Length();i++)
	{
		Encode(s.Data()[i],tmp);
	}

	return tmp;
}

/** */
CString CEncrypt::Decode( CString tmp )
{
	long i;

	while( (i=tmp.Find("/%DCN124%/")) != -1 )
		tmp = tmp.Left(i) + CString(124) + tmp.Mid(i+10,tmp.Length()-i-10);
	while( (i=tmp.Find("/%DCN126%/")) != -1 )
		tmp = tmp.Left(i) + CString(126) + tmp.Mid(i+10,tmp.Length()-i-10);
	while( (i=tmp.Find("/%DCN036%/")) != -1 )
		tmp = tmp.Left(i) + CString(36) + tmp.Mid(i+10,tmp.Length()-i-10);
	while( (i=tmp.Find("/%DCN096%/")) != -1 )
		tmp = tmp.Left(i) + CString(96) + tmp.Mid(i+10,tmp.Length()-i-10);
	while( (i=tmp.Find("/%DCN005%/")) != -1 )
		tmp = tmp.Left(i) + CString(5) + tmp.Mid(i+10,tmp.Length()-i-10);

	return tmp;
}
