// Encode.cpp : Encoding function for datafiles.
//

#include "stdafx.h"
#include "stdlib.h"
#include "stdio.h"
#include "string.h"

#include "encode.h"

void createEncoderPattern
  (long   nSeed,        // seed
   char*  szCharSet,    // character set
   char*  szPattern)    // generated pattern
//
//  Creates a translation pattern for a set of characters.
//  szPattern must be at least as large as szCharSet.
//
{
  unsigned long ulIndexPattern = 0;
  srand (nSeed);
  while (true)
      {
        // Add a random char to the pattern
        long  nSelectedChar = rand() % strlen (szCharSet);
        if (szCharSet [nSelectedChar] != '~')
           {
             szPattern [ulIndexPattern] = szCharSet [nSelectedChar];
             ulIndexPattern++;
             szCharSet [nSelectedChar] = '~';
           }

        // Check if we are done
        bool  bFinished = true;
        for (unsigned long nIndexCharSet=0; (nIndexCharSet < strlen (szCharSet)); nIndexCharSet++)
            if (szCharSet [nIndexCharSet] != '~')
               {
                 bFinished = false;
                 break;
               }

        // Return if we are done
        if (bFinished)
           return;
      }
}

void encodeLine
  (bool   bEncode,            // flag: true to encode, false to decode
   char*  szSourceCharSet,    // source character set
   char*  szPatternCharSet,   // encoding pattern
   char*  szLine)             // line to encode/decode
//
//  Encodes/decodes a line of text using a source/pattern combination.
//  szSourceCharSet and szPatternCharSet must contain the same set of chars.
//  szTargetLine must be at least as large as 
//
{
  for (unsigned long ulIndex=0; (ulIndex < strlen (szLine)); ulIndex++)
    {
      char            ch = szLine [ulIndex];
      unsigned long   ulLocatedChar = 0;

      // Find translation of current char
      unsigned long   ulPatternLength = strlen (szPatternCharSet);
      for (ulLocatedChar=0; (ulLocatedChar < ulPatternLength); ulLocatedChar++)
          if (bEncode)
             {
               if (ch == szSourceCharSet [ulLocatedChar])
                  {
                    szLine [ulIndex] = szPatternCharSet [ulLocatedChar];
                    break;
                  }
             }
          else
             {
               if (ch == szPatternCharSet [ulLocatedChar])
                  {
                    szLine [ulIndex] = szSourceCharSet [ulLocatedChar];
                    break;
                  }
             }
    }
  return;
}
