#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <regex.h>
#include <ctype.h>

int trim_string_by_lines(char *instr, char *outstr, int lines) {
  /* space must be allocated for outstr */
  int i, good;
  char *ptr, *ptr2;

  good=0;
  ptr2=instr;
  for (i=0; i<lines; i++) {
    ptr=strchr(ptr2, '\n');
    if (!ptr) {
      good=1;
      break;
    }
    ptr2=ptr+1;
  }

  strcpy(outstr, instr);

  if (!good) {
    outstr[ptr2-instr]='\0';
    return(1);
  }
  return(0);
}

void replace_string_sections(char *in, regmatch_t pmatch[], char *out, char *newstr) {
  /* What we do here is replace all the substituion sections of the
   regex with "newstr".  The way we'll do it is to set up a mask of
   the characters in instr.  A 1 in the mask means to carry the
   character through, a 0 means it shouldn't be carried through.  Then
   we'll create the output string by replacing contiguous sections of
   0's with "newstr" */
  int len, i, j, outptr, lock, newstrlen;
  char *mask;

  newstrlen=strlen(newstr);
  
  /* mask */
  len=strlen(in);
  mask=malloc((sizeof(int)*len)+20);
  /* initialize everything to OK (1) */
  for (i=0; i<len; i++) {
    mask[i]='1';
  }
  /* set substitutions to not OK (0) */
  for (i=1; i<15; i++) { /* skip 0 */
    if ((pmatch[i].rm_so != -1) && (pmatch[i].rm_eo != -1)) {
      for (j=pmatch[i].rm_so; j<pmatch[i].rm_eo; j++) {
	mask[j]='0';
      }
    }
  }

  /* create the output string, i.e. do the newchar */
  outptr=0;
  for (i=0; i<len; i++) {
    if (mask[i] == '1') {
      out[outptr]=in[i];
      outptr++;
      lock=0;
    } else {
      if (lock!=1) {
	for (j=0; j<newstrlen; j++) {
	  out[outptr+j]=newstr[j];
	}
	outptr+=newstrlen;
      }
      lock=1;
    }
  }
  out[outptr]='\0';

  free(mask);
  return;
}


char **argstring_to_argv(char *in, int *outargc) {
  char **out;
  int i, len, ao, trail, argc;
  char *nextarg;
  
  argc=0;
  trail=0;
  ao=0;
  nextarg=malloc(200); /* eh */
  len=strlen(in);
  out=malloc(len+30); /* eh */
  
  for (i=0; i<len; i++) {
    if (!isspace((int) in[i])) {
      nextarg[ao]=in[i];
      ao++;
      trail=1;
    } else {
      if (trail==1) {
	nextarg[ao]='\0';
	ao=0;
	trail=0;
	out[argc]=strdup(nextarg);
	argc++;
	nextarg[0]='\0'; /* just to be safe */
      }
    }
  }
  if (trail==1) {
    nextarg[ao]='\0';
    out[argc]=strdup(nextarg);
    argc++;
  }
  free(nextarg);

  *outargc=argc;
  return(out);
}
