// 
// File name: Pattern.cpp
//
// Discription: Описание методов класса Выборка
//
// Programmer: Vladimir P. Stasevich (SV)
//
// History: 
//    Created 24.02.2000 (SV)
//

#include <math.h>

#include "TPattern.h"

void TSolverLearnPattern::destroyPattern( void )
{
   if( patt ) 
   {
      delete [] patt;
      patt = NULL;
   }

   numb = 0;
}

int TSolverLearnPattern::loadPattern
(
   const char *fileName
)
{
   FILE     *fp;
   unsigned  numbElems;

   fp = fopen( fileName, "rt" );
      
   if( fp == NULL ) 
      return 1;
      
   fscanf( fp, "%u\n" , &numbElems );
   numb = numbElems;

   patt = new TSolverPatternElem[numbElems];

   for( int j = 0; j < numbElems; j++ )
   {
      int i[SOLVER_INPUTS_NUMB], o[SOLVER_OUTPUTS_NUMB];
      float i7;

      fscanf( 
         fp,
         "%d %d %d %d %d %d %d %f    %d %d %d %d %d %d %d %d\n",
         &i[0],
         &i[1],
         &i[2],
         &i[3],
         &i[4],
         &i[5],
         &i[6],
         &patt[j].i[7],

         &o[0],
         &o[1],
         &o[2],
         &o[3],
         &o[4],
         &o[5],
         &o[6],
         &o[7]
         );

      for( int i1 = 0; i1 < SOLVER_INPUTS_NUMB - 1; i1++ )
         patt[j].i[i1] = ((float)i[i1])/SOLVER_PATT_COEFF;

      patt[j].i[7] += 1.5;
      patt[j].i[7] /= 6;

      for( int o1 = 0; o1 < SOLVER_OUTPUTS_NUMB; o1++ )
         patt[j].o[o1] = o[o1];

      for( o1 = 0; o1 < SOLVER_OUTPUTS_NUMB; o1++ )
      {
         if( patt[j].o[o1] ) patt[j].o[o1] = 8.;
         else                patt[j].o[o1] = 0.;
      }

      for( o1 = 0; o1 < SOLVER_OUTPUTS_NUMB; o1++ )
         patt[j].o[o1] = patt[j].o[o1]/SOLVER_PATT_COEFF;
   }

   fclose( fp );
   return 0;
}

int TSolverLearnPattern::savePattern
(
   const char *fileName
)
{
   FILE     *fp;

   fp = fopen( fileName, "wt" );
      
   if( fp == NULL ) 
      return 1;
      
   fprintf( fp, "%u\n", getNumb() );

   for( int j = 0; j < getNumb(); j++ )
   {
      TSolverPatternElem* elem = get(j);

      int i[SOLVER_INPUTS_NUMB], o[SOLVER_OUTPUTS_NUMB];
      float i7;

      for( int o1 = 0; o1 < SOLVER_OUTPUTS_NUMB; o1++ )
      {
         float oF = elem->o[o1]*SOLVER_PATT_COEFF;

         if( oF > 4.5 ) o[o1] = 1;
         else           o[o1] = 0;
      }

      i7 = elem->i[7]*6;
      i7 -= 1.5;

      for( o1 = 0; o1 < SOLVER_INPUTS_NUMB - 1; o1++ )
      {
         i[o1] = floorf(elem->i[o1]*SOLVER_PATT_COEFF+0.5);
      }

      fprintf( 
         fp,
         "%d %d %d %d %d %d %d %+1.1f    %d %d %d %d %d %d %d %d\n",
         i[0],
         i[1],
         i[2],
         i[3],
         i[4],
         i[5],
         i[6],
         i7,

         o[0],
         o[1],
         o[2],
         o[3],
         o[4],
         o[5],
         o[6],
         o[7]
         );
   }

   fclose( fp );
   return 0;
}
