#ifndef __COMMON_H
#define __COMMON_H

#include <stdio.h>

/**************************************************
 * Stale dotyczace wejscia/wyjscia
 */

#define MAXLINE 1024

#define EMPTYFORM '*'
#define INFIELD_SEP ':'
#define MAXAUX 16
#define FIELD_SEP " \t\n"


/***************************************************************/
/* problems with casing                                        */
/* sprawdzenie wielkosci liter                                 */
/* wartość zwracana:                                           */
/* 0 - wszystkie małe litery, 1 - pierwsza wielka, reszta male */
/* 2 - wszystkie wielkie, 3 - inne                             */
/***************************************************************/
inline int casing(char* s)
{
  int ret = isupper(*s) ? 1 : 0;
  while(*++s != '\0')
  {
    if(isupper(*s))
    {
      if(ret==1) ret=2;
      else if(ret==0) ret=3;
    }
    else
    {
      if(ret==2) ret=3;
    }
  }
  return ret;
}

// 
inline void tolowers(char* s, char* d)
{
  *d=tolower(*s);
  while(*s != '\0') * ++d = tolower(* ++s);
}


// przepisuje s do d
// nadajac wielkość liter zgodnie z wartością casing
// casing - wartość zwracana przez casing()
// jeśli casing==3 przepisuje bez zmian (za mało informacji)
inline void restorecasing(char *s, char *d, int casing)
{
  switch(casing)
  {
  case 0:
  case 3:
    *d=*s;
    while(*s != '\0') * ++d = * ++s;
    break;
  case 1:
    *d=toupper(*s);
    while(*s != '\0') * ++d = * ++s;
    break;
  case 2:
    *d=toupper(*s);
    while(*s != '\0') * ++d = toupper(* ++s);
    break;
  }
}


/**************************************************/
/*
parameters:
  -seg  - segment
  -name - field name
  +val  - field contents
return value:
  1 if specified field exists, 0 otherwise
*/

inline int getfield(char* seg, const char* pref, char* val)
{
  char* p=seg;

  while(isspace(*p)) ++p;
  
 pos:
  if(isdigit(*p) or *p=='*') while(!isspace(*p)) ++p; 
  else goto type;

  while(isspace(*p)) ++p;
  
 len:
  if(isdigit(*p) or *p=='*') while(!isspace(*p)) ++p; 
  else goto type;

  while(isspace(*p)) ++p;
  
 type:
  while(isspace(*p)) ++p; while(!isspace(*p)) ++p;

  while(isspace(*p)) ++p;

 form:
  while(isspace(*p)) ++p; while(!isspace(*p)) ++p;

 annotation:
  do p=strstr(p,pref); while(p!=NULL && *(p-1)!=' ' && *(p-1)!='\t');
  
  if(p==NULL) return 0;
  else
  {
    p+=strlen(pref);
    int len=strcspn(p,FIELD_SEP "\n\r\f\0");
    strncpy(val,p,len);
    val[len]='\0';
    return 1;
  }
}


/*
parameters:
  +seg - segment
  -pref - prefix of the new field
  -val  - contents of the new field
return value:
  1 - success, 0 - fail (limit on segment length exceeded)
*/
inline int addfield(char *seg, const char *pref, const char *val)
     // zalozenie, ze seg konczy sie znakiem \n
{
  if(strlen(seg)+strlen(pref)+strlen(val) >= MAXLINE) return 0; // bezpieczniej, ale wolniej

  int seglen=strlen(seg);
  sprintf(seg+(seglen-1)," %s%s\n",pref,val);
  return 1;
}


#endif
