/*__________________________________________________________________________

	strcut           strcut terminate string at position n
						
    Copyright (C) 2003 jan schacher

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
    
    initial build 20030511
    fixed end conditions 20040713
    
____________________________________________________________________________*/

#include "m_pd.h"
#include <string.h>
#define MIN(a,b) ((a)<(b)?(a):(b))


typedef struct strcut 		
{
	t_object		ob;		
	void 			*s_outlet;	
	long			s_numChar;
} t_strcut;

void *strcut_class;
void *strcut_new(t_symbol *s, long argc, t_atom *argv);
void strcut_free(t_strcut *x);
void strcut_float(t_strcut *x, float f);
void strcut_anything(t_strcut *x, t_symbol *s, long argc, t_atom *argv);

void strcut_setup(void)
{	
	strcut_class = class_new(gensym("strcut"), (t_newmethod)strcut_new, (t_method)strcut_free, sizeof(t_strcut), 0, A_GIMME, 0);
	class_addfloat(strcut_class, (t_method)strcut_float);
	class_addsymbol(strcut_class, (t_method)strcut_anything);
	post(".    strcut    .    jasch    .    "__DATE__" ",0);
}

void *strcut_new(t_symbol *s, long argc, t_atom *argv)
{
	short i;
	t_strcut	*x;
	x = (t_strcut *)pd_new(strcut_class);

	x->s_outlet = outlet_new(&x->ob, gensym("symbol"));	
	
	x->s_numChar = 1;
	for(i=0; i<argc; i++){
		if(argv[i].a_type == A_FLOAT){
			x->s_numChar = argv[i].a_w.w_float;
			// post("argument %ld is %f", i, argv[i].a_w.w_float);
		}else if(argv[i].a_type == A_SYMBOL){
			// post("argument %ld is %s", i, argv[i].a_w.w_symbol->s_name);
		}
	}
	return (x);									
}

void strcut_assist(t_strcut *x, void *b, long msg, long arg, char *dst)
{
	if(msg==1) 	
		switch(arg){
			case 0: strcpy(dst, "string in (symbol) cut pos (int)"); break;
			}
	else if(msg==2){ 				
		 strcpy(dst, "string out");	
 	}		
}

void strcut_anything(t_strcut *x, t_symbol *s, long argc, t_atom *argv)
{
	char	*ptr;
	char	local[4096];

	strcpy(local, s->s_name);
	local[MIN((long)strlen(local), x->s_numChar)] = 0;
	ptr = local;
	outlet_anything(x->s_outlet, gensym(ptr), 0, 0L);
}

void strcut_float(t_strcut *x, float f)
{
	x->s_numChar = (long)((f >= 0) ? f : 0);
}

void strcut_free(t_strcut *x)
{
		// notify_free((t_object *)x);
}