#include "../include/Endianness.h"
#include <iostream>

namespace environment {
namespace endianness {

/*
 * swapBytes -> change the endiannes
 * exemple for 16 and size_access = 4, [0123456789abcdef] -> [32107654ba98fedc]
 */
  char * swapBytes (char * string_src , uint32_t size_string, uint32_t size_access)
  {
    char string_tmp [size_string];
    
    if ( (size_access == 1) or
	 (size_access >  size_string))
      return string_src;
    
//     if (size_string % size_access != 0)
//       {
// 	std::cerr << "<swapBytes> : Size of string must be a multiple of size_access." << std::endl;
// 	exit(1);
//       }
    
    // size_access :
    // 1 -> bytes
    // 2 -> half
    // 4 -> word
    // 8 -> doubleword
    
    memcpy (string_tmp,string_src,size_string);
    
  // Loop to reorganize the string
    for (uint32_t i = 0 ; i < size_string; i += size_access)
      {
	switch (size_access)
	  {
	  case 2  : 
	    {
	      string_src[i+0] = string_tmp[i+1];
	      string_src[i+1] = string_tmp[i+0];
	      break;
	    }
	  case 4  :
	    {
	      string_src[i+0] = string_tmp[i+3];
	      string_src[i+1] = string_tmp[i+2];
	      string_src[i+2] = string_tmp[i+1];
	      string_src[i+3] = string_tmp[i+0];
	      break;
	    }
	  case 8  :
	    {
	      string_src[i+0] = string_tmp[i+7];
	      string_src[i+1] = string_tmp[i+6];
	      string_src[i+2] = string_tmp[i+5];
	      string_src[i+3] = string_tmp[i+4];
	      string_src[i+4] = string_tmp[i+3];
	      string_src[i+5] = string_tmp[i+2];
	      string_src[i+6] = string_tmp[i+1];
	      string_src[i+7] = string_tmp[i+0];
	      break;
	    }
	  default :  
	    {
	      std::cerr << "<swapBytes> : Illegal size of access (size_access = " << size_access << ")" << std::endl;
	      exit(1);
	      break;
	    }
	  }//end switch(size_access)
      }//end i
    
    return string_src;
  }

};
};
