/*
 * Esercizi sulla ricorsione con le stringhe
 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

/* Indice del carattere piu' piccolo */
int ind_min(char *s){
	int i, min=0;
	for(i=0; s[i]!='\0'; i++)
		if (s[i]<s[min]) min=i;
	return min;
}

char *ind_min_rec(char *s, char *min){
    if (*s=='\0') return min;
    if (*s<*min) min=s;
    return ind_min_rec(&s[1],min);
}

void insert_in_order(char *s, char c){
	int p,i;
	for(p=0; s[p]<c && s[p]!='\0'; p++);
	for(i=strlen(s); i>=p; i--)
		s[i+1]=s[i];
	s[p]=c;
}


/* Ordinamenti di stringhe */
void sort_in_place(char *s){
	int i, tmp;
	if(s[0]=='\0') return;
	i=ind_min(s);
	tmp=s[0];	
	s[0]=s[i];
	s[i]=tmp;
	sort_in_place(&s[1]);
}

char *sort_copy(char *s){
	char *r=malloc(sizeof(char)*(strlen(s)+1));
	r[0]='\0';
	int i;
	for(i=0; s[i]!='\0'; i++){
		insert_in_order(r, s[i]);
		printf("%d: %s\n",i, r);
	}
	return r;
}

char *sort_copy_rec(char *s){
    char *tmp=NULL;
    char *res=NULL;
    if (*s=='\0') return strdup(s);
    tmp=sort_copy_rec(&s[1]);
    res=malloc(sizeof(char)*(strlen(tmp)+2);
    strcpy(res, tmp);
    free(tmp);
    insert_in_order(res, s[0]);
    return res;
}

/* Ricerca carattere su stringa ordinata */
int search_ord(char *s, char k, int l){
	if (l==1) 
		if (s[0]==k) return 1;
		else return 0;
	if (s[l/2+l%2]==k) return 1;
	else if(s[l/2+l%2]>k) return search_ord(s, k, l/2);
	else return search(&s[l/2+l%2+1], k, l/2-l%2-1);
}

/* Ricerca la sottostringa sub e conta il numero di occorrenze in s */
int search(char *s, char *sub){
	if(strlen(s)<strlen(sub)) return 0;
	if(strncmp(s,sub,strlen(sub))==0)
		return 1+search(&s[1],sub);
	else return search(&s[1],sub);
}

int strlen_r(char *s){
	if (s[0]=='\0') return 0;
	return 1+strlen_r(&s[1]);
}

int main(int argc, char **argv){
	if (argc>2) {
		printf("%s appare in %s %d volte\n", 
			argv[2], argv[1], 
			search(argv[1],argv[2])
		);
	} else if (argc>1) {
		printf("len(%s)=%d\n", argv[1], strlen(argv[1]));
		printf("len(%s)=%d\n", argv[1], strlen_r(argv[1]));
		printf("sorted=%s\n", sort_copy(argv[1]));
		sort_in_place(argv[1]);
		printf("sorted=%s\n",argv[1]); 
	}
}
