/******************************************************************************

  This file is part of the:

  TCEditor class by SET, copyright (c) 1996.

    This files can be used by Robert Hhne for your RHIDE, any other use
  needs the permission of the author.

  E-Mail: salvador@inti.edu.ar
  
  Telephone: (+541) 759-0013
  
  Postal Address:
  Salvador E. Tropea
  Curapalige 2124
  (1678) Caseros - 3 de Febrero
  Prov: Buenos Aires
  Argentina

******************************************************************************/

// That's the first include because is used to configure the editor.
#include "ceditint.h"

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "ceditor.h"

#define MaxSection 7

static unsigned char *kbSections[MaxSection] =
{
 kbFunNormal,
 kbFunShift,
 kbFunCtrl,
 kbFunShiftCtrl,
 kbFunCtrlQNorm,
 kbFunCtrlKNorm,
 kbFunCtrlKShift
};

static char Error[80];

char *LoadKeyForTCEditorError(void)
{
 return Error;
}

static int EmptyLine(char *s)
{
 for (; *s; s++)
     if (*s!='\n' && *s!='\t' && *s!='\r' && *s!=' ') return 0;
 return 1;
}

#define GenError(a) \
{\
 sprintf(Error,"%s, line %d, file \"%s\", section %d\n",a,line,file,section);\
 fclose(f);\
 return 1;\
}

int LoadKeysForTCEditor(char *file)
{
 FILE *f;
 char b[256];
 int section=0;
 unsigned char *k=kbSections[0];
 int scan,command,line=0;

 if ((f=fopen(file,"rt"))==NULL)
   {
    sprintf(Error,_("Can't open %s\n"),file);
    return -1;
   }

 fgets(b,250,f);
 while (!feof(f))
   {
    line++;
    if (b[0]!='\n' && b[0]!='\r' && b[0]!='#' && b[0] && !EmptyLine(b))
      {
       if (b[0]=='[')
         {
          char *s=strchr(b,']');
          if (s==NULL)
             GenError(_("[ without ]"));
          s[0]=0;
          section=atoi(b+1);
          if (section<1 || section>MaxSection)
             GenError(_("Section out of range"));
          k=kbSections[section-1];
         }
       else
         {
          char *s=strchr(b,'=');
          if (s==NULL)
             GenError(_("Missing ="));
          s[0]=0;
          scan=atoi(b);
          if (scan<1 || scan>127)
             GenError(_("Scan code out of range"));
          command=atoi(s+1);
          if (command<0 || command>255)
             GenError(_("Command out of range"));
          k[scan]=command;
         }
      }
    fgets(b,250,f);
   }
 fclose(f);
 return 0;
}