/*{{{  #includes*/
#ifdef CONFIG_H
#   include "config.h"
#endif

#include <sys/types.h>
#include <string.h>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>

#include <local/bool.h>

#define STRING_C

#include "origami.h"
/*}}}  */

/*{{{  strinsert*/
public void strinsert(unsigned char *src,unsigned char *dst)
{
  int slen, dlen;

  dlen = strlen((char *)dst);
  dst += dlen;
  if (dlen <= 0) {strcpy((char *)dst, (char *)src);return;}
  slen = strlen((char *)src);
  do {dst[slen] = *dst;--dst;} while (--dlen >= 0);
  dst++;
  while (--slen >= 0) *dst++ = *src++;
}
/*}}}  */
/*{{{  strpos2*/
public int strpos2(unsigned char *s,unsigned char *pat)
{ unsigned char *f=(unsigned char*)strstr((char*)s,(char*)pat);

  if (!f) return(-1);
  return(f-s);
}
/*}}}  */
/*{{{  strsub  strsub(x,off)=x+min(off,strlen(x))*/
public unsigned char *strsub(unsigned char *s,int off)
{
  while (--off>0 && *s) s++;
  return(s);
}
/*}}}  */
/*{{{  proc_replace*/
public int proc_replace(unsigned char *search, unsigned char *replace,
                        unsigned char *line,
                        int position, int length)
{
  int ls=strlen((char *)search),
      lr=strlen((char *)replace),
      ll=strlen((char *)line),
      space=length-ll,
      i;
  bool rep;
  unsigned char STR[LINELEN + 1];

  if (ll < position + ls - 1) return(0);
  rep = TRUE;
  for (i = 0; i < ls; i++)
    rep = (rep && line[position+i] == search[i]);
  if (rep)
    if ((space=space-lr+ls)>=0) {
      strcpy((char *)STR,(char *)replace);
      strcat((char *)STR,(char *)line+(position+ls));
      strcpy((char *)line+position, (char *)STR);
      return(1);
    } else
      return(-1);
  return(0);
}
/*}}}  */
