#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include <string>

#define BYTE unsigned char
using namespace std;

#define MAXLEN 5000

char buffer[MAXLEN];
int len;
unsigned char key[8],orderkey[8];
unsigned char decode[10000];
unsigned char dest[10000];

void OrderKey(BYTE *dest,BYTE *source)
{
  int step = source[5] % 7;
  int i=1;

  dest[0]=source[0];
  while (i < 7)
   dest[i] = source[(i++*step) % 7];
}

void XorCode(BYTE *pSorg,BYTE *pDest,BYTE *pKeyOrd,int len)
{
  int i,j=0;

	for(i=0;i<len;i++)
    {
      pDest[i]=pSorg[i]^pKeyOrd[j];
		  j++;
		  if(j==7)
        j=0;
	  }
}

int main(void)
{
  ifstream ifile ("log");
  
  if (!ifile.is_open())
    { 
      cout << "Error opening file"; 
      exit (1); 
    }
  else
    {
      int position = 0;

      ifile.getline(buffer,MAXLEN);
      
      int i=0;
      string temp(buffer),t;

      if (temp.size() > 1)
	{
	  while (position < temp.size())
	    {
	      t = temp.substr(position,2);
	      key[i++] = strtol(t.c_str(),NULL,16);
	      position+=2;
	    }
	}


      printf("\nKey is\n");
      for (int j=0; j < 8; j++)
	printf("%x ",key[j]);

      printf("\n");

      OrderKey(orderkey,key);

      ifile.getline(buffer,MAXLEN);

      i=0;

      while (!ifile.eof())
	{
	  position = 0;
	  ifile.getline(buffer,MAXLEN);
	  string temp(buffer),t;

	  while (position < temp.size())
	    {
	      t = temp.substr(position,2);
	      decode[i] = strtol(t.c_str(),NULL,16);
	      position+=2;
	      t = temp.substr(position,2);
	      decode[i+1] = strtol(t.c_str(),NULL,16);
	      position+=3; // skip space
	      i+=2;
	    }
	}

      printf("\n original buffer\n");
      
      for (int j=0; j < i-1; j++)
	printf("%x ",decode[j]);
      
      printf("\nbuffer size %x \n",i);
      
      printf("\n decoded buffer\n");
      
      XorCode(decode,dest,orderkey,i-1);

      for (int j=0; j < i-1; j++)
	printf("%02x ",dest[j]);

      printf("\n here it is\n");

 for (int j=0; j < i-1; j++)
        {
          if ((dest[j] >= 0x20) && (dest[j] < 0x7f))
            {
              printf("%c",dest[j]);
            }
          else
            {
              printf(".");
            }
        }


//      for (int j=0; j < i-1; j++)
//	printf("%c ",dest[j]);
      
      printf("\n here it is\n");

      ifile.close();
    }
  
    
  return 0;
}
