Browse Source

initial commit

richarddobson 3 years ago
parent
commit
b109931350

+ 194 - 0
dev/standnew/CMakeLists.txt

@@ -0,0 +1,194 @@
+if(APPLE)
+  set(CMAKE_C_FLAGS "-O2 -Wall -mmacosx-version-min=10.8 -Dunix")
+else()
+  if(MINGW)
+    set(CMAKE_C_FLAGS "-O2 -Wall -DWIN32")
+  else()
+    set(CMAKE_C_FLAGS "-O2 -Wall -Dlinux -Dunix")
+  endif()
+endif()
+#RWD only need this for APPLE?
+link_directories (/usr/local/lib)
+find_library(AAIOLIB NAMES libaaio.a)
+
+link_directories(../cdp2k ../sfsys)
+
+include_directories(../../include)
+
+add_executable(asciiget asciiget.c)
+target_link_libraries(asciiget ${EXTRA_LIBRARIES})
+
+my_install(asciiget)
+
+add_executable(caltrain caltrain.c)
+target_link_libraries(caltrain  cdp2k sfsys ${EXTRA_LIBRARIES})
+
+my_install(caltrain)
+
+
+add_executable(clicknew clicknew.c)
+target_link_libraries(clicknew  cdp2k sfsys ${EXTRA_LIBRARIES})
+
+my_install(clicknew)
+
+
+add_executable(clip clip.c)
+target_link_libraries(clip  cdp2k sfsys ${EXTRA_LIBRARIES})
+
+my_install(clip)
+
+add_executable(convert_to_midi convert_to_midi.c)
+target_link_libraries(convert_to_midi ${EXTRA_LIBRARIES})
+
+my_install(convert_to_midi)
+
+add_executable(distcut distcut.c)
+target_link_libraries(distcut  cdp2k sfsys ${EXTRA_LIBRARIES})
+
+my_install(distcut)
+
+add_executable(distmark distmark.c)
+target_link_libraries(distmark  cdp2k sfsys ${EXTRA_LIBRARIES})
+
+my_install(distmark)
+
+add_executable(distmore distmore.c)
+target_link_libraries(distmore  cdp2k sfsys ${EXTRA_LIBRARIES})
+
+my_install(distmore)
+
+add_executable(distrep distrep.c)
+target_link_libraries(distrep  cdp2k sfsys ${EXTRA_LIBRARIES})
+
+my_install(distrep)
+
+add_executable(distshift distshift.c)
+target_link_libraries(distshift  cdp2k sfsys ${EXTRA_LIBRARIES})
+
+my_install(distshift)
+
+# OUT
+# add_executable(distwarp distwarp.c)
+# target_link_libraries(distwarp  cdp2k sfsys ${EXTRA_LIBRARIES})
+# my_install(distwarp)
+
+add_executable(envcut envcut.c)
+target_link_libraries(envcut  cdp2k sfsys ${EXTRA_LIBRARIES})
+
+my_install(envcut)
+
+# add_executable(envnu_other envnu_other.c)
+# target_link_libraries(envnu_other  cdp2k sfsys ${EXTRA_LIBRARIES})
+# my_install(envnu_other)
+
+add_executable(envspeak envspeak.c)
+target_link_libraries(envspeak cdp2k sfsys ${EXTRA_LIBRARIES})
+
+my_install(envspeak)
+
+#waiting for code fix from TW
+#add_executable(extspeak extspeak.c)
+#target_link_libraries(extspeak cdp2k sfsys ${AAIOLIB} ${EXTRA_LIBRARIES})
+#my_install(extspeak)
+
+add_executable(fractal fractal.c)
+target_link_libraries(fractal cdp2k sfsys ${EXTRA_LIBRARIES})
+
+my_install(fractal)
+
+# OUT
+#add_executable(fturanal fturanal.c)
+#target_link_libraries(fturanal cdp2k sfsys ${EXTRA_LIBRARIES})
+#my_install(fturanal)
+
+# headview.c ?
+
+add_executable(hover2 hover2.c)
+target_link_libraries(hover2 cdp2k sfsys ${EXTRA_LIBRARIES})
+
+my_install(hover2)
+
+# OUT (too many problems, undeclared variables)
+# add_executable(integrate integrate.c)
+# target_link_libraries(integrate ${EXTRA_LIBRARIES})
+# my_install(integrate)
+
+add_executable(onset onset.c)
+target_link_libraries(onset cdp2k sfsys ${EXTRA_LIBRARIES})
+
+my_install(onset)
+
+add_executable(pairex pairex.c)
+target_link_libraries(pairex cdp2k sfsys ${EXTRA_LIBRARIES})
+
+my_install(pairex)
+
+add_executable(partition partition.c)
+target_link_libraries(partition cdp2k sfsys ${EXTRA_LIBRARIES})
+
+my_install(partition)
+
+add_executable(phasor phasor.c)
+target_link_libraries(phasor cdp2k sfsys ${EXTRA_LIBRARIES})
+
+my_install(phasor)
+
+add_executable(quirk quirk.c)
+target_link_libraries(quirk cdp2k sfsys ${EXTRA_LIBRARIES})
+
+my_install(quirk)
+
+add_executable(repair repair.c)
+target_link_libraries(repair cdp2k sfsys ${EXTRA_LIBRARIES})
+
+my_install(repair)
+
+#add_executable(rotate rotate.c)
+#target_link_libraries(rotate ${EXTRA_LIBRARIES})
+#my_install(rotate)
+
+# scales.c ignore: just textual exploratory comments
+
+add_executable(specenv specenv.c)
+target_link_libraries(specenv cdp2k sfsys ${EXTRA_LIBRARIES})
+
+my_install(specenv)
+
+add_executable(speculate speculation.c)
+target_link_libraries(speculate cdp2k sfsys ${EXTRA_LIBRARIES})
+
+my_install(speculate)
+
+add_executable(spike spike.c)
+target_link_libraries(spike cdp2k sfsys ${EXTRA_LIBRARIES})
+
+my_install(spike)
+
+# OUT (ID 'SUPERLOOP' not found)
+# add_executable(superloop superloop.c)
+# target_link_libraries(superloop cdp2k sfsys ${EXTRA_LIBRARIES})
+# my_install(superloop)
+
+add_executable(suppress suppress.c)
+target_link_libraries(suppress cdp2k sfsys ${EXTRA_LIBRARIES})
+
+my_install(suppress)
+
+# excluded by TW (standalone.h)
+# add_executable(toptail toptail.c)
+# target_link_libraries(toptail cdp2k sfsys ${EXTRA_LIBRARIES})
+# my_install(toptail)
+
+add_executable(tostereo tostereo.c)
+target_link_libraries(tostereo cdp2k sfsys ${EXTRA_LIBRARIES})
+
+my_install(tostereo)
+
+add_executable(matrix unitary_matrix.c)
+target_link_libraries(matrix cdp2k sfsys ${EXTRA_LIBRARIES})
+
+my_install(matrix)
+
+
+
+

+ 25 - 0
dev/standnew/asciiget.c

@@ -0,0 +1,25 @@
+#include <stdio.h>
+#include <stdlib.h>
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	FILE *fp;
+	int c;
+	if(argc != 2) {
+		fprintf(stderr,"USAGE: getascii filename: where file is an ascii textfile\n");
+		return 0;
+	}
+	if((fp = fopen(argv[1],"r"))==NULL) {
+		fprintf(stderr,"Cannot open file %s for output.\n",argv[1]);
+		return 0;
+	}
+	fseek(fp,0,0);
+	do {
+		c = fgetc(fp);
+		fprintf(stderr,"%c %d\t",c,c);
+	} while(c != EOF);
+	fclose(fp);
+	return 1;
+}

+ 1194 - 0
dev/standnew/caltrain.c

@@ -0,0 +1,1194 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <tkglobals.h>
+#include <pnames.h>
+#include <filetype.h>
+#include <processno.h>
+#include <modeno.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <math.h>
+#include <mixxcon.h>
+#include <osbind.h>
+#include <standalone.h>
+#include <speccon.h>
+#include <ctype.h>
+#include <sfsys.h>
+#include <string.h>
+#include <srates.h>
+
+#ifdef unix
+#define round lround
+#endif
+
+char errstr[2400];
+
+int anal_infiles = 1;
+int	sloom = 0;
+int sloombatch = 0;
+
+#define	CALIBUF		(0)
+#define	BLURBUF		(1)
+#define	BLURNRM		(2)
+#define	CALOBUF		(3)
+#define	OBUFEND		(4)
+
+const char* cdp_version = "7.0.0";
+
+/* CDP LIBRARY FUNCTIONS TRANSFERRED HERE */
+
+static int 	set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist);
+static int  set_vflgs(aplptr ap,char *optflags,int optcnt,char *optlist,
+				char *varflags,int vflagcnt, int vparamcnt,char *varlist);
+static int 	setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int	initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int	mark_parameter_types(dataptr dz,aplptr ap);
+static int  establish_application(dataptr dz);
+static int  application_init(dataptr dz);
+static int  initialise_vflags(dataptr dz);
+static int  setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int  setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int  get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int  assign_file_data_storage(int infilecnt,dataptr dz);
+
+/* CDP LIB FUNCTION MODIFIED TO AVOID CALLING setup_particular_application() */
+
+static int  parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+
+/* SIMPLIFICATION OF LIB FUNC TO APPLY TO JUST THIS FUNCTION */
+
+static int  parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int  handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int  setup_the_application(dataptr dz);
+static int  setup_the_param_ranges_and_defaults(dataptr dz);
+static int	check_the_param_validity_and_consistency(dataptr dz);
+static int  get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+static int  setup_and_init_input_brktable_constants(dataptr dz,int brkcnt);
+static void force_wav_extension(char *filename);
+
+/* BYPASS LIBRARY GLOBAL FUNCTION TO GO DIRECTLY TO SPECIFIC APPLIC FUNCTIONS */
+
+static int allocate_caltrain_buffer(dataptr dz);
+static int swap_chans(int startchan,int endchan,int windows_in_buf,dataptr dz);
+static int caltrain(dataptr dz);
+
+
+#ifndef HUGE
+#define HUGE 3.40282347e+38F
+#endif
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status;
+	dataptr dz = NULL;
+	char **cmdline;
+	int  cmdlinecnt;
+	aplptr ap;
+	int is_launched = FALSE;
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+						/* CHECK FOR SOUNDLOOM */
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {					// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+					  
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc == 2) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		dz->maxmode = 0;
+		if((exit_status = setup_the_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+	// parse_infile_and_hone_type() = 
+	if((exit_status = parse_infile_and_check_type(cmdline,dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// setup_param_ranges_and_defaults() =
+	if((exit_status = setup_the_param_ranges_and_defaults(dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// open_first_infile		CDP LIB
+	if((exit_status = open_first_infile(cmdline[0],dz))<0) {	
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);	
+		return(FAILED);
+	}
+	cmdlinecnt--;
+	cmdline++;
+
+	if((exit_status = handle_the_outfile(&cmdlinecnt,&cmdline,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+//	handle_formants()			redundant
+//	handle_formant_quiksearch()	redundant
+//	handle_special_data()		redundant except
+
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//check_param_validity_and_consistency .....
+	if((exit_status = check_the_param_validity_and_consistency(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	is_launched = TRUE;
+	dz->extra_bufcnt =  0;	
+	dz->bptrcnt = 6;
+	if((exit_status = establish_spec_bufptrs_and_extra_buffers(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = allocate_caltrain_buffer(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//param_preprocess()						redundant
+	//spec_process_file =
+	if((exit_status = caltrain(dz))< 0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+	if((exit_status = complete_output(dz))<0) {										// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);		// CDP LIB
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc, brkcnt;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	brkcnt = tipc;
+	if(brkcnt>0) {
+		if((exit_status = setup_and_init_input_brktable_constants(dz,brkcnt))<0)			  
+			return(exit_status);
+	}
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+			return(exit_status);
+	
+	// establish_infile_constants() replaced by
+	dz->infilecnt = 1;
+	return(FINISHED);
+}
+
+/******************************** SETUP_AND_INIT_INPUT_BRKTABLE_CONSTANTS ********************************/
+
+int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt)
+{	
+	int n;
+	if((dz->brk      = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<brkcnt;n++) {
+		dz->brk[n]     = NULL;
+		dz->brkptr[n]  = NULL;
+		dz->brkinit[n] = 0;
+		dz->brksize[n] = 0;
+	}
+	return(FINISHED);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}						 		/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/***************************** HANDLE_THE_OUTFILE **************************/
+
+int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status;
+	char *filename = (*cmdline)[0];
+	if(filename[0]=='-' && filename[1]=='f') {
+		dz->floatsam_output = 1;
+		dz->true_outfile_stype = SAMP_FLOAT;
+		filename+= 2;
+	}
+	if(!sloom) {
+		if(file_has_invalid_startchar(filename) || value_is_numeric(filename)) {
+			sprintf(errstr,"Outfile name %s has invalid start character(s) or looks too much like a number.\n",filename);
+			return(DATA_ERROR);
+		}
+	}
+	strcpy(dz->outfilename,filename);	   
+	if((exit_status = create_sized_outfile(filename,dz))<0)
+		return(exit_status);
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+/***************************** INSERT_NEWNUMBER_AT_FILENAME_END **************************/
+
+void insert_newnumber_at_filename_end(char *filename,int num,int overwrite_last_char)
+/* FUNCTIONS ASSUMES ENOUGH SPACE IS ALLOCATED !! */
+{
+	char *p;
+	char ext[64];
+	p = filename + strlen(filename) - 1;
+	while(p > filename) {
+		if(*p == '/' || *p == '\\' || *p == ':') {
+			p = filename;
+			break;
+		}
+		if(*p == '.') {
+			strcpy(ext,p);
+			if(overwrite_last_char)
+				p--;
+			sprintf(p,"%d",num);
+			strcat(filename,ext);
+			return;
+		}
+		p--;
+	}
+	if(p == filename) {
+		p += strlen(filename);
+		if(overwrite_last_char)
+			p--;
+		sprintf(p,"%d",num);
+	}
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/************************* SETUP_THE_APPLICATION *******************/
+
+int setup_the_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	// SEE parstruct FOR EXPLANATION of next 2 functions
+	if((exit_status = set_param_data(ap,0   ,2,2,"dd"      ))<0)
+		return(FAILED);
+	if((exit_status = set_vflgs(ap,"l",1,"d","",0,0,""))<0)
+		return(FAILED);
+	dz->has_otherfile = FALSE;
+	dz->input_data_type = ANALFILE_ONLY;
+	dz->process_type	= EQUAL_ANALFILE;	
+	dz->outfiletype  	= ANALFILE_OUT;
+	return application_init(dz);	//GLOBAL
+}
+
+/************************* PARSE_INFILE_AND_CHECK_TYPE *******************/
+
+int parse_infile_and_check_type(char **cmdline,dataptr dz)
+{
+	int exit_status;
+	infileptr infile_info;
+	if(!sloom) {
+		if((infile_info = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for infile structure to test file data.");
+			return(MEMORY_ERROR);
+		} else if((exit_status = cdparse(cmdline[0],infile_info))<0) {
+			sprintf(errstr,"Failed tp parse input file %s\n",cmdline[0]);
+			return(PROGRAM_ERROR);
+		} else if(infile_info->filetype != ANALFILE)  {
+			sprintf(errstr,"File %s is not of correct type\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if((exit_status = copy_parse_info_to_main_structure(infile_info,dz))<0) {
+			sprintf(errstr,"Failed to copy file parsing information\n");
+			return(PROGRAM_ERROR);
+		}
+		free(infile_info);
+	}
+	dz->clength		= dz->wanted / 2;
+	dz->chwidth 	= dz->nyquist/(double)(dz->clength-1);
+	dz->halfchwidth = dz->chwidth/2.0;
+	return(FINISHED);
+}
+
+/************************* SETUP_THE_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_the_param_ranges_and_defaults(dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	// NB total_input_param_cnt is > 0 !!!s
+	if((exit_status = setup_input_param_range_stores(ap->total_input_param_cnt,ap))<0)
+		return(FAILED);
+	// get_param_ranges()
+	ap->lo[0]			= dz->frametime;
+	ap->hi[0]			= dz->duration;
+	ap->default_val[0]	= 1.0;
+	ap->lo[1]			= 0;
+	ap->hi[1]			= dz->nyquist;
+	ap->default_val[1]	= 440;
+	ap->lo[2]			= 0;
+	ap->hi[2]			= dz->nyquist;
+	ap->default_val[2]	= 0;
+	dz->maxmode = 0;
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_the_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+/*********************** CHECK_THE_PARAM_VALIDITY_AND_CONSISTENCY *********************/
+
+int check_the_param_validity_and_consistency(dataptr dz)
+{
+	dz->iparam[0] = (int)floor(dz->param[0]/dz->frametime);
+	dz->iparam[1] = (int)round(dz->param[1]/dz->chwidth);
+	dz->iparam[2] = (int)round(dz->param[2]/dz->chwidth);
+	if(dz->iparam[2] >= dz->iparam[1]) {
+		sprintf(errstr,"Bass cutoff frq (%lf = chan %d) must be in lower chan than blur-bound frq (%lf = chan %d)\n",
+			dz->param[2],dz->iparam[2],dz->param[1],dz->iparam[1]);
+		return(DATA_ERROR);
+	}
+	return FINISHED;
+}
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int read_special_data(char *str,dataptr dz)	
+{
+	return(FINISHED);
+}
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return FINISHED;
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if      (!strcmp(prog_identifier_from_cmdline,"caltrain"))		dz->process = CALTRAIN;
+	else {
+		sprintf(errstr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+	return (usage2("caltrain"));
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+	if(!strcmp(str,"caltrain")) {
+		fprintf(stdout,
+	    "USAGE:\n"
+		"caltrain caltrain inanalfile outanalfile blurfact blurabov [-llocut]\n"
+		"\n"
+		"BLURFACT Time over which upper part of spectrum is blurred.\n"
+		"BLURABOV frequency above which spectrum is blurred.\n"
+		"LOCUT    bass cutoff frequency (defalut: no bass cutoff).\n"
+		"\n"
+		"Generates version of source with upper spectral channels time-blurred.\n"
+		"\n");
+	} else
+		fprintf(stdout,"Unknown option '%s'\n",str);
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	fprintf(stderr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/*********************** SPECULATE ***************************/
+
+int caltrain(dataptr dz)
+{
+	int exit_status, ibufsiz = dz->buflen/dz->wanted, outofinput = 0;
+	float *readbuf = dz->bigfbuf, *writebuf = dz->bigfbuf, *obufptr = dz->flbufptr[CALOBUF];
+	double maxisamp, maxosamp = 0.0, scaler;
+	int n, vc, remain, truebuflen = dz->buflen;
+	int finished = 0, windows_written = 0;
+				//	deal with 1st (zeroed) buffer	
+	if((sndseekEx(dz->ifd[0],dz->wanted,0)<0)){
+		sprintf(errstr,"sndseek() failed at first (zeros) window.\n");
+		return SYSTEM_ERROR;
+	}
+	memset((char *)obufptr,0,dz->wanted * sizeof(float));
+	obufptr += dz->wanted;
+	if(++windows_written >= dz->wlength) {
+		sprintf(errstr,"No significant data in input file.\n");
+		return DATA_ERROR;
+	}
+	if(obufptr >= dz->flbufptr[OBUFEND]) {
+		if((exit_status = write_samps(dz->flbufptr[CALOBUF],dz->buflen2,dz))<0)
+			return(exit_status);
+		memset((char *)dz->flbufptr[CALOBUF],0,dz->buflen2 * sizeof(float));
+		obufptr = dz->flbufptr[CALOBUF];
+	}
+			//	Initially, fill the input buffer
+			//	"readbuf" and "writebuf" point to the 1st window in inbuffer
+	if((exit_status = read_samps(dz->bigfbuf,dz))<0)
+		return(exit_status);
+
+	while(!finished) {
+		maxisamp = -HUGE;							//	Find maxsamp, ABOVE blur frq-boundary, in current input window
+		for(vc=dz->iparam[1] * 2;vc < dz->wanted; vc+=2) {
+			if(readbuf[AMPP] > maxisamp)
+				maxisamp = readbuf[AMPP];
+		}
+		memcpy((char *)(dz->flbufptr[BLURNRM]),(char *)readbuf,((dz->iparam[1] - 1) * 2 * sizeof(float)));
+												//	Copy, from current-window-to-read-from in input buffer, all channel data BELOW the blurboundary
+		readbuf += dz->wanted;					//	Then advance by one-window the buffer-to-read-from
+		if(readbuf >= dz->flbufptr[BLURBUF])	// ... but if end of input buffer reached, return to start for subsequent read
+			readbuf = dz->bigfbuf;
+
+		if(!outofinput) {						//	If out-of-input, we already know the sum of the spectra in the input buffer, and the maxosamp level
+			memset((char *)(dz->flbufptr[BLURBUF]),0,dz->wanted * sizeof(float));		//	Zero blur buffer, as values are ADDED IN to the upper chans
+			for(n=0; n < ibufsiz; n++) {		//	Sum amps and frqs from equivalent chans in all windows
+				for(vc=dz->iparam[1] * 2;vc < dz->wanted; vc+=2) {
+					dz->flbufptr[BLURBUF][AMPP] = (float)(dz->flbufptr[BLURBUF][AMPP] + (dz->flbufptr[CALIBUF][(n * dz->wanted) + AMPP]));
+					dz->flbufptr[BLURBUF][FREQ] = (float)(dz->flbufptr[BLURBUF][FREQ] + (dz->flbufptr[CALIBUF][(n * dz->wanted) + FREQ]));
+				}
+			}
+			maxosamp = 0;
+			for(vc=dz->iparam[1] * 2;vc < dz->wanted; vc+=2) {
+				if(dz->flbufptr[BLURBUF][AMPP] > maxosamp)
+					maxosamp = dz->flbufptr[BLURBUF][AMPP];			//	Get the maximum amplitude in the (summed-data) chans 
+				dz->flbufptr[BLURNRM][FREQ] = (float)(dz->flbufptr[BLURBUF][FREQ]/(double)ibufsiz);
+			}														//	Get the average frequency in the (summed-data) channels
+		}
+		if(maxosamp > FLTERR)
+			scaler = maxisamp/maxosamp;								//	Set scaling for new channel levels according to max chan level of orig input
+		else
+			scaler = 1.0;
+		for(vc=dz->iparam[1] * 2;vc < dz->wanted; vc+=2)			//	Blurred channels are scaled in level before being copied			
+			dz->flbufptr[BLURNRM][AMPP] = (float)(dz->flbufptr[BLURBUF][AMPP] * scaler);
+		if(dz->iparam[2] > 0) {										//	Do bass rolloff, if ness
+			for(vc = 0; vc <= dz->iparam[2] * 2; vc+=2)
+				dz->flbufptr[BLURNRM][AMPP] = 0.0f;
+		}															//	Copy window to outbuf
+		memcpy((char *)(obufptr),(char *)(dz->flbufptr[BLURNRM]),dz->wanted * sizeof(float));
+		obufptr += dz->wanted;
+		if(++windows_written >= dz->wlength)
+			finished = 1;
+		if((obufptr >= dz->flbufptr[OBUFEND]) || finished) {
+			if((exit_status = write_samps(dz->flbufptr[CALOBUF],obufptr - dz->flbufptr[CALOBUF],dz))<0)
+				return(exit_status);
+			memset((char *)dz->flbufptr[CALOBUF],0,dz->buflen2 * sizeof(float));
+			obufptr = dz->flbufptr[CALOBUF];
+			if(finished)
+				break;
+		}
+		dz->buflen = dz->wanted;
+		if((exit_status = read_samps(writebuf,dz))<0)		//	Read single window into the input buffer (overwriting previously used read-out window)
+			return(exit_status);							//	Even if at end of infile (zero samples read) continue
+		if(dz->ssampsread == 0)
+			outofinput = 1;
+		dz->buflen = truebuflen; 
+		writebuf += dz->wanted;
+		if(writebuf >= dz->flbufptr[BLURBUF])	// ... if place-to-write-input-to falls beyond end of input buffer, skip back to ibuf start
+			writebuf = dz->bigfbuf;
+	}
+	if((remain = obufptr - dz->flbufptr[CALOBUF]) > 0) {
+		if((exit_status = write_samps(dz->flbufptr[CALOBUF],remain,dz))<0)
+			return(exit_status);
+	}
+	return(FINISHED);
+}
+
+/**************************** ALLOCATE_CALTRAIN_BUFFER ****************************/
+
+int allocate_caltrain_buffer(dataptr dz)
+{
+	unsigned int buffersize;
+	dz->buflen = dz->iparam[0] * dz->wanted;
+	dz->buflen = min((dz->wlength - 1) * dz->wanted,dz->buflen);
+	dz->buflen2 = 16 * dz->wanted;
+	dz->buflen2 = min((dz->wlength - 1) * dz->wanted,dz->buflen2);
+	buffersize = dz->buflen + dz->buflen2 + (dz->wanted * 2);
+	if((dz->bigfbuf	= (float*)calloc(buffersize,sizeof(float)))==NULL) {  
+		sprintf(errstr,"INSUFFICIENT MEMORY for sound buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	dz->flbufptr[CALIBUF]	= dz->bigfbuf;							//	Several windows = input buf
+	dz->flbufptr[BLURBUF]	= dz->bigfbuf + dz->buflen;				//	1 window  : data blurred data
+	dz->flbufptr[BLURNRM]	= dz->flbufptr[BLURBUF] + dz->wanted;	//	1 window  : data blurred data, scaled
+	dz->flbufptr[CALOBUF]	= dz->flbufptr[BLURNRM] + dz->wanted;	//	N windows : output buffer
+	dz->flbufptr[OBUFEND]	= dz->flbufptr[CALOBUF] + dz->buflen2;
+	return(FINISHED);
+}

+ 1168 - 0
dev/standnew/clicknew.c

@@ -0,0 +1,1168 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <tkglobals.h>
+#include <pnames.h>
+#include <filetype.h>
+#include <processno.h>
+#include <modeno.h>
+#include <synth.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <math.h>
+#include <mixxcon.h>
+#include <osbind.h>
+#include <standalone.h>
+#include <ctype.h>
+#include <sfsys.h>
+#include <string.h>
+#include <srates.h>
+#include <limits.h>
+
+
+#ifdef unix
+#define round(x) lround((x))
+#endif
+
+char errstr[2400];
+
+int anal_infiles = 1;
+int	sloom = 0;
+int sloombatch = 0;
+
+const char* cdp_version = "6.1.0";
+
+#define NUCLICKDATA -2000
+
+//CDP LIB REPLACEMENTS
+static int check_nuclick_param_validity_and_consistency(dataptr dz);
+static int setup_nuclick_application(dataptr dz);
+static int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+static int parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int setup_nuclick_param_ranges_and_defaults(dataptr dz);
+static int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int remember_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int handle_the_outfile(dataptr dz);
+static int setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int establish_application(dataptr dz);
+static int initialise_vflags(dataptr dz);
+//static int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int mark_parameter_types(dataptr dz,aplptr ap);
+static int assign_file_data_storage(int infilecnt,dataptr dz);
+static int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+static int get_the_mode_from_cmdline(char *str,dataptr dz);
+static int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt);
+static int do_click(dataptr dz);
+static int read_clicktrack_data(char *,dataptr dz);
+static int generate_clicktable(dataptr dz);
+static int handle_the_special_data(int *cmdlinecnt,char ***cmdline,dataptr dz);
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status;
+	dataptr dz = NULL;
+	char **cmdline;
+	int  cmdlinecnt;
+	int n;
+	aplptr ap;
+	int is_launched = FALSE;
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+						/* CHECK FOR SOUNDLOOM */
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {					// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc < 5) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+	}
+	if(!sloom) {
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		dz->maxmode = 0;
+		// setup_particular_application =
+		if((exit_status = setup_nuclick_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+	if((exit_status = setup_nuclick_param_ranges_and_defaults(dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	dz->array_cnt=2; 
+	dz->iarray_cnt=0; 
+	dz->larray_cnt=0; 
+	dz->ptr_cnt= 0; 
+	dz->fptr_cnt = 0;
+	if((dz->parray = (double **)malloc(dz->array_cnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"Insufficient memory to store data.\n");
+		return(MEMORY_ERROR);
+	}
+	dz->parray[0] = NULL;
+	dz->parray[1] = NULL;
+
+	if((exit_status = generate_clicktable(dz))<0)
+		return(exit_status);
+
+	// handle_outfile() = 
+	if((exit_status = remember_the_outfile(&cmdlinecnt,&cmdline,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = handle_the_special_data(&cmdlinecnt,&cmdline,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+//	check_param_validity_and_consistency....
+	if((exit_status = check_nuclick_param_validity_and_consistency(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	dz->infile->srate = dz->iparam[0];
+	dz->infile->channels = 1;
+
+	// handle_outfile() = 
+	if((exit_status = handle_the_outfile(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	is_launched = TRUE;
+	dz->bufcnt = 1;
+	if((dz->sampbuf = (float **)malloc(sizeof(float *) * (dz->bufcnt+1)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->sbufptr = (float **)malloc(sizeof(float *) * dz->bufcnt))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffer pointers.\n");
+		return(MEMORY_ERROR);
+	}
+	for(n = 0;n <dz->bufcnt; n++)
+		dz->sampbuf[n] = dz->sbufptr[n] = (float *)0;
+	dz->sampbuf[n] = (float *)0;
+	dz->infile->channels = 1;
+	if((exit_status = create_sndbufs(dz))<0) {							// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = do_click(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	
+	if((exit_status = complete_output(dz))<0) {										// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);		// CDP LIB
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc, brkcnt;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	brkcnt = tipc;
+	//THERE ARE NO INPUTFILE brktables USED IN THIS PROCESS
+	if(brkcnt>0) {
+		if((exit_status = setup_and_init_input_brktable_constants(dz,brkcnt))<0)			  
+			return(exit_status);
+	}
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+		return(exit_status);
+	
+	// establish_infile_constants() replaced by
+	dz->infilecnt = 1;
+	//establish_bufptrs_and_extra_buffers():
+	return(FINISHED);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************************ REMEMBER_THE_OUTFILE *********************/
+
+int remember_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	char *filename = (*cmdline)[0];
+	if(filename[0]=='-' && filename[1]=='f') {
+		dz->floatsam_output = 1;
+		dz->true_outfile_stype = SAMP_FLOAT;
+		filename+= 2;
+	}
+	if(!sloom) {
+		if(file_has_invalid_startchar(filename) || value_is_numeric(filename)) {
+			sprintf(errstr,"Outfile name %s has invalid start character(s) or looks too much like a number.\n",filename);
+			return(DATA_ERROR);
+		}
+	}
+	strcpy(dz->outfilename,filename);	   
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_OUTFILE *********************/
+
+int handle_the_outfile(dataptr dz)
+{
+	int exit_status;
+	if((exit_status = create_sized_outfile(dz->outfilename,dz))<0)
+		return(exit_status);
+	return(FINISHED);
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* SETUP_NUCLICK_APPLICATION *******************/
+
+int setup_nuclick_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	// SEE parstruct FOR EXPLANATION of next 2 functions
+	if((exit_status = set_param_data(ap,NUCLICKDATA	   ,1,1,"i"))<0)
+		return(FAILED);
+	if((exit_status = set_vflgs(ap,"",0,"","",0,0,""))<0)
+		return(FAILED);
+	// set_legal_infile_structure -->
+	dz->has_otherfile = FALSE;
+	// assign_process_logic -->
+	dz->input_data_type = NO_FILE_AT_ALL;
+	dz->process_type	= UNEQUAL_SNDFILE;	
+	dz->outfiletype  	= SNDFILE_OUT;
+	dz->maxmode = 0;
+	return application_init(dz);	//GLOBAL
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_nuclick_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int read_special_data(char *str,dataptr dz)	
+{
+	return(FINISHED);
+}
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+    fprintf(stderr,
+    "USAGE: clicknew clicks outfile clicktimes_datafile srate\n\n"
+	"      make clicktrack using times listed in textfile.\n"
+	"      LEGAL SRATES are 16000, 22050, 32000, 44100, 88200, 48000, 88200 and 96000\n");
+	return(USAGE_ONLY);
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if(!strcmp(prog_identifier_from_cmdline,"clicks"))				dz->process = NUCLICK;
+	else {
+		sprintf(errstr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+    fprintf(stderr,
+	"INSUFFICIENT (OR TOO MANY) PARAMETERS\n\n"
+    "USAGE: clicknew clicks outfile clicktimes_datafile srate\n\n"
+	"      make clicktrack using times listed in textfile.\n"
+	"      LEGAL SRATES are 16000, 22050, 32000, 44100, 88200, 48000, 88200 and 96000\n");
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	fprintf(stderr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/******************************** DO_CLICK ********************************/
+
+int do_click(dataptr dz)
+{
+	double *clikdata = dz->parray[0], *clik = dz->parray[1];
+	double amp = 0.9;
+	int n, j = 0, bufsamptime, bufsampendtime, samptime;
+	float *buf = dz->sampbuf[0];
+	int k, exit_status;
+	memset((char *)buf,0,dz->buflen * sizeof(float));
+	for(n=0;n<dz->itemcnt;n++) {
+		samptime = (int)round(clikdata[n] * dz->infile->srate);
+		bufsamptime = samptime - dz->total_samps_written;
+		while(bufsamptime >= dz->buflen) {
+			if((exit_status = write_samps(dz->bigbuf,dz->buflen,dz))<0)
+				return(exit_status);
+			memset((char *)buf,0,dz->buflen * sizeof(float));
+			bufsamptime = samptime - dz->total_samps_written;
+		}
+		bufsampendtime = bufsamptime + CLICKLEN + 1;
+		k = 0;
+		if(bufsampendtime <= dz->buflen) {
+			for(j = bufsamptime; j < bufsampendtime; j++)
+				buf[j] = (float)((double)clik[k++] * amp);
+		} else {
+			for(j = bufsamptime; j < dz->buflen; j++)
+				buf[j] = (float)((double)clik[k++] * amp);
+			if((exit_status = write_samps(dz->bigbuf,dz->buflen,dz))<0)
+				return(exit_status);
+			memset((char *)buf,0,dz->buflen * sizeof(float));
+			j = 0;
+			while(k <= CLICKLEN)
+				buf[j++] = (float)((double)clik[k++] * amp);
+		}
+	}
+	if(j > 0) {
+		if((exit_status = write_samps(dz->bigbuf,j,dz))<0)
+			return(exit_status);
+	}
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_SPECIAL_DATA *********************/
+
+int handle_the_special_data(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+
+	if(!sloom) {
+		if(*cmdlinecnt <= 0) {
+			sprintf(errstr,"Insufficient parameters on command line.\n");
+			return(USAGE_ONLY);
+		}
+	}
+
+	ap->min_special 	= 0;
+	ap->max_special 	= 32767.0;
+	if((exit_status = read_clicktrack_data((*cmdline)[0],dz))<0)
+		return(exit_status);
+	(*cmdline)++;		
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/******************************** READ_CLICKTRACK_DATA ********************************/
+
+int read_clicktrack_data(char *str,dataptr dz)
+{
+	int timescnt;
+	char temp[200], *q;
+	double d, lasttime;
+	FILE *fp;
+	aplptr ap = dz->application;
+
+	if((fp = fopen(str,"r"))==NULL) {			
+		sprintf(errstr,"Cannot open clicktrack data file %s\n",str);
+		return(DATA_ERROR);
+	}
+	timescnt = 0;
+	while(fgets(temp,200,fp)!=NULL) {	 /* READ AND TEST BRKPNT VALS */
+		q = temp;
+		while(isspace(*q))
+			q++;
+		if(*q == ';')	//	Allow comments in file
+			continue;
+		lasttime = -1.0;
+		while(get_float_from_within_string(&q,&d)) {
+			if(d < 0.0 || d <= lasttime) {
+				sprintf(errstr,"Times do not advance at time %lf\n",d);
+				return(DATA_ERROR);
+			}
+			if (d >= ap->max_special) {
+				sprintf(errstr,"Maximum time is excessive : %lf\n",d);
+				return(DATA_ERROR);
+			}
+			lasttime = d;
+			timescnt++;
+		}
+	}
+	if(timescnt <= 0) {
+		sprintf(errstr,"No time data found in file %s\n",str);
+		return(DATA_ERROR);
+	}
+	if((dz->parray[0] = (double *)malloc(timescnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"Insufficient memory to store CLICKS time data.\n");
+		return(MEMORY_ERROR);
+	}
+	rewind(fp);
+	timescnt = 0;
+	while(fgets(temp,200,fp)!=NULL) {	 /* READ VALS */
+		q = temp;
+		while(isspace(*q))
+			q++;
+		if(*q == ';')	//	Allow comments in file
+			continue;
+		lasttime = 0.0;
+		while(get_float_from_within_string(&q,&d))
+			dz->parray[0][timescnt++] = d;
+	}
+	dz->itemcnt = timescnt;
+	return(FINISHED);
+}
+
+/*********************************** GENERATE_CLICKTABLE ***********************************************/
+
+int generate_clicktable(dataptr dz)
+{
+	int n;
+	double rand1, rand2, maxval;
+	if((dz->parray[1] = (double *)malloc((CLICKLEN +1) * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to store click table.\n");
+		return(MEMORY_ERROR);
+	}
+	initrand48();
+	maxval = 0.0;
+	for(n=0;n < CLICKLEN;n++) {
+		rand1 = (drand48() * 2.0) - 1.0;	/* in case I decide to modify it every time !! */
+		rand2 = (drand48() * .02) - .01;
+		dz->parray[1][n] = sqrt(sin(PI/(double)n)) * ((double)n * 2.0 * PI/(6.0+ rand1)) * rand2 * (MAXSHORT * .98);
+						/* 1/2 sin envel, steepened *    sin oscil every 6 or so samps    * noise *  maxsamp adjusted for noise wander */ 
+		maxval= max(maxval,fabs(dz->parray[1][n]));
+	}
+	maxval = MAXSHORT/maxval;
+	for(n=0;n < CLICKLEN;n++)
+		dz->parray[1][n] *= maxval;
+	dz->parray[1][n] = 0.0;
+	return(FINISHED);
+}
+
+/************************* SETUP_NUCLICK_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_nuclick_param_ranges_and_defaults(dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	if((exit_status = setup_input_param_range_stores(ap->total_input_param_cnt,ap))<0)
+		return(FAILED);
+	// get_param_ranges()
+	ap->lo[0]	= 44100;
+	ap->hi[0]	= 96000;
+	ap->default_val[0]	= 44100;
+	dz->maxmode = 0;
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/**************************** CHECK_NUCLICK_PARAM_VALIDITY_AND_CONSISTENCY *****************************/
+
+int check_nuclick_param_validity_and_consistency(dataptr dz)
+{
+	if(!LEGAL_SRATE(dz->param[0])) {
+		sprintf(errstr,"Illegal Sampling Rate.\n");
+		return(DATA_ERROR);
+	}
+// TW Mar: 2015
+//	dz->iparam[1] = (int)round(dz->param[1] * (double)(dz->infile->srate * dz->infile->channels));
+	return FINISHED;
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}						 		/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/******************************** SETUP_AND_INIT_INPUT_BRKTABLE_CONSTANTS ********************************/
+
+int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt)
+{	
+	int n;
+	if((dz->brk      = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<brkcnt;n++) {
+		dz->brk[n]     = NULL;
+		dz->brkptr[n]  = NULL;
+		dz->brkinit[n] = 0;
+		dz->brksize[n] = 0;
+	}
+	return(FINISHED);
+}
+
+

+ 1244 - 0
dev/standnew/clip.c

@@ -0,0 +1,1244 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <tkglobals.h>
+#include <pnames.h>
+#include <filetype.h>
+#include <processno.h>
+#include <modeno.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <math.h>
+#include <mixxcon.h>
+#include <osbind.h>
+#include <standalone.h>
+#include <ctype.h>
+#include <sfsys.h>
+#include <string.h>
+#include <srates.h>
+
+
+#ifdef unix
+#define round(x) lround((x))
+#endif
+
+char errstr[2400];
+
+int anal_infiles = 1;
+int	sloom = 0;
+int sloombatch = 0;
+
+const char* cdp_version = "6.1.0";
+
+//CDP LIB REPLACEMENTS
+static int check_clip_param_validity_and_consistency(dataptr dz);
+static int setup_clip_application(dataptr dz);
+static int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+static int parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int setup_clip_param_ranges_and_defaults(dataptr dz);
+static int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int establish_application(dataptr dz);
+static int initialise_vflags(dataptr dz);
+static int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int mark_parameter_types(dataptr dz,aplptr ap);
+static int assign_file_data_storage(int infilecnt,dataptr dz);
+static int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+static int get_the_mode_from_cmdline(char *str,dataptr dz);
+static int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt);
+static int create_long_sndbuf(dataptr dz);   //RWD may as well keep this as "long"
+static int clip(dataptr dz);
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status;
+	dataptr dz = NULL;
+	char **cmdline;
+	int  cmdlinecnt;
+	int n;
+	aplptr ap;
+	int is_launched = FALSE;
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+						/* CHECK FOR SOUNDLOOM */
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {					// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc == 2) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+	}
+	if(!sloom) {
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		dz->maxmode = 2;
+		if((exit_status = get_the_mode_from_cmdline(cmdline[0],dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);
+		}
+		cmdline++;
+		cmdlinecnt--;
+		// setup_particular_application =
+		if((exit_status = setup_clip_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+
+	// parse_infile_and_hone_type() = 
+	if((exit_status = parse_infile_and_check_type(cmdline,dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// setup_param_ranges_and_defaults() =
+	if((exit_status = setup_clip_param_ranges_and_defaults(dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// open_first_infile		CDP LIB
+	if((exit_status = open_first_infile(cmdline[0],dz))<0) {	
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);	
+		return(FAILED);
+	}
+	cmdlinecnt--;
+	cmdline++;
+
+//	handle_extra_infiles() : redundant
+	// handle_outfile() = 
+	if((exit_status = handle_the_outfile(&cmdlinecnt,&cmdline,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+//	handle_formants()			redundant
+//	handle_formant_quiksearch()	redundant
+//	handle_special_data()		redundant
+ 
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+//	check_param_validity_and_consistency....
+	if((exit_status = check_clip_param_validity_and_consistency(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	is_launched = TRUE;
+	dz->bufcnt = 1;
+	if((dz->sampbuf = (float **)malloc(sizeof(float *) * (dz->bufcnt+1)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->sbufptr = (float **)malloc(sizeof(float *) * dz->bufcnt))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffer pointers.\n");
+		return(MEMORY_ERROR);
+	}
+	for(n = 0;n <dz->bufcnt; n++)
+		dz->sampbuf[n] = dz->sbufptr[n] = (float *)0;
+	dz->sampbuf[n] = (float *)0;
+
+	if(dz->mode == 0) {
+		if((exit_status = create_sndbufs(dz))<0) {							// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		if((exit_status = create_long_sndbuf(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	}
+	//param_preprocess()						redundant
+	//spec_process_file =
+	if((exit_status = clip(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = complete_output(dz))<0) {										// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);		// CDP LIB
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc, brkcnt;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	brkcnt = tipc;
+	//THERE ARE NO INPUTFILE brktables USED IN THIS PROCESS
+	if(brkcnt>0) {
+		if((exit_status = setup_and_init_input_brktable_constants(dz,brkcnt))<0)			  
+			return(exit_status);
+	}
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+		return(exit_status);
+	
+	// establish_infile_constants() replaced by
+	dz->infilecnt = 1;
+	//establish_bufptrs_and_extra_buffers():
+	return(FINISHED);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}						 		/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_OUTFILE *********************/
+
+int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status;
+	char *filename = (*cmdline)[0];
+	if(filename[0]=='-' && filename[1]=='f') {
+		dz->floatsam_output = 1;
+		dz->true_outfile_stype = SAMP_FLOAT;
+		filename+= 2;
+	}
+	if(!sloom) {
+		if(file_has_invalid_startchar(filename) || value_is_numeric(filename)) {
+			sprintf(errstr,"Outfile name %s has invalid start character(s) or looks too much like a number.\n",filename);
+			return(DATA_ERROR);
+		}
+	}
+	strcpy(dz->outfilename,filename);	   
+	if((exit_status = create_sized_outfile(filename,dz))<0)
+		return(exit_status);
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/************************* SETUP_CLIP_APPLICATION *******************/
+
+int setup_clip_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	// SEE parstruct FOR EXPLANATION of next 2 functions
+	switch(dz->mode) {
+	case(0):	// fall thro
+	case(1):
+		exit_status = set_param_data(ap,0   ,1,1,"d");
+		break;
+	}
+	if(exit_status <0)
+		return(FAILED);
+	if((exit_status = set_vflgs(ap,"",0,"","",0,0,""))<0)
+		return(FAILED);
+	// set_legal_infile_structure -->
+	dz->has_otherfile = FALSE;
+	// assign_process_logic -->
+	dz->input_data_type = SNDFILES_ONLY;
+	dz->process_type	= EQUAL_SNDFILE;	
+	dz->outfiletype  	= SNDFILE_OUT;
+	return application_init(dz);	//GLOBAL
+}
+
+/************************* PARSE_INFILE_AND_CHECK_TYPE *******************/
+
+int parse_infile_and_check_type(char **cmdline,dataptr dz)
+{
+	int exit_status;
+	infileptr infile_info;
+	if(!sloom) {
+		if((infile_info = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for infile structure to test file data.");
+			return(MEMORY_ERROR);
+		} else if((exit_status = cdparse(cmdline[0],infile_info))<0) {
+			sprintf(errstr,"Failed to parse input file %s\n",cmdline[0]);
+			return(PROGRAM_ERROR);
+		} else if(infile_info->filetype != SNDFILE)  {
+			sprintf(errstr,"File %s is not of correct type\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if(dz->mode == 1 && infile_info->channels != 1)  {
+			sprintf(errstr,"File %s is not of correct type (must be mono)\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if((exit_status = copy_parse_info_to_main_structure(infile_info,dz))<0) {
+			sprintf(errstr,"Failed to copy file parsing information\n");
+			return(PROGRAM_ERROR);
+		}
+		free(infile_info);
+	}
+	return(FINISHED);
+}
+
+/************************* SETUP_CLIP_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_clip_param_ranges_and_defaults(dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	// NB total_input_param_cnt is > 0 !!!
+	if((exit_status = setup_input_param_range_stores(ap->total_input_param_cnt,ap))<0)
+		return(FAILED);
+	// get_param_ranges()
+	switch(dz->mode) {
+	case(0):
+		ap->lo[0]	= 0.0;						// clip level
+		ap->hi[0]	= 1.0;
+		ap->default_val[0]	= 0.1;
+	case(1):
+		ap->lo[0]	= 0.0;						// clip fraction of half-waveset level
+		ap->hi[0]	= 1.0;
+		ap->default_val[0]	= 0.5;
+		break;
+	}
+	dz->maxmode = 2;
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_clip_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int read_special_data(char *str,dataptr dz)	
+{
+	return(FINISHED);
+}
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+	usage2("clip");
+	return(USAGE_ONLY);
+}
+
+/**************************** CHECK_CLIP_PARAM_VALIDITY_AND_CONSISTENCY *****************************/
+
+int check_clip_param_validity_and_consistency(dataptr dz)
+{
+	if(dz->param[0] <= 0.0) {
+		sprintf(errstr,"No distortion with a zero parameter value.\n");
+		return(DATA_ERROR);
+	}
+// TW Mar: 2015
+//	dz->iparam[1] = (int)round(dz->param[1] * (double)(dz->infile->srate * dz->infile->channels));
+	return FINISHED;
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if(!strcmp(prog_identifier_from_cmdline,"clip"))				dz->process = CLIP;
+	else {
+		sprintf(errstr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/******************************** SETUP_AND_INIT_INPUT_BRKTABLE_CONSTANTS ********************************/
+
+int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt)
+{	
+	int n;
+	if((dz->brk      = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<brkcnt;n++) {
+		dz->brk[n]     = NULL;
+		dz->brkptr[n]  = NULL;
+		dz->brkinit[n] = 0;
+		dz->brksize[n] = 0;
+	}
+	return(FINISHED);
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+	if(!strcmp(str,"clip")) {
+		fprintf(stderr,
+	    "USAGE:\n"
+	    "clip clip mode infile outfile params\n"
+		"\n"
+		"Mode 1: Clip signal at specified level.\n"
+		"Mode 2: Clip half-waveforms at specified fraction.\n"
+		"\n");
+	} else
+		fprintf(stdout,"Unknown option '%s'\n",str);
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	fprintf(stderr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/******************************** CLIP ********************************/
+
+int clip(dataptr dz)
+{
+	int exit_status, chans = dz->infile->channels;
+	float *ibuf = dz->sampbuf[0];
+	double gain;
+	float *maxsamp = NULL, *minsamp = NULL;
+	float localmin, localmax;
+	int	*phase = NULL;
+	int *halfwavsetstart = NULL, n = 0, m, j, k;
+
+	if((maxsamp = (float *)malloc(chans * sizeof(float)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for maximum sample storage.\n");
+		return(MEMORY_ERROR);
+	}
+	if(dz->mode == 1) {
+		if((minsamp = (float *)malloc(chans * sizeof(float)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for minimum sample storage.\n");
+			return(MEMORY_ERROR);
+		}
+		if((phase = (int *)malloc(chans * sizeof(int)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for phase-flags.\n");
+			return(MEMORY_ERROR);
+		}
+		if((halfwavsetstart = (int *)malloc(chans * sizeof(int)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for waveset start-marker.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if((exit_status = read_samps(ibuf,dz))<0)
+		return(exit_status);
+	switch(dz->mode) {
+	case(0):
+		maxsamp[0] = 0.0;
+		while(dz->ssampsread > 0) {
+			for(n=0;n<dz->ssampsread;n++) {
+				if(fabs(ibuf[n]) > maxsamp[0])
+					maxsamp[0] = (float)fabs(ibuf[n]);
+			}
+			if((exit_status = read_samps(ibuf,dz))<0)
+				return(exit_status);
+		}
+		if(maxsamp[0] <= dz->param[0]) {
+			sprintf(errstr,"None of signal is above the input clipping level.\n");
+			return(DATA_ERROR);
+		}
+		gain = maxsamp[0]/dz->param[0];
+		if(sndseekEx(dz->ifd[0],0,0) < 0) {
+			sprintf(errstr,"File rewinding failed.\n");
+			return(DATA_ERROR);
+		}
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+		while(dz->ssampsread > 0) {
+			for(n=0;n<dz->ssampsread;n++) {
+				if(ibuf[n] > dz->param[0])
+					ibuf[n] = (float)dz->param[0];
+				else if(ibuf[n] < -dz->param[0])
+					ibuf[n] = (float)(-dz->param[0]);
+				ibuf[n] = (float)(ibuf[n] * gain);
+			}
+			if((exit_status = write_samps(ibuf,dz->ssampsread,dz))<0)
+				return(exit_status);
+			if((exit_status = read_samps(ibuf,dz))<0)
+				return(exit_status);
+		}
+		break;
+	case(1):
+/* TEST *
+fprintf(stderr,"buflen = %d sampsread = %d ifd = %d ofd = %d ibuf = %d\n",dz->buflen,dz->ssampsread,dz->ifd[0],dz->ofd,ibuf);
+* TEST */           //RWD don't want nested comments
+		for(n=0;n<chans;n++) {
+			maxsamp[n] = 0.0;
+			minsamp[n] = 0.0;
+			phase[n] = 0;
+			halfwavsetstart[n] = 0;
+		}
+		for(n=0;n<dz->ssampsread;n+=chans) {
+			for(m = 0;m < chans; m++) {
+				k = m + n;
+				switch(phase[m]) {
+				case(0):
+					if(ibuf[k] > maxsamp[m]) {
+						maxsamp[m] = ibuf[k];
+						phase[m] = 1;
+					} else if(ibuf[k] < minsamp[m]) {
+						minsamp[m] = ibuf[k];
+						phase[m] = -1;
+					}
+					break;
+				case(1):
+					if(ibuf[k] > 0) {
+						if(ibuf[k] > maxsamp[m])
+							maxsamp[m] = ibuf[k];
+					} else if(ibuf[k] < 0) {
+						localmax = (float)(maxsamp[m] * dz->param[0]);
+						for(j = halfwavsetstart[m]; j < k; j+=chans) {
+							if(ibuf[j] > localmax)
+								ibuf[j] = localmax;
+						}
+						halfwavsetstart[m] = k;
+						minsamp[m] = ibuf[k];
+						maxsamp[m] = 0;
+						phase[m] = -1;
+					}
+					break;
+				case(-1):
+					if(ibuf[k] < 0) {
+						if(ibuf[k] < minsamp[m])
+							minsamp[m] = ibuf[k];
+					} else if(ibuf[k] > 0) {
+						localmin = (float)(minsamp[m] * dz->param[0]);
+						for(j = halfwavsetstart[m]; j < k; j+=chans) {
+							if(ibuf[j] < localmin)
+								ibuf[j] = localmin;
+						}
+						halfwavsetstart[m] = k;
+						maxsamp[m] = ibuf[k];
+						minsamp[m] = 0;
+						phase[m] = 1;
+					}
+					break;
+				}
+			}
+		}
+		gain = 1.0/dz->param[0];
+		for(n = 0; n < dz->ssampsread; n++)
+			ibuf[n] = (float)(ibuf[n] * gain);
+		if((exit_status = write_samps(ibuf,dz->ssampsread,dz))<0)
+			return(exit_status);
+		break;
+	}
+	return FINISHED;
+}
+
+/****************************** GET_MODE *********************************/
+
+int get_the_mode_from_cmdline(char *str,dataptr dz)
+{
+	char temp[200], *p;
+	if(sscanf(str,"%s",temp)!=1) {
+		sprintf(errstr,"Cannot read mode of program.\n");
+		return(USAGE_ONLY);
+	}
+	p = temp + strlen(temp) - 1;
+	while(p >= temp) {
+		if(!isdigit(*p)) {
+			fprintf(stderr,"Invalid mode of program entered.\n");
+			return(USAGE_ONLY);
+		}
+		p--;
+	}
+	if(sscanf(str,"%d",&dz->mode)!=1) {
+		fprintf(stderr,"Cannot read mode of program.\n");
+		return(USAGE_ONLY);
+	}
+	if(dz->mode <= 0 || dz->mode > dz->maxmode) {
+		fprintf(stderr,"Program mode value [%d] is out of range [1 - %d].\n",dz->mode,dz->maxmode);
+		return(USAGE_ONLY);
+	}
+	dz->mode--;		/* CHANGE TO INTERNAL REPRESENTATION OF MODE NO */
+	return(FINISHED);
+}
+
+/****************************** CREATE_LONG_SNDBUF *********************************/
+
+int create_long_sndbuf(dataptr dz)
+{
+	int n;
+	long bigbufsize;
+	dz->buflen = dz->insams[0];
+	bigbufsize = dz->buflen * sizeof(float);
+	if(bigbufsize < 0) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to create sound buffer of the whole sound.\n");
+		return(PROGRAM_ERROR);
+	}
+	if((dz->bigbuf = (float *)malloc(bigbufsize)) == NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to create sound buffer for the whole sound.\n");
+		return(PROGRAM_ERROR);
+	}
+	for(n=0;n<dz->bufcnt;n++)
+		dz->sbufptr[n] = dz->sampbuf[n] = dz->bigbuf + (dz->buflen * n);
+	dz->sampbuf[n] = dz->bigbuf + (dz->buflen * n);
+	return(FINISHED);
+}
+

+ 522 - 0
dev/standnew/convert_to_midi.c

@@ -0,0 +1,522 @@
+/*
+ * CREATE STANDARD MIDI FILE FROM CDP FRQ BRKPNT FILE FOR STABLE PITCHES (WHICH HAS NOTE STARTS AND ENDS)
+ *
+ *	Assumes a single voice, using a sigle MIDI channel (0)
+ *	and note-off occurs before following note-on
+ *
+ *	If "staccato" is set to 0, program reads note on and note off times.
+ *	If "staccato" > 0, note-offs are generated from note ons, and note-ends in input file are ignored.
+ *
+ *	CALL WITH
+ *	convert_to_midi(seqfile,envfile,infiledatalen,staccato,outfilename,system);
+ *
+ *  where infiledatalen is no of midi notes in input = 1/4 of entries in frq-brkpnt file. 
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <ctype.h>
+#include <string.h>
+#include <math.h>
+#include <sfsys.h>   // RWD for macro defs
+
+#if defined unix || defined __GNUC__
+#define round(x) lround((x))
+#else
+# ifndef round
+//static int round(double d);
+static int twround(double d);   //RWD
+#define round(x) twround((x))   //RWD
+# endif
+#endif
+
+
+#define MIDI_NOTE_ON	(unsigned char)144	/*	0x90 = 1001 0000 = 1001 is Note-on : 0000 is channel number */
+#define MIDI_NOTE_OFF	(unsigned char)128	/*	0x80 = 1000 0000 = 1001 is Note-on : 0000 is channel number */
+#define LOW_A			6.875				/*	Frequency of A below MIDI 0 */
+#define CONVERT_LOG10_TO_LOG2	3.321928	/* MiditoHz conversions */
+#define TRUE	1
+#define FALSE	0
+#define NEWLINE		('\n')
+#define ENDOFSTR	('\0')
+
+static void Write_ThisIsAMIDI_MThdChunk_with_mS_timings (char format_type,char track_cnt,FILE *fp);
+static void WriteTrackID (unsigned int midi_track_data_bytes,FILE *fp);
+static void WriteVarLen (unsigned int value,FILE *fp);
+static void WriteNormalLong (unsigned int value,FILE *fp);
+static void Write_TrackEnd (FILE *fp);
+static void create_note(double timestep,char midi,double thislevel,int on,FILE *fp);
+static char HzToMidi (double frq);
+static int  get_float_from_within_string(char **str,double *val);
+static int midi_data_bytes_in_midi_track (int infiledatalen,double *seqdata,double staccato);
+static int  CalcVarLen (unsigned int value);
+static void Write_ThisIsAMIDI_PC_header(unsigned int total_bytes_in_file,FILE *fp);
+
+#ifndef round
+static int round(double d);
+#endif
+
+int main(int argc,char *argv[])
+{
+	FILE *fp;
+	double *seqdata, *envdata, *p, *end;
+	char *q;
+	double lasttime, thistime, nexttime, timestep, thislevel, stacdur;
+	int on, padbyte;
+	int n,m,k;
+	unsigned int midi_track_data_bytes, total_bytes_in_file;
+	char temp[200];
+	int system;
+	char seqfile[64];
+	char envfile[64];
+	int infiledatalen;
+	double staccato;
+	char outfilename[64];
+	char thismidi;
+
+	if(argc == 1) {
+		fprintf(stdout,"Converts frqequency-brkpnt and peakdata textfiles to a standard midi data file.\n");
+		fprintf(stdout,"\n");
+		fprintf(stdout,"USAGE:\n");
+		fprintf(stdout,"convert_to_midi  frqbrkpnt  peakvals  datalen  staccato  outfilename  system\n");
+		fprintf(stdout,"\n");
+		fprintf(stdout,"FRQBRKPNT   File of time-frq pairs for note starts and ends.\n");
+		fprintf(stdout,"PEAKVALS    Levels of each note (Range 0-1).\n");
+		fprintf(stdout,"DATALEN     Number of peaks (no. of vals in 'frqbrkpnt' should be datalen * 4)\n");
+		fprintf(stdout,"STACCATO    Force staccato output.\n");
+		fprintf(stdout,"OUTFILENAME (File extension will be forced to '.mid' or '.rmi')\n");
+		fprintf(stdout,"SYSTEM      0 gives Standard Midi File, with extension '.mid'\n");
+		fprintf(stdout,"            1 gives PC Midi File, with extension '.rmi'\n");
+		fflush(stdout);
+		return 1;
+	}
+	if(argc != 7) {
+		fprintf(stdout,"ERROR: WRONG NUMBER OF ARGUMENTS\n");
+		fflush(stdout);
+		return 0;
+	}
+	strcpy(seqfile,argv[1]);
+	strcpy(envfile,argv[2]);
+	if(sscanf(argv[3],"%d",&infiledatalen)<1) {
+		fprintf(stdout,"ERROR: CANNOT READ INFILE DATA LENGTH [%s].\n",argv[3]);
+		fflush(stdout);
+		return 0;
+	}	
+	if(sscanf(argv[4],"%lf",&staccato)<1) {
+		fprintf(stdout,"ERROR: CANNOT READ STACCATO DURATION [%s].\n",argv[4]);
+		fflush(stdout);
+		return 0;
+	}	
+	strcpy(outfilename,argv[5]);
+	q = outfilename + strlen(outfilename);
+	q--;
+	while(*q != '.') {
+		q--;
+		if(q <= outfilename)
+			break;
+	}
+	if(q > outfilename)
+		*q = ENDOFSTR;
+	if(sscanf(argv[6],"%d",&system)<1) {
+		fprintf(stdout,"ERROR: CANNOT READ HEADER TYPE [%s].\n",argv[4]);
+		fflush(stdout);
+		return 0;
+	}	
+	if(system == 1)
+		strcat(outfilename,".rmi");
+	else
+		strcat(outfilename,".mid");
+
+	if((seqdata = (double *)malloc((infiledatalen * 4) * sizeof(double)))==NULL) {
+		fprintf(stdout,"ERROR: INSUFFICIENT MEMORY TO CREATE INPUT DATA ARRAY.\n");
+		fflush(stdout);
+		return 0;
+	}
+	if((envdata = (double *)malloc(infiledatalen * sizeof(double)))==NULL) {
+		fprintf(stdout,"ERROR: INSUFFICIENT MEMORY TO CREATE LOUDNESS DATA ARRAY.\n");
+		fflush(stdout);
+		return 0;
+	}
+	p = seqdata;
+	if((fp = fopen(seqfile,"r"))==NULL) {			
+		fprintf(stdout,"ERROR: FAILED TO OPEN FILE %s TO READ SEQUENCE DATA\n",seqfile);
+		fflush(stdout);
+		return 0;
+	}
+	end = p + (infiledatalen * 4);
+	while(fgets(temp,200,fp)!=NULL) {	 /* READ AND TEST MIDI DATA INFO, ASSUMING IT TO BE IN CORRECT FORMAT!! */
+		q = temp;
+		while(get_float_from_within_string(&q,p)) {
+			p++;			
+			if (p >= end)
+				break;
+		}	    
+	}
+	fclose(fp);
+	if(p - seqdata != infiledatalen * 4) {
+		fprintf(stdout,"ERROR: COUNT OF MIDI DATA ITEMS DOES NOT CORRESPOND TO PARAM FOR INPUT DATA LENGTH\n");
+		fflush(stdout);
+		return 0;
+	}	
+	p = envdata;
+	end = p + infiledatalen;
+	if((fp = fopen(envfile,"r"))==NULL) {			
+		fprintf(stdout,"ERROR: FAILED TO OPEN FILE %s TO READ LOUDNESS DATA\n",envfile);
+		fflush(stdout);
+		return 0;
+	}
+	while(fgets(temp,200,fp)!=NULL) {	 /* READ AND TEST MIDI DATA INFO, ASSUMING IT TO BE IN CORRECT FORMAT!! */
+		q = temp;
+		while(get_float_from_within_string(&q,p)) {
+			p++;			
+			if (p >= end)
+				break;
+		}	    
+	}
+	fclose(fp);
+	if(p - envdata != infiledatalen) {
+		fprintf(stdout,"ERROR: COUNT OF LOUDNESS ITEMS DOES NOT CORRESPOND TO PARAM FOR INPUT DATA LENGTH\n");
+		fflush(stdout);
+		return 0;
+	}	
+
+	if((fp = fopen(outfilename,"w"))==NULL) {			
+		fprintf(stdout,"ERROR: FAILED TO OPEN MIDI DATAFILE %s TO WRITE DATA\n",outfilename);
+		fflush(stdout);
+		return 0;
+	}
+	total_bytes_in_file = 14 /* MThd Chunk */ + 4 /*MTrk track identifier */ ;
+	midi_track_data_bytes = midi_data_bytes_in_midi_track(infiledatalen,seqdata,staccato);
+	total_bytes_in_file += CalcVarLen(midi_track_data_bytes) + midi_track_data_bytes;
+	
+	if((total_bytes_in_file/2)*2 != total_bytes_in_file) {	/* Does (single) chunk have EVEN number of bytes? */
+		padbyte = 1;
+	} else {
+		padbyte = 0;
+	}
+	if (system == 1)
+		total_bytes_in_file += padbyte;	/* For PC, force an EVEN chunk-size */
+	switch(system) {
+	case(0):
+		break;
+	case(1): /* PC */
+		Write_ThisIsAMIDI_PC_header(total_bytes_in_file,fp);
+		break;
+	}
+	Write_ThisIsAMIDI_MThdChunk_with_mS_timings ((char)0,(char)1,fp);
+		/* Assuming format type 0, 1 track only */
+	WriteTrackID (midi_track_data_bytes,fp);
+		/* Assuming there is 1 track, numbered 0 */
+	lasttime = 0.0;
+	on = 1;
+	k = 0;
+	for(n=0,m=1;n < infiledatalen * 4;n+=2,m+=2) {
+		thistime  = seqdata[n];
+		thismidi  = (char)round(HzToMidi(seqdata[m]));
+		timestep  = thistime - lasttime;
+		if (on) {
+			thislevel = envdata[k++];
+			create_note(timestep,thismidi,thislevel,1,fp);
+			lasttime = thistime;
+			if (staccato > 0.0) {		/* If staccato, note off determined by staccato dur */
+				if(m+4 < infiledatalen) {
+					nexttime = seqdata[m+4];
+					stacdur = (nexttime - thistime)/2.0;
+					stacdur = min(stacdur,staccato);
+				} else {
+					stacdur = staccato;
+				}
+				create_note(stacdur,thismidi,thislevel,0,fp);
+				lasttime = thistime + stacdur;
+			}
+			on = 0;
+		} else {
+			if (staccato <= 0.0) {		/* IF not staccato, note-off taken from input data */
+				create_note(timestep,thismidi,thislevel,0,fp);
+				lasttime = thistime;	/*	But, if staccato, ignore the note off input */
+			}
+			on = 1;
+		}
+	}
+	Write_TrackEnd(fp);
+	if(system == 1)	{ /* PC riff format */
+		if(padbyte)
+			putc(0,fp);
+	}
+	fclose(fp);
+	return 1;
+}
+
+/*********************** WRITE A 32-BIT REPRESENTATION OF "THIS is MIDI data = ascii MThd" ***********/
+
+void Write_ThisIsAMIDI_MThdChunk_with_mS_timings (char format_type,char track_cnt,FILE *fp)
+{
+	register char buffer;
+	buffer = 77;	/* M */
+	putc(buffer,fp);
+	buffer = 84;	/* T */
+	putc(buffer,fp);
+	buffer = 104;	/* h */
+	putc(buffer,fp);
+	buffer = 100;	/* d */
+	putc(buffer,fp);
+	buffer = 0;		/* sizeof MThd chunk is 6 = 0006 */
+	putc(buffer,fp);
+	putc(buffer,fp);
+	putc(buffer,fp);
+	buffer = 6;		/* sizeof MThd chunk is 6 = 0006 */
+	putc(buffer,fp);
+	buffer = 0;		/* format_type 00 0x */
+	putc(buffer,fp);
+	buffer = format_type;
+	putc(buffer,fp);
+	buffer = 0;		/* track_cnt   00 0x */
+	putc(buffer,fp);
+	buffer = track_cnt;
+	putc(buffer,fp);
+	buffer = (char)-25;	/* -25 means 25 frames per sec */
+	putc(buffer,fp);
+	buffer = 40;	/* 40 units per frame -> 1 unit per ms */
+	putc(buffer,fp);
+}
+
+/*********************** WRITE TRACK ID  ***********/
+
+void WriteTrackID (unsigned int midi_track_data_bytes,FILE *fp)
+{
+	register char buffer;
+	buffer = 77;	/* M */
+	putc(buffer,fp);
+	buffer = 84;	/* T */
+	putc(buffer,fp);
+	buffer = 114;	/* r */
+	putc(buffer,fp);
+	buffer = 107;	/* k */
+	putc(buffer,fp);
+	WriteVarLen(midi_track_data_bytes,fp);
+}
+
+/*********************** WRITE A 32-BIT int, SPLIT INTO 7-bit WORDS IN REVERSE BYTE ORDER = MIDI TIME REPRESENTATION ***********/
+
+void WriteVarLen (unsigned int value,FILE *fp)
+{
+	register unsigned int buffer;
+	buffer = value & 0x7F;
+	while (value >>= 7) {
+		buffer <<= 8;
+		buffer |= ((value & 0x7F) | 0x80);
+	}
+	for (;;) {
+		putc(buffer,fp);
+		if(buffer & 0x80)
+			buffer >>= 8;
+		else
+			break;
+	}
+}
+
+/*********************** WRITE A 32-BIT int IN NORMAL ORDER ***********/
+
+void WriteNormalLong (unsigned int value,FILE *fp)
+{
+	unsigned int buffer;
+	int n = 0;
+	while (n < 4) {
+		buffer = value & 0xFF;
+		putc(buffer,fp);
+		value >>= 8;
+		n++;
+	}
+}
+
+/*********************** ASCERTAIN BYTE LENGTH OF MIDI TIME REPRESENTATION ***********/
+
+int CalcVarLen (unsigned int value)
+{
+	register unsigned int buffer;
+	int cnt = 0;
+	buffer = value & 0x7F;
+	while (value >>= 7) {
+		buffer <<= 8;
+		buffer |= ((value & 0x7F) | 0x80);
+	}
+	for (;;) {
+		cnt++;
+		if(buffer & 0x80)
+			buffer >>= 8;
+		else
+			break;
+	}
+	return cnt;
+}
+
+/*********************** WRITE "END OF TRACK" ***********/
+
+void Write_TrackEnd (FILE *fp)
+{
+	register char buffer;
+	buffer = (char)-1;				/* FF = |1111|1111| = -128 */
+	putc(buffer,fp);
+	buffer = (char)0x2F;
+	putc(buffer,fp);
+	buffer = 0;
+	putc(buffer,fp);
+}
+
+/*********************** CREATE MIDI NOTE ON OR NOTE OFF DATA ***********/
+
+void create_note(double timestep,char midi,double thislevel,int on,FILE *fp)
+{
+	register unsigned char buffer;
+	unsigned int timedata;
+	char velocity;
+	timedata = (unsigned int)round(timestep * 1000.0);	/* TIME IN mS */
+	velocity = (char)round(thislevel * 127.0);
+	WriteVarLen(timedata,fp);
+	if (on)
+		buffer = MIDI_NOTE_ON;
+	else
+		buffer = MIDI_NOTE_OFF;
+	putc(buffer,fp);
+	buffer = midi;
+	putc(buffer,fp);
+	buffer = velocity;
+	putc(buffer,fp);
+}
+
+/*********************** CONVERT FRQ TO MIDI ***********/
+
+char HzToMidi (double frq) {
+	double dmidi;
+	char midi;
+	if (frq < LOW_A) {
+		frq = LOW_A;
+	}
+   	dmidi = frq / LOW_A;
+	dmidi = (log10(dmidi) * CONVERT_LOG10_TO_LOG2 * 12.0) - 3.0;
+	midi  = (char)round(dmidi);
+	if (midi > 127) {
+		midi = 127;
+	} else if(midi < 0) {
+		midi = 0;
+	}
+	return midi;
+}
+
+/************************** GET_FLOAT_FROM_WITHIN_STRING **************************
+ * takes a pointer TO A POINTER to a string. If it succeeds in finding 
+ * a float it returns the float value (*val), and it's new position in the
+ * string (*str).
+ */
+
+int  get_float_from_within_string(char **str,double *val)
+{
+	char   *p, *valstart;
+	int    decimal_point_cnt = 0, has_digits = 0;
+	p = *str;
+	while(isspace(*p))
+		p++;
+	valstart = p;	
+	switch(*p) {
+	case('-'):						break;
+	case('.'): decimal_point_cnt=1;	break;
+	default:
+		if(!isdigit(*p))
+			return(FALSE);
+		has_digits = TRUE;
+		break;
+	}
+	p++;		
+	while(!isspace(*p) && *p!=NEWLINE && *p!=ENDOFSTR) {
+		if(isdigit(*p))
+			has_digits = TRUE;
+		else if(*p == '.') {
+			if(++decimal_point_cnt>1)
+				return(FALSE);
+		} else
+			return(FALSE);
+		p++;
+	}
+	if(!has_digits || sscanf(valstart,"%lf",val)!=1)
+		return(FALSE);
+	*str = p;
+	return(TRUE);
+}
+
+/*********************** CALCULATE NUMBER OF DATA BYTES TO FOLLOW ***********/
+
+int midi_data_bytes_in_midi_track(int infiledatalen,double *seqdata,double staccato)
+{
+	double thistime, nexttime, timestep, stacdur; 
+	double lasttime = 0.0;
+	unsigned int timedata;
+	unsigned int cnt = 0;
+	int on = 1;
+	int n,m;
+	for(n=0,m=1;n < infiledatalen * 4;n+=2,m+=2) {
+		thistime  = seqdata[n];
+		timestep  = thistime - lasttime;
+		lasttime = thistime;
+		if (on) {
+			timedata = (unsigned int)round(timestep * 1000.0);	/* TIME IN mS */
+			cnt += CalcVarLen(timedata);
+			cnt += 3;					/* MIDI status + key + velocity */
+			if (staccato > 0.0) {
+				if(m+4 < infiledatalen) {
+					nexttime = seqdata[m+4];
+					stacdur = (nexttime - thistime)/2.0;
+					stacdur = min(stacdur,staccato);
+				} else {
+					stacdur = staccato;
+				}
+				timedata = (unsigned int)round(stacdur * 1000.0);
+				cnt += CalcVarLen(timedata);
+				cnt += 3;
+				lasttime = thistime + stacdur;
+			}
+			on = 0;
+		} else {
+			if (staccato <= 0.0) {
+				timedata = (unsigned int)round(timestep * 1000.0);
+				cnt += CalcVarLen(timedata);
+				cnt += 3;
+				lasttime = thistime;
+			}
+			on = 1;
+		}
+	}
+	cnt += 3;		/* Add Track end bytes */
+	return cnt;
+}
+
+void Write_ThisIsAMIDI_PC_header(unsigned int total_bytes_in_file,FILE *fp)
+{
+	register char buffer;
+	buffer = 82;	/* R */
+	putc(buffer,fp);
+	buffer = 73;	/* I */
+	putc(buffer,fp);
+	buffer = 70;	/* F */
+	putc(buffer,fp);
+	buffer = 70;	/* F */
+	putc(buffer,fp);
+	WriteNormalLong(total_bytes_in_file,fp);
+	buffer = 82;	/* R */
+	putc(buffer,fp);
+	buffer = 77;	/* M */
+	putc(buffer,fp);
+	buffer = 73;	/* I */
+	putc(buffer,fp);
+	buffer = 68;	/* D */
+	putc(buffer,fp);
+}
+
+//#ifndef round
+
+static int twround(double d)
+{
+	d += 0.5;
+	return (int)floor(d);
+}
+
+//endif

+ 1505 - 0
dev/standnew/distcut.c

@@ -0,0 +1,1505 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <tkglobals.h>
+#include <pnames.h>
+#include <filetype.h>
+#include <processno.h>
+#include <modeno.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <math.h>
+#include <mixxcon.h>
+#include <osbind.h>
+#include <standalone.h>
+#include <ctype.h>
+#include <sfsys.h>
+#include <string.h>
+#include <srates.h>
+
+
+#ifdef unix
+#define round(x) lround((x))
+#endif
+
+#define	fileno ringsize
+#define ebuflen rampbrksize
+#define badfile is_rectified
+
+char errstr[2400];
+
+int anal_infiles = 1;
+int	sloom = 0;
+int sloombatch = 0;
+
+const char* cdp_version = "6.1.0";
+
+//CDP LIB REPLACEMENTS
+static int check_gate_param_validity_and_consistency(dataptr dz);
+static int setup_distcut_application(dataptr dz);
+static int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+static int parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int setup_distcut_param_ranges_and_defaults(dataptr dz);
+static int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int open_next_outfile(dataptr dz);
+static int setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int establish_application(dataptr dz);
+static int initialise_vflags(dataptr dz);
+static int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int mark_parameter_types(dataptr dz,aplptr ap);
+static int assign_file_data_storage(int infilecnt,dataptr dz);
+static int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+static int get_the_mode_from_cmdline(char *str,dataptr dz);
+static int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt);
+static int create_distcut_sndbufs1(dataptr dz);
+static int create_distcut_sndbufs2(dataptr dz);
+static int preprocess_distcut(dataptr dz);
+static int distcut(dataptr dz);
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status;
+	dataptr dz = NULL;
+	char **cmdline;
+	int  cmdlinecnt;
+	int n;
+	aplptr ap;
+	int is_launched = FALSE;
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+						/* CHECK FOR SOUNDLOOM */
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {					// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc == 2) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+	}
+	if(!sloom) {
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		dz->maxmode = 2;
+		if((exit_status = get_the_mode_from_cmdline(cmdline[0],dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);
+		}
+		cmdline++;
+		cmdlinecnt--;
+		// setup_particular_application =
+		if((exit_status = setup_distcut_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+
+	// parse_infile_and_hone_type() = 
+	if((exit_status = parse_infile_and_check_type(cmdline,dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// setup_param_ranges_and_defaults() =
+	if((exit_status = setup_distcut_param_ranges_and_defaults(dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// open_first_infile		CDP LIB
+	if((exit_status = open_first_infile(cmdline[0],dz))<0) {	
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);	
+		return(FAILED);
+	}
+	cmdlinecnt--;
+	cmdline++;
+
+//	handle_extra_infiles() : redundant
+	// handle_outfile() = 
+	if((exit_status = handle_the_outfile(&cmdlinecnt,&cmdline,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+//	handle_formants()			redundant
+//	handle_formant_quiksearch()	redundant
+//	handle_special_data()		redundant
+ 
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+//	check_param_validity_and_consistency() : redundant
+
+	is_launched = TRUE;
+	dz->bufcnt = 1;
+	if((dz->sampbuf = (float **)malloc(sizeof(float *) * (dz->bufcnt+1)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->sbufptr = (float **)malloc(sizeof(float *) * dz->bufcnt))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffer pointers.\n");
+		return(MEMORY_ERROR);
+	}
+	for(n = 0;n <dz->bufcnt; n++)
+		dz->sampbuf[n] = dz->sbufptr[n] = (float *)0;
+	dz->sampbuf[n] = (float *)0;
+
+	if((exit_status = create_distcut_sndbufs1(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//param_preprocess ......
+	if((exit_status = preprocess_distcut(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+	//create_sndbufs =
+	if((exit_status = create_distcut_sndbufs2(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//spec_process_file =
+	if((exit_status = open_next_outfile(dz))<0)			//	Create first outfile
+		return exit_status;
+	if((exit_status = distcut(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if(!dz->badfile) {
+		if((exit_status = complete_output(dz))<0) {									// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);		// CDP LIB
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc, brkcnt;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	brkcnt = tipc;
+	//THERE ARE NO INPUTFILE brktables USED IN THIS PROCESS
+	if(brkcnt>0) {
+		if((exit_status = setup_and_init_input_brktable_constants(dz,brkcnt))<0)			  
+			return(exit_status);
+	}
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+		return(exit_status);
+	
+	// establish_infile_constants() replaced by
+	dz->infilecnt = 1;
+	//establish_bufptrs_and_extra_buffers():
+	return(FINISHED);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}						 		/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_OUTFILE *********************/
+
+int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status;
+	char *filename = (*cmdline)[0], *p;
+	if(filename[0]=='-' && filename[1]=='f') {
+		dz->floatsam_output = 1;
+		dz->true_outfile_stype = SAMP_FLOAT;
+		filename+= 2;
+	}
+	if(!sloom) {
+		if(file_has_invalid_startchar(filename) || value_is_numeric(filename)) {
+			sprintf(errstr,"Outfile name %s has invalid start character(s) or looks too much like a number.\n",filename);
+			return(DATA_ERROR);
+		}
+	}
+	strcpy(dz->outfilename,filename);	   
+	p = filename + strlen(filename);
+	p--;
+	while(p > filename) {
+		if(*p == '.') {
+			*p = ENDOFSTR;		//	Snip off any extension
+			break;
+		}
+		p--;
+	}
+	if(sloom) {					//	If sloom, snip off trailing zero
+		p = filename + strlen(filename);
+		p--;	
+		*p = ENDOFSTR;
+	}
+	if(dz->wordstor!=NULL)
+		free_wordstors(dz);
+	dz->all_words = 0;
+	if((exit_status = store_filename(filename,dz))<0)
+		return(exit_status);
+	dz->fileno = 0;
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/************************ OPEN_NEXT_OUTFILE *********************/
+
+int open_next_outfile(dataptr dz)
+{
+	int exit_status;
+	char filename[400], temp[16];
+	if(dz->fileno > 0) {
+		if((exit_status = headwrite(dz->ofd,dz))<0)
+			return(exit_status);
+		if((exit_status = reset_peak_finder(dz))<0)
+			return(exit_status);
+		if(sndcloseEx(dz->ofd) < 0) {
+			fprintf(stdout,"WARNING: Can't close output soundfile %s\n",dz->outfilename);
+			fflush(stdout);
+		}
+		dz->ofd = -1;
+		fprintf(stdout,"INFO: Writing File %d\n",dz->fileno);
+		fflush(stdout);
+	}
+	strcpy(filename,dz->wordstor[0]);
+	sprintf(temp,"%d",dz->fileno);
+	strcat(filename,temp);
+	strcat(filename,".wav");
+	strcpy(dz->outfilename,filename);
+	if((exit_status = create_sized_outfile(dz->outfilename,dz))<0)
+		return(exit_status);
+	dz->fileno++;
+	return(FINISHED);
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/************************* SETUP_DISTCUT_APPLICATION *******************/
+
+int setup_distcut_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	// SEE parstruct FOR EXPLANATION of next 2 functions
+	if(dz->mode == 0)
+		exit_status = set_param_data(ap,0   ,3,2,"I0D");
+	else
+		exit_status = set_param_data(ap,0   ,3,3,"IID");
+	if(exit_status<0)
+		return(FAILED);
+	if((exit_status = set_vflgs(ap,"c",1,"d","",0,0,""))<0)
+		return(FAILED);
+	// set_legal_infile_structure -->
+	dz->has_otherfile = FALSE;
+	// assign_process_logic -->
+	dz->input_data_type = SNDFILES_ONLY;
+	dz->process_type	= UNEQUAL_SNDFILE;	
+	dz->outfiletype  	= SNDFILE_OUT;
+	return application_init(dz);	//GLOBAL
+}
+
+/************************* PARSE_INFILE_AND_CHECK_TYPE *******************/
+
+int parse_infile_and_check_type(char **cmdline,dataptr dz)
+{
+	int exit_status;
+	infileptr infile_info;
+	if(!sloom) {
+		if((infile_info = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for infile structure to test file data.");
+			return(MEMORY_ERROR);
+		} else if((exit_status = cdparse(cmdline[0],infile_info))<0) {
+			sprintf(errstr,"Failed to parse input file %s\n",cmdline[0]);
+			return(PROGRAM_ERROR);
+		} else if(infile_info->filetype != SNDFILE)  {
+			sprintf(errstr,"File %s is not of correct type\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if(infile_info->channels != 1)  {
+			sprintf(errstr,"File %s is not of correct type (must be mono)\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if((exit_status = copy_parse_info_to_main_structure(infile_info,dz))<0) {
+			sprintf(errstr,"Failed to copy file parsing information\n");
+			return(PROGRAM_ERROR);
+		}
+		free(infile_info);
+	}
+	return(FINISHED);
+}
+
+/************************* SETUP_DISTCUT_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_distcut_param_ranges_and_defaults(dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	// NB total_input_param_cnt is > 0 !!!
+	if((exit_status = setup_input_param_range_stores(ap->total_input_param_cnt,ap))<0)
+		return(FAILED);
+	// get_param_ranges()
+	ap->lo[DCUT_CNT]	= 1;
+	ap->hi[DCUT_CNT]	= 1000;
+	ap->default_val[DCUT_CNT]	= 64;
+	if(dz->mode==1) {
+		ap->lo[DCUT_STP]	= 1;
+		ap->hi[DCUT_STP]	= 1000;
+		ap->default_val[DCUT_STP]	= 64;
+	}
+	ap->lo[DCUT_EXP]	= 0.02;
+	ap->hi[DCUT_EXP]	= 50;
+	ap->default_val[DCUT_EXP] = 1.0;
+	ap->lo[DCUT_LIM]	= 0;
+	ap->hi[DCUT_LIM]	= 96;
+	ap->default_val[DCUT_LIM] = 40;
+	dz->maxmode = 2;
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_distcut_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int read_special_data(char *str,dataptr dz)	
+{
+	return(FINISHED);
+}
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+	usage2("distcut");
+	return(USAGE_ONLY);
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if(!strcmp(prog_identifier_from_cmdline,"distcut"))				dz->process = DISTCUT;
+	else {
+		sprintf(errstr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/******************************** SETUP_AND_INIT_INPUT_BRKTABLE_CONSTANTS ********************************/
+
+int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt)
+{	
+	int n;
+	if((dz->brk      = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<brkcnt;n++) {
+		dz->brk[n]     = NULL;
+		dz->brkptr[n]  = NULL;
+		dz->brkinit[n] = 0;
+		dz->brksize[n] = 0;
+	}
+	return(FINISHED);
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+	if(!strcmp(str,"distcut")) {
+		fprintf(stderr,
+	    "USAGE:\n"
+	    "distcut distcut 1 infile generic_outfilename cyclecnt exp [-climit]\n"
+	    "OR:\n"
+	    "distcut distcut 2 infile generic_outfilename cyclecnt cyclestep exp [-climit]\n"
+		"\n"
+		"Cut sound into elements with falling envelope.\n"
+		"\n"
+		"CYCLECNT  number of wavesets in each outfile.\n"
+		"CYCLESTEP number of wavesets steps from start of one group to start of next.\n"
+		"          (In mode 1 : cyclestep = cyclecnt : waveset-groups abutted and disjunct).\n"
+		"EXP       Envelope Decay shape. 1 linear : >1 more rapid decay : < 1 less rapid.\n"
+		"LIMIT     Minimum level of output events to accept (value 70 = -70dB).\n"
+		"\n");
+	} else
+		fprintf(stdout,"Unknown option '%s'\n",str);
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	fprintf(stderr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/*************************** PREPROCESS_DISTCUT **************************/
+
+int preprocess_distcut(dataptr dz) {
+
+	int exit_status, wavesetcnt = 0, wvlencnt = 0, kk, k, j, jj, phase, initial_phase = 0, done;
+	float *ibuf = dz->sampbuf[0];
+	double time = 0.0 , val, srate = (double)dz->infile->srate;
+	int *envlen = NULL, *waveset_len = NULL, *envstart = NULL;
+	int envcnt = 0, maxenvset = 0, waveset_sampcnt, env_sampcnt = 0, bufpos, waveset_group_start, waveset_group_len;
+
+	if(flteq(dz->param[DCUT_LIM],0.0))
+		dz->zeroset = 0;
+	else {
+		dz->zeroset = 1;
+		val = -dz->param[DCUT_LIM];
+		if(val<=MIN_DB_ON_16_BIT)
+			val = 0.0;
+		else {
+			val  = -(val);
+			val /= 20.0;
+			val  = pow(10.0,val);
+			val  = 1.0/(val);
+		}
+		dz->param[DCUT_LIM] = val;
+	}
+	if(dz->brksize[DCUT_CNT]) {
+		if((exit_status = read_value_from_brktable(time,DCUT_CNT,dz))<0)
+			return(exit_status);
+	}
+	for(kk=0;kk<2;kk++) {
+		if((sndseekEx(dz->ifd[0],0,0) < 0)){
+			sprintf(errstr,"sndseek failed\n");
+			return SYSTEM_ERROR;
+		}
+		dz->total_samps_read = 0;
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+		bufpos = 0;
+		waveset_sampcnt = 0;
+		dz->samps_left = dz->insams[0];
+		
+		//	FIND INITIAL PHASE
+
+		if(kk==0) {
+			phase = 0;
+			while(bufpos < dz->ssampsread) {
+				if(ibuf[bufpos] > 0) {
+					initial_phase = 1;
+					phase = 1;
+				} else if(ibuf[bufpos] < 0) {
+					initial_phase = -1;
+					phase = -1;
+				}
+				waveset_sampcnt++;
+				if(++bufpos >= dz->buflen) {
+					if((exit_status = read_samps(ibuf,dz))<0)
+						return(exit_status);
+					bufpos = 0;
+				}
+				if(phase != 0)
+					break;
+			}
+			if(phase == 0) {
+				sprintf(errstr,"No sound found in source soundfile.\n");
+				return DATA_ERROR;
+			}
+		} else
+			phase = initial_phase;
+		
+		//	READ AND COUNT WAVESETS
+
+		while(bufpos < dz->ssampsread) {
+			switch(initial_phase) {
+			case(1):
+				switch(phase) {
+				case(1):
+					if(ibuf[bufpos] >= 0)
+						waveset_sampcnt++;
+					else {
+						phase = -1;
+						waveset_sampcnt++;
+					}
+					break;
+				case(-1):
+					if(ibuf[bufpos] <= 0)
+						waveset_sampcnt++;
+					else {												//	Waveset completed	
+						wavesetcnt++;									//	Count the wavesets
+						if(kk == 0)										//	FIRST PASS
+							waveset_sampcnt = 0;						//	Reset waveset-sample-count
+
+						else {											//	SECOND_PASS	
+							if(dz->mode==0) {								//	Mode 0 stores lengths of waveset-groups to use
+								env_sampcnt += waveset_sampcnt;				//	Add wavesetcount to overall envelope-unit sample-count
+								if(wavesetcnt >= dz->iparam[DCUT_CNT]) {	//	If we have enough wavesets for the envelope
+									envlen[envcnt++] = env_sampcnt;			//	Store the envelope-unit sample-count
+									maxenvset = max(maxenvset,env_sampcnt);	//	Find largest envelope-unit sample-count
+									env_sampcnt = 0;						//	Rest envelope-unit sample-count
+									wavesetcnt = 0;							//	Reset waveset count
+									if(dz->brksize[DCUT_CNT]) {				//	If ness: find the new value of waveset-grouping
+										time = (double)(dz->total_samps_read + bufpos)/srate;
+										if((exit_status = read_value_from_brktable(time,DCUT_CNT,dz))<0)
+											return(exit_status);
+									}
+								}
+							} else											//	Mode 1 initially just stores size of wavesets
+								waveset_len[wvlencnt++] = waveset_sampcnt;
+						}
+						waveset_sampcnt = 0;							//	Reset waveset-sample-count
+						phase = initial_phase;							//	Reset phase
+					}
+					break;
+				}
+				break;
+			case(-1):
+				switch(phase) {
+				case(-1):
+					if(ibuf[bufpos] <= 0)
+						waveset_sampcnt++;
+					else {
+						phase = 1;
+						waveset_sampcnt++;
+					}
+					break;
+				case(1):
+					if(ibuf[bufpos] >= 0)
+						waveset_sampcnt++;
+					else {												//	Waveset completed	
+						wavesetcnt++;									//	Count the wavesets
+
+						if(kk == 0)										//	FIRST PASS
+							waveset_sampcnt = 0;						//	Reset waveset-sample-count
+
+						else {											//	SECOND_PASS	
+							if(dz->mode==0) {								//	Mode 0 stores lengths of waveset-groups to use
+								env_sampcnt += waveset_sampcnt;				//	Add wavesetcount to overall envelope-unit sample-count
+								if(wavesetcnt >= dz->iparam[DCUT_CNT]) {	//	If we have enough wavesets for the envelope
+									envlen[envcnt++] = env_sampcnt;			//	Store the envelope-unit sample-count
+									maxenvset = max(maxenvset,env_sampcnt);	//	Find largest envelope-unit sample-count
+									env_sampcnt = 0;						//	Rest envelope-unit sample-count
+									wavesetcnt = 0;							//	Reset waveset count
+									if(dz->brksize[DCUT_CNT]) {				//	If ness: find the new value of waveset-grouping
+										time = (double)(dz->total_samps_read + bufpos)/srate;
+										if((exit_status = read_value_from_brktable(time,DCUT_CNT,dz))<0)
+											return(exit_status);
+									}
+								}
+							} else											//	Mode 1 initially just stores size of wavesets
+								waveset_len[wvlencnt++] = waveset_sampcnt;
+						}
+						waveset_sampcnt = 0;							//	Reset waveset-sample-count
+						phase = initial_phase;							//	Reset phase
+					}
+					break;
+				}
+				break;
+			}
+			if(++bufpos >= dz->buflen) {
+				if((exit_status = read_samps(ibuf,dz))<0)
+					return(exit_status);
+				bufpos = 0;
+			}
+		}
+		if(kk == 0) {
+			if(wavesetcnt <= 0) {
+				sprintf(errstr,"No complete wavesets found.\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode == 1) {
+				if((dz->lparray = (int **)malloc(3 * sizeof(int *)))==NULL) {
+					sprintf(errstr,"INSUFFICIENT MEMORY for internal int arrays.\n");
+					return(MEMORY_ERROR);
+				}
+			} else {
+				if((dz->lparray = (int **)malloc(sizeof(int *)))==NULL) {
+					sprintf(errstr,"INSUFFICIENT MEMORY for internal int arrays.\n");
+					return(MEMORY_ERROR);
+				}
+			}
+			if((dz->lparray[0] = (int *)malloc(wavesetcnt * sizeof(int)))==NULL) {
+				sprintf(errstr,"INSUFFICIENT MEMORY for internal int arrays.\n");
+				return(MEMORY_ERROR);
+			}
+			envlen = dz->lparray[0];
+			if(dz->mode == 1) {
+				if((dz->lparray[1] = (int *)malloc((wavesetcnt+1) * sizeof(int)))==NULL) {
+					sprintf(errstr,"INSUFFICIENT MEMORY for internal int arrays.\n");
+					return(MEMORY_ERROR);
+				}
+				if((dz->lparray[2] = (int *)malloc(wavesetcnt * sizeof(int)))==NULL) {
+					sprintf(errstr,"INSUFFICIENT MEMORY for internal int arrays.\n");
+					return(MEMORY_ERROR);
+				}
+				waveset_len = dz->lparray[2];
+				envstart = dz->lparray[1];
+			}
+		} else {
+			if(dz->mode == 0) {
+				if(envcnt <= 0) {
+					sprintf(errstr,"No complete set of wavesets found.\n");
+					return(DATA_ERROR);
+				}
+			} else {				//	In mode 1, use lengths of individual wavesets to calculate envelope sizes, and start-samples
+				done = 0;
+				time = 0.0;
+				waveset_group_start = 0;						//	Sample-time of start of current waveset-group
+				while(waveset_group_start < dz->insams[0]) {
+					if(dz->brksize[DCUT_CNT]) {
+						if((exit_status = read_value_from_brktable(time,DCUT_CNT,dz))<0)
+							return(exit_status);
+					}
+					if(dz->brksize[DCUT_STP]) {
+						if((exit_status = read_value_from_brktable(time,DCUT_STP,dz))<0)
+							return(exit_status);
+					}
+					envstart[envcnt] = waveset_group_start;		//	Start position (in samples) = (0 or) end of previous step
+					for(k=0,j = waveset_group_start;k < dz->iparam[DCUT_STP];k++,j++) {
+						if(j >= wvlencnt) {						//	Ran off end of wavesets
+							done = 1;
+							break;
+						}
+						waveset_group_start += waveset_len[j];	//	Advance to next start position, summing sample_cnt as we go
+					}
+					if(done)
+						break;
+					waveset_group_len = 0;						//	Go back to start of waveset_group: advance by size of envelope-group
+					for(k=0,jj = waveset_group_start;k < dz->iparam[DCUT_CNT];k++,jj++) {
+						if(jj >= wvlencnt) {					//	Ran off end of wavesets
+							done = 1;
+							break;
+						}
+						waveset_group_len += waveset_len[j];	//	Summing samples as we go
+					}
+					if(done)
+						break;
+					envlen[envcnt] = waveset_group_len;			//	This gives us the length of the envelope here
+					maxenvset = max(maxenvset,waveset_group_len);
+					waveset_group_start = j;					//	Reset the number of the waveset to start of next group
+					time = (double)(waveset_group_start)/srate;
+					envcnt++;
+				}
+				envstart[envcnt] = envstart[envcnt-1];			//	Wrap-around point so no anomalous read at table end
+			}
+			dz->itemcnt = envcnt;		//	Store number of envelopes to extract
+			dz->ebuflen = maxenvset;	//	Store samplesize of maximum envelope-group
+		}
+	}		
+	return FINISHED;
+}
+
+/*************************** CREATE_DISTCUT_SNDBUFS **************************/
+
+int create_distcut_sndbufs1(dataptr dz)
+{
+	int framesize = F_SECSIZE;
+	int bigbufsize;
+	if(dz->sbufptr == 0 || dz->sampbuf==0) {
+		sprintf(errstr,"buffer pointers not allocated: create_sndbufs()\n");
+		return(PROGRAM_ERROR);
+	}
+	bigbufsize = framesize;	// SAFETY
+	dz->buflen = bigbufsize;
+	bigbufsize  *= sizeof(float);
+	if((dz->bigbuf = (float *)malloc(bigbufsize * sizeof(float))) == NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to create sound buffers.\n");
+		return(PROGRAM_ERROR);
+	}
+	dz->sbufptr[0] = dz->sampbuf[0] = dz->bigbuf;
+	dz->sampbuf[1] = dz->sampbuf[0] + dz->buflen;
+	return(FINISHED);
+}
+
+/*************************** CREATE_DISTCUT_SNDBUFS **************************/
+
+int create_distcut_sndbufs2(dataptr dz)
+{
+	int framesize = F_SECSIZE;
+	int bigbufsize;
+	bigbufsize = dz->ebuflen/framesize;	// SAFETY
+	if(bigbufsize * framesize != dz->ebuflen)
+		bigbufsize++;
+	bigbufsize *= framesize;
+	dz->buflen = bigbufsize;
+	bigbufsize += 16;	//	SAFETY
+	if((dz->sampbuf[1] = (float *)malloc(bigbufsize * sizeof(float))) == NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to create sound buffers.\n");
+		return(PROGRAM_ERROR);
+	}
+	dz->sbufptr[1] = dz->sampbuf[1];
+	dz->sampbuf[2] = dz->sampbuf[1] + dz->buflen;
+	return(FINISHED);
+}
+
+/*************************** DISTCUT **************************/
+
+int distcut(dataptr dz)
+{
+	int exit_status, n;
+	int samptime;
+	float *buf = dz->sampbuf[1];
+	double ee, maxsamp, time = 0.0, srate = (double)dz->infile->srate;
+	int *envsize = dz->lparray[0], bufpos, *envstart = NULL;
+	if(dz->mode==1)
+		envstart = dz->lparray[1];
+	dz->badfile = 0;
+	samptime = 0;											//	Start at start of sound;
+	for(n = 0;n < dz->itemcnt; n++) {						//	For every envelope-group needed
+		memset((char *)buf,0,dz->ebuflen * sizeof(float));	//	preset obuf to 0
+		if((sndseekEx(dz->ifd[0],samptime,0) < 0)) {		//	Seek to start of envelope group
+			sprintf(errstr,"sndseek failed\n");
+			return SYSTEM_ERROR;
+		}
+		dz->buflen = envsize[n];
+		if((exit_status = read_samps(buf,dz))<0)
+			return(exit_status);
+
+		for(bufpos=0;bufpos < envsize[n];bufpos++) {		//	Envelope the samples
+			ee = 1.0 - ((double)bufpos/(double)envsize[n]);
+			ee = pow(ee,dz->param[DCUT_EXP]);
+			buf[bufpos] = (float)(buf[bufpos] * ee);
+		}													//	Write envelope-group to file
+		if(dz->zeroset) {
+			maxsamp = 0.0;
+			for(bufpos=0;bufpos < envsize[n];bufpos++) {
+				if(fabs(buf[bufpos]) > maxsamp)
+					maxsamp = fabs(buf[bufpos]);
+			}
+			if(maxsamp < dz->param[DCUT_LIM]) {
+				dz->badfile = envsize[n];
+				continue;
+			}
+		}
+		dz->badfile = 0;
+		if((exit_status = write_samps(buf,envsize[n],dz))<0)
+			return(exit_status);	
+		if(n < dz->itemcnt - 1) {
+			if((exit_status = open_next_outfile(dz))<0)			//	Get next file
+				return exit_status;
+		}
+		if(dz->mode==0)
+			samptime += envsize[n];								//	Advance to next envelope-group of samples
+		else
+			samptime = envstart[n+1];							
+		if(dz->brksize[DCUT_EXP]) {
+			time = (double)samptime/srate;						//	If EXP varies, read brktable
+			if((exit_status = read_value_from_brktable(time,DCUT_EXP,dz))<0)
+				return(exit_status);
+		}
+	}
+	if(dz->badfile) {											//	If the last file opened was not written to (too low level)
+		if((exit_status = write_samps(buf,dz->badfile,dz))<0)	//	Write data to it: this allows sfsys to truncate the file in sndcloseEx
+			return(exit_status);								//	Then delete it
+		if(sndunlink(dz->ofd) < 0) {
+			fprintf(stdout,"WARNING: Can't set output soundfile %s for deletion.\n",dz->outfilename);
+			fflush(stdout);
+		}
+		if(sndcloseEx(dz->ofd) < 0) {
+			fprintf(stdout,"WARNING: Can't close output soundfile %s :%s\n",dz->outfilename,sferrstr());        //RWD sferrstr is function
+			fflush(stdout);
+		}
+		dz->ofd = -1;
+	}
+	return FINISHED;
+}
+
+/****************************** GET_MODE *********************************/
+
+int get_the_mode_from_cmdline(char *str,dataptr dz)
+{
+	char temp[200], *p;
+	if(sscanf(str,"%s",temp)!=1) {
+		sprintf(errstr,"Cannot read mode of program.\n");
+		return(USAGE_ONLY);
+	}
+	p = temp + strlen(temp) - 1;
+	while(p >= temp) {
+		if(!isdigit(*p)) {
+			fprintf(stderr,"Invalid mode of program entered.\n");
+			return(USAGE_ONLY);
+		}
+		p--;
+	}
+	if(sscanf(str,"%d",&dz->mode)!=1) {
+		fprintf(stderr,"Cannot read mode of program.\n");
+		return(USAGE_ONLY);
+	}
+	if(dz->mode <= 0 || dz->mode > dz->maxmode) {
+		fprintf(stderr,"Program mode value [%d] is out of range [1 - %d].\n",dz->mode,dz->maxmode);
+		return(USAGE_ONLY);
+	}
+	dz->mode--;		/* CHANGE TO INTERNAL REPRESENTATION OF MODE NO */
+	return(FINISHED);
+}
+

+ 1968 - 0
dev/standnew/distmark.c

@@ -0,0 +1,1968 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <tkglobals.h>
+#include <pnames.h>
+#include <filetype.h>
+#include <processno.h>
+#include <modeno.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <math.h>
+#include <mixxcon.h>
+#include <osbind.h>
+#include <standalone.h>
+#include <ctype.h>
+#include <sfsys.h>
+#include <string.h>
+#include <srates.h>
+
+
+#ifdef unix
+#define round(x) lround((x))
+#endif
+
+#define minstep scalefact
+#define stepstorecnt rampbrksize
+#define maxstep is_sharp
+
+char errstr[2400];
+
+int anal_infiles = 1;
+int	sloom = 0;
+int sloombatch = 0;
+
+#define DMARK_CNT 0
+#define DMARK_STR 1
+#define DMARK_RND 2
+#define DMARK_GAIN 3
+
+#define DMARK_FLIP 0
+#define DMARK_TAIL 1
+
+#define SAFETY 16
+
+const char* cdp_version = "6.1.0";
+
+//CDP LIB REPLACEMENTS
+static int check_distmark_param_validity_and_consistency(dataptr dz);
+static int setup_distmark_application(dataptr dz);
+static int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+static int parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int setup_distmark_param_ranges_and_defaults(dataptr dz);
+static int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int establish_application(dataptr dz);
+static int initialise_vflags(dataptr dz);
+static int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int mark_parameter_types(dataptr dz,aplptr ap);
+static int assign_file_data_storage(int infilecnt,dataptr dz);
+static int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+static int get_the_mode_from_cmdline(char *str,dataptr dz);
+static int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt);
+static int create_distmark_sndbufs(dataptr dz);
+static int create_distmark_sndbufs2(dataptr dz);
+static int preprocess_distmark(dataptr dz);
+static int handle_the_special_data(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int read_mark_data(char *filename,dataptr dz);
+static int get_timeinterpcnt(int lastgplen,int gplen,int markstep,double time,dataptr dz);
+static int distmark(dataptr dz);
+static int distmark2(dataptr dz);
+static int  get_the_mode_no(char *str, dataptr dz);
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status;
+	dataptr dz = NULL;
+	char **cmdline;
+	int  cmdlinecnt;
+	int n;
+	aplptr ap;
+	int is_launched = FALSE;
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+						/* CHECK FOR SOUNDLOOM */
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {					// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc == 2) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+	}
+	if(!sloom) {
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		dz->maxmode = 2;
+		if(cmdlinecnt <= 0) {
+			sprintf(errstr,"Too few commandline parameters.\n");
+			return(FAILED);
+		}
+		if((get_the_mode_no(cmdline[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		// setup_particular_application =
+		if((exit_status = setup_distmark_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+
+	// parse_infile_and_hone_type() = 
+	if((exit_status = parse_infile_and_check_type(cmdline,dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// setup_param_ranges_and_defaults() =
+	if((exit_status = setup_distmark_param_ranges_and_defaults(dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// open_first_infile		CDP LIB
+	if((exit_status = open_first_infile(cmdline[0],dz))<0) {	
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);	
+		return(FAILED);
+	}
+	cmdlinecnt--;
+	cmdline++;
+
+//	handle_extra_infiles() : redundant
+	// handle_outfile() = 
+	if((exit_status = handle_the_outfile(&cmdlinecnt,&cmdline,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+//	handle_formants()			redundant
+//	handle_formant_quiksearch()	redundant
+//	handle_special_data ............
+	if((exit_status = handle_the_special_data(&cmdlinecnt,&cmdline,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+//	check_param_validity_and_consistency .......
+	if((exit_status = check_distmark_param_validity_and_consistency(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	is_launched = TRUE;
+ 	dz->bufcnt = 7;
+	if((dz->sampbuf = (float **)malloc(sizeof(float *) * (dz->bufcnt+1)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->sbufptr = (float **)malloc(sizeof(float *) * dz->bufcnt))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffer pointers.\n");
+		return(MEMORY_ERROR);
+	}
+	for(n = 0;n <dz->bufcnt; n++)
+		dz->sampbuf[n] = dz->sbufptr[n] = (float *)0;
+	dz->sampbuf[n] = (float *)0;
+
+	if((exit_status = create_distmark_sndbufs(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//param_preprocess ......
+	if((exit_status = preprocess_distmark(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = create_distmark_sndbufs2(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	switch(dz->mode) {
+	case(0):
+		if((exit_status = distmark(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		break;
+	case(1):
+		if((exit_status = distmark2(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		break;
+	}
+	if((exit_status = complete_output(dz))<0) {									// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);		// CDP LIB
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc, brkcnt;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	brkcnt = tipc;
+	//THERE ARE NO INPUTFILE brktables USED IN THIS PROCESS
+	if(brkcnt>0) {
+		if((exit_status = setup_and_init_input_brktable_constants(dz,brkcnt))<0)			  
+			return(exit_status);
+	}
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+		return(exit_status);
+	
+	// establish_infile_constants() replaced by
+	dz->infilecnt = 1;
+	//establish_bufptrs_and_extra_buffers():
+	return(FINISHED);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}						 		/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_OUTFILE *********************/
+
+int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status;
+	char *filename = (*cmdline)[0];
+	if(filename[0]=='-' && filename[1]=='f') {
+		dz->floatsam_output = 1;
+		dz->true_outfile_stype = SAMP_FLOAT;
+		filename+= 2;
+	}
+	if(!sloom) {
+		if(file_has_invalid_startchar(filename) || value_is_numeric(filename)) {
+			sprintf(errstr,"Outfile name %s has invalid start character(s) or looks too much like a number.\n",filename);
+			return(DATA_ERROR);
+		}
+	}
+	strcpy(dz->outfilename,filename);	   
+	if((exit_status = create_sized_outfile(filename,dz))<0)
+		return(exit_status);
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/************************* SETUP_DISTMARK_APPLICATION *******************/
+
+int setup_distmark_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	// SEE parstruct FOR EXPLANATION of next 2 functions
+	if((exit_status = set_param_data(ap,MARKLIST   ,1,1,"D"))<0)
+		return(FAILED);
+	switch(dz->mode) {
+	case(0):	exit_status = set_vflgs(ap,"sr",2,"DD","ft",2,0,"00");	break;
+	case(1):	exit_status = set_vflgs(ap,"srg",3,"DDD","fa" ,2,0,"00");	break;
+	}
+	// set_legal_infile_structure -->
+	if(exit_status <0)
+		return(FAILED);
+	dz->has_otherfile = FALSE;
+	// assign_process_logic -->
+	dz->input_data_type = SNDFILES_ONLY;
+	dz->process_type	= UNEQUAL_SNDFILE;	
+	dz->outfiletype  	= SNDFILE_OUT;
+	return application_init(dz);	//GLOBAL
+}
+
+/************************* PARSE_INFILE_AND_CHECK_TYPE *******************/
+
+int parse_infile_and_check_type(char **cmdline,dataptr dz)
+{
+	int exit_status;
+	infileptr infile_info;
+	if(!sloom) {
+		if((infile_info = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for infile structure to test file data.");
+			return(MEMORY_ERROR);
+		} else if((exit_status = cdparse(cmdline[0],infile_info))<0) {
+			sprintf(errstr,"Failed to parse input file %s\n",cmdline[0]);
+			return(PROGRAM_ERROR);
+		} else if(infile_info->filetype != SNDFILE)  {
+			sprintf(errstr,"File %s is not of correct type\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if(infile_info->channels != 1)  {
+			sprintf(errstr,"File %s is not of correct type (must be mono)\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if((exit_status = copy_parse_info_to_main_structure(infile_info,dz))<0) {
+			sprintf(errstr,"Failed to copy file parsing information\n");
+			return(PROGRAM_ERROR);
+		}
+		free(infile_info);
+	}
+	return(FINISHED);
+}
+
+/************************* SETUP_DISTMARK_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_distmark_param_ranges_and_defaults(dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	// NB total_input_param_cnt is > 0 !!!
+	if((exit_status = setup_input_param_range_stores(ap->total_input_param_cnt,ap))<0)
+		return(FAILED);
+	// get_param_ranges()
+	ap->lo[DMARK_CNT]	= .5;
+	ap->hi[DMARK_CNT]	= 1000;
+	ap->default_val[DMARK_CNT]	= 5;
+	ap->lo[DMARK_STR]	= 1;
+	ap->hi[DMARK_STR]	= 256;
+	ap->default_val[DMARK_STR]	= 1;
+	ap->lo[DMARK_RND]	= 0;
+	ap->hi[DMARK_RND]	= 1;
+	ap->default_val[DMARK_RND]	= 0;
+	if(dz->mode == 1) {
+		ap->lo[DMARK_GAIN]	= 0.0;
+		ap->hi[DMARK_GAIN]	= 1.0;
+		ap->default_val[DMARK_GAIN]	= 1.0;
+	}
+	dz->maxmode = 2;
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_distmark_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int read_special_data(char *str,dataptr dz)	
+{
+	return(FINISHED);
+}
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+	usage2("distmark");
+	return(USAGE_ONLY);
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if(!strcmp(prog_identifier_from_cmdline,"distmark"))				dz->process = DISTMARK;
+	else {
+		fprintf(stderr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/******************************** SETUP_AND_INIT_INPUT_BRKTABLE_CONSTANTS ********************************/
+
+int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt)
+{	
+	int n;
+	if((dz->brk      = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<brkcnt;n++) {
+		dz->brk[n]     = NULL;
+		dz->brkptr[n]  = NULL;
+		dz->brkinit[n] = 0;
+		dz->brksize[n] = 0;
+	}
+	return(FINISHED);
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+	if(!strcmp(str,"distmark")) {
+		fprintf(stderr,
+	    "USAGE:\n"
+	    "distmark distmark 1 infile outfile marklist unitlen [-ststretch] [-rrand] [-f] [-t]\n"
+	    "distmark distmark 2 infile outfile marklist unitlen [-ststretch] [-rrand] [-f]\n"
+		"\n"
+		"Interpolate between waveset-groups at marked points in MONO soundfile.\n"
+		"In Mode 2 interpolate within ALTERNATE marked blocks.\n"
+		"\n"
+		"MARKLIST List of times within source at which to find waveset-groups.\n"
+		"UNITLEN  (approx) size of waveset group to find (mS). Can vary over time.\n"
+		"         Min UNITLEN < 1/2 of min step between Times in MARKLIST.\n"  
+		"TSTRETCH Timestretch distances between marks, in making output.\n"
+		"RAND     Randomise duration of interpolated wavesets (Range 0 - 1).\n" 
+		"         Randomisation decreases waveset lengths (heard \"pitch\" higher).\n"
+		"-f   Flip phase of alternate wavesets.\n"
+		"-t   Add original (remaining) tail of source sound to output.\n"  
+		"\n");
+	} else
+		fprintf(stdout,"Unknown option '%s'\n",str);
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	fprintf(stderr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/*************************** PREPROCESS_DISTMARK **************************/
+
+int preprocess_distmark(dataptr dz) 
+{
+	int exit_status, seek_forward;
+	float *ibuf = dz->sampbuf[0];
+	double *times = dz->parray[0], mindur, time;
+	int *wavesetbloks, n, m, sampcnt, seccnt, nusampcnt, offset, bufpos, stt, wgstt, wavsetgplen;
+	double srate = (double)dz->infile->srate;
+	if((dz->lparray = (int **)malloc(2 * sizeof(int *)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for Waveset samplecnt stores.\n");
+		return(MEMORY_ERROR);
+	}
+
+	//	Create array big enough to store sizes of each intermediate time-interpd waveset-gp as we step from one mark to next
+
+	if(dz->brksize[DMARK_CNT]) {						//	Get smallest waveset-gp size
+		if((exit_status = get_minvalue_in_brktable(&mindur,DMARK_CNT,dz))<0)
+			return exit_status;
+	} else
+		mindur = dz->param[DMARK_CNT];
+	mindur *= MS_TO_SECS;
+	dz->stepstorecnt = (int)ceil(dz->maxstep/mindur);
+	dz->stepstorecnt *= 8;	//	SAFETY
+	if((dz->lparray[1] = (int *)malloc(dz->stepstorecnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for Waveset startsample store (2).\n");
+		return(MEMORY_ERROR);
+	}
+
+	//	Set up store for true startsample and samplelen of waveset-gp at each time-mark
+
+	if((dz->lparray[0] = (int *)malloc(dz->itemcnt * 2 * sizeof(int)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for Waveset startsample store (2).\n");
+		return(MEMORY_ERROR);
+	}
+	wavesetbloks = dz->lparray[0];
+
+	//	Find exact locations and sizes of wavset-gps to be used
+
+	for(n=0,m=0;n < dz->itemcnt;n++,m+=2) {
+		time = times[n];						//	Go to next timemark in sndfile
+		sampcnt = (int)round(time * srate);
+		seccnt = sampcnt/F_SECSIZE;
+		nusampcnt = seccnt * F_SECSIZE;			//	Curtal to nearest sector boundary (may be unness)
+		offset = sampcnt - nusampcnt;
+		if((sndseekEx(dz->ifd[0],nusampcnt,0))<0) {
+			sprintf(errstr,"sndseek 1 failed.\n");
+			return GOAL_FAILED;
+		}
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+		bufpos = offset;
+		while(ibuf[bufpos] < 0.0) {				//	Search for 1st downward-going waveset start, after "time"
+			if(++bufpos > dz->ssampsread) {
+				sprintf(errstr,"No waveset-group start found (1) at time %lf (Buffer too short?)\n",time);
+				return(GOAL_FAILED);
+			}
+		}
+		while(ibuf[bufpos] >= 0.0) {
+			if(++bufpos > dz->ssampsread) {
+				sprintf(errstr,"No waveset-group start found (2) at time %lf (Buffer too short?)\n",time);
+				return(GOAL_FAILED);
+			}
+		}
+		stt = bufpos;
+		wgstt = nusampcnt + bufpos;				//	Note absolute sample-cnt at start of waveset-gp
+
+		if(dz->brksize[DMARK_CNT]) {					//	Get size of required waveset group at this "time"
+			if((exit_status = read_value_from_brktable(time,DMARK_CNT,dz))<0)
+				return(exit_status);			//	(either fixed param dz->param[0] mS or read brktable val)
+		}
+		wavsetgplen = (int)round(dz->param[DMARK_CNT] * MS_TO_SECS * srate);
+		bufpos += wavsetgplen;
+		if(bufpos >= dz->ssampsread) {
+			sprintf(errstr,"Anomaly in buffer sizing looking for end of waveset-group at time %lf (1)\n",time);
+			return(PROGRAM_ERROR);
+		}
+		seek_forward = 1;
+		while(seek_forward) {
+			while(ibuf[bufpos] < 0.0) {				//	Skip over samples below zero
+				if(++bufpos > dz->ssampsread) {
+					seek_forward = 0;				//	IF run off buf end, try backward seek instead
+					break;
+				}
+			}
+			if(!seek_forward)
+				break;
+			while(ibuf[bufpos] >= 0.0) {			//	Search for 1st downward-going waveset end, after "time"
+				if(++bufpos > dz->ssampsread) {
+					seek_forward = 0;				//	IF run off buf end, try backward seek instead
+					break;
+				}
+			}
+			break;									//	If reached 1st subzero sample after zero-crossing (still seeking forward) break
+		}
+		if(!seek_forward) {							//	Else, seek backwards
+			bufpos = stt + wavsetgplen;
+			while(ibuf[bufpos] >= 0.0) {			//	Searching bkwds, if samps above zero, skip over samples above zero
+				if(--bufpos < stt) {
+					sprintf(errstr,"No waveset-group end found (1) after time %lf\n",time);
+					return(GOAL_FAILED);
+				}
+			}
+			while(ibuf[bufpos] < 0.0) {				//	Search bkwds, skip over samples below zero
+				if(--bufpos < stt) {
+					sprintf(errstr,"No waveset-group end found (2) after time %lf\n",time);
+					return(GOAL_FAILED);
+				}
+			}
+			bufpos++;								//	Go back to last below-zero sample found 
+		}
+		wavesetbloks[m]   = wgstt;					//	Absolute sample position of start of waveset-group
+		wavesetbloks[m+1] = bufpos - stt;			//	Size of waveset group
+	}
+	return FINISHED;
+}
+
+/*************************** CREATE_DISTMARK_SNDBUFS **************************/
+
+int create_distmark_sndbufs(dataptr dz)
+{
+	int framesize = F_SECSIZE;
+	int bigbufsize, doubleframe, seccnt, n;
+	doubleframe = framesize * 2;
+	if(dz->sbufptr == 0 || dz->sampbuf==0) {
+		sprintf(errstr,"buffer pointers not allocated: create_sndbufs()\n");
+		return(PROGRAM_ERROR);
+	}
+	seccnt = dz->buflen/framesize;
+	if(seccnt * framesize < dz->buflen)
+		seccnt++;
+	dz->buflen = seccnt * framesize;			//	Input/output bufs are a multiple of framesize
+	if(dz->buflen2 < doubleframe)				//	Waveset-group processing buffers must be at least 2 framesizes int
+		dz->buflen2 = doubleframe;				//	because of the way seek approximates to framesize boundaries	
+	bigbufsize = dz->buflen * 3;
+	if((dz->bigbuf = (float *)malloc(bigbufsize * sizeof(float))) == NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to create sound buffers.\n");
+		return(PROGRAM_ERROR);
+	}
+	for(n=0; n<3; n++)
+		dz->sbufptr[n] = dz->sampbuf[n] = dz->bigbuf + (n * dz->buflen);
+	return(FINISHED);
+}
+
+int create_distmark_sndbufs2(dataptr dz)
+{
+	int framesize = F_SECSIZE;
+	int bigbufsize, doubleframe, n, m;
+	int *wavesetlens = dz->lparray[0];
+	doubleframe = framesize * 2;
+	dz->buflen2 = 0;
+	for(n = 0,m = 1; n < dz->itemcnt; n++,m+=2)
+		dz->buflen2 = max(dz->buflen2,wavesetlens[m]);
+	dz->buflen2 += SAFETY;
+	if(dz->buflen2 < doubleframe)				//	Waveset-group processing buffers must be at least 2 framesizes int
+		dz->buflen2 = doubleframe;				//	because of the way seek approximates to framesize boundaries	
+	bigbufsize = dz->buflen2 * 4;
+	if((dz->bigfbuf = (float *)malloc(bigbufsize * sizeof(float))) == NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to create sound buffers.\n");
+		return(PROGRAM_ERROR);
+	}
+	for(m = 0,n=3; n<7; m++,n++)				//	This creates buffers 4 to 7 out of dz->bigFFFbuf
+		dz->sbufptr[n] = dz->sampbuf[n] = dz->bigfbuf + (m * dz->buflen2);
+	return(FINISHED);
+}
+
+/*************************** DISTMARK **************************
+ *
+ *	1st waveset-group is read into BUFA
+ *	2nd waveset-group is read into BUFB
+ *	The smaller waveset-group is stretched to length of larger, and written into STRETCHBUF
+ *	Sample-by-sample amplitude interpolation is initially between the larger waveset-group and the stretched waveset-group ...
+ *		These are labelled BUF1 and BUF2 and the output goes to INTERPBUF
+ *	The output in interpbuf is now Time-interpolated into the OBUF
+ *
+ */
+
+int distmark(dataptr dz)
+{
+	int exit_status, n, m, j, k, invertphase;
+	int gpstt, gplen, lastgpstt = 0, lastgplen = 0, seekto, bufpos, thispos, nextpos, biglen, timinterpcnt, samplen, obufpos, rbufpos = 0, presamps;
+	float *ibuf = dz->sampbuf[0],*obuf = dz->sampbuf[1];
+	float *bufa = dz->sampbuf[2],*bufb = dz->sampbuf[3],*stretchbuf = dz->sampbuf[4],*interpbuf = dz->sampbuf[5], *revbuf = dz->sampbuf[6];
+	float *buf1,*buf2;
+	int *wavgpdata = dz->lparray[0], *intplens = dz->lparray[1];
+	double time, fracpos, thisval, valdiff, val, val1, val2, fpos, advnc = 0.0, rndval;
+	double *times = dz->parray[0];
+
+	obufpos = 0;
+	for(n=0,m=0;n < dz->itemcnt;n++,m+=2) {
+		invertphase = 0; 
+		gpstt = wavgpdata[m];
+		gplen = wavgpdata[m+1];
+		time = times[n];
+		memset((char *)bufa,0,dz->buflen2 * sizeof(float));
+		if(n==0) {												//	If 1st waveset-grp
+			if(gpstt != 0) {
+				if((sndseekEx(dz->ifd[0],0,0))<0) {				//	If 1st mark not at file start
+					sprintf(errstr,"sndseek 2 failed.\n");		//	Copy sound before 1st mark direct to output
+					return GOAL_FAILED;
+				}
+				if((exit_status = read_samps(ibuf,dz))<0)
+					return(exit_status);
+				presamps = gpstt;
+				while(presamps > dz->buflen) {					//	Copy any complete buflens of this material, directly to output file
+					if((exit_status = write_samps(ibuf,dz->ofd,dz))<0)
+						return(exit_status);
+					presamps -= dz->buflen;			
+					if((exit_status = read_samps(ibuf,dz))<0)
+						return(exit_status);
+				}
+				if(presamps > 0) {								//	and if there's any incomplete buffer, copy this into the output buffer
+					memcpy((char *)obuf,(char *)ibuf,presamps * sizeof(float));
+					obufpos = presamps;
+				}
+			}
+			seekto = (gpstt/F_SECSIZE) * F_SECSIZE;				//	Seek to nearest sector boundary below desired location
+			if((sndseekEx(dz->ifd[0],seekto,0))<0) {
+				sprintf(errstr,"sndseek 3 failed.\n");
+				return GOAL_FAILED;
+			}
+			if((exit_status = read_samps(ibuf,dz))<0)
+				return(exit_status);
+			bufpos = gpstt - seekto;							//	Copy wavesetgroup to buffer B			
+			memcpy((char *)bufb,(char *)(ibuf + bufpos),gplen * sizeof(float));
+		} else {												//	If NOT 1st waveset-grp, copy contents of buf B to buf A
+			memcpy((char *)bufa,(char *)bufb,lastgplen * sizeof(float));
+
+		// After 1st waveset group, look for next waveset-group and put in buffer B
+
+			seekto = (gpstt/F_SECSIZE) * F_SECSIZE;				//	Seek to nearest sector boundary below desired location
+			if((sndseekEx(dz->ifd[0],seekto,0))<0) {
+				sprintf(errstr,"sndseek 4 failed.\n");
+				return GOAL_FAILED;
+			}
+			if((exit_status = read_samps(ibuf,dz))<0)
+				return(exit_status);
+			bufpos = gpstt - seekto;							//	Copy wavesetgroup to buffer B			
+			memcpy((char *)bufb,(char *)(ibuf + bufpos),gplen * sizeof(float));
+
+			if(gplen > lastgplen)  {							//	If new waveset-gp (in bufB) longer than previous waveset-gp (in bufA)
+
+				bufa[lastgplen] = 0.0f;							//	Add wrap-around point to buffer A
+				advnc = (double)lastgplen/(double)gplen;		//	Set read-incr. Expanding, so incr < 1.0
+				fpos = 0.0;										//	Stretch contents of bufA into bufC
+				k = 0;
+				while(fpos < lastgplen) {
+					thispos = (int)floor(fpos);
+					nextpos = thispos+1;
+					fracpos = fpos - (double)thispos;
+					thisval = bufa[thispos];
+					valdiff = bufa[nextpos] - thisval;
+					val = thisval + (valdiff * fracpos);
+					stretchbuf[k++] = (float)val;
+					fpos += advnc;
+				}
+				buf1 = stretchbuf;								//	Interp is from tstretched bufa (in stretchbuf)
+				buf2 = bufb;									//	to bufb
+				biglen = gplen;									//	Length of samples whos values to be interpd (biggest waveset-gp)
+
+			} else if(gplen < lastgplen)  {						//	If new waveset-gp (bufB) shorter than previous waveset-gp (bugA)
+
+				bufb[gplen] = 0.0f;								//	Add wrap-around point to buffer B
+				advnc = (double)gplen/(double)lastgplen;		//	Set read-incr. Expanding ... so incr < 1.0
+				fpos = 0.0;										//	Stretch contents of bufB into bufC
+				k = 0;
+				while(fpos < gplen) {
+					thispos = (int)floor(fpos);
+					nextpos = thispos+1;
+					fracpos = fpos - (double)thispos;
+					thisval = bufb[thispos];
+					valdiff = bufb[nextpos] - thisval;
+					val = thisval + (valdiff * fracpos);
+					stretchbuf[k++] = (float)val;
+					fpos += advnc;
+				}
+				buf1 = bufa;									//	Interp is from bufa 
+				buf2 = stretchbuf;								//	to tstretched version of bufb (in stretchbuf)
+				biglen = lastgplen;
+
+			} else {											// ELSE buffers are same length
+
+				buf1 = bufa;									//	Interp is from bufa to bufb 
+				buf2 = bufb;
+				biglen = gplen;
+			}
+	
+		//	Calculate number of waveset-gp copies needed for time-interpolation, and store the lengths of the copies
+
+			if((timinterpcnt = get_timeinterpcnt(lastgplen,gplen,gpstt-lastgpstt,time,dz))<0) {
+				exit_status = timinterpcnt;
+				return exit_status;
+			}
+			for(k=0;k<lastgplen;k++) {							//	Copy unchanged previous waveset to output
+				obuf[obufpos++] = bufa[k];
+				if(obufpos >= dz->buflen) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					obufpos = 0;
+				}
+			}
+			for(j=1;j < timinterpcnt;j++) {						//	For each intervening waveset-gp
+
+				for(k=0;k<biglen;k++) {							//	Interp between sample vals in buf1 and buf2 to get new waveset shape
+					val1 = buf1[k] * (double)(timinterpcnt - j)/(double)timinterpcnt;
+					val2 = buf2[k] * (double)j/(double)timinterpcnt;
+					interpbuf[k] = (float)(val1 + val2);
+				}												//	and add wrap-around zero at end
+				interpbuf[k] = 0.0;
+				samplen = intplens[j];							//	Timestretch new shape appropriately, and put in obuf
+				if(dz->brksize[DMARK_RND]) {
+					if((exit_status = read_value_from_brktable(time,DMARK_RND,dz))<0)
+						return exit_status;
+				}
+				if(dz->param[DMARK_RND] > 0.0) {
+					rndval = drand48() * 0.5 * dz->param[DMARK_RND];	//	Randval in range 0 to 1/2, if dmark_rnd param = (max) 1.0
+					rndval = 1.0 - rndval;								//	Randval in range 1 to 1/2, if dmark_rnd param = (max) 1.0 : otherwise in range 1 to > 1/2
+					samplen = (int)round((double)samplen * rndval);
+				}
+				advnc = (double)biglen/(double)samplen;
+				if(dz->vflag[DMARK_FLIP])
+					invertphase = !invertphase;
+				fpos = 0.0;
+				if(invertphase) {
+					rbufpos = 0;
+					while(fpos < biglen) {
+						thispos = (int)floor(fpos);
+						nextpos = thispos+1;
+						fracpos = fpos - (double)thispos;
+						thisval = interpbuf[thispos];
+						valdiff = interpbuf[nextpos] - thisval;
+						val = thisval + (valdiff * fracpos);
+						revbuf[rbufpos++] = (float)val;
+						fpos += advnc;
+					}
+					rbufpos--;
+					while(rbufpos >= 0) {
+						obuf[obufpos++] = -(revbuf[rbufpos]);		//	Time-reverse and invert phase
+						if(obufpos >= dz->buflen) {
+							if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+								return(exit_status);
+							obufpos = 0;
+						}
+						rbufpos--;
+					}
+				} else {
+					while(fpos < biglen) {
+						thispos = (int)floor(fpos);
+						nextpos = thispos+1;
+						fracpos = fpos - (double)thispos;
+						thisval = interpbuf[thispos];
+						valdiff = interpbuf[nextpos] - thisval;
+						val = thisval + (valdiff * fracpos);
+						obuf[obufpos++] = (float)val;
+						if(obufpos >= dz->buflen) {
+							if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+								return(exit_status);
+							obufpos = 0;
+						}
+						fpos += advnc;
+					}
+				}
+			}
+		}
+		lastgpstt = gpstt;
+		lastgplen = gplen;
+	}
+
+	//	Write tail of file
+
+	seekto = (lastgpstt/F_SECSIZE) * F_SECSIZE;
+	if((sndseekEx(dz->ifd[0],seekto,0))<0) {
+		sprintf(errstr,"sndseek 5 failed.\n");
+		return GOAL_FAILED;
+	}
+	if((exit_status = read_samps(ibuf,dz))<0)
+		return(exit_status);
+	bufpos = lastgpstt - seekto;							//	Copy wavesetgroup to buffer B			
+	if(dz->vflag[DMARK_TAIL]) {
+		while(dz->ssampsread > 0) {
+			while(bufpos < dz->ssampsread) {
+				obuf[obufpos++] = ibuf[bufpos++];
+				if(obufpos >= dz->buflen) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					obufpos = 0;
+				}
+			}
+			if((exit_status = read_samps(ibuf,dz))<0)
+				return(exit_status);
+			bufpos = 0;
+		}
+	} else {
+		for(n=0;n < lastgplen;n++) {
+			obuf[obufpos++] = ibuf[bufpos++];
+			if(obufpos >= dz->buflen) {
+				if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+					return(exit_status);
+				obufpos = 0;
+			}
+		}
+	}
+	if(obufpos > 0) {
+		if((exit_status = write_samps(obuf,obufpos,dz))<0)
+			return(exit_status);
+	}
+	return FINISHED;
+}
+
+/************************ HANDLE_THE_SPECIAL_DATA *********************/
+
+int handle_the_special_data(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status;
+	if(!sloom) {
+		if(*cmdlinecnt <= 0) {
+			sprintf(errstr,"Insufficient parameters on command line.\n");
+			return(USAGE_ONLY);
+		}
+	}
+	if((exit_status = read_mark_data((*cmdline)[0],dz))<0)
+		return(exit_status);
+	(*cmdline)++;		
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/************************************ READ_MARK_DATA ************************************/
+
+int read_mark_data(char *filename,dataptr dz)
+{
+	double *time, lasttime, dummy, timestep;
+	int cnt, warned = 0;
+	char temp[200], *q;
+	aplptr ap;
+	FILE *fp;
+
+	ap = dz->application;
+	if((fp = fopen(filename,"r"))==NULL) {
+		sprintf(errstr,	"Can't open file %s to read data.\n",filename);
+		return(DATA_ERROR);
+	}
+	cnt = 0;
+	while(fgets(temp,200,fp)==temp) {
+		q = temp;
+		if(*q == ';')	//	Allow comments in file
+			continue;
+		while(get_float_from_within_string(&q,&dummy)) {
+			cnt++;
+		}
+	}	    
+	if(cnt == 0) {
+		sprintf(errstr,"No data in file %s\n",filename);
+		return(DATA_ERROR);
+	}
+	if((dz->parray = (double **)malloc(sizeof(double *)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for data in file %s. (1)\n",filename);
+		return(MEMORY_ERROR);
+	}
+	if((dz->parray[0] = (double *)malloc(cnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for data in file %s. (2)\n",filename);
+		return(MEMORY_ERROR);
+	}
+	time = dz->parray[0];
+	rewind(fp);
+	lasttime = -1.0;
+	cnt = 0;
+	dz->minstep = HUGE;
+	dz->maxstep = 0.0;
+	while(fgets(temp,200,fp)==temp) {
+		q = temp;
+		if(*q == ';')	//	Allow comments in file
+			continue;
+		while(get_float_from_within_string(&q,&dummy)) {
+			if(dummy < 0.0 || dummy <= lasttime) {
+				sprintf(errstr,"Times do not advance correctly in file %s.\n",filename);
+				return(DATA_ERROR);
+			}
+			if(dummy >= dz->duration) {
+				if (!warned) {
+					fprintf(stdout,"WARNING: Times beyond end of sndfile (%lf) in file %s. Ignoring them.\n",dz->duration,filename);
+					fflush(stdout);
+					warned = 1;
+				}
+				break;
+			}
+			*time = dummy;
+			if(cnt > 0) {
+				timestep = *time - lasttime;
+				if(timestep < dz->minstep)
+					dz->minstep = timestep;
+				if(timestep > dz->maxstep)
+					dz->maxstep = timestep;
+			}
+			lasttime = *time;
+			time++;
+			cnt++;
+		}
+	}
+	timestep = dz->duration - lasttime;
+	if(timestep < dz->minstep)
+		dz->minstep = timestep;
+	if(timestep > dz->maxstep)
+		dz->maxstep = timestep;
+	if(fclose(fp)<0) {
+		fprintf(stdout,"WARNING: Failed to close file %s.\n",filename);
+		fflush(stdout);
+	}
+	dz->itemcnt = cnt;
+	return(FINISHED);
+}
+
+/**************************** CHECK_DISTMARK_PARAM_VALIDITY_AND_CONSISTENCY *****************************/
+
+int check_distmark_param_validity_and_consistency(dataptr dz)
+{
+	int exit_status;
+	double maxdur, maxstr, srate = (double)dz->infile->srate;
+	if(dz->brksize[DMARK_CNT]) {					//	Find maximum duration of waveset-gps (param in mS)
+		if((exit_status = get_maxvalue_in_brktable(&maxdur,DMARK_CNT,dz))<0)
+			return exit_status;
+	} else
+		maxdur = dz->param[DMARK_CNT];
+	maxdur *= MS_TO_SECS;
+	if(maxdur >= dz->minstep/2.0) {
+		sprintf(errstr,"Max dur of waveset-units (%lf secs) greater than 1/2 of min step between marks (%lf secs).\n",maxdur,dz->minstep);
+		return(DATA_ERROR);
+	}
+	if(dz->brksize[DMARK_STR]) {					//	Find maximum tmestretch value
+		if((exit_status = get_maxvalue_in_brktable(&maxstr,DMARK_STR,dz))<0)
+			return exit_status;
+	} else
+		maxstr = dz->param[DMARK_STR];
+	dz->buflen  = (int)ceil(dz->maxstep * maxstr * srate) * 2;			//	Larger than largest step in infile * largest tstretch val
+	dz->buflen2 = (int)ceil(maxdur * (double)dz->infile->srate) * 2;	//	Larger than largest waveset-gp unit
+	return FINISHED;
+}
+
+/************************************** GET_TIMEINTERPCNT **********************************************
+ *
+ * Calculate number, and sizes, of intermediate time-interpd waveset-gps
+ */
+
+int get_timeinterpcnt(int lastgplen,int gplen,int markstep,double time,dataptr dz)
+{
+	int exit_status;
+	int *unitlens = dz->lparray[1];
+	double avlen;	
+	int timeinterpcnt, totallen, lendiff, n, thislen, offset, lastoffset = 0, outmarkstep;
+	avlen = (double)(lastgplen + gplen)/2.0;				//	Average unit length
+	if(dz->brksize[DMARK_STR]) {
+		if((exit_status = read_value_from_brktable(time,DMARK_STR,dz))<0)
+			return exit_status;
+	}
+	outmarkstep = (int)round((double)markstep * dz->param[DMARK_STR]);
+	timeinterpcnt = (int)round((double)outmarkstep/avlen);	//	Number of average units in total length
+	totallen = 0;
+	lendiff = gplen - lastgplen;
+	for(n=0;n < timeinterpcnt;n++) {						//	Using this 1st estimated value, sum sample-duration of all the interpd waveset-gps between 1 mark and next
+		thislen = lastgplen + (int)round(lendiff * (double)n/(double)timeinterpcnt);
+		totallen += thislen;
+	}
+	offset = outmarkstep - totallen;						//	Compare this with the desired samplelen
+	if(offset > 0) {
+		while(offset > 0) {									//	IF sum falls below desired value
+			lastoffset = offset;							//	try incrementing "timeinterpcnt"
+			totallen = 0;									//	until sum falls ABOVE desired value.
+			timeinterpcnt++;
+			for(n=0;n < timeinterpcnt;n++) {
+				thislen = lastgplen + (int)round(lendiff * (double)n/(double)timeinterpcnt);
+				totallen += thislen;
+			}
+			offset = outmarkstep - totallen;
+		}
+		if(abs(offset) > abs(lastoffset))					//	choose the timeinterpcnt which gives closest approx to outmarkstep
+			timeinterpcnt--;
+	} else if(offset < 0) {									//	ELSE of sum falls above desired value
+		while(offset < 0) {									//	try decrementing "timeinterpcnt"
+			lastoffset = offset;							//	until sum falls BELOW desired value.	
+			totallen = 0;
+			timeinterpcnt--;
+			if(timeinterpcnt == 0)
+				break;
+			for(n=0;n < timeinterpcnt;n++) {
+				thislen = lastgplen + (int)round(lendiff * (double)n/(double)timeinterpcnt);
+				totallen += thislen;
+			}
+			offset = outmarkstep - totallen;
+		}
+		if(abs(offset) > abs(lastoffset))					//	choose the timeinterpcnt which gives closest approx to outmarkstep
+			timeinterpcnt++;
+	}
+	if(timeinterpcnt < 2) {									//	Force at least 2 interp steps (1 = orig waveset-gp, 2 = interp towards next waveset-gp)
+		fprintf(stdout,"WARNING: Less than 2 interpolation steps before time %lf\n",time);
+		fflush(stdout);
+		timeinterpcnt = 2;
+	} else if(dz->vflag[DMARK_FLIP] && !EVEN(timeinterpcnt))
+		timeinterpcnt++;
+	if(timeinterpcnt >= dz->stepstorecnt) {
+		sprintf(errstr,"Memory store for sizes of intermediate waveset-groups (%d), not large enough (%d needed).\n",dz->stepstorecnt,timeinterpcnt);
+		return PROGRAM_ERROR;
+	}
+	for(n=0;n < timeinterpcnt;n++) {
+		thislen = lastgplen + (int)round(lendiff * (double)n/(double)timeinterpcnt);
+		unitlens[n] = thislen;
+	}
+	return timeinterpcnt;
+}
+
+
+int distmark2(dataptr dz)
+{
+	int exit_status, n, m, j, k, invertphase, done = 0;
+	int gpstt, gplen, lastgpstt = 0, lastgplen = 0, seekto, bufpos, thispos, nextpos, biglen, timinterpcnt, samplen, obufpos, rbufpos = 0, presamps;
+	float *ibuf = dz->sampbuf[0],*obuf = dz->sampbuf[1];
+	float *bufa = dz->sampbuf[2],*bufb = dz->sampbuf[3],*stretchbuf = dz->sampbuf[4],*interpbuf = dz->sampbuf[5], *revbuf = dz->sampbuf[6];
+	float *buf1,*buf2;
+	int *wavgpdata = dz->lparray[0], *intplens = dz->lparray[1];
+	double time, fracpos, thisval, valdiff, val, val1, val2, fpos, advnc = 0.0, rndval, thistime;
+	double *times = dz->parray[0];
+	int lastbufpos = 0, samps_to_copy;
+	obufpos = 0;
+	for(n=0,m=0;n < dz->itemcnt;n++,m+=2) {
+		invertphase = 0; 
+		gpstt = wavgpdata[m];
+		gplen = wavgpdata[m+1];
+		time = times[n];
+		if((dz->vflag[1] == 0 && EVEN(n)) || (dz->vflag[1] == 1 && ODD(n))) {
+			memset((char *)bufa,0,dz->buflen2 * sizeof(float));
+			if (n > 0) {										//	If not the first marked-waveset-group (0 is EVEN)
+				lastbufpos = lastbufpos + lastgplen;			//	copy from end of last interp-block to current interp-block start
+				j = lastbufpos;
+				samps_to_copy = wavgpdata[m] - wavgpdata[m-2];
+				for(k = 0; k < samps_to_copy;k++) {
+					obuf[obufpos++] = ibuf[j++];
+					if(obufpos >= dz->buflen) {
+						if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+							return(exit_status);
+						obufpos = 0;
+					}
+					if(j >= dz->buflen) {
+						if((exit_status = read_samps(ibuf,dz))<0)
+							return(exit_status);
+						if(dz->ssampsread == 0) {
+							done = 1;
+							break;
+						}
+						j = 0;
+					}
+				}
+				if(done)
+					break;
+			}
+			if(n == 0 && gpstt != 0) {
+				if((sndseekEx(dz->ifd[0],0,0))<0) {				//	If 1st mark not at file start
+					sprintf(errstr,"sndseek 2 failed.\n");		//	Copy sound before 1st mark direct to output
+					return GOAL_FAILED;
+				}
+				if((exit_status = read_samps(ibuf,dz))<0)
+					return(exit_status);
+				presamps = gpstt;
+				while(presamps > dz->buflen) {					//	Copy any complete buflens of this material, directly to output file
+					if((exit_status = write_samps(ibuf,dz->ofd,dz))<0)
+						return(exit_status);
+					presamps -= dz->buflen;			
+					if((exit_status = read_samps(ibuf,dz))<0)
+						return(exit_status);
+				}
+				if(presamps > 0) {								//	and if there's any incomplete buffer, copy this into the output buffer
+					memcpy((char *)obuf,(char *)ibuf,presamps * sizeof(float));
+					obufpos = presamps;
+				}
+			}
+			seekto = (gpstt/F_SECSIZE) * F_SECSIZE;				//	Seek to nearest sector boundary below desired location
+			if((sndseekEx(dz->ifd[0],seekto,0))<0) {
+				sprintf(errstr,"sndseek 3 failed.\n");
+				return GOAL_FAILED;
+			}
+			if((exit_status = read_samps(ibuf,dz))<0)
+				return(exit_status);
+			bufpos = gpstt - seekto;							//	Copy wavesetgroup to buffer B			
+			memcpy((char *)bufb,(char *)(ibuf + bufpos),gplen * sizeof(float));
+		} else {												//	If NOT 1st waveset-grp, copy contents of buf B to buf A
+			memcpy((char *)bufa,(char *)bufb,lastgplen * sizeof(float));
+
+		// After 1st waveset group, look for next waveset-group and put in buffer B
+
+			seekto = (gpstt/F_SECSIZE) * F_SECSIZE;				//	Seek to nearest sector boundary below desired location
+			if((sndseekEx(dz->ifd[0],seekto,0))<0) {
+				sprintf(errstr,"sndseek 4 failed.\n");
+				return GOAL_FAILED;
+			}
+			if((exit_status = read_samps(ibuf,dz))<0)
+				return(exit_status);
+			bufpos = gpstt - seekto;							//	Copy wavesetgroup to buffer B			
+			lastbufpos = bufpos;
+			lastgplen = gplen;
+			memcpy((char *)bufb,(char *)(ibuf + bufpos),gplen * sizeof(float));
+
+			if(gplen > lastgplen)  {							//	If new waveset-gp (in bufB) longer than previous waveset-gp (in bufA)
+
+				bufa[lastgplen] = 0.0f;							//	Add wrap-around point to buffer A
+				advnc = (double)lastgplen/(double)gplen;		//	Set read-incr. Expanding, so incr < 1.0
+				fpos = 0.0;										//	Stretch contents of bufA into bufC
+				k = 0;
+				while(fpos < lastgplen) {
+					thispos = (int)floor(fpos);
+					nextpos = thispos+1;
+					fracpos = fpos - (double)thispos;
+					thisval = bufa[thispos];
+					valdiff = bufa[nextpos] - thisval;
+					val = thisval + (valdiff * fracpos);
+					stretchbuf[k++] = (float)val;
+					fpos += advnc;
+				}
+				buf1 = stretchbuf;								//	Interp is from tstretched bufa (in stretchbuf)
+				buf2 = bufb;									//	to bufb
+				biglen = gplen;									//	Length of samples whos values to be interpd (biggest waveset-gp)
+
+			} else if(gplen < lastgplen)  {						//	If new waveset-gp (bufB) shorter than previous waveset-gp (bugA)
+
+				bufb[gplen] = 0.0f;								//	Add wrap-around point to buffer B
+				advnc = (double)gplen/(double)lastgplen;		//	Set read-incr. Expanding ... so incr < 1.0
+				fpos = 0.0;										//	Stretch contents of bufB into bufC
+				k = 0;
+				while(fpos < gplen) {
+					thispos = (int)floor(fpos);
+					nextpos = thispos+1;
+					fracpos = fpos - (double)thispos;
+					thisval = bufb[thispos];
+					valdiff = bufb[nextpos] - thisval;
+					val = thisval + (valdiff * fracpos);
+					stretchbuf[k++] = (float)val;
+					fpos += advnc;
+				}
+				buf1 = bufa;									//	Interp is from bufa 
+				buf2 = stretchbuf;								//	to tstretched version of bufb (in stretchbuf)
+				biglen = lastgplen;
+
+			} else {											// ELSE buffers are same length
+
+				buf1 = bufa;									//	Interp is from bufa to bufb 
+				buf2 = bufb;
+				biglen = gplen;
+			}
+
+			//	Calculate number of waveset-gp copies needed for time-interpolation, and store the lengths of the copies
+
+			if((timinterpcnt = get_timeinterpcnt(lastgplen,gplen,gpstt-lastgpstt,time,dz))<0) {
+				exit_status = timinterpcnt;
+				return exit_status;
+			}
+			if(dz->brksize[DMARK_GAIN]) {
+				thistime = (dz->total_samps_written + obufpos)/(double)dz->infile->srate;
+				if((exit_status = read_value_from_brktable(thistime,DMARK_GAIN,dz)) < 0)
+					return exit_status;
+			}
+			for(k=0;k<lastgplen;k++) {							//	Copy unchanged previous waveset to output
+				obuf[obufpos++] = (float)(bufa[k] * dz->param[DMARK_GAIN]);
+				if(obufpos >= dz->buflen) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					obufpos = 0;
+				}
+			}
+			for(j=1;j < timinterpcnt;j++) {						//	For each intervening waveset-gp
+
+				for(k=0;k<biglen;k++) {							//	Interp between sample vals in buf1 and buf2 to get new waveset shape
+					val1 = buf1[k] * (double)(timinterpcnt - j)/(double)timinterpcnt;
+					val2 = buf2[k] * (double)j/(double)timinterpcnt;
+					interpbuf[k] = (float)(val1 + val2);
+				}												//	and add wrap-around zero at end
+				interpbuf[k] = 0.0;
+				samplen = intplens[j];							//	Timestretch new shape appropriately, and put in obuf
+				if(dz->brksize[DMARK_RND]) {
+					if((exit_status = read_value_from_brktable(time,DMARK_RND,dz))<0)
+						return exit_status;
+				}
+				if(dz->param[DMARK_RND] > 0.0) {
+					rndval = drand48() * 0.5 * dz->param[DMARK_RND];	//	Randval in range 0 to 1/2, if dmark_rnd param = (max) 1.0
+					rndval = 1.0 - rndval;								//	Randval in range 1 to 1/2, if dmark_rnd param = (max) 1.0 : otherwise in range 1 to > 1/2
+					samplen = (int)round((double)samplen * rndval);
+				}
+				advnc = (double)biglen/(double)samplen;
+				if(dz->vflag[DMARK_FLIP])
+					invertphase = !invertphase;
+				fpos = 0.0;
+				if(invertphase) {
+					rbufpos = 0;
+					while(fpos < biglen) {
+						thispos = (int)floor(fpos);
+						nextpos = thispos+1;
+						fracpos = fpos - (double)thispos;
+						thisval = interpbuf[thispos];
+						valdiff = interpbuf[nextpos] - thisval;
+						val = thisval + (valdiff * fracpos);
+						revbuf[rbufpos++] = (float)val;
+						fpos += advnc;
+					}
+					rbufpos--;
+					while(rbufpos >= 0) {
+						obuf[obufpos++] = (float)(-revbuf[rbufpos] * dz->param[DMARK_GAIN]);		//	Time-reverse and invert phase
+						if(obufpos >= dz->buflen) {
+							if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+								return(exit_status);
+							obufpos = 0;
+						}
+						rbufpos--;
+					}
+				} else {
+					while(fpos < biglen) {
+						thispos = (int)floor(fpos);
+						nextpos = thispos+1;
+						fracpos = fpos - (double)thispos;
+						thisval = interpbuf[thispos];
+						valdiff = interpbuf[nextpos] - thisval;
+						val = thisval + (valdiff * fracpos);
+						obuf[obufpos++] = (float)(val * dz->param[DMARK_GAIN]);
+						if(obufpos >= dz->buflen) {
+							if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+								return(exit_status);
+							obufpos = 0;
+						}
+						fpos += advnc;
+					}
+				}
+			}
+		}
+		lastgpstt = gpstt;
+		lastgplen = gplen;
+	}
+	if(!done)  {
+		seekto = (lastgpstt/F_SECSIZE) * F_SECSIZE;
+		if((sndseekEx(dz->ifd[0],seekto,0))<0) {
+			sprintf(errstr,"sndseek 5 failed.\n");
+			return GOAL_FAILED;
+		}
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+		bufpos = lastgpstt - seekto;							//	Copy wavesetgroup to buffer B			
+		while(dz->ssampsread > 0) {
+			while(bufpos < dz->ssampsread) {
+				obuf[obufpos++] = ibuf[bufpos++];
+				if(obufpos >= dz->buflen) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					obufpos = 0;
+				}
+			}
+			if((exit_status = read_samps(ibuf,dz))<0)
+				return(exit_status);
+			bufpos = 0;
+		}
+	}
+	if(obufpos > 0) {
+		if((exit_status = write_samps(obuf,obufpos,dz))<0)
+			return(exit_status);
+	}
+	return FINISHED;
+}
+
+/************************ GET_THE_MODE_NO *********************/
+
+int get_the_mode_no(char *str, dataptr dz)
+{
+	if(sscanf(str,"%d",&dz->mode)!=1) {
+		sprintf(errstr,"Cannot read mode of program.\n");
+		return(USAGE_ONLY);
+	}
+	if(dz->mode <= 0 || dz->mode > dz->maxmode) {
+		sprintf(errstr,"Program mode value [%d] is out of range [1 - %d].\n",dz->mode,dz->maxmode);
+		return(USAGE_ONLY);
+	}
+	dz->mode--;		/* CHANGE TO INTERNAL REPRESENTATION OF MODE NO */
+	return(FINISHED);
+}
+

+ 2668 - 0
dev/standnew/distmore.c

@@ -0,0 +1,2668 @@
+/*
+ *	SPLICES NOT WORKING IN REASSEMBLY.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <tkglobals.h>
+#include <pnames.h>
+#include <filetype.h>
+#include <processno.h>
+#include <modeno.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <math.h>
+#include <mixxcon.h>
+#include <osbind.h>
+#include <standalone.h>
+#include <ctype.h>
+#include <sfsys.h>
+#include <string.h>
+#include <srates.h>
+#include <formants.h>
+#include <speccon.h>
+
+#define	SAFETY 64
+#define maxstep is_sharp
+#define minstep scalefact
+#define maxxstep rampbrksize
+
+#define SSPLICELEN 15
+
+#define DISTMORERAND (0.2)
+
+#define ZREPETS 0
+#define ZDUR	1
+#define ZMINSIZ 2
+#define ZFRAC   3
+
+#ifdef unix
+#define round(x) lround((x))
+#endif
+
+char errstr[2400];
+
+int anal_infiles = 1;
+int	sloom = 0;
+int sloombatch = 0;
+
+const char* cdp_version = "6.2.0";
+
+//CDP LIB REPLACEMENTS
+static int setup_distmore_application(dataptr dz);
+static int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+static int parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int setup_distmore_param_ranges_and_defaults(dataptr dz);
+static int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int establish_application(dataptr dz);
+static int initialise_vflags(dataptr dz);
+static int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int mark_parameter_types(dataptr dz,aplptr ap);
+static int assign_file_data_storage(int infilecnt,dataptr dz);
+static int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+static int get_the_mode_from_cmdline(char *str,dataptr dz);
+static int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt);
+
+static int handle_the_special_data(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int read_mark_data(char *filename,dataptr dz);
+static int read_feature_data(char *filename,dataptr dz);
+static int check_distmore_param_validity_and_consistency(dataptr dz);
+static int distmore_param_preprocess(dataptr dz);
+static int distbright (dataptr dz);
+static int distdouble (dataptr dz);
+
+static int generate_tail_segments(dataptr dz);
+static int create_distmore_sndbufs(dataptr dz);
+static int recreate_distmore_sndbufs(dataptr dz);
+static void reversebuf2(float *buf1,float *buf2,int sampcnt);
+static void reversebuf(float *buf,int sampcnt);
+static int segsbkwd(dataptr dz);
+static int segszig(dataptr dz);
+static void cutend_and_splicend(float *buf,int cutlen,int sampcnt,int splicelen);
+static double getstepratio(dataptr dz);
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status;
+	dataptr dz = NULL;
+	char **cmdline;
+	int  cmdlinecnt;
+	aplptr ap;
+	int is_launched = FALSE;
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+						/* CHECK FOR SOUNDLOOM */
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {					// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc == 2) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+	}
+	if(!sloom) {
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		switch(dz->process) {
+		case(DISTBRIGHT):	dz->maxmode = 3;	break;
+		case(DISTDOUBLE):	dz->maxmode = 0;	break;
+		case(SEGSBKWD):		dz->maxmode = 9;	break;
+		case(SEGSZIG):		dz->maxmode = 3;	break;
+		}
+		if(dz->maxmode > 0) {
+			if((exit_status = get_the_mode_from_cmdline(cmdline[0],dz))<0) {
+				print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+				return(exit_status);
+			}
+			cmdline++;
+			cmdlinecnt--;
+		}
+		// setup_particular_application =
+		if((exit_status = setup_distmore_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+
+	// parse_infile_and_hone_type() = 
+	if((exit_status = parse_infile_and_check_type(cmdline,dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// open_first_infile		CDP LIB
+	if((exit_status = open_first_infile(cmdline[0],dz))<0) {	
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);	
+		return(FAILED);
+	}
+	cmdlinecnt--;
+	cmdline++;
+	// setup_param_ranges_and_defaults() =
+	if((exit_status = setup_distmore_param_ranges_and_defaults(dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+//	handle_extra_infiles() : redundant
+	// handle_outfile() = 
+	if((exit_status = handle_the_outfile(&cmdlinecnt,&cmdline,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+//	handle_formants()			redundant
+//	handle_formant_quiksearch()	redundant
+	dz->array_cnt  = 0;
+	dz->iarray_cnt = 0;
+	dz->larray_cnt = 0;
+	if(dz->process == DISTBRIGHT) {
+		dz->array_cnt  = 3;		//	3 for: Seg starttimes, average zerocross rates, possibly expanded seg starttimes
+		dz->iarray_cnt = 2;		//	2 for: H/T labels, reordering list
+		dz->larray_cnt = 1;		//	For times as sample-cnts
+	}
+	if(dz->process == SEGSBKWD || dz->process == SEGSZIG) {
+		dz->array_cnt  = 1;		//	1 for: Seg starttimes
+		dz->larray_cnt = 1;		//	For times as sample-cnts
+	}
+//	handle_special_data ....
+	if(dz->process != DISTDOUBLE && !(dz->process == SEGSZIG && dz->mode != 0)) {
+		if((exit_status = handle_the_special_data(&cmdlinecnt,&cmdline,dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	}
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+//	check_param_validity_and_consistency .....
+	if((exit_status = check_distmore_param_validity_and_consistency(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = create_distmore_sndbufs(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if(dz->process == DISTDOUBLE) {
+		if((exit_status = distmore_param_preprocess(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	}
+	is_launched = TRUE;
+	switch(dz->process) {
+	case(DISTBRIGHT):
+		if((exit_status = distbright(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		break;
+	case(DISTDOUBLE):				
+		if((exit_status = distdouble(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		break;
+	case(SEGSBKWD):				
+		if((exit_status = segsbkwd(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		break;
+	case(SEGSZIG):				
+		if((exit_status = segszig(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		break;
+	}
+	if((exit_status = complete_output(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc, brkcnt;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	brkcnt = tipc;
+	//THERE ARE NO INPUTFILE brktables USED IN THIS PROCESS
+	if(brkcnt>0) {
+		if((exit_status = setup_and_init_input_brktable_constants(dz,brkcnt))<0)			  
+			return(exit_status);
+	}
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+		return(exit_status);
+	
+	// establish_infile_constants() replaced by
+	dz->infilecnt = 1;
+	//establish_bufptrs_and_extra_buffers():
+	return(FINISHED);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_OUTFILE *********************/
+
+int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status;
+	char *filename = (*cmdline)[0];
+	if(filename[0]=='-' && filename[1]=='f') {
+		dz->floatsam_output = 1;
+		dz->true_outfile_stype = SAMP_FLOAT;
+		filename+= 2;
+	}
+	if(!sloom) {
+		if(file_has_invalid_startchar(filename) || value_is_numeric(filename)) {
+			sprintf(errstr,"Outfile name %s has invalid start character(s) or looks too much like a number.\n",filename);
+			return(DATA_ERROR);
+		}
+	}
+	strcpy(dz->outfilename,filename);
+	if((exit_status = create_sized_outfile(filename,dz))<0)
+		return(exit_status);
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/************************* SETUP_DISTMORE_APPLICATION *******************/
+
+int setup_distmore_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	// SEE parstruct FOR EXPLANATION of next 2 functions
+	switch(dz->process) {
+	case(DISTBRIGHT):
+		if((exit_status = set_param_data(ap,MARKLIST,0,0,""))<0)
+			return(FAILED);
+		if((exit_status = set_vflgs(ap,"s",1,"d","d",1,0,"0"))<0)
+			return(FAILED);
+		dz->maxmode = 3;
+		break;
+	case(DISTDOUBLE):
+		if((exit_status = set_param_data(ap,0,1,1,"i"))<0)
+			return(FAILED);
+		if((exit_status = set_vflgs(ap,"",0,"","",0,0,""))<0)
+			return(FAILED);
+		dz->maxmode = 0;
+		break;
+	case(SEGSBKWD):
+		if((exit_status = set_param_data(ap,MARKLIST,0,0,""))<0)
+			return(FAILED);
+		if((exit_status = set_vflgs(ap,"",0,"","",0,0,""))<0)
+			return(FAILED);
+		dz->maxmode = 9;
+		break;
+	case(SEGSZIG):
+		switch(dz->mode) {
+		case(0):	exit_status = set_param_data(ap,MARKLIST,2,1,"I0"); break;
+		case(1):	exit_status = set_param_data(ap,0       ,2,1,"i0"); break;
+		case(2):	exit_status = set_param_data(ap,0       ,2,2,"id"); break;
+		}
+		if(exit_status < 0)
+			return(FAILED);
+		switch(dz->mode) {
+		case(0): exit_status = set_vflgs(ap,"sp",2,"dD","l",1,0,"0"); break;
+		case(1): exit_status = set_vflgs(ap,"sp",2,"dd","l",1,0,"0"); break;
+		case(2): exit_status = set_vflgs(ap,"sp",2,"dd","l",1,0,"0"); break;
+		}
+		if(exit_status < 0)
+			return(FAILED);
+		dz->maxmode = 3;
+		break;
+	}
+	dz->input_data_type = SNDFILES_ONLY;
+	dz->process_type	= UNEQUAL_SNDFILE;	
+	dz->outfiletype  	= SNDFILE_OUT;
+	// set_legal_infile_structure -->
+	dz->has_otherfile = FALSE;
+	// assign_process_logic -->
+	return application_init(dz);	//GLOBAL
+}
+
+/************************* PARSE_INFILE_AND_CHECK_TYPE *******************/
+
+int parse_infile_and_check_type(char **cmdline,dataptr dz)
+{
+	int exit_status;
+	infileptr infile_info;
+	if(!sloom) {
+		if((infile_info = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for infile structure to test file data.");
+			return(MEMORY_ERROR);
+		} else if((exit_status = cdparse(cmdline[0],infile_info))<0) {
+			sprintf(errstr,"Failed to parse input file %s\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if(infile_info->filetype != SNDFILE)  {
+			sprintf(errstr,"File %s is not of correct type\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if(infile_info->channels != 1)  {
+			sprintf(errstr,"File %s is not of correct type (must be mono)\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if((exit_status = copy_parse_info_to_main_structure(infile_info,dz))<0) {
+			sprintf(errstr,"Failed to copy file parsing information\n");
+			return(PROGRAM_ERROR);
+		}
+		free(infile_info);
+	}
+	return(FINISHED);
+}
+
+/************************* SETUP_DISTMORE_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_distmore_param_ranges_and_defaults(dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	// NB total_input_param_cnt is > 0 !!!
+	if((exit_status = setup_input_param_range_stores(ap->total_input_param_cnt,ap))<0)
+		return(FAILED);
+	// get_param_ranges()
+	switch(dz->process) {
+	case(DISTBRIGHT):
+		ap->lo[0] = 2;
+		ap->hi[0] = 15;
+		ap->default_val[0]	= 15;
+		dz->maxmode = 3;
+		break;
+	case(DISTDOUBLE):
+		ap->lo[0] = 1;
+		ap->hi[0] = 4;
+		ap->default_val[0]	= 1;
+		dz->maxmode = 0;
+		break;
+	case(SEGSBKWD):
+		dz->maxmode = 0;
+		break;
+	case(SEGSZIG):
+		ap->lo[0] = 1;
+		ap->hi[0] = 64;
+		ap->default_val[0]	= 1;
+		if(dz->mode==2) {
+			ap->lo[1] = dz->duration * 2;
+			ap->hi[1] = dz->duration * 64;
+			ap->default_val[1]	= dz->duration * 4;
+		}
+		ap->lo[2] = 0;
+		ap->hi[2] = 1000;
+		ap->default_val[2] = 0;
+		ap->lo[3] = 0.2;
+		ap->hi[3] = 1.0;
+		ap->default_val[3] = 1.0;
+		dz->maxmode = 3;
+		break;
+	}
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_distmore_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int read_special_data(char *str,dataptr dz)	
+{
+	return(FINISHED);
+}
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+	fprintf(stderr,
+	"\nUSAGE: distmore NAME (mode) infile outfile (parameters)\n"
+	"\n"
+	"MORE WAVESET DISTORTION PROGRAMS\n"
+	"\n"
+	"where NAME can be any one of\n"
+	"\n"
+	"bright   double   segsbkwd   segszig\n"
+	"\n"
+	"Type 'distmore bright' for more info on distmore bright.. ETC.\n");
+	return(USAGE_ONLY);
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if(		!strcmp(prog_identifier_from_cmdline,"bright"))		dz->process = DISTBRIGHT;
+	else if(!strcmp(prog_identifier_from_cmdline,"double"))		dz->process = DISTDOUBLE;
+	else if(!strcmp(prog_identifier_from_cmdline,"segsbkwd"))	dz->process = SEGSBKWD;
+	else if(!strcmp(prog_identifier_from_cmdline,"segszig"))	dz->process = SEGSZIG;
+	else {
+		fprintf(stderr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/******************************** SETUP_AND_INIT_INPUT_BRKTABLE_CONSTANTS ********************************/
+
+int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt)
+{	
+	int n;
+	if((dz->brk      = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<brkcnt;n++) {
+		dz->brk[n]     = NULL;
+		dz->brkptr[n]  = NULL;
+		dz->brkinit[n] = 0;
+		dz->brksize[n] = 0;
+	}
+	return(FINISHED);
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+	if(!strcmp(str,"bright")) {
+		fprintf(stderr,
+	    "USAGE:  distmore bright 1-3 infil outfil marklist [-ssplicelen -d]\n"
+		"\n"
+		"\nReorders sound segments in order of average zero-crossing rate\n."
+		"\n"
+		"MARKLIST A list of timemarks in source, marking (paired) Heads and Tails.\n"
+		"         e.g. consonant onset, and vowel continuation of source.\n"
+		"         (It is assumed that the first mark is at a Head segment.)\n"
+		"\n"
+		"Extract data ...\n"
+		"MODE 1   from Heads, & from Tails cut to segments, size approx equal to Heads.\n"
+		"MODE 2   from Heads and Tails, as defined by marklist.\n"
+		"MODE 3   from Tails only.\n"
+		"\n"
+		"SPLICELEN Length of splice in mS\n"
+		"-d        Output in decreasing order of brightness. (Default: increasing).\n");
+	} else if(!strcmp(str,"double")) {
+		fprintf(stderr,
+	    "USAGE:  distmore double infil outfil mult\n"
+		"\n"
+		"Doubles (quadruples etc.) frq of each waveset\n."
+		"\n"
+		"MULT   Octave step up (1-4).\n");
+	} else if(!strcmp(str,"segsbkwd")) {
+		fprintf(stderr,
+	    "USAGE:  distmore segsbkwd 1-9 infil outfil marklist\n"
+		"\n"
+		"Reverses certain (sets of) segments\n."
+		"\n"
+		"MODE 1: Reverse Tails\n"
+		"MODE 2: Reverse Heads\n"
+		"MODE 3: Reverse Head+Tail pairs\n"
+		"MODE 4: Reverse Head & Tail+Head+Tail set\n"
+		"MODE 5: Reverse Head+Tail+Head+Tail set\n"
+		"MODE 6: Reverse Head & Tail+Head+Tail+Head+Tail set\n"
+		"MODE 7: Reverse Head+Tail+Head+Tail+Head+Tail set\n"
+		"MODE 8: Reverse Head & Tail+Head+Tail+Head+Tail+Head+Tail set\n"
+		"MODE 9: Reverse Head+Tail+Head+Tail+Head+Tail+Head+Tail set\n"
+		"\n"
+		"MARKLIST A list of timemarks in source, marking (paired) Heads and Tails.\n"
+		"         e.g. consonant onset, and vowel continuation of source.\n"
+		"         (It is assumed that the first mark is at a Head segment.)\n");
+	} else if(!strcmp(str,"segszig")) {
+		fprintf(stderr,
+	    "USAGE:  distmore segszig 1 infil outfil marklist repets [-sshrinkto] [-pprop] [-l]\n"
+	    "OR:     distmore segszig 2 infil outfil          repets [-sshrinkto] [-pprop] [-l]\n"
+	    "OR:     distmore segszig 3 infil outfil          repets dur [-sshrinkto] [-pprop]\n"
+		"\n"
+		"MODE1     Zigzags across tail segments of a soundfile while playing it.\n"
+		"MODES 2&3 Zigzag across entire soundfile.\n"
+		"\n"
+		"MARKLIST A list of timemarks in source, marking (paired) Heads and Tails.\n"
+		"         e.g. consonant onsets, and vowel continuations in source.\n"
+		"         (First mark is assumed to be a Head segment).\n"
+		"         In Mode 2, the whole file is processed.\n"
+		"\n"
+		"REPETS   Number of zigzags (timevariable).\n"
+		"\n"
+		"SHRINKTO If set to zero, has no effect.\n"
+		"         Otherwize Zigzags contract to minimum size 'minsiz' mS (Range %d upwards).\n"
+		"\n"
+		"DUR      Duration of zigged output.\n"
+		"\n"
+		"PROP     Proportion of Tail to use. Default, all of it. (timevariable).\n"
+		"         CARE: If length of used-portion of any particular tail too short,\n"
+		"         (less than \"SHRINKTO\" size) zigs for that tail will not shrink.\n"
+		"-l       Shrink zigs logarithmically (default, linear shrink).\n",(SSPLICELEN * 2) + 1);
+	} else {
+		fprintf(stdout,"Unknown option '%s'\n",str);
+		fflush(stdout);
+	}
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	fprintf(stderr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/****************************** GET_MODE *********************************/
+
+int get_the_mode_from_cmdline(char *str,dataptr dz)
+{
+	char temp[200], *p;
+	if(sscanf(str,"%s",temp)!=1) {
+		sprintf(errstr,"Cannot read mode of program.\n");
+		return(USAGE_ONLY);
+	}
+	p = temp + strlen(temp) - 1;
+	while(p >= temp) {
+		if(!isdigit(*p)) {
+			fprintf(stderr,"Invalid mode of program entered.\n");
+			return(USAGE_ONLY);
+		}
+		p--;
+	}
+	if(sscanf(str,"%d",&dz->mode)!=1) {
+		fprintf(stderr,"Cannot read mode of program.\n");
+		return(USAGE_ONLY);
+	}
+	if(dz->mode <= 0 || dz->mode > dz->maxmode) {
+		fprintf(stderr,"Program mode value [%d] is out of range [1 - %d].\n",dz->mode,dz->maxmode);
+		return(USAGE_ONLY);
+	}
+	dz->mode--;		/* CHANGE TO INTERNAL REPRESENTATION OF MODE NO */
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_SPECIAL_DATA *********************/
+
+int handle_the_special_data(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status;
+	if(!sloom) {
+		if(*cmdlinecnt <= 0) {
+			sprintf(errstr,"Insufficient parameters on command line.\n");
+			return(USAGE_ONLY);
+		}
+	}
+	if((exit_status = read_mark_data((*cmdline)[0],dz))<0)
+		return(exit_status);
+	(*cmdline)++;		
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/************************************ READ_MARK_DATA ************************************/
+
+int read_mark_data(char *filename,dataptr dz)
+{
+	double *time, lasttime, dummy, timestep;
+	int cnt, warned = 0;
+	int arraysize;
+	char temp[200], *q;
+	aplptr ap;
+	FILE *fp;
+
+	ap = dz->application;
+	if((fp = fopen(filename,"r"))==NULL) {
+		sprintf(errstr,	"Can't open file %s to read data.\n",filename);
+		return(DATA_ERROR);
+	}
+	cnt = 0;
+	lasttime = -1.0;
+	dz->minstep = HUGE;
+	dz->maxstep = 0.0;
+	while(fgets(temp,200,fp)==temp) {
+		q = temp;
+		if(*q == ';')	//	Allow comments in file
+			continue;
+		while(get_float_from_within_string(&q,&dummy)) {
+			if(dummy < 0.0 || dummy <= lasttime) {
+				sprintf(errstr,"Times do not advance correctly in file %s.\n",filename);
+				return(DATA_ERROR);
+			}
+			if(dummy >= dz->duration) {
+				if(!warned) {
+					fprintf(stdout,"WARNING: Times beyond end of sndfile (%lf) in file %s. Ignoring them.\n",dz->duration,filename);
+					fflush(stdout);
+					warned = 1;
+				}
+				break;
+			}
+			if(cnt > 0) {
+				timestep = dummy - lasttime;
+				if(timestep < dz->minstep)
+					dz->minstep = timestep;
+				if(timestep > dz->maxstep)
+					dz->maxstep = timestep;
+			}
+			lasttime = dummy;
+			cnt++;
+		}
+	}	    
+	if(cnt == 0) {
+		sprintf(errstr,"No data in file %s\n",filename);
+		return(DATA_ERROR);
+	}
+	if(cnt < 4) {
+		sprintf(errstr,"Insufficient data (%d values) in file %s : Need at least 4\n",cnt,filename);
+		return(DATA_ERROR);
+	}
+	dz->itemcnt = cnt;
+	timestep = dz->duration - lasttime;
+	if(timestep < dz->minstep)
+		dz->minstep = timestep;
+	if(timestep > dz->maxstep)
+		dz->maxstep = timestep;
+
+	if((dz->parray = (double **)malloc(dz->array_cnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for zerocross-density array (1)\n");
+		return(MEMORY_ERROR);
+	}
+	if(dz->iarray_cnt > 0) {
+		if((dz->iparray = (int **)malloc(dz->iarray_cnt * sizeof(int *)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for reordering array (1)\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(dz->larray_cnt > 0) {
+		if((dz->lparray = (int **)malloc(dz->larray_cnt * sizeof(int *)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for sample times (1)\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(dz->process == DISTBRIGHT && dz->mode == 0)
+		arraysize = (int)ceil(dz->duration/dz->minstep) + SAFETY;					//	In this mode, tail segs are further subdivided
+	else
+		arraysize = dz->itemcnt + SAFETY;
+
+	if(dz->process == DISTBRIGHT) {
+		if((dz->iparray[0] = (int *)malloc(arraysize * sizeof(int)))==NULL) {		//	Array for Head/Tail flags for labelling segments
+			sprintf(errstr,"INSUFFICIENT MEMORY for Head/Tail flags for labelling segments\n");
+			return(MEMORY_ERROR);
+		}
+		if((dz->iparray[1] = (int *)malloc(arraysize * sizeof(int)))==NULL) {		//	Array for Reordering these segments
+			sprintf(errstr,"INSUFFICIENT MEMORY for reordering array\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if((dz->parray[0] = (double *)malloc(arraysize * sizeof(double)))==NULL) {		//	Array for segment times
+		sprintf(errstr,"INSUFFICIENT MEMORY for time data in file %s. (2)\n",filename);
+		return(MEMORY_ERROR);
+	}
+	if(dz->process == DISTBRIGHT) {
+		if((dz->parray[1] = (double *)malloc(arraysize * sizeof(double)))==NULL) {	//	Array for zcross-density values (and possibly also for expanded time-set)
+			sprintf(errstr,"INSUFFICIENT MEMORY for time data in file %s. (2)\n",filename);
+			return(MEMORY_ERROR);
+		}
+	}
+	if((dz->lparray[0] = (int *)malloc(arraysize * 2 * sizeof(int)))==NULL) {		//	Array for segment sampletimes
+		sprintf(errstr,"INSUFFICIENT MEMORY for sampletime data from file %s. (2)\n",filename);
+		return(MEMORY_ERROR);
+	}
+	time = dz->parray[0];
+	rewind(fp);
+	lasttime = -1.0;
+	cnt = 0;
+	while(fgets(temp,200,fp)==temp) {
+		q = temp;
+		if(*q == ';')	//	Allow comments in file
+			continue;
+		while(get_float_from_within_string(&q,&dummy)) {
+			if(dummy >= dz->duration) {
+				if(!warned) {
+					fprintf(stdout,"WARNING: Times beyond end of sndfile (%lf) in file %s. Ignoring them.\n",dz->duration,filename);
+					fflush(stdout);
+				}
+				break;
+			}
+			*time = dummy;
+			lasttime = *time;
+			time++;
+			cnt++;
+		}
+	}
+	if(fclose(fp)<0) {
+		fprintf(stdout,"WARNING: Failed to close file %s.\n",filename);
+		fflush(stdout);
+	}
+	if((dz->process == SEGSBKWD || dz->process == SEGSZIG) && dz->minstep <= (2.0 * SSPLICELEN * MS_TO_SECS)) {
+		sprintf(errstr,"Some marked segment(s) shorter (%lf secs) than 2 splices (%lf): Cannot proceed.\n",dz->minstep,2.0 * SSPLICELEN * MS_TO_SECS);
+		return DATA_ERROR;
+	}
+	dz->itemcnt = cnt;
+	return(FINISHED);
+}
+
+/************************************ DISTMORE_PARAM_PREPROCESS ************************************/
+
+int distmore_param_preprocess(dataptr dz)
+{
+	int exit_status, phase = 0, startphase = 0, halfwavesetcnt = 0;
+	int n, wavsetsize = 0, maxwavsetsize = 0;
+	float *ibuf = dz->sampbuf[0];
+	if((exit_status = read_samps(ibuf,dz))<0)
+		return(exit_status);
+	while(dz->ssampsread > 0) {
+		for(n = 0; n < dz->ssampsread;n++) {
+			if(ibuf[n] > 0.0) {
+				if(startphase == 0)						//	If startphase not set (at outset), set startphase to equal phase found
+					startphase = 1;
+				phase = 1;
+			} else if(ibuf[n] < 0.0) {
+				if(startphase == 0)
+					startphase = -1;
+				phase = -1;
+			}
+			if(phase != startphase) {								//	If phase changes
+				halfwavesetcnt++;									//	Count half-wavesets
+				if(halfwavesetcnt > 1) {							//	Once we have 2 half-wavesets, we have a waveset
+					maxwavsetsize = max(maxwavsetsize,wavsetsize);	//	Save largest
+					wavsetsize = 0;									//	Reset counts of wavsetsize and halfwavesets	
+					halfwavesetcnt = 0;
+				}
+				startphase = phase;									//	Starting phase reset to current phase
+			}
+			wavsetsize++;											//	Count size of current waveset
+		}
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+	}
+	if(maxwavsetsize > dz->maxxstep) {
+		dz->maxxstep = maxwavsetsize;
+		if((exit_status = recreate_distmore_sndbufs(dz))<0)
+			return(exit_status);
+	}
+	sndseekEx(dz->ifd[0],0,0);
+	return FINISHED;
+}
+
+/************************************ CHECK_DISTMORE_PARAM_VALIDITY_AND_CONSISTENCY ************************************/
+
+int check_distmore_param_validity_and_consistency(dataptr dz)
+{
+	double srate = (double)dz->infile->srate;
+	switch(dz->process) {
+	case(DISTDOUBLE):
+		dz->iparam[0] = (int)round(pow(2.0,dz->iparam[0]));				//	Convert octs to frq multiplier
+		break;
+	case(DISTBRIGHT):
+		dz->iparam[0] = (int)round(dz->param[0] * MS_TO_SECS * srate);	//	Splicelen in samples
+		break;
+	case(SEGSZIG):
+		if(dz->param[ZMINSIZ] > 0 && dz->param[ZMINSIZ] < (SSPLICELEN * 2) + 1) {
+			sprintf(errstr,"MINIMUM ZIG SIZE CANNOT BE LESS THAN %d IF IT IS NOT ZERO\n",(SSPLICELEN * 2) + 1);
+			return DATA_ERROR;
+		}
+		dz->iparam[ZMINSIZ] = (int)round(dz->param[ZMINSIZ] * MS_TO_SECS * srate);	//	Min size of zigs in samples
+		break;
+	}
+	return FINISHED;
+}
+
+/************************************ DISTBRIGHT ************************************/
+
+int distbright(dataptr dz)
+{
+	int exit_status, n, m, done = 0;
+	int lastphase = 0, phase = 0;
+	int startindex, zcro = 0, sttindex = 0;
+	double srate = (double)dz->infile->srate;
+	double *time = dz->parray[0];
+	double *zcros = dz->parray[1];
+	int firsttime, nexttime, samptime;
+	int *ishead = dz->iparray[0], is_head;
+	int *order = dz->iparray[1];			//	Holds reordering sequence
+	float *ibuf = dz->sampbuf[0], *obuf = dz->sampbuf[1], *buf1, *buf2, *bufa = dz->sampbuf[2], *bufb = dz->sampbuf[3], *tempbuf;
+	int increases = 1, temp;
+	int k, j, z, obufpos, stt, sttsamp, endsamp, sampcnt1, sampcnt2;
+	int *sttend = dz->lparray[0];
+	double valn, valm;
+	int splicelen = dz->iparam[0];
+	samptime = 0;
+	startindex = 0;
+	is_head = 1;
+	for(n=0;n<dz->itemcnt;n++) {							//	Initially mark Head/Tail sequence
+		ishead[n] = is_head;
+		is_head = !is_head;
+	}
+	time[dz->itemcnt] = dz->duration;						//	Complete times array with the duration of the src
+	if(dz->mode == 0) {
+		if((exit_status = generate_tail_segments(dz)) < 0)	//	For mode 0, Head/Tail sequence re-marked here, as tail subdivisions added 
+			return exit_status;								//	& dz->itemcnt increased
+	}
+	for(n=0,m=0;n < dz->itemcnt;n++,m+=2) {
+		sttend[m] = (int)round(time[n] * srate);				//	starttime of segment
+		if(flteq(time[n+1],dz->duration))
+			sttend[m+1] = dz->insams[0];
+		else {													//	endtime of segment
+			sttend[m+1] = (int)round(time[n+1] * srate);		//	including splice fade-down time
+			sttend[m+1] += splicelen;
+			sttend[m+1] = min(sttend[m+1],dz->insams[0]);
+		}
+	}
+	firsttime = sttend[sttindex];
+	nexttime  = sttend[sttindex+2];
+	is_head = 1;
+	if((exit_status = read_samps(ibuf,dz))< 0) {
+		sprintf(errstr,"Failed to read data from input file.\n");
+		return(SYSTEM_ERROR);
+	}
+	while(dz->ssampsread > 0) {
+		n = 0;
+		while(n < dz->ssampsread) {
+			if(samptime >= firsttime) {					//	Skip over any sound before the first timemark in marklist
+				if(samptime >= nexttime) {
+					zcros[startindex] = (double)zcro/(time[sttindex+2] - time[sttindex]);
+					startindex++;
+					sttindex += 2;
+					zcro = 0;
+					lastphase = 0;
+					if(startindex >= dz->itemcnt) {	//	NB there is an extra time (src duration) at end of times data
+						done = 1;
+						break;
+					}
+					is_head  = ishead[startindex];
+					nexttime = sttend[sttindex+2];
+				}
+				if(ibuf[n] > 0.0) {
+					phase = 1;
+					if(lastphase == 0)
+						lastphase = phase;
+				} else if(ibuf[n] < 0.0) {
+					phase = -1;
+					if(lastphase == 0)
+						lastphase = phase;
+				}
+				if(phase != lastphase) {
+					zcro++;
+					lastphase = phase;
+				}
+			}
+			samptime++;
+			n++;
+		}
+		if(done)
+			break;
+		if((exit_status = read_samps(ibuf,dz))< 0) {
+			sprintf(errstr,"Failed to read data from input file.\n");
+			return(SYSTEM_ERROR);
+		}
+	}
+	if(dz->mode == 2) {							//	In mode 2, join together H+T segs as single items
+		for(m=1,n=2;n<dz->itemcnt;m++,n+=2)		//						  itemcnt							  itemcnt	
+			time[m] = time[n];					//	H T		H T		H T		END		~OR~	H T		H T		 H END
+		dz->itemcnt = m;						//	h		h		h						h		h		 h
+	}											
+
+	// DO SORT AND THEN RECONSTRUCT
+
+	dz->itemcnt = startindex;					//	Reset count to actual count of zcros data items
+	if(dz->vflag[0])
+		increases = 0;
+	for(n=0;n<dz->itemcnt;n++)
+		order[n] = n;
+	for(n=0;n < dz->itemcnt-1;n++) {			//	Do the data/order sort
+		valn = zcros[n];
+		for(m=n+1;m < dz->itemcnt;m++) {
+			valm = zcros[m];					//	If vals out of order
+			if((increases && valn > valm) || (!increases && valn < valm)) {
+				zcros[n] = valm;				//	Swap vals in array
+				zcros[m] = valn;	
+				valn = zcros[n];				//	Reset valn to its new value
+
+				temp = order[n];				//	Swap order of items
+				order[n] = order[m];
+				order[m] = temp;
+			}
+		}
+	}
+	buf1 = bufa;
+	buf2 = bufb;
+	obufpos = 0;
+
+	//	Copy initial segment into buffer 1
+
+	stt = order[0] * 2;					//	Start and endtimes of segs are in double-length int-array
+	sttsamp = sttend[stt];
+	endsamp = sttend[stt+1];
+	sampcnt1 = endsamp - sttsamp;
+	sndseekEx(dz->ifd[0],sttsamp,0);
+	if((exit_status = read_samps(ibuf,dz))<0)
+		return(exit_status);
+	memcpy((char *)buf1,(char *)ibuf,sampcnt1 * sizeof(float));		//	Copy src chunk to buf1
+	for(k = 0; k < splicelen; k++)
+		buf1[k] = (float)(buf1[k] * ((double)k/(double)splicelen));	//	DO start and end splices
+	for(k = 0, j = sampcnt1-1; k < splicelen; k++,j--)
+		buf1[j] = (float)(buf1[j] * ((double)k/(double)splicelen));
+
+	//	Write the upsplice portion of 1st segment to obuf
+	
+	for(m=0; m < splicelen; m++) {
+		obuf[obufpos++] = buf1[m];
+		//PROBABLY REDUNDANT
+		if(obufpos >= dz->buflen) {
+			if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+				return(exit_status);
+			obufpos = 0;
+		}
+	}
+	//	Copy next segment into buffer 2
+
+	for(n=1;n < dz->itemcnt;n++) {
+		stt = order[n] * 2;
+		sttsamp = sttend[stt];
+		endsamp = sttend[stt+1];
+		sampcnt2 = endsamp - sttsamp;
+		sndseekEx(dz->ifd[0],sttsamp,0);
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+		memcpy((char *)buf2,(char *)ibuf,sampcnt2 * sizeof(float));
+		for(k = 0; k < splicelen; k++)
+			buf2[k] = (float)(buf2[k] * ((double)k/(double)splicelen));
+		for(k = 0, j = sampcnt2-1; k < splicelen; k++,j--)
+			buf2[j] = (float)(buf2[j] * ((double)k/(double)splicelen));
+
+		//	Write buf1 apart from the splice-brackets, to obuf
+
+		for(m=splicelen; m < sampcnt1 - splicelen;m++) {
+			obuf[obufpos++] = buf1[m];
+			if(obufpos >= dz->buflen) {
+				if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+					return(exit_status);
+				obufpos = 0;
+			}
+		}
+
+		//	Write the cross-splice
+
+		for(z = 0;z < splicelen; z++,m++) {
+			obuf[obufpos++] = (float)(buf1[m] + buf2[z]);
+			if(obufpos >= dz->buflen) {
+				if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+					return(exit_status);
+				obufpos = 0;
+			}
+		}
+
+		//	Swap the buffers, and buffer-data
+
+		tempbuf = buf1;
+		buf1	= buf2;
+		buf2	= tempbuf;
+		sampcnt1 = sampcnt2;
+	}
+
+	//	Write all of the remaining segment
+
+	for(m=splicelen; m < sampcnt1; m++) {
+		obuf[obufpos++] = buf1[m];
+		if(obufpos >= dz->buflen) {
+			if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+				return(exit_status);
+			obufpos = 0;
+		}
+	}
+
+	//	Flush the output buffer
+
+	if(obufpos > 0) {
+		if((exit_status = write_samps(obuf,obufpos,dz))<0)
+			return(exit_status);
+	}	
+	return FINISHED;
+}
+
+/************************************ GENERATE_TAIL_SEGMENTS ************************************
+ *
+ *	Slice tail sections into segments approx same size as bracketing head segments
+ */
+
+int generate_tail_segments(dataptr dz)
+{
+	int n, j, k, tailsegcnt;
+	double *time   = dz->parray[0];
+	double *nutime = dz->parray[1];
+	int *ishead   = dz->iparray[0];
+	double stthsize, endhsize, meanhsize, tailsize, randoffset = 0.0;
+	ishead[0] = 1;
+	ishead[1] = 0;
+	nutime[0] = time[0];									//	H T			  H T			H T		
+	nutime[1] = time[1];									// n0 n1		 n2 n3		   n4 n5
+	j = 2;													//	|-|-----------|-|-----------|-|---------
+	stthsize = time[1] - time[0];							//      tailsize
+	for(n=2;n < dz->itemcnt; n+=2) { // Step to next HEAD	//stthsize		endhsize	
+		tailsize = time[n] - time[n-1];						//
+		endhsize = time[n+1] - time[n];						
+		meanhsize = (stthsize + endhsize)/2.0;				// New times(j), at n = 2, if tailsegcnt = 4
+		tailsegcnt = (int)round(tailsize/meanhsize);		// n0 n1		 n2 n3		   n4 n5
+		meanhsize = tailsize/(double)tailsegcnt;			//	|-|-----------|-|-----------|-|---------
+		for(k=1;k < tailsegcnt;k++)	{						// j0 j1 |  |  |		
+			nutime[j] = time[n-1] + (meanhsize * k);		//       j2 j3 j4 (3 new times inserted)
+															//	H T	 T  T  T  		 
+			randoffset = ((drand48() * 2.0) - 1.0)/3.0;		//		<-> <-> <->
+			randoffset *= DISTMORERAND;						//		 j2  j3  j4
+			randoffset *= meanhsize;						//	Rand in range max of (-1/3 to + 1/3 * meanhsize)
+			nutime[j] += randoffset;						//		
+															//
+			ishead[j] = 0;									//	
+			j++;											//	Ending at j5 = n2
+		}													// n0 n1		 n2 n3		   n4 n5
+		nutime[j] = time[n];								//	|-|-----------|-|-----------|-|---------
+		ishead[j++] = 1;									// j0 j1 j2 j3 j4 | |
+		nutime[j] = time[n+1];								//				 j5 j6
+		ishead[j++] = 0;									//	H T	 T  T  T  H T
+		stthsize = endhsize;
+	}
+	if(n == dz->itemcnt) {									//	IF end of file is end of a tail
+		tailsize = time[n] - time[n-1];						//	H T		H T		    End
+		meanhsize = stthsize;								//	| |		| |			 |
+		tailsegcnt = (int)round(tailsize/meanhsize);		//			 n-1		 n	
+		meanhsize = tailsize/(double)tailsegcnt;			//		   endhsize		 |
+		for(k=1;k < tailsegcnt;k++)	{						//		  j22 j23  |  |	 | 
+			nutime[j] = time[n-1] + (meanhsize * k);		//				 j24 j25 |
+															//				 <-> <-> |	
+			randoffset = ((drand48() * 2.0) - 1.0)/3.0;		//			  			 j26
+			randoffset *= DISTMORERAND;						//	....... H  T  T  T   T
+			randoffset *= meanhsize;					
+			nutime[j] += randoffset;
+															
+			ishead[j] = 0;
+			j++;
+		}
+		nutime[j] = time[n];
+	}
+	dz->itemcnt = j;
+	memcpy((char *)time,(char *)nutime,(dz->itemcnt+1) * sizeof(double));
+	memset((char *)nutime,0,(dz->itemcnt+1) * sizeof(double));	//	Clear, as array is reused for zcros-density vals
+	return FINISHED;
+}
+
+/**************************** CREATE_DISTMORE_SNDBUFS ****************************/
+
+int create_distmore_sndbufs(dataptr dz)
+{
+	int n;
+	unsigned int buffersize = 0;
+	switch(dz->process) {
+	case(DISTBRIGHT):
+		dz->bufcnt = 4;
+		buffersize = (unsigned int)round((dz->maxstep * 2) * (double)dz->infile->srate);
+		break;
+	case(DISTDOUBLE):
+		dz->bufcnt = 3;
+		dz->maxxstep = F_SECSIZE * 64;
+		buffersize = dz->maxxstep * 2;
+		break;
+	case(SEGSBKWD):
+		dz->bufcnt = 4;
+		if(dz->mode < 2)
+			buffersize = (unsigned int)round((dz->maxstep * 2) * (double)dz->infile->srate);				//	largest seg + overflow
+		else 
+			buffersize = (unsigned int)round((dz->maxstep * (dz->mode+1)) * (double)dz->infile->srate);	//	largest N segs + overflow
+		break;
+	case(SEGSZIG):
+		if(dz->mode == 0) {
+			dz->bufcnt = 5;
+			buffersize = (unsigned int)round((dz->maxstep * 2) * (double)dz->infile->srate);				//	largest seg + overflow
+		} else {
+			dz->bufcnt = 3;
+			buffersize = (unsigned int)(dz->insams[0] + SAFETY);											//	infile size + overflow
+		}
+		break;
+	}
+	if((dz->sampbuf = (float **)malloc(sizeof(float *) * (dz->bufcnt+1)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->sbufptr = (float **)malloc(sizeof(float *) * dz->bufcnt))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffer pointers.\n");
+		return(MEMORY_ERROR);
+	}
+	buffersize = (buffersize/F_SECSIZE + 1) * F_SECSIZE;
+	dz->buflen = buffersize;
+	if((dz->buflen	< 0) || (dz->buflen	* dz->bufcnt < 0)) {  
+		sprintf(errstr,"INSUFFICIENT MEMORY for sound buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->bigfbuf	= (float*) malloc(dz->buflen * dz->bufcnt * sizeof(float)))==NULL) {  
+		sprintf(errstr,"INSUFFICIENT MEMORY for sound buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	dz->sbufptr[0] = dz->sampbuf[0] = dz->bigfbuf;
+	for(n = 1;n < dz->bufcnt;n++)
+		dz->sbufptr[n] = dz->sampbuf[n] = dz->bigfbuf + (n * dz->buflen);
+	dz->sampbuf[n] = dz->bigfbuf + (n * dz->buflen);
+
+	return(FINISHED);
+}
+
+/**************************** RECREATE_DISTMORE_SNDBUFS ****************************/
+
+int recreate_distmore_sndbufs(dataptr dz)
+{
+	int n;
+	unsigned int buffersize = 0;
+	free(dz->bigbuf);
+	buffersize = dz->maxxstep * 2;
+	buffersize = (buffersize/F_SECSIZE) * F_SECSIZE;
+	dz->buflen = buffersize;
+	if((dz->buflen	< 0) || (dz->buflen	* dz->bufcnt < 0)) {  
+		sprintf(errstr,"INSUFFICIENT MEMORY for sound buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->bigfbuf	= (float*) malloc(dz->buflen * dz->bufcnt * sizeof(float)))==NULL) {  
+		sprintf(errstr,"INSUFFICIENT MEMORY for sound buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	dz->sbufptr[0] = dz->sampbuf[0] = dz->bigfbuf;
+	for(n = 1;n < dz->bufcnt;n++)
+		dz->sbufptr[n] = dz->sampbuf[n] = dz->bigfbuf + (n * dz->buflen);
+	dz->sampbuf[n] = dz->bigfbuf + (n * dz->buflen);
+	return(FINISHED);
+}
+
+/**************************** DISTDOUBLE ****************************/
+
+int distdouble(dataptr dz)
+{
+	int exit_status;
+	int obufpos = 0, wbufpos = 0, n, j, k, lastk = 0, fill, m;
+	float *ibuf = dz->sampbuf[0], *obuf = dz->sampbuf[1], *wbuf = dz->sampbuf[2];
+	int lastphase = 0, phase = 0, zerocross = 0, jj, group = dz->iparam[0];
+	if((exit_status = read_samps(ibuf,dz))< 0) {
+		sprintf(errstr,"Failed to read data from input file.\n");
+		return(SYSTEM_ERROR);
+	}
+	while(dz->ssampsread > 0) {
+		n = 0;
+		while(n < dz->ssampsread) {
+			if(ibuf[n] > 0.0) {
+				phase = 1;
+				if(lastphase == 0)
+					lastphase = phase;
+			} else if(ibuf[n] < 0.0) {
+				phase = -1;
+				if(lastphase == 0)
+					lastphase = phase;
+			}
+			if((lastphase != 0) && (phase != lastphase)) {
+				zerocross++;
+				if(zerocross == 2) {
+					switch(group) {
+					case(2):
+						if(EVEN(wbufpos)) {
+							for(k=0,j=0;k < wbufpos; k+=2,j++)		//	Copy every other sample
+								wbuf[j] = wbuf[k];
+							jj = j;
+							for(k=0;k < jj; k++,j++)				//	Duplicate the copy
+								wbuf[j] = wbuf[k];
+						} else {
+							for(k=0,j=0;k < wbufpos; k+=2,j++)		//	Copy every other sample
+								wbuf[j] = wbuf[k];
+							jj = j;
+							for(k=1;k < jj; k++,j++)				//	Duplicate the copy
+								wbuf[j] = wbuf[k];
+						}
+						break;
+					default:
+						if(wbufpos > dz->iparam[0]) {
+							for(k = 0,j= 0; k < wbufpos; k+=group,j++) {
+								wbuf[j] = wbuf[k];
+								lastk = k;
+							}
+							if(lastk != wbufpos - 1)
+								wbuf[j++] = wbuf[wbufpos - 1];
+							jj = j;
+							fill = (int)round((double)wbufpos/(double)j);
+							for(m=1;m < fill;m++) {
+								for(k=0;k < jj; k++,j++)			//	Duplicate the copy
+									wbuf[j] = wbuf[k];
+							}
+							wbufpos = j;							//	Truncate output (if ness)
+						}
+						break;
+					}
+					for(k=0;k < wbufpos; k++) {					//	Copy to output buffer
+						obuf[obufpos++] = wbuf[k];
+						if(obufpos >= dz->buflen) {
+							if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+								return(exit_status);
+							obufpos = 0;
+						}
+					}
+					memset((char *)wbuf,0,dz->buflen * sizeof(float));
+					zerocross = 0;
+					wbufpos = 0;
+				}
+				lastphase = phase;
+			}
+			wbuf[wbufpos++] = ibuf[n];
+			n++;
+		}
+		if((exit_status = read_samps(ibuf,dz))< 0) {
+			sprintf(errstr,"Failed to read data from input file.\n");
+			return(SYSTEM_ERROR);
+		}
+	}
+	if(obufpos > 0) {
+		if((exit_status = write_samps(obuf,obufpos,dz))<0)
+			return(exit_status);
+	}	
+	return FINISHED;
+}
+
+/************************************ SEGSBKWD ************************************/
+
+int segsbkwd(dataptr dz)
+{
+	int exit_status, n, m, forwards, reversals;
+	double srate = (double)dz->infile->srate;
+	double *time = dz->parray[0];
+	int samptime;
+	float *ibuf = dz->sampbuf[0], *obuf = dz->sampbuf[1], *buf1, *buf2, *bufa = dz->sampbuf[2], *bufb = dz->sampbuf[3], *tempbuf;
+	int modd;
+	int k, j, z, obufpos, stt, sttsamp, endsamp, sampcnt1, sampcnt2;
+	int *sttend = dz->lparray[0];
+	int splicelen = (int)round(SSPLICELEN * MS_TO_SECS * srate);
+	samptime = 0;
+	time[0] = 0.0;											//	Stretch initial time to start of file	
+	time[dz->itemcnt] = dz->duration;						//	Complete times array with the duration of the src
+
+	switch(dz->mode) {
+	case(0):	// H->	<-T
+	case(1):	// H<-	->T
+		break;	
+	case(2):	//  <-- <--
+				//	H T H T
+		for(m=0,n=0;n<=dz->itemcnt;m++,n+=2)	//	H1 T2	H2 T2	H3 T3	end		~OR~	H1 T1	H2 T2	H3	end
+			time[m] = time[n];					//	H1		H2		H3						H1		H2		H3
+		dz->itemcnt = m-1;
+		break;
+	default:
+		modd = dz->mode;						//	modulus for selecting  times to keep
+		if(ODD(dz->mode))						//	modulus is 4 for modes 3 and 4 (etc)
+			modd++;
+		m = 0;
+		for(n=0;n<=dz->itemcnt;n++) {			//	case(3):->	<--------					case(4):<------------	
+			k = n % modd;						//			H	T	H	T							H	T	H	T
+			if(k == 0)							//	case(5):->	<----------------			case(6)	<--------------------
+				time[m++] = time[n];			//			H	T	H	T	H	T					H	T	H	T	H	T
+			if(ODD(dz->mode) && k == 1)			//	case(7):->	<------------------------	case(8):<----------------------------
+				time[m++] = time[n];			//			H	T	H	T	H	T	H	T			H	T	H	T	H	T	H	T
+		}
+		if(time[m-1] != dz->duration)
+			time[m++] = dz->duration;
+		dz->itemcnt = m-1;
+		break;
+	}
+	for(n=0,m=0;n < dz->itemcnt;n++,m+=2) {
+		sttend[m] = (int)round(time[n] * srate);			//	sample-starttime of segment
+		if(flteq(time[n+1],dz->duration))
+			sttend[m+1] = dz->insams[0];
+		else {												//	sample-endtime of segment
+			sttend[m+1] = (int)round(time[n+1] * srate);	//	including splice fade-down time
+			sttend[m+1] += splicelen;
+			sttend[m+1] = min(sttend[m+1],dz->insams[0]);
+		}
+	}
+	switch(dz->mode) {
+	case(0):	// FR
+		forwards = 1;
+		reversals = 1;
+		break;
+	case(1):	// RF
+		forwards = 0;
+		reversals = 1;
+		break;
+	default:					
+		if(EVEN(dz->mode)) {	
+			forwards = 0;		//	case(EVEN):	RRRR.....
+			reversals = 0;
+		} else {
+			forwards = 1;		//	case(ODD):	FRFR.....
+			reversals = 1;
+		}
+		break;
+	}
+
+	// RECONSTRUCT
+
+	buf1 = bufa;
+	buf2 = bufb;
+	obufpos = 0;
+
+	//	Copy initial segment into buffer 1
+
+	stt = 0;						//	Start and endtimes of segs are in double-length int-array
+	sttsamp = sttend[stt];
+	endsamp = sttend[stt+1];
+	sampcnt1 = endsamp - sttsamp;
+	sndseekEx(dz->ifd[0],sttsamp,0);
+	if((exit_status = read_samps(ibuf,dz))<0)
+		return(exit_status);
+	memcpy((char *)buf1,(char *)ibuf,sampcnt1 * sizeof(float));		//	Copy src chunk to buf1
+	if(!forwards)
+		reversebuf(buf1,sampcnt1);
+	if(reversals)
+		forwards = !forwards;
+	for(k = 0; k < splicelen; k++)
+		buf1[k] = (float)(buf1[k] * ((double)k/(double)splicelen));	//	DO start and end splices
+	for(k = 0, j = sampcnt1-1; k < splicelen; k++,j--)
+		buf1[j] = (float)(buf1[j] * ((double)k/(double)splicelen));
+
+	//	Write the upsplice portion of 1st segment to obuf
+	
+	for(m=0; m < splicelen; m++) {
+		obuf[obufpos++] = buf1[m];
+		//PROBABLY REDUNDANT
+		if(obufpos >= dz->buflen) {
+			if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+				return(exit_status);
+			obufpos = 0;
+		}
+	}
+	//	Copy next segment into buffer 2
+
+	for(n=1;n < dz->itemcnt;n++) {
+		stt += 2;
+		sttsamp = sttend[stt];
+		endsamp = sttend[stt+1];
+		sampcnt2 = endsamp - sttsamp;
+		sndseekEx(dz->ifd[0],sttsamp,0);
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+		memcpy((char *)buf2,(char *)ibuf,sampcnt2 * sizeof(float));
+		if(!forwards)
+			reversebuf(buf2,sampcnt2);
+		if(reversals)
+			forwards = !forwards;
+		for(k = 0; k < splicelen; k++)
+			buf2[k] = (float)(buf2[k] * ((double)k/(double)splicelen));
+		for(k = 0, j = sampcnt2-1; k < splicelen; k++,j--)
+			buf2[j] = (float)(buf2[j] * ((double)k/(double)splicelen));
+
+		//	Write buf1 apart from the splice-brackets, to obuf
+
+		for(m=splicelen; m < sampcnt1 - splicelen;m++) {
+			obuf[obufpos++] = buf1[m];
+			if(obufpos >= dz->buflen) {
+				if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+					return(exit_status);
+				obufpos = 0;
+			}
+		}
+
+		//	Write the cross-splice
+
+		for(z = 0;z < splicelen; z++,m++) {
+			obuf[obufpos++] = (float)(buf1[m] + buf2[z]);
+			if(obufpos >= dz->buflen) {
+				if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+					return(exit_status);
+				obufpos = 0;
+			}
+		}
+
+		//	Swap the buffers, and buffer-data
+
+		tempbuf = buf1;
+		buf1	= buf2;
+		buf2	= tempbuf;
+		sampcnt1 = sampcnt2;
+	}
+
+	//	Write all of the remaining segment
+
+	for(m=splicelen; m < sampcnt1; m++) {
+		obuf[obufpos++] = buf1[m];
+		if(obufpos >= dz->buflen) {
+			if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+				return(exit_status);
+			obufpos = 0;
+		}
+	}
+
+	//	Flush the output buffer
+
+	if(obufpos > 0) {
+		if((exit_status = write_samps(obuf,obufpos,dz))<0)
+			return(exit_status);
+	}	
+	return FINISHED;
+}
+
+/************************************ REVERSEBUF ************************************/
+
+void reversebuf(float *buf,int sampcnt)
+{
+	int n,m,k;
+	float temp;
+	k = sampcnt/2;									//	ODD LEN(eg5) k = 5/2 -> 2		EVEN LEN(eg6) k = 6/2 -> 3
+	for(n = 0,m = sampcnt-1;n < k; n++, m--) {		//	len = 5 k = 2	0 1 2 3 4		len = 6 k = 3	0 1 2 3 4 5	
+		temp    = buf[n];							//					|_______|						|_________|
+		buf[n] = buf[m];							//					  |___|							  |_____|	
+		buf[m] = temp;								//				n = 0 1									|_|
+	}												//												n = 0 1 2
+}
+
+/************************************ REVERSEBUF2 ************************************/
+
+void reversebuf2(float *buf1,float *buf2,int sampcnt)
+{
+	int n,m;
+	for(n = 0,m = sampcnt-1;n < sampcnt; n++, m--)
+		buf2[m] = buf1[n];
+}
+
+/************************************ SEGSZIG ************************************/
+
+int segszig(dataptr dz)
+{
+	int exit_status, n, m, repets, done;
+	double srate = (double)dz->infile->srate, stepratio = 1.0;
+	double *time=NULL, thistime = 0.0;
+	int step, cutlen;
+	float *ibuf = dz->sampbuf[0], *obuf=NULL, *buf1=NULL, *buf2=NULL, *bufr=NULL;
+	int k, j, z, obufpos = 0, stt, sttsamp = 0, endsamp = 0, sampcnt1, sampcnt2;
+	int *sttend = NULL;
+	int splicelen = (int)round(SSPLICELEN * MS_TO_SECS * srate);
+	if(dz->mode == 0) {
+		bufr = dz->sampbuf[1];
+		buf1 = dz->sampbuf[2];
+		buf2 = dz->sampbuf[3];
+		obuf = dz->sampbuf[4];
+		time = dz->parray[0];
+		time[0] = 0.0;											//	Stretch initial time to start of file	
+		time[dz->itemcnt] = dz->duration;						//	Complete times array with the duration of the src
+		sttend = dz->lparray[0];
+		for(n=0,m=0;n < dz->itemcnt;n++,m+=2) {
+			sttend[m] = (int)round(time[n] * srate);			//	sample-starttime of segment
+			if(sttend[m] > splicelen)
+				sttend[m] -= splicelen;
+			if(flteq(time[n+1],dz->duration))
+				sttend[m+1] = dz->insams[0];
+			else {												//	sample-endtime of segment
+				sttend[m+1] = (int)round(time[n+1] * srate);	//	including splice fade-down time
+				sttend[m+1] += splicelen;
+				sttend[m+1] = min(sttend[m+1],dz->insams[0]);
+			}
+		}
+	} else {
+		bufr = dz->sampbuf[1];
+		obuf = dz->sampbuf[2];
+	}
+	switch(dz->mode) {
+	case(0):
+
+		done = 0;
+		n = 0;
+		stt = 0;						//	Start and endtimes of segs are in double-length int-array
+		sttsamp = sttend[stt];
+		endsamp = sttend[stt+1];
+		sampcnt1 = endsamp - sttsamp;
+		sndseekEx(dz->ifd[0],sttsamp,0);
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+
+
+		//	Read 1st Head (or whole file) and splice ends
+		
+		memcpy((char *)buf1,(char *)ibuf,sampcnt1 * sizeof(float));		//	Copy src chunk to buf1
+		for(k = 0; k < splicelen; k++)
+			buf1[k] = (float)(buf1[k] * ((double)k/(double)splicelen));	//	DO start and end splices
+		for(k = 0, j = sampcnt1-1; k < splicelen; k++,j--)
+			buf1[j] = (float)(buf1[j] * ((double)k/(double)splicelen));
+
+	//	Write the upsplice portion of 1st segment to obuf
+	
+		for(m=0; m < splicelen; m++) {
+			obuf[obufpos++] = buf1[m];
+			if(obufpos >= dz->buflen) {
+				if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+					return(exit_status);
+				obufpos = 0;
+			}
+		}
+		n++;
+		while(n < dz->itemcnt) {
+			thistime = time[n];
+			if((exit_status = read_values_from_all_existing_brktables(thistime,dz))<0)
+				return exit_status;
+			stt += 2;
+			sttsamp = sttend[stt];
+			endsamp = sttend[stt+1];
+			sampcnt2 = endsamp - sttsamp;
+			sndseekEx(dz->ifd[0],sttsamp,0);
+			if(dz->param[ZFRAC] < 1.0)
+				sampcnt2 = (int)ceil((double)sampcnt2 * dz->param[ZFRAC]);
+
+			if(dz->vflag[0])
+				stepratio = 1.0;
+			step = 0;
+
+			//	If the zigzag is to repeat (dz->iparam[ZREPETS] > 1) then it must shrink
+			//	If shrink MINSIZ IS set as 0, this flags NO  shrinkage
+			//	If shrink MINSIZ <= size of segment, shrinkage is impossible
+
+			if (dz->iparam[ZREPETS] > 1 && (dz->iparam[ZMINSIZ] > 0) && (dz->iparam[ZMINSIZ] <= sampcnt2))
+			if(dz->vflag[0]) {
+				stepratio = 1.0/(pow(((double)sampcnt2/(double)dz->iparam[ZMINSIZ]),(1.0/((double)dz->iparam[ZREPETS] * 2.0))));
+				step = 1;
+            } else {                //RWD added braces
+				step = (int)floor((double)(sampcnt2 - dz->iparam[ZMINSIZ])/((double)dz->iparam[ZREPETS] * 2.0));
+            }
+			//	Copy Tail segment into buffer 2 and splice ends
+			
+			if((exit_status = read_samps(ibuf,dz))<0)
+				return(exit_status);
+			memcpy((char *)buf2,(char *)ibuf,sampcnt2 * sizeof(float));
+			for(k = 0; k < splicelen; k++)
+				buf2[k] = (float)(buf2[k] * ((double)k/(double)splicelen));
+			for(k = 0, j = sampcnt2-1; k < splicelen; k++,j--)
+				buf2[j] = (float)(buf2[j] * ((double)k/(double)splicelen));
+
+			//	Copy Reversed Tailsegment into buffer r 
+			
+			reversebuf2(buf2,bufr,sampcnt2);
+
+			//	Write buf1 (Head) apart from the splice-brackets, to obuf
+
+			for(m=splicelen; m < sampcnt1 - splicelen;m++) {
+				obuf[obufpos++] = buf1[m];
+				if(obufpos >= dz->buflen) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					obufpos = 0;
+				}
+			}
+
+			//	Write the cross-splice from Head to Tail
+
+			for(z = 0;z < splicelen; z++,m++) {
+				obuf[obufpos++] = (float)(buf1[m] + buf2[z]);
+				if(obufpos >= dz->buflen) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					obufpos = 0;
+				}
+			}
+			repets = 0;
+			while(repets < dz->iparam[ZREPETS]) {
+			
+				//	Write buf2 apart from the splice-brackets, to obuf
+
+				for(m=splicelen; m < sampcnt2 - splicelen;m++) {
+					obuf[obufpos++] = buf2[m];
+					if(obufpos >= dz->buflen) {
+						if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+							return(exit_status);
+						obufpos = 0;
+					}
+				}
+
+					//	Write the cross-splice to the reversed version
+
+				if(step > 0) {						
+					reversebuf2(buf2,bufr,sampcnt2);//	Get the reversed version from the possibly shortened normal version
+					if(dz->vflag[0])
+						cutlen = (int)ceil((double)sampcnt2 * stepratio);
+					else
+						cutlen = sampcnt2 - step;		//	Cut short the reversed version
+					cutend_and_splicend(bufr,cutlen,sampcnt2,splicelen);
+					sampcnt2 = cutlen;
+				}
+				for(z = 0;z < splicelen; z++,m++) {
+					obuf[obufpos++] = (float)(buf2[m] + bufr[z]);
+					if(obufpos >= dz->buflen) {
+						if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+							return(exit_status);
+						obufpos = 0;
+					}
+				}
+				
+				//	Write bufr (reversed version) apart from the splice-brackets, to obuf
+
+				for(m=splicelen; m < sampcnt2 - splicelen;m++) {
+					obuf[obufpos++] = bufr[m];
+					if(obufpos >= dz->buflen) {
+						if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+							return(exit_status);
+						obufpos = 0;
+					}
+				}
+				repets++;
+				if(repets < dz->iparam[ZREPETS]) {
+				//	Write the cross-splice FROM the reversed version to the forward version
+					if(step > 0) {
+						reversebuf2(bufr,buf2,sampcnt2);	//	Get the forwards version from the shortened reversed version
+						if(dz->vflag[0])
+							cutlen = (int)ceil((double)sampcnt2 * stepratio);
+						else
+							cutlen = sampcnt2 - step;		//	Cut it short
+						cutend_and_splicend(buf2,cutlen,sampcnt2,splicelen);
+						sampcnt2 = cutlen;
+					}
+					for(z = 0;z < splicelen; z++,m++) {
+						obuf[obufpos++] = (float)(bufr[m] + buf2[z]);
+						if(obufpos >= dz->buflen) {
+							if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+								return(exit_status);
+							obufpos = 0;
+						}
+					}
+				}
+			}
+			n++;
+			if(n >= dz->itemcnt) {
+		
+				//	If no more Heads: Write remainder of reversed version to output and quit
+
+				while(m < sampcnt2) {
+					obuf[obufpos++] = bufr[m++];
+					if(obufpos >= dz->buflen) {
+						if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+							return(exit_status);
+						obufpos = 0;
+					}
+				}
+				done = 1;
+				break;
+			}
+			stt += 2;
+			sttsamp = sttend[stt];
+			endsamp = sttend[stt+1];
+			sampcnt1 = endsamp - sttsamp;
+			sndseekEx(dz->ifd[0],sttsamp,0);
+
+			//	Read Next Head, and splice ends
+
+			if((exit_status = read_samps(ibuf,dz))<0)
+				return(exit_status);
+			memcpy((char *)buf1,(char *)ibuf,sampcnt1 * sizeof(float));
+			for(k = 0; k < splicelen; k++)
+				buf1[k] = (float)(buf1[k] * ((double)k/(double)splicelen));
+			for(k = 0, j = sampcnt1-1; k < splicelen; k++,j--)
+				buf1[j] = (float)(buf1[j] * ((double)k/(double)splicelen));
+
+			//	Write the cross-splice FROM the reversed version to the Head
+
+			for(z = 0;z < splicelen; z++,m++) {
+				obuf[obufpos++] = (float)(bufr[m] + buf1[z]);
+				if(obufpos >= dz->buflen) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					obufpos = 0;
+				}
+			}
+			n++;
+		}
+		if(!done) {				//	Can only be "done" if ended on a Tail
+				
+			//	If not done, Write remainder of (FINAL) head to output
+
+			for(m=splicelen; m < sampcnt1;m++) {
+				obuf[obufpos++] = buf1[m];
+				if(obufpos >= dz->buflen) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					obufpos = 0;
+				}
+			}
+		}
+		break;
+
+	case(1):
+	case(2):
+		sampcnt1 = dz->insams[0];
+		if(dz->param[ZFRAC] < 1.0)
+			sampcnt1 = (int)round(sampcnt1 * dz->param[ZFRAC]);
+		step = 0;
+		if(dz->mode == 2 || dz->vflag[0])
+			stepratio = 1.0;
+		if (dz->iparam[ZREPETS] > 1 && (dz->iparam[ZMINSIZ] > 0) && (dz->iparam[ZMINSIZ] <= sampcnt1)) {
+			if(dz->mode ==1) {
+				if(dz->vflag[0]) {
+					stepratio = 1.0/(pow(((double)sampcnt1/(double)dz->iparam[ZMINSIZ]),(1.0/((double)dz->iparam[ZREPETS] * 2.0))));
+					step = 1;
+				} else
+					step = (int)floor((double)(sampcnt1 - dz->iparam[ZMINSIZ])/((double)dz->iparam[ZREPETS] * 2.0));
+			} else {
+				stepratio = getstepratio(dz);
+				step = 1;
+			}
+		}
+
+		//	Write buf1 (forwards) apart from the endsplice-len, to obuf
+
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+
+		if(dz->param[ZFRAC] < 1.0) {
+			for(k = 0,j = sampcnt1 - 1;k < splicelen; k++,j--)
+				ibuf[j] = (float)(ibuf[j] * ((double)k/(double)splicelen));
+		}
+		for(m=0; m < sampcnt1 - splicelen;m++) {
+			obuf[obufpos++] = ibuf[m];
+			if(obufpos >= dz->buflen) {
+				if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+					return(exit_status);
+				obufpos = 0;
+			}
+		}
+		//	Copy segment (reversing it) into buffer r 
+		
+		reversebuf2(ibuf,bufr,sampcnt1);
+
+		if(step > 0) {
+			if(dz->mode == 2 || dz->vflag[0]) {
+				cutlen = (int)ceil((double)sampcnt1 * stepratio);
+				cutlen += splicelen;
+				if(cutlen > dz->insams[0])
+					cutlen = dz->insams[0];
+			} else
+				cutlen = sampcnt1 - step;							//	Cut short the reversed version if ness
+			cutend_and_splicend(bufr,cutlen,sampcnt1,splicelen);	//	and splice the end
+			sampcnt1 = cutlen;
+		}
+		//	Write the cross-splice from Forwards to Reverse
+
+		for(z = 0;z < splicelen; z++,m++) {
+			obuf[obufpos++] = (float)(ibuf[m] + bufr[z]);
+			if(obufpos >= dz->buflen) {
+				if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+					return(exit_status);
+				obufpos = 0;
+			}
+		}
+
+		//	Write the body of the Reverse file
+
+		for(m=splicelen; m < sampcnt1 - splicelen;m++) {
+			obuf[obufpos++] = bufr[m];
+			if(obufpos >= dz->buflen) {
+				if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+					return(exit_status);
+				obufpos = 0;
+			}
+		}
+		repets = 1;
+		while(repets < dz->iparam[ZREPETS]) {
+		//	Copy reversed segment (possibly shortened) (righting it) into buffer 1 
+		
+			reversebuf2(bufr,ibuf,sampcnt1);
+
+			if(step > 0) {						
+				if(dz->mode == 2 || dz->vflag[0]) {
+					sampcnt1 -= splicelen;
+					cutlen = (int)ceil((double)sampcnt1 * stepratio);
+					cutlen += splicelen;
+					if(cutlen > dz->insams[0])
+						cutlen = dz->insams[0];
+				} else
+					cutlen = sampcnt1 - step;		//	Cut short the righted version
+				cutend_and_splicend(ibuf,cutlen,sampcnt1,splicelen);
+				sampcnt1 = cutlen;
+			}
+				//	Write the cross-splice to the righted version
+
+			for(z = 0;z < splicelen; z++,m++) {
+				obuf[obufpos++] = (float)(bufr[m] + ibuf[z]);
+				if(obufpos >= dz->buflen) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					obufpos = 0;
+				}
+			}
+			//	Write the body of the Righted file
+
+			for(m=splicelen; m < sampcnt1 - splicelen;m++) {
+				obuf[obufpos++] = ibuf[m];
+				if(obufpos >= dz->buflen) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					obufpos = 0;
+				}
+			}
+			//	Copy righted segment (possibly shortened) (reversing it) into buffer r 
+		
+			reversebuf2(ibuf,bufr,sampcnt1);
+
+			if(step > 0) {						
+				if(dz->mode == 2 || dz->vflag[0]) {
+					sampcnt1 -= splicelen;
+					cutlen = (int)ceil((double)sampcnt1 * stepratio);
+					cutlen += splicelen;
+					if(cutlen > dz->insams[0])
+						cutlen = dz->insams[0];
+				} else
+					cutlen = sampcnt1 - step;		//	Cut short the reversed version
+				cutend_and_splicend(bufr,cutlen,sampcnt1,splicelen);
+				sampcnt1 = cutlen;
+			}
+			
+				//	Write the cross-splice to the reversed version
+
+			for(z = 0;z < splicelen; z++,m++) {
+				obuf[obufpos++] = (float)(ibuf[m] + bufr[z]);
+				if(obufpos >= dz->buflen) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					obufpos = 0;
+				}
+			}
+			//	Write the body of the Reversed file
+
+			for(m=splicelen; m < sampcnt1 - splicelen;m++) {
+				obuf[obufpos++] = bufr[m];
+				if(obufpos >= dz->buflen) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					obufpos = 0;
+				}
+			}
+			repets++;
+		}
+
+		//	Write the remainder of the last reversed file
+
+		while(m < sampcnt1) {
+			obuf[obufpos++] = bufr[m++];
+			if(obufpos >= dz->buflen) {
+				if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+					return(exit_status);
+				obufpos = 0;
+			}
+		}
+		break;
+	}
+
+	//	Flush the output buffer
+
+	if(obufpos > 0) {
+		if((exit_status = write_samps(obuf,obufpos,dz))<0)
+			return(exit_status);
+	}	
+	return FINISHED;
+}
+
+/************************************ CUTEND_AND_SPLICEND ************************************/
+
+void cutend_and_splicend(float *buf,int cutlen,int sampcnt,int splicelen)
+{
+	int k, j;
+	for(k = 0,j=cutlen-1;k < splicelen;k++,j--)
+		buf[j] = (float)(buf[j] * ((double)k/(double)splicelen));
+	for(j=cutlen;j < sampcnt;j++)
+		buf[j] = 0.0;
+}
+
+/******************************** GETSTEPRATIO **********************
+ *
+ *		Start length  A: endlen B
+ *		If k = 2 * repets (counts every zig and zag), and "r" = stepratio
+ *		Outsamps = A + (A*r) + (A*r*r) + (A*r*r*r) ....+ B
+ *					 0	  1    2		 (k-1)
+ *				 = Ar + Ar + Ar +  ....Ar       + B
+ */
+
+double getstepratio(dataptr dz)
+{
+	int n, k = dz->iparam[ZREPETS] * 2, increasing, decreasing;
+	double splicedur = SSPLICELEN * MS_TO_SECS;
+	double r, outlen, outlenbas = dz->param[ZMINSIZ] * MS_TO_SECS;
+	double miss, lastmiss, flterr = FLTERR, duration;
+	duration = dz->duration;
+	duration *= dz->param[ZFRAC];
+	while(duration + (outlenbas * (k-1)) >= dz->param[ZDUR]) {		//	If required output dur too SHORT for no of repets
+		if(k == 2) {													//	reduce number of repets	
+			r = duration/(dz->param[ZDUR] + splicedur);
+			dz->iparam[ZREPETS] = k/2;
+			return r;
+		}
+		k -= 2;
+	}
+	outlen = -1;
+	while(outlen <= dz->param[ZDUR]) {					//	If required output dur too long for no of repets
+		outlen = outlenbas;								//	increase number of repets		
+		for(n = 0; n < k-1; n++)
+			outlen += duration;
+		if(outlen < dz->param[ZDUR] * 2.0)				//	i.e. start with an overshoot estimate, to shrink from
+			k += 2;
+	}
+	r = pow((outlenbas/duration),(1.0/(double)(k-1)));
+	outlen = -1.0;
+	lastmiss = HUGE;
+	increasing = 0;
+	decreasing = 0;
+	//	Find the number of repetitions which gives a ratio approaching closest to min value
+	for(;;) {
+		r = pow((outlenbas/duration),(1.0/(double)(k-1)));
+		outlen = outlenbas;
+		for(n = 0; n < k-1; n++)						//						  2		  3			  (k-1)
+			outlen += duration * pow(r,n);			//	dur(1) + dur*r + dur*r + dur*r .... +dur*r
+		miss = fabs(outlen - dz->param[ZDUR]);
+		if(miss < lastmiss) {
+			if(decreasing)
+				break;
+			k++;
+			increasing = 1;
+		} else {
+			if(increasing)
+				break;
+			k--;
+			decreasing = 1;
+		}
+		lastmiss = miss;
+	}
+	k--;
+	r = pow((outlenbas/duration),(1.0/(double)(k-1)));
+	if(outlen > dz->param[ZDUR])
+		increasing = 0;
+	else
+		increasing = 1;
+	//	Hone ratio to give exaxct output duration
+	while(!flteq(outlen,dz->param[ZDUR])) {
+		if(outlen > dz->param[ZDUR]) {
+			if(increasing)					//	i.e. outlen increasing but now too big
+				flterr /= 2.0;				//	Start to step down, by smaller steps
+			r -= flterr;
+			increasing = 0;
+		} else {
+			if(!increasing)					//	i.e. outlen decreasing but now too small
+				flterr /= 2.0;				//	Start to step up, by smaller steps
+			r += flterr;
+			increasing = 1;
+		}
+		outlen = outlenbas;
+		for(n = 0; n < k-1; n++)						//						  2		  3			  (k-1)
+			outlen += duration * pow(r,n);			//	dur(1) + dur*r + dur*r + dur*r .... +dur*r
+	}
+	dz->iparam[ZREPETS] = k/2;
+	return r;
+}

+ 1260 - 0
dev/standnew/distrep.c

@@ -0,0 +1,1260 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <tkglobals.h>
+#include <pnames.h>
+#include <filetype.h>
+#include <processno.h>
+#include <modeno.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <math.h>
+#include <mixxcon.h>
+#include <osbind.h>
+#include <standalone.h>
+#include <ctype.h>
+#include <sfsys.h>
+#include <string.h>
+#include <srates.h>
+
+#define DRSPLICE	15
+#define drsplice ringsize
+
+#define	DRREP 0
+#define	DRGRP 1
+#define	DRSKP 2
+#define	DRSPL 3
+
+#ifdef unix
+#define round(x) lround((x))
+#endif
+
+char errstr[2400];
+
+int anal_infiles = 1;
+int	sloom = 0;
+int sloombatch = 0;
+
+const char* cdp_version = "6.1.0";
+
+//CDP LIB REPLACEMENTS
+static int check_distrep_param_validity_and_consistency(dataptr dz);
+static int setup_distrep_application(dataptr dz);
+static int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+static int parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int setup_distrep_param_ranges_and_defaults(dataptr dz);
+static int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int establish_application(dataptr dz);
+static int initialise_vflags(dataptr dz);
+static int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int mark_parameter_types(dataptr dz,aplptr ap);
+static int assign_file_data_storage(int infilecnt,dataptr dz);
+static int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+static int get_the_mode_from_cmdline(char *str,dataptr dz);
+static int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt);
+static double dbtolevel(double val);
+static int distrep(dataptr dz);
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status;
+	dataptr dz = NULL;
+	char **cmdline;
+	int  cmdlinecnt;
+	int n;
+	aplptr ap;
+	int is_launched = FALSE;
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+						/* CHECK FOR SOUNDLOOM */
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {					// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc == 2) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+	}
+	if(!sloom) {
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		dz->maxmode = 2;
+		if((exit_status = get_the_mode_from_cmdline(cmdline[0],dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);
+		}
+		cmdline++;
+		cmdlinecnt--;
+		// setup_particular_application =
+		if((exit_status = setup_distrep_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+
+	// parse_infile_and_hone_type() = 
+	if((exit_status = parse_infile_and_check_type(cmdline,dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// setup_param_ranges_and_defaults() =
+	if((exit_status = setup_distrep_param_ranges_and_defaults(dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// open_first_infile		CDP LIB
+	if((exit_status = open_first_infile(cmdline[0],dz))<0) {	
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);	
+		return(FAILED);
+	}
+	cmdlinecnt--;
+	cmdline++;
+
+//	handle_extra_infiles() : redundant
+	// handle_outfile() = 
+	if((exit_status = handle_the_outfile(&cmdlinecnt,&cmdline,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+//	handle_formants()			redundant
+//	handle_formant_quiksearch()	redundant
+//	handle_special_data()		redundant
+ 
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+//	check_param_validity_and_consistency....
+	if((exit_status = check_distrep_param_validity_and_consistency(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	is_launched = TRUE;
+	dz->bufcnt = 2;
+	if((dz->sampbuf = (float **)malloc(sizeof(float *) * (dz->bufcnt+1)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->sbufptr = (float **)malloc(sizeof(float *) * dz->bufcnt))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffer pointers.\n");
+		return(MEMORY_ERROR);
+	}
+	for(n = 0;n <dz->bufcnt; n++)
+		dz->sampbuf[n] = dz->sbufptr[n] = (float *)0;
+	dz->sampbuf[n] = (float *)0;
+
+	if((exit_status = create_sndbufs(dz))<0) {							// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//param_preprocess()						redundant
+	//spec_process_file =
+	if((exit_status = distrep(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = complete_output(dz))<0) {										// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);		// CDP LIB
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc, brkcnt;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	brkcnt = tipc;
+	//THERE ARE NO INPUTFILE brktables USED IN THIS PROCESS
+	if(brkcnt>0) {
+		if((exit_status = setup_and_init_input_brktable_constants(dz,brkcnt))<0)			  
+			return(exit_status);
+	}
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+		return(exit_status);
+	
+	// establish_infile_constants() replaced by
+	dz->infilecnt = 1;
+	//establish_bufptrs_and_extra_buffers():
+	return(FINISHED);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}						 		/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_OUTFILE *********************/
+
+int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status;
+	char *filename = (*cmdline)[0];
+	if(filename[0]=='-' && filename[1]=='f') {
+		dz->floatsam_output = 1;
+		dz->true_outfile_stype = SAMP_FLOAT;
+		filename+= 2;
+	}
+	if(!sloom) {
+		if(file_has_invalid_startchar(filename) || value_is_numeric(filename)) {
+			sprintf(errstr,"Outfile name %s has invalid start character(s) or looks too much like a number.\n",filename);
+			return(DATA_ERROR);
+		}
+	}
+	strcpy(dz->outfilename,filename);	   
+	if((exit_status = create_sized_outfile(filename,dz))<0)
+		return(exit_status);
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/************************* SETUP_DISTREP_APPLICATION *******************/
+
+int setup_distrep_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	// SEE parstruct FOR EXPLANATION of next 2 functions
+	if((exit_status = set_param_data(ap,0   ,2,2,"II"))<0)
+		return(FAILED);
+	if((exit_status = set_vflgs(ap,"ks",2,"id","",0,0,""))<0)
+		return(FAILED);
+	// set_legal_infile_structure -->
+	dz->has_otherfile = FALSE;
+	// assign_process_logic -->
+	dz->input_data_type = SNDFILES_ONLY;
+	dz->process_type	= UNEQUAL_SNDFILE;	
+	dz->outfiletype  	= SNDFILE_OUT;
+	return application_init(dz);	//GLOBAL
+}
+
+/************************* PARSE_INFILE_AND_CHECK_TYPE *******************/
+
+int parse_infile_and_check_type(char **cmdline,dataptr dz)
+{
+	int exit_status;
+	infileptr infile_info;
+	if(!sloom) {
+		if((infile_info = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for infile structure to test file data.");
+			return(MEMORY_ERROR);
+		} else if((exit_status = cdparse(cmdline[0],infile_info))<0) {
+			sprintf(errstr,"Failed to parse input file %s\n",cmdline[0]);
+			return(PROGRAM_ERROR);
+		} else if(infile_info->filetype != SNDFILE)  {
+			sprintf(errstr,"File %s is not of correct type\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if(infile_info->channels != 1)  {
+			sprintf(errstr,"File %s is not of correct type (must be mono)\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if((exit_status = copy_parse_info_to_main_structure(infile_info,dz))<0) {
+			sprintf(errstr,"Failed to copy file parsing information\n");
+			return(PROGRAM_ERROR);
+		}
+		free(infile_info);
+	}
+	return(FINISHED);
+}
+
+/************************* SETUP_DISTREP_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_distrep_param_ranges_and_defaults(dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	// NB total_input_param_cnt is > 0 !!!
+	if((exit_status = setup_input_param_range_stores(ap->total_input_param_cnt,ap))<0)
+		return(FAILED);
+	// get_param_ranges()
+	ap->lo[0]  		= 2.0;
+	ap->hi[0]  		= BIG_VALUE;
+	ap->default_val[0]  = 2.0;
+	ap->lo[1]  		= 1.0;
+	ap->hi[1]  		= MAX_CYCLECNT;
+	ap->default_val[1]  = 1.0;
+	ap->lo[2]  		= 0.0;
+	ap->hi[2]  		= MAX_CYCLECNT;
+	ap->default_val[2]  = 0.0;
+	ap->lo[3]  		= 0.0;
+	ap->hi[3]  		= 50.0;
+	ap->default_val[3]  = DRSPLICE;
+	dz->maxmode = 2;
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_distrep_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int read_special_data(char *str,dataptr dz)	
+{
+	return(FINISHED);
+}
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+	usage2("distrep");
+	return(USAGE_ONLY);
+}
+
+/**************************** CHECK_DISTREP_PARAM_VALIDITY_AND_CONSISTENCY *****************************/
+
+int check_distrep_param_validity_and_consistency(dataptr dz)
+{
+	dz->iparam[DRSPL] = (int)round(dz->param[DRSPL] * MS_TO_SECS * (double)dz->infile->srate);
+	return FINISHED;
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if(!strcmp(prog_identifier_from_cmdline,"distrep"))				dz->process = DISTREP;
+	else {
+		sprintf(errstr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/******************************** SETUP_AND_INIT_INPUT_BRKTABLE_CONSTANTS ********************************/
+
+int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt)
+{	
+	int n;
+	if((dz->brk      = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<brkcnt;n++) {
+		dz->brk[n]     = NULL;
+		dz->brkptr[n]  = NULL;
+		dz->brkinit[n] = 0;
+		dz->brksize[n] = 0;
+	}
+	return(FINISHED);
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+	if(!strcmp(str,"distrep")) {
+		fprintf(stderr,
+	    "USAGE:\n"
+	    "distrep distrep mode infile outfile multiplier ccyleccnt\n"
+		"       [-kskipcycles] [-ssplicelen]\n"
+		"\n"
+		"Mode 1: TIMESTRETCH FILE BY REPEATING 'WAVECYCLES'\n"
+		"Mode 2: REPEAT 'WAVECYCLES' BUT THEN CYCLES SKIP TO AVOID TIMESTRETCH\n"
+		"\n"
+		"Uses brief splices between repeated blocks.\n"
+		"\n"
+		"MULTIPLIER: (integer) is no. of times each wavecycle(grp) repeats.\n"
+    	"CYCLECNT:   (integer) is no. wavecycles in repeated groups.\n"
+		"SKIPCYCLES: number of cycles to ignore (skip over) at file start.\n"
+		"SPLICELEN:  mS splices of repeated blocks (default 15).\n"
+		"\n"
+		"multiplier and cyclecnt may vary over time.\n"
+		"\n"
+		"Works on MONO files only\n");
+	} else
+		fprintf(stdout,"Unknown option '%s'\n",str);
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	fprintf(stderr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/******************************** DISTREP ********************************/
+
+int distrep(dataptr dz)
+{
+	int exit_status, startphase = 0, zerocrossed = 0, last_total_samps_read = 0;
+	float *ibuf = dz->sampbuf[0], *obuf = dz->sampbuf[1];
+	int arraysize = (dz->insams[0]/2) + 1, k, n = 0, obufpos = 0, ibufpos = 0, wavsetcnt = 0;
+	double srate = (double)dz->infile->srate, time, spliceratio;
+	int *wavsetarray = NULL;
+	int sttwavset, endwavset, sttsamp, endsamp, sampcnt, outrepgpcnt, samps_writ, totalsamps, reversecnt, passno;
+	int done, splic, advanced;
+	
+	if((wavsetarray = (int *)malloc(sizeof(int) * arraysize))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for waveset_store..\n");
+		return(MEMORY_ERROR);
+	}
+
+	if((exit_status = read_samps(ibuf,dz))<0)
+		return(exit_status);
+
+	//	Find and store absolute sample-addresses of all wavesets
+
+	while(dz->ssampsread > 0) {
+		for(n=0;n<dz->ssampsread;n++) {
+			switch(startphase) {
+			case(0):
+				if(ibuf[n] > 0.0) {
+					startphase = 1;
+					wavsetarray[wavsetcnt++] = last_total_samps_read + n;
+				} else if(ibuf[n] < 0.0) {
+					startphase = -1;
+					wavsetarray[wavsetcnt++] = last_total_samps_read + n;
+				}
+				break;
+			case(1):
+				if(zerocrossed && (ibuf[n] > 0.0)) {
+					wavsetarray[wavsetcnt++] = last_total_samps_read + n;
+					zerocrossed = 0;
+				}
+				if(!zerocrossed && (ibuf[n] < 0.0))
+					zerocrossed = 1;
+				break;
+			case(-1):
+				if(zerocrossed && (ibuf[n] < 0.0)) {
+					wavsetarray[wavsetcnt++] = last_total_samps_read + n;
+					zerocrossed = 0;
+				}
+				if(!zerocrossed && (ibuf[n] > 0.0))
+					zerocrossed = 1;
+				break;
+			}
+		}
+		last_total_samps_read = dz->total_samps_read;
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+	}
+	if((sndseekEx(dz->ifd[0],0,0) < 0)){
+        sprintf(errstr,"sndseek failed\n");
+        return SYSTEM_ERROR;
+    }
+	dz->total_samps_read = 0;
+
+	if(dz->iparam[DRSKP] > 0) {										//	Skip any unwanted initial wavesets
+		for(n=0,k = dz->iparam[DRSKP];k < wavsetcnt; n++,k++)
+			wavsetarray[n] = wavsetarray[k];
+		wavsetcnt = n;
+	}
+	if(wavsetcnt == 0) {
+		sprintf(errstr,"No wavesets found.\n");
+		return GOAL_FAILED;
+	}
+	obufpos = 0;
+	sttwavset = 0;
+	done = 0;
+	passno = 0;
+	while(!done) {
+		time = (double)wavsetarray[sttwavset]/srate;
+		if((exit_status = read_values_from_all_existing_brktables(time,dz)) < 0)
+			return exit_status;
+		sttsamp   = wavsetarray[sttwavset];
+		endwavset = sttwavset + dz->iparam[DRGRP]; 
+		if(endwavset > wavsetcnt) { 
+			if(passno == 0) {
+				sprintf(errstr,"Insufficient wavesets found for the parameters used.\n");
+				return SYSTEM_ERROR;
+			}
+			break;
+		}
+		endsamp   = wavsetarray[endwavset];
+		sampcnt = endsamp - sttsamp;
+		outrepgpcnt = sampcnt * dz->iparam[DRREP];
+		if(outrepgpcnt <= dz->iparam[DRSPL] * 2)
+			splic = outrepgpcnt/2;										//	If repeated group is less than 2 splices in length
+		else															//	Shorten splice
+			splic = dz->iparam[DRSPL];
+		if((sndseekEx(dz->ifd[0],sttsamp,0) < 0)){
+			sprintf(errstr,"sndseek failed\n");
+			return SYSTEM_ERROR;
+		}
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+		ibufpos = 0;
+		advanced = 0;
+		totalsamps = 0;
+		reversecnt = outrepgpcnt - 1;
+		for(k = 0; k < dz->iparam[DRREP]; k++) {						//	For each grp repetition
+			if(advanced) {												//	If last read of wavesetgrp involved reading a further input buffer
+				if((sndseekEx(dz->ifd[0],sttsamp,0) < 0)){				//	Reset the read-position in input file, and read a new buffer
+					sprintf(errstr,"sndseek failed\n");
+					return SYSTEM_ERROR;
+				}
+				if((exit_status = read_samps(ibuf,dz))<0)
+					return(exit_status);
+			}
+			ibufpos = 0;
+			for(n = 0; n < sampcnt;n++) {								//	Copy input group to obuf
+				if(totalsamps < splic) {
+					spliceratio = (double)totalsamps/(double)splic;		//	Splice start of entire repeating-group
+					obuf[obufpos++] = (float)(ibuf[ibufpos] * spliceratio);
+					ibufpos++;
+				} else if(reversecnt < splic) {
+					spliceratio = (double)reversecnt/(double)splic;		//	Splice end of entire repeating-group
+					obuf[obufpos++] = (float)(ibuf[ibufpos] * spliceratio);
+					ibufpos++;
+				} else 	
+					obuf[obufpos++] = ibuf[ibufpos++];	
+				if(obufpos >= dz->buflen) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					obufpos = 0;
+				}
+				if(ibufpos >= dz->buflen) {
+					if((exit_status = read_samps(ibuf,dz))<0)
+						return(exit_status);
+					advanced = 1;										//	If read exceeds buffer size, note that we've advanced in infile
+					ibufpos = 0;										//	so will need to baktrak (seek) for next repetition of group
+				}
+				totalsamps++;
+				reversecnt--;
+			}
+		}
+		if(dz->mode == 0)
+			sttwavset = endwavset;
+		else {
+			samps_writ = dz->total_samps_written + obufpos;
+			k = sttwavset;
+			while(wavsetarray[k] < samps_writ) {
+				k++;
+				if(k >= wavsetcnt) {
+					done = 1;
+					break;
+				}
+			}
+			if(done)
+				break;
+			if(samps_writ - wavsetarray[k-1] < wavsetarray[k] - samps_writ)
+				k--;													//	This is waveset nearest to output time so far
+
+			sttwavset = k;
+		}
+		passno++;
+	}
+	if(obufpos > 0) {
+		if((exit_status = write_samps(obuf,obufpos,dz))<0)
+			return(exit_status);
+	}
+	if(dz->total_samps_written <= 0) {
+		sprintf(errstr,"No output created.\n");
+		return GOAL_FAILED;
+	}
+	return FINISHED;
+}
+
+/****************************** GET_MODE *********************************/
+
+int get_the_mode_from_cmdline(char *str,dataptr dz)
+{
+	char temp[200], *p;
+	if(sscanf(str,"%s",temp)!=1) {
+		sprintf(errstr,"Cannot read mode of program.\n");
+		return(USAGE_ONLY);
+	}
+	p = temp + strlen(temp) - 1;
+	while(p >= temp) {
+		if(!isdigit(*p)) {
+			fprintf(stderr,"Invalid mode of program entered.\n");
+			return(USAGE_ONLY);
+		}
+		p--;
+	}
+	if(sscanf(str,"%d",&dz->mode)!=1) {
+		fprintf(stderr,"Cannot read mode of program.\n");
+		return(USAGE_ONLY);
+	}
+	if(dz->mode <= 0 || dz->mode > dz->maxmode) {
+		fprintf(stderr,"Program mode value [%d] is out of range [1 - %d].\n",dz->mode,dz->maxmode);
+		return(USAGE_ONLY);
+	}
+	dz->mode--;		/* CHANGE TO INTERNAL REPRESENTATION OF MODE NO */
+	return(FINISHED);
+}
+

+ 1495 - 0
dev/standnew/distshift.c

@@ -0,0 +1,1495 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <tkglobals.h>
+#include <pnames.h>
+#include <filetype.h>
+#include <processno.h>
+#include <modeno.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <math.h>
+#include <mixxcon.h>
+#include <osbind.h>
+#include <standalone.h>
+#include <ctype.h>
+#include <sfsys.h>
+#include <string.h>
+#include <srates.h>
+
+
+#ifdef unix
+#define round(x) lround((x))
+#endif
+
+char errstr[2400];
+
+int anal_infiles = 1;
+int	sloom = 0;
+int sloombatch = 0;
+
+const char* cdp_version = "7.0.0";
+
+//CDP LIB REPLACEMENTS
+static int check_distshift_param_validity_and_consistency(dataptr dz);
+static int setup_distshift_application(dataptr dz);
+static int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+static int parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int setup_distshift_param_ranges_and_defaults(dataptr dz);
+static int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int establish_application(dataptr dz);
+static int initialise_vflags(dataptr dz);
+static int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int mark_parameter_types(dataptr dz,aplptr ap);
+static int assign_file_data_storage(int infilecnt,dataptr dz);
+static int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+static int get_the_mode_from_cmdline(char *str,dataptr dz);
+static int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt);
+static int count_wavesets(int *initial_phase,dataptr dz);
+static int store_wavesets(int initial_phase,dataptr dz);
+static int distort_shift(dataptr dz);
+static int distort_swap(dataptr dz);
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status;
+	dataptr dz = NULL;
+	char **cmdline;
+	int  cmdlinecnt;
+	int n;
+	aplptr ap;
+	int is_launched = FALSE;
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+						/* CHECK FOR SOUNDLOOM */
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {					// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc == 2) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+	}
+	if(!sloom) {
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		dz->maxmode = 2;
+		if((exit_status = get_the_mode_from_cmdline(cmdline[0],dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);
+		}
+		cmdline++;
+		cmdlinecnt--;
+		// setup_particular_application =
+		if((exit_status = setup_distshift_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+
+	// parse_infile_and_hone_type() = 
+	if((exit_status = parse_infile_and_check_type(cmdline,dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// setup_param_ranges_and_defaults() =
+	if((exit_status = setup_distshift_param_ranges_and_defaults(dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// open_first_infile		CDP LIB
+	if((exit_status = open_first_infile(cmdline[0],dz))<0) {	
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);	
+		return(FAILED);
+	}
+	cmdlinecnt--;
+	cmdline++;
+
+//	handle_extra_infiles() : redundant
+	// handle_outfile() = 
+	if((exit_status = handle_the_outfile(&cmdlinecnt,&cmdline,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+//	handle_formants()			redundant
+//	handle_formant_quiksearch()	redundant
+//	handle_special_data()		redundant
+ 
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	is_launched = TRUE;
+	dz->bufcnt = 1;
+	if((dz->sampbuf = (float **)malloc(sizeof(float *) * (dz->bufcnt+1)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->sbufptr = (float **)malloc(sizeof(float *) * dz->bufcnt))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffer pointers.\n");
+		return(MEMORY_ERROR);
+	}
+	for(n = 0;n <dz->bufcnt; n++)
+		dz->sampbuf[n] = dz->sbufptr[n] = (float *)0;
+	dz->sampbuf[n] = (float *)0;
+
+	if((exit_status = create_sndbufs(dz))<0) {							// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+//	check_param_validity_and_consistency....
+	if((exit_status = check_distshift_param_validity_and_consistency(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//param_preprocess()						redundant
+	//spec_process_file =
+	switch(dz->mode) {
+	case(0): exit_status = distort_shift(dz);	break;
+	case(1): exit_status = distort_swap(dz);	break;
+	}
+	if(exit_status < 0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = complete_output(dz))<0) {										// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);		// CDP LIB
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc, brkcnt;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	brkcnt = tipc;
+	//THERE ARE NO INPUTFILE brktables USED IN THIS PROCESS
+	if(brkcnt>0) {
+		if((exit_status = setup_and_init_input_brktable_constants(dz,brkcnt))<0)			  
+			return(exit_status);
+	}
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+		return(exit_status);
+	
+	// establish_infile_constants() replaced by
+	dz->infilecnt = 1;
+	//establish_bufptrs_and_extra_buffers():
+	return(FINISHED);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}						 		/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_OUTFILE *********************/
+
+int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status;
+	char *filename = (*cmdline)[0];
+	if(filename[0]=='-' && filename[1]=='f') {
+		dz->floatsam_output = 1;
+		dz->true_outfile_stype = SAMP_FLOAT;
+		filename+= 2;
+	}
+	if(!sloom) {
+		if(file_has_invalid_startchar(filename) || value_is_numeric(filename)) {
+			sprintf(errstr,"Outfile name %s has invalid start character(s) or looks too much like a number.\n",filename);
+			return(DATA_ERROR);
+		}
+	}
+	strcpy(dz->outfilename,filename);	   
+	if((exit_status = create_sized_outfile(filename,dz))<0)
+		return(exit_status);
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/************************* SETUP_DISTSHIFT_APPLICATION *******************/
+
+int setup_distshift_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	// SEE parstruct FOR EXPLANATION of next 2 functions
+	if(dz->mode==0)	exit_status = set_param_data(ap,0   ,2,2,"ii");
+	else			exit_status = set_param_data(ap,0   ,2,1,"i0");
+	if(exit_status < 0)
+		return(FAILED);
+	if((exit_status = set_vflgs(ap,"",0,"","",0,0,""))<0)
+		return(FAILED);
+	// set_legal_infile_structure -->
+	dz->has_otherfile = FALSE;
+	// assign_process_logic -->
+	dz->input_data_type = SNDFILES_ONLY;
+	dz->process_type	= UNEQUAL_SNDFILE;	
+	dz->outfiletype  	= SNDFILE_OUT;
+	return application_init(dz);	//GLOBAL
+}
+
+/************************* PARSE_INFILE_AND_CHECK_TYPE *******************/
+
+int parse_infile_and_check_type(char **cmdline,dataptr dz)
+{
+	int exit_status;
+	infileptr infile_info;
+	if(!sloom) {
+		if((infile_info = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for infile structure to test file data.");
+			return(MEMORY_ERROR);
+		} else if((exit_status = cdparse(cmdline[0],infile_info))<0) {
+			sprintf(errstr,"Failed to parse input file %s\n",cmdline[0]);
+			return(PROGRAM_ERROR);
+		} else if(infile_info->filetype != SNDFILE)  {
+			sprintf(errstr,"File %s is not of correct type\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if(infile_info->channels != 1)  {
+			sprintf(errstr,"File %s is not of correct type (must be mono)\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if((exit_status = copy_parse_info_to_main_structure(infile_info,dz))<0) {
+			sprintf(errstr,"Failed to copy file parsing information\n");
+			return(PROGRAM_ERROR);
+		}
+		free(infile_info);
+	}
+	return(FINISHED);
+}
+
+/************************* SETUP_DISTSHIFT_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_distshift_param_ranges_and_defaults(dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	// NB total_input_param_cnt is > 0 !!!
+	if((exit_status = setup_input_param_range_stores(ap->total_input_param_cnt,ap))<0)
+		return(FAILED);
+	// get_param_ranges()
+	ap->lo[0]	= 1;
+	ap->hi[0]	= 32767;
+	ap->default_val[0]	= 1;
+	if(dz->mode==0) {
+		ap->lo[1]	= 1;
+		ap->hi[1]	= 32767;
+		ap->default_val[1] = 1;
+	}
+	dz->maxmode = 2;
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_distshift_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int read_special_data(char *str,dataptr dz)	
+{
+	return(FINISHED);
+}
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+	usage2("distshift");
+	return(USAGE_ONLY);
+}
+
+/**************************** CHECK_DISTSHIFT_PARAM_VALIDITY_AND_CONSISTENCY *****************************/
+
+int check_distshift_param_validity_and_consistency(dataptr dz)
+{
+	int exit_status;
+	int wscnt = 0;
+	int initial_phase = 0;
+	if((exit_status = count_wavesets(&initial_phase,dz))<0)	//	returns no. of half-wavesets as dz->itemcnt
+		return exit_status ;
+
+	if(dz->iparam[0] >= dz->itemcnt) {
+		sprintf(errstr,"Insufficient wavesets in source (%d) to make group of %d\n",wscnt,dz->iparam[0]);
+		return(DATA_ERROR);
+	}
+	if(dz->mode == 0) {
+		if(dz->iparam[1] >= dz->itemcnt) {
+			sprintf(errstr,"Insufficient wavesets in source (%d) to make shift of %d\n",wscnt,dz->iparam[0]);
+			return(DATA_ERROR);
+		}
+	}
+	if((exit_status = store_wavesets(initial_phase,dz))<0)
+		return exit_status;
+	return FINISHED;
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if(!strcmp(prog_identifier_from_cmdline,"distshift"))				dz->process = DISTSHIFT;
+	else {
+		sprintf(errstr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/******************************** SETUP_AND_INIT_INPUT_BRKTABLE_CONSTANTS ********************************/
+
+int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt)
+{	
+	int n;
+	if((dz->brk      = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<brkcnt;n++) {
+		dz->brk[n]     = NULL;
+		dz->brkptr[n]  = NULL;
+		dz->brkinit[n] = 0;
+		dz->brksize[n] = 0;
+	}
+	return(FINISHED);
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+	if(!strcmp(str,"distshift")) {
+		fprintf(stderr,
+	    "USAGE:\n"
+	    "distshift distshift 1 infile outfile grpcnt shift\n"
+	    "distshift distshift 2 infile outfile grpcnt\n"
+		"\n"
+		"Mode 1: Shift alternate (groups of) half-wavecycles forward in time\n"
+		"        (wrapping back around zero-time if pushed beyond sound end).\n"
+		"Mode 2: Swap alternate half-wavecycle(group)s.\n"
+		"\n"
+		"GRPCNT Size of elements to operate on.\n"
+		"             1 = single half-wavesets\n"
+		"             2 = 1 waveset + single half-waveset.\n"
+		"             3 = 2 wavesets + single half-waveset.\n"
+		"             etc.\n"
+		"SHIFT  Move alternate groups forward by \"shift\" waveset(group)s.\n"
+		"\n");
+	} else
+		fprintf(stdout,"Unknown option '%s'\n",str);
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	fprintf(stderr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/****************************** COUNT_WAVESETS *********************************/
+
+int count_wavesets(int *initial_phase,dataptr dz)
+{
+	int exit_status;
+	int n, cnt = 0;
+	float *ibuf = dz->sampbuf[0];
+	int halfwaveset_cnt = 0;
+	int phase = 0;
+	int *wavesetsampcnt;
+	dz->samps_left = dz->insams[0];
+
+	//	DETERMINE INITIAL PHASE
+	
+	while(dz->samps_left > 0) {
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+		n = 0;
+		while(n < dz->ssampsread) {
+			if(ibuf[n] > 0.0) {
+				*initial_phase = 1;
+				break;
+			} else if(ibuf[n] < 0.0) {
+				*initial_phase = -1;
+				break;
+			}
+			n++;
+		}
+		if(*initial_phase != 0)
+			break;
+	}
+	if(*initial_phase == 0) {
+		fprintf(stderr,"No signal found in soundfile: Cannot proceed\n");
+		return DATA_ERROR;
+	}
+	phase = *initial_phase;
+	if((sndseekEx(dz->ifd[0],0,0) < 0)){
+        sprintf(errstr,"sndseek failed\n");
+        return SYSTEM_ERROR;
+    }
+	dz->samps_left = dz->insams[0];
+	dz->total_samps_read = 0;
+	while(dz->samps_left > 0) {
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+		n = 0;
+		while(n < dz->ssampsread) {
+			switch(*initial_phase) {
+			case(1):
+				if(phase == *initial_phase) {
+					if(ibuf[n] < 0.0) {		//	i.e. phase has changed from 1 (initial_phase) to -1
+						halfwaveset_cnt++;	//	Count half-waveset
+						phase = -phase;		//	Switch phase
+					}
+				} else {
+					if(ibuf[n] >= 0.0) {	//	i.e. phase has changed from -1 to 1
+						halfwaveset_cnt++;	//	Count half-waveset
+						phase = -phase;		//	Switch phase
+					}
+				}
+				break;
+			case(-1): 
+				if(phase == *initial_phase) {
+					if(ibuf[n] >= 0.0) {	//	i.e. phase has changed from -1 (initial_phase) to 1
+						halfwaveset_cnt++;	//	Count half-waveset
+						phase = -phase;		//	Switch phase
+					}
+				} else {
+					if(ibuf[n] < 0.0) {		//	i.e. phase has changed from 1 to -1
+						halfwaveset_cnt++;	//	Count half-waveset
+						phase = -phase;		//	Switch phase
+					}
+				}
+				break;
+			}
+			n++;
+		}
+	}
+	if(halfwaveset_cnt < 2) {
+        sprintf(errstr,"Failed to find any half-wavesets.\n");
+        return DATA_ERROR;
+    }
+	dz->itemcnt = halfwaveset_cnt;
+	if((sndseekEx(dz->ifd[0],0,0) < 0)){
+        sprintf(errstr,"sndseek failed\n");
+        return SYSTEM_ERROR;
+    }
+	dz->samps_left = dz->insams[0];
+	dz->total_samps_read = 0;
+	dz->total_samps_written = 0;
+
+	//	establish array to store waveset sizes
+	
+	if((dz->iparray = (int **)malloc(sizeof(int *)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for waveset samplecnts storage.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparray[0] = (int *)malloc(dz->itemcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for waveset samplecnts storage.\n");
+		return(MEMORY_ERROR);
+	}
+	wavesetsampcnt = dz->iparray[0];
+	halfwaveset_cnt = 0;
+	phase = *initial_phase;
+	while(dz->samps_left > 0) {
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+		n = 0;
+		while(n < dz->ssampsread) {
+			switch(*initial_phase) {
+			case(1):
+				if(phase == *initial_phase) {
+					if(ibuf[n] >= 0.0)
+						cnt++;
+					else {					//	i.e. phase has changed from 1 (initial_phase) to -1
+						wavesetsampcnt[halfwaveset_cnt] = cnt;
+						cnt = 1;
+						halfwaveset_cnt++;
+						phase = -phase;		//	Switch phase
+					}
+				} else {
+					if(ibuf[n] < 0.0)
+						cnt++;
+					else {					//	i.e. phase has changed from -1 to 1
+						wavesetsampcnt[halfwaveset_cnt] = cnt;					
+						cnt = 1;
+						halfwaveset_cnt++;
+						phase = -phase;		//	Switch phase
+					}
+				}
+				break;
+			case(-1): 
+				if(phase == *initial_phase) {
+					if(ibuf[n] < 0.0)
+						cnt++;
+					else {					//	i.e. phase has changed from -1 (initial_phase) to 1
+						wavesetsampcnt[halfwaveset_cnt] = cnt;					
+						cnt = 1;
+						halfwaveset_cnt++;
+						phase = -phase;		//	Switch phase
+					}
+				} else {
+					if(ibuf[n] >= 0.0)
+						cnt++;
+					else {					//	i.e. phase has changed from 1 to -1
+						wavesetsampcnt[halfwaveset_cnt] = cnt;					
+						cnt = 1;
+						halfwaveset_cnt++;
+						phase = -phase;		//	Switch phase
+					}
+				}
+				break;
+			}
+			n++;
+		}
+	}
+	if((sndseekEx(dz->ifd[0],0,0) < 0)){
+        sprintf(errstr,"sndseek failed\n");
+        return SYSTEM_ERROR;
+    }
+	if((dz->fptr = (float **)malloc(dz->itemcnt * sizeof(float *)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for waveset stores.\n");
+		return(MEMORY_ERROR);
+	}
+	for(n = 0;n < dz->itemcnt;n++) {
+		if((dz->fptr[n] = (float *)malloc(wavesetsampcnt[n] * sizeof(float)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for waveset store %d.\n",n+1);
+			return(MEMORY_ERROR);
+		}
+	}
+	dz->samps_left = dz->insams[0];
+	dz->total_samps_read = 0;
+	dz->total_samps_written = 0;
+	
+	return FINISHED;
+}
+
+/****************************** STORE_WAVESETS *********************************/
+
+int store_wavesets(int initial_phase,dataptr dz)
+{
+	int exit_status, phase, done = 0;
+	float *ibuf = dz->sampbuf[0];
+	int cnt = 0, n, thisarray = 0;
+	float **waveset = dz->fptr;
+	dz->samps_left = dz->insams[0];
+	phase = initial_phase;
+	while(dz->samps_left > 0) {
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+		n = 0;
+		while(n < dz->ssampsread) {
+			switch(initial_phase) {
+			case(1):
+				if(phase == initial_phase) {
+					if(ibuf[n] >= 0.0)
+						waveset[thisarray][cnt++] = ibuf[n];
+					else {
+						if(++thisarray >= dz->itemcnt)	//	Step to next array store
+							done = 1;					//	Ignoring any incomplete half-cycle at end
+						cnt = 0;		//	Reset waveset-size counter to 0.
+						phase = -phase;	//	Switch phase
+					}
+				} else {
+					if(ibuf[n] < 0.0)
+						waveset[thisarray][cnt++] = ibuf[n];
+					else {
+						if(++thisarray >= dz->itemcnt)	//	Step to next array store
+							done = 1;					//	Ignoring any incomplete half-cycle at end
+						cnt = 0;		//	Reset waveset-size counter to 0.
+						phase = -phase;	//	Switch phase
+					}
+				}
+				break;
+			case(-1): 
+				if(phase == initial_phase) {
+					if(ibuf[n] < 0.0)
+						waveset[thisarray][cnt++] = ibuf[n];
+					else {
+						if(++thisarray >= dz->itemcnt)	//	Step to next array store
+							done = 1;					//	Ignoring any incomplete half-cycle at end
+						cnt = 0;		//	Reset waveset-size counter to 0.
+						phase = -phase;	//	Switch phase
+					}
+				} else {
+					if(ibuf[n] >= 0)
+						waveset[thisarray][cnt++] = ibuf[n];
+					else {
+						if(++thisarray >= dz->itemcnt)	//	Step to next array store
+							done = 1;					//	Ignoring any incomplete half-cycle at end
+						cnt = 0;		//	Reset waveset-size counter to 0.
+						phase = -phase;	//	Switch phase
+					}
+				}
+				break;
+			}
+			if(done)
+				break;
+			n++;
+		}
+		if(done)
+			break;
+	}
+	if((sndseekEx(dz->ifd[0],0,0) < 0)){
+        sprintf(errstr,"sndseek failed\n");
+        return SYSTEM_ERROR;
+    }
+	dz->samps_left = dz->insams[0];
+	dz->total_samps_read = 0;
+	dz->total_samps_written = 0;
+	return FINISHED;
+}
+
+/****************************** DISTORT_SHIFT *********************************/
+
+int distort_shift(dataptr dz)
+{
+	int exit_status;
+	float *obuf = dz->sampbuf[0];
+	int bufpos = 0, k, kend, j, jend, n, gpsize, shift, thisarray, thatarray;
+	int *wavesetsampcnt = dz->iparray[0];
+	float **waveset = dz->fptr;
+	gpsize = (dz->iparam[0]  * 2) - 1;	// i.e. param			 1	2	3	4
+										// whole cycles in group 0	1	2	3
+										// = halfcycles in group 1	2	4	6
+										// + required halfcycle	 1	1	1	1
+										// gives gpsize			 1	3	5	7
+	shift =  2 * dz->iparam[1];			//	i.e. for single-halfcycle groups, moving an up-phase halfcycle 
+										//	move up-phase halfcycle back to before previous dn-phase halfcycle (2 half-cycle steps)
+										//	and do this dz->param[1] times
+	shift *= gpsize;					//  but if the groups are size "gpsize", upscale this
+
+	for(k=0;k < dz->itemcnt; k+= gpsize * 2) {	//	For first of each PAIR of gps, just read it to output
+		kend = min(k + gpsize,dz->itemcnt);		//	End of group to copy (not beyond end of all wavesets).
+		j = (k+gpsize - shift);					//	For 2nd of each pair, search to the offset required then read
+		while(j < 0)
+			j += dz->itemcnt;
+		jend = j + gpsize;						//	Possible overflow checked later
+		for(thisarray = k; thisarray < kend; thisarray++) {	//	For all half-wavesets in (non-moved) group,
+			for(n=0;n<wavesetsampcnt[thisarray];n++) {		//	For every sample in waveset,
+				obuf[bufpos++]  = waveset[thisarray][n];	//	Copy to output
+				if(bufpos >= dz->buflen) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					bufpos = 0;
+				}
+			}
+		}													//	For second of each PAIR of gps (the moved group)
+		for(thisarray = j; thisarray < jend; thisarray++) {	//	For all half-wavesets in group
+			thatarray = thisarray % dz->itemcnt;			//	Check not gone past end of waveset store (cycle back to start if so)
+			for(n=0;n<wavesetsampcnt[thatarray];n++) {		//	For every sample in waveset,
+				obuf[bufpos++]  = waveset[thatarray][n];	//	Copy to output
+				if(bufpos >= dz->buflen) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					bufpos = 0;
+				}
+			}
+		}
+	}
+	if(bufpos > 0) {
+		if((exit_status = write_samps(obuf,bufpos,dz))<0)
+			return(exit_status);
+	}
+	return FINISHED;
+}
+
+/****************************** DISTORT_SWAP *********************************
+ *
+ *		A     B     C     D     E     F      (e.g. upper case are up-wavesets)
+ *		   a     b     c     d     e     f   (lower case, down-wavesets)
+ *		0  1  2  3  4  5  6  7  8  9  10 11
+ *
+ *		A     B     C     D     E     F
+ *		   b     a     d     c     f     e   (swapped pairwise)
+ * (-3)	0  3  2  1  4  7  6  5  8  11 10 9
+ *	i.e.
+ *    +3 +3 -1 -1 +3 +3 -1 -1 etc.
+ *	   ----------  ---------
+ *
+ */
+
+int distort_swap(dataptr dz)
+{
+	int exit_status;
+	float *obuf = dz->sampbuf[0];
+	int bufpos = 0, j, jend, n, gpsize, thisarray;
+	int *wavesetsampcnt = dz->iparray[0];
+	float **waveset = dz->fptr;
+	gpsize = (dz->iparam[0]  * 2) - 1;	// i.e. param			 1	2	3	4
+										// whole cycles in group 0	1	2	3
+										// = halfcycles in group 1	2	4	6
+										// + required halfcycle	 1	1	1	1
+										// gives gpsize			 1	3	5	7
+	j = -(3 * gpsize);										// "j" starts at -3, advancing initially to zero inside while-loop
+	while(j < dz->itemcnt) {
+		if((j += gpsize * 3) >= dz->itemcnt)				//	Advance by 3 positions
+			break;
+		if((jend = j + gpsize) >= dz->itemcnt)				//	End of group to copy (not beyond end of all wavesets).
+			break;
+		for(thisarray = j; thisarray < jend; thisarray++) {	//	For all half-wavesets in (non-moved) group,
+			for(n=0;n<wavesetsampcnt[thisarray];n++) {		//	For every sample in waveset,
+				obuf[bufpos++]  = waveset[thisarray][n];	//	Copy to output
+				if(bufpos >= dz->buflen) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					bufpos = 0;
+				}
+			}
+		}
+		if((j += gpsize * 3) >= dz->itemcnt)				//	Advance by 3 positions
+			break;
+		if((jend = j + gpsize) >= dz->itemcnt)
+			break;
+		for(thisarray = j; thisarray < jend; thisarray++) {	//	For all half-wavesets in group
+			for(n=0;n<wavesetsampcnt[thisarray];n++) {		//	For every sample in waveset,
+				obuf[bufpos++]  = waveset[thisarray][n];	//	Copy to output
+				if(bufpos >= dz->buflen) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					bufpos = 0;
+				}
+			}
+		}
+		j -= gpsize;										//	Regress by 1 position
+		jend = j + gpsize;
+		for(thisarray = j; thisarray < jend; thisarray++) {	//	For all half-wavesets in group
+			for(n=0;n<wavesetsampcnt[thisarray];n++) {		//	For every sample in waveset,
+				obuf[bufpos++]  = waveset[thisarray][n];	//	Copy to output
+				if(bufpos >= dz->buflen) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					bufpos = 0;
+				}
+			}
+		}
+		j -= gpsize;										//	Regress by 1 position
+		jend = j + gpsize;
+		for(thisarray = j; thisarray < jend; thisarray++) {	//	For all half-wavesets in group
+			for(n=0;n<wavesetsampcnt[thisarray];n++) {		//	For every sample in waveset,
+				obuf[bufpos++]  = waveset[thisarray][n];	//	Copy to output
+				if(bufpos >= dz->buflen) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					bufpos = 0;
+				}
+			}
+		}
+	}
+	if(bufpos > 0) {
+		if((exit_status = write_samps(obuf,bufpos,dz))<0)
+			return(exit_status);
+	}
+	return FINISHED;
+}
+
+/****************************** GET_MODE *********************************/
+
+int get_the_mode_from_cmdline(char *str,dataptr dz)
+{
+	char temp[200], *p;
+	if(sscanf(str,"%s",temp)!=1) {
+		sprintf(errstr,"Cannot read mode of program.\n");
+		return(USAGE_ONLY);
+	}
+	p = temp + strlen(temp) - 1;
+	while(p >= temp) {
+		if(!isdigit(*p)) {
+			fprintf(stderr,"Invalid mode of program entered.\n");
+			return(USAGE_ONLY);
+		}
+		p--;
+	}
+	if(sscanf(str,"%d",&dz->mode)!=1) {
+		fprintf(stderr,"Cannot read mode of program.\n");
+		return(USAGE_ONLY);
+	}
+	if(dz->mode <= 0 || dz->mode > dz->maxmode) {
+		fprintf(stderr,"Program mode value [%d] is out of range [1 - %d].\n",dz->mode,dz->maxmode);
+		return(USAGE_ONLY);
+	}
+	dz->mode--;		/* CHANGE TO INTERNAL REPRESENTATION OF MODE NO */
+	return(FINISHED);
+}
+

+ 1411 - 0
dev/standnew/envcut.c

@@ -0,0 +1,1411 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <tkglobals.h>
+#include <pnames.h>
+#include <filetype.h>
+#include <processno.h>
+#include <modeno.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <math.h>
+#include <mixxcon.h>
+#include <osbind.h>
+#include <standalone.h>
+#include <ctype.h>
+#include <sfsys.h>
+#include <string.h>
+#include <srates.h>
+
+
+#ifdef unix
+#define round(x) lround((x))
+#endif
+
+#define	fileno ringsize
+#define ebuflen rampbrksize
+#define badfile is_rectified
+
+char errstr[2400];
+
+int anal_infiles = 1;
+int	sloom = 0;
+int sloombatch = 0;
+
+const char* cdp_version = "7.0.0";
+
+//CDP LIB REPLACEMENTS
+static int check_gate_param_validity_and_consistency(dataptr dz);
+static int setup_envcut_application(dataptr dz);
+static int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+static int parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int setup_envcut_param_ranges_and_defaults(dataptr dz);
+static int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int open_next_outfile(dataptr dz);
+static int setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int establish_application(dataptr dz);
+static int initialise_vflags(dataptr dz);
+static int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int mark_parameter_types(dataptr dz,aplptr ap);
+static int assign_file_data_storage(int infilecnt,dataptr dz);
+static int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+static int get_the_mode_from_cmdline(char *str,dataptr dz);
+static int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt);
+static int create_envcut_sndbufs1(dataptr dz);
+static int create_envcut_sndbufs2(dataptr dz);
+static int preprocess_envcut(dataptr dz);
+static int envcut(dataptr dz);
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status;
+	dataptr dz = NULL;
+	char **cmdline;
+	int  cmdlinecnt;
+	int n;
+	aplptr ap;
+	int is_launched = FALSE;
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+						/* CHECK FOR SOUNDLOOM */
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {					// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc == 2) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+	}
+	if(!sloom) {
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		dz->maxmode = 2;
+		if((exit_status = get_the_mode_from_cmdline(cmdline[0],dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);
+		}
+		cmdline++;
+		cmdlinecnt--;
+		// setup_particular_application =
+		if((exit_status = setup_envcut_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+
+	// parse_infile_and_hone_type() = 
+	if((exit_status = parse_infile_and_check_type(cmdline,dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// setup_param_ranges_and_defaults() =
+	if((exit_status = setup_envcut_param_ranges_and_defaults(dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// open_first_infile		CDP LIB
+	if((exit_status = open_first_infile(cmdline[0],dz))<0) {	
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);	
+		return(FAILED);
+	}
+	cmdlinecnt--;
+	cmdline++;
+
+//	handle_extra_infiles() : redundant
+	// handle_outfile() = 
+	if((exit_status = handle_the_outfile(&cmdlinecnt,&cmdline,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+//	handle_formants()			redundant
+//	handle_formant_quiksearch()	redundant
+//	handle_special_data()		redundant
+ 
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+//	check_param_validity_and_consistency() : redundant
+
+	is_launched = TRUE;
+	dz->bufcnt = 1;
+	if((dz->sampbuf = (float **)malloc(sizeof(float *) * (dz->bufcnt+1)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->sbufptr = (float **)malloc(sizeof(float *) * dz->bufcnt))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffer pointers.\n");
+		return(MEMORY_ERROR);
+	}
+	for(n = 0;n <dz->bufcnt; n++)
+		dz->sampbuf[n] = dz->sbufptr[n] = (float *)0;
+	dz->sampbuf[n] = (float *)0;
+
+	if((exit_status = create_envcut_sndbufs1(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//param_preprocess ......
+	if((exit_status = preprocess_envcut(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+	//create_sndbufs =
+	if((exit_status = create_envcut_sndbufs2(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//spec_process_file =
+	if((exit_status = open_next_outfile(dz))<0)			//	Create first outfile
+		return exit_status;
+	if((exit_status = envcut(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if(!dz->badfile) {
+		if((exit_status = complete_output(dz))<0) {									// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);		// CDP LIB
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc, brkcnt;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	brkcnt = tipc;
+	//THERE ARE NO INPUTFILE brktables USED IN THIS PROCESS
+	if(brkcnt>0) {
+		if((exit_status = setup_and_init_input_brktable_constants(dz,brkcnt))<0)			  
+			return(exit_status);
+	}
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+		return(exit_status);
+	
+	// establish_infile_constants() replaced by
+	dz->infilecnt = 1;
+	//establish_bufptrs_and_extra_buffers():
+	return(FINISHED);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}						 		/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_OUTFILE *********************/
+
+int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status;
+	char *filename = (*cmdline)[0], *p;
+	if(filename[0]=='-' && filename[1]=='f') {
+		dz->floatsam_output = 1;
+		dz->true_outfile_stype = SAMP_FLOAT;
+		filename+= 2;
+	}
+	if(!sloom) {
+		if(file_has_invalid_startchar(filename) || value_is_numeric(filename)) {
+			sprintf(errstr,"Outfile name %s has invalid start character(s) or looks too much like a number.\n",filename);
+			return(DATA_ERROR);
+		}
+	}
+	strcpy(dz->outfilename,filename);	   
+	p = filename + strlen(filename);
+	p--;
+	while(p > filename) {
+		if(*p == '.') {
+			*p = ENDOFSTR;		//	Snip off any extension
+			break;
+		}
+		p--;
+	}
+	if(sloom) {					//	If sloom, snip off trailing zero
+		p = filename + strlen(filename);
+		p--;	
+		*p = ENDOFSTR;
+	}
+	if(dz->wordstor!=NULL)
+		free_wordstors(dz);
+	dz->all_words = 0;
+	if((exit_status = store_filename(filename,dz))<0)
+		return(exit_status);
+	dz->fileno = 0;
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/************************ OPEN_NEXT_OUTFILE *********************/
+
+int open_next_outfile(dataptr dz)
+{
+	int exit_status;
+	char filename[400], temp[16];
+	if(dz->fileno > 0) {
+		if((exit_status = headwrite(dz->ofd,dz))<0)
+			return(exit_status);
+		if((exit_status = reset_peak_finder(dz))<0)
+			return(exit_status);
+		if(sndcloseEx(dz->ofd) < 0) {
+			fprintf(stdout,"WARNING: Can't close output soundfile %s\n",dz->outfilename);
+			fflush(stdout);
+		}
+		dz->ofd = -1;
+		fprintf(stdout,"INFO: Writing File %d\n",dz->fileno);
+		fflush(stdout);
+	}
+	strcpy(filename,dz->wordstor[0]);
+	sprintf(temp,"%d",dz->fileno);
+	strcat(filename,temp);
+	strcat(filename,".wav");
+	strcpy(dz->outfilename,filename);
+	if((exit_status = create_sized_outfile(dz->outfilename,dz))<0)
+		return(exit_status);
+	dz->fileno++;
+	return(FINISHED);
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/************************* SETUP_ENVCUT_APPLICATION *******************/
+
+int setup_envcut_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	// SEE parstruct FOR EXPLANATION of next 2 functions
+	if(dz->mode == 0)
+		exit_status = set_param_data(ap,0   ,4,3,"D0DD");
+	else
+		exit_status = set_param_data(ap,0   ,4,4,"DDDD");
+	if(exit_status<0)
+		return(FAILED);
+	if((exit_status = set_vflgs(ap,"c",1,"d","",0,0,""))<0)
+		return(FAILED);
+	// set_legal_infile_structure -->
+	dz->has_otherfile = FALSE;
+	// assign_process_logic -->
+	dz->input_data_type = SNDFILES_ONLY;
+	dz->process_type	= UNEQUAL_SNDFILE;	
+	dz->outfiletype  	= SNDFILE_OUT;
+	return application_init(dz);	//GLOBAL
+}
+
+/************************* PARSE_INFILE_AND_CHECK_TYPE *******************/
+
+int parse_infile_and_check_type(char **cmdline,dataptr dz)
+{
+	int exit_status;
+	infileptr infile_info;
+	if(!sloom) {
+		if((infile_info = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for infile structure to test file data.");
+			return(MEMORY_ERROR);
+		} else if((exit_status = cdparse(cmdline[0],infile_info))<0) {
+			sprintf(errstr,"Failed to parse input file %s\n",cmdline[0]);
+			return(PROGRAM_ERROR);
+		} else if(infile_info->filetype != SNDFILE)  {
+			sprintf(errstr,"File %s is not of correct type\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if(infile_info->channels != 1)  {
+			sprintf(errstr,"File %s is not of correct type (must be mono)\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if((exit_status = copy_parse_info_to_main_structure(infile_info,dz))<0) {
+			sprintf(errstr,"Failed to copy file parsing information\n");
+			return(PROGRAM_ERROR);
+		}
+		free(infile_info);
+	}
+	return(FINISHED);
+}
+
+/************************* SETUP_ENVCUT_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_envcut_param_ranges_and_defaults(dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	// NB total_input_param_cnt is > 0 !!!
+	if((exit_status = setup_input_param_range_stores(ap->total_input_param_cnt,ap))<0)
+		return(FAILED);
+	// get_param_ranges()
+	ap->lo[ECUT_CNT]	= 0.001;
+	ap->hi[ECUT_CNT]	= dz->duration;
+	ap->default_val[ECUT_CNT]	= dz->duration/4.0;
+	if(dz->mode==1) {
+		ap->lo[ECUT_STP]	= 0.001;
+		ap->hi[ECUT_STP]	= dz->duration;
+		ap->default_val[ECUT_STP]	= dz->duration/4.0;
+	}
+	ap->lo[ECUT_ATT]	= 0.5;
+	ap->hi[ECUT_ATT]	= (dz->duration/2.0) * SECS_TO_MS;
+	ap->default_val[ECUT_ATT] = 1;
+	ap->lo[ECUT_EXP]	= 0.02;
+	ap->hi[ECUT_EXP]	= 50;
+	ap->default_val[ECUT_EXP] = 1.0;
+	ap->lo[ECUT_LIM]	= 0;
+	ap->hi[ECUT_LIM]	= 96;
+	ap->default_val[ECUT_LIM] = 40;
+	dz->maxmode = 2;
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_envcut_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int read_special_data(char *str,dataptr dz)	
+{
+	return(FINISHED);
+}
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+	usage2("envcut");
+	return(USAGE_ONLY);
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if(!strcmp(prog_identifier_from_cmdline,"envcut"))				dz->process = ENVCUT;
+	else {
+		sprintf(errstr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/******************************** SETUP_AND_INIT_INPUT_BRKTABLE_CONSTANTS ********************************/
+
+int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt)
+{	
+	int n;
+	if((dz->brk      = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<brkcnt;n++) {
+		dz->brk[n]     = NULL;
+		dz->brkptr[n]  = NULL;
+		dz->brkinit[n] = 0;
+		dz->brksize[n] = 0;
+	}
+	return(FINISHED);
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+	if(!strcmp(str,"envcut")) {
+		fprintf(stderr,
+	    "USAGE:\n"
+	    "envcut envcut 1 infile generic_outfilename attack envlen exp [-climit]\n"
+	    "OR:\n"
+	    "envcut envcut 2 infile generic_outfilename attack envlen step exp [-climit]\n"
+		"\n"
+		"Cut sound into elements with falling envelope.\n"
+		"\n"
+		"ENVLEN    Duration of each outfile.\n"
+		"STEP      Timestep between start of each envelope cut.\n"
+		"          (In mode 1 : envlen = step : cut-segments abutted and disjunct).\n"
+		"ATTACK    Envelope attack duration (mS) : (must be less than half envelope duration).\n"
+		"EXP       Envelope Decay shape. 1 linear : >1 more rapid decay : < 1 less rapid.\n"
+		"LIMIT     Minimum level of output events to accept (value 70 = -70dB).\n"
+		"\n");
+	} else
+		fprintf(stdout,"Unknown option '%s'\n",str);
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	fprintf(stderr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/*************************** PREPROCESS_ENVCUT **************************/
+
+int preprocess_envcut(dataptr dz) {
+
+	int exit_status, k, chans = dz->infile->channels;
+	double time = 0.0 , val, srate = (double)dz->infile->srate;
+	int *envlen = NULL, *envstart = NULL;
+	int envcnt = 0, maxenvset = 0, envelope_group_start, envelope_group_len, totalsampcnt = dz->insams[0]/chans;
+
+	//	Convert loudness limit from dB to gain
+	
+	if(flteq(dz->param[ECUT_LIM],0.0))
+		dz->zeroset = 0;
+	else {
+		dz->zeroset = 1;
+		val = -dz->param[ECUT_LIM];
+		if(val<=MIN_DB_ON_16_BIT)
+			val = 0.0;
+		else {
+			val  = -(val);
+			val /= 20.0;
+			val  = pow(10.0,val);
+			val  = 1.0/(val);
+		}
+		dz->param[ECUT_LIM] = val;
+	}
+
+	if(!dz->brksize[ECUT_CNT])
+		dz->iparam[ECUT_CNT] = (int)round(dz->param[ECUT_CNT] * srate);
+	if(dz->mode==1) {
+		if(!dz->brksize[ECUT_STP])
+			dz->iparam[ECUT_STP] = (int)round(dz->param[ECUT_STP] * srate);
+	}
+	//	Count the number of envelopes
+
+	time = 0.0;
+	envelope_group_start = 0;						//	Sample-time of start of current envelope_group
+	while(envelope_group_start < totalsampcnt) {
+		if(dz->brksize[ECUT_CNT]) {
+			if((exit_status = read_value_from_brktable(time,ECUT_CNT,dz))<0)
+				return(exit_status);
+			dz->iparam[ECUT_CNT] = (int)round(dz->param[ECUT_CNT] * srate);
+		}
+		if(dz->mode==1) {
+			if(dz->brksize[ECUT_STP]) {
+				if((exit_status = read_value_from_brktable(time,ECUT_STP,dz))<0)
+					return(exit_status);
+				dz->iparam[ECUT_STP] = (int)round(dz->param[ECUT_STP] * srate);
+			}
+		} else
+			dz->iparam[ECUT_STP] = dz->iparam[ECUT_CNT];
+		envelope_group_len = dz->iparam[ECUT_CNT];		//	Start position (in samples) = (0 or) end of previous step
+		if(envelope_group_start + envelope_group_len >= totalsampcnt)
+			break;
+		envelope_group_start += dz->iparam[ECUT_STP];
+		time = (double)(envelope_group_start)/srate;
+		envcnt++;
+		if(envcnt > 1000) {
+			sprintf(errstr,"Will generate more than 1000 outputfiles : cannot proceed.\n");
+			return DATA_ERROR;
+		}
+	}
+	if(envcnt <= 0) {
+		sprintf(errstr,"No complete envelopes found. Envelope too long for source??\n");
+		return(DATA_ERROR);
+	}
+	if((dz->lparray = (int **)malloc(2 * sizeof(int *)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for internal int arrays.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lparray[0] = (int *)malloc(envcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for internal int arrays.\n");
+		return(MEMORY_ERROR);
+	}
+	envlen = dz->lparray[0];
+	if((dz->lparray[1] = (int *)malloc((envcnt+1) * sizeof(int)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for internal int arrays.\n");
+		return(MEMORY_ERROR);
+	}
+	envstart = dz->lparray[1];
+	time = 0.0;
+	envcnt = 0;
+	envelope_group_start = 0;						//	Sample-time of start of current envelope_group
+	while(envelope_group_start < totalsampcnt) {
+		if(dz->brksize[ECUT_CNT]) {
+			if((exit_status = read_value_from_brktable(time,ECUT_CNT,dz))<0)
+				return(exit_status);
+			dz->iparam[ECUT_CNT] = (int)round(dz->param[ECUT_CNT] * srate);
+		}
+		if(dz->mode==1) {
+			if(dz->brksize[ECUT_STP]) {
+				if((exit_status = read_value_from_brktable(time,ECUT_STP,dz))<0)
+					return(exit_status);
+				dz->iparam[ECUT_STP] = (int)round(dz->param[ECUT_STP] * srate);
+			}
+		} else
+			dz->iparam[ECUT_STP] = dz->iparam[ECUT_CNT];
+		envstart[envcnt] = envelope_group_start;		//	Start position (in samples) = (0 or) end of previous step
+		envelope_group_len = dz->iparam[ECUT_CNT];		//	Start position (in samples) = (0 or) end of previous step
+		if(envelope_group_start + envelope_group_len >= totalsampcnt)
+			break;
+		envlen[envcnt] = envelope_group_len;
+		maxenvset = max(maxenvset,envelope_group_len);
+		envelope_group_start += dz->iparam[ECUT_STP];
+		time = (double)(envelope_group_start)/srate;
+		envcnt++;
+	}
+	envstart[envcnt] = envstart[envcnt-1];			//	Wrap-around point so no anomalous read at table end
+	dz->itemcnt = envcnt;							//	Store number of envelopes to extract
+	dz->ebuflen = maxenvset * chans;				//	Store samplesize of maximum envelope-group (for buffer creation)
+
+	//	Convert attack duration from millisecs to sample-groups
+	//	And test envelope sizes against attack duration specified
+	
+	if(!dz->brksize[ECUT_ATT])
+		dz->iparam[ECUT_ATT] = (int)round(dz->param[ECUT_ATT] * MS_TO_SECS * srate);
+	for(k=0;k < envcnt;k++) {
+		if(dz->brksize[ECUT_ATT]) {
+			time = (double)envstart[k]/srate;
+			if((exit_status = read_value_from_brktable(time,ECUT_ATT,dz))<0)
+				return(exit_status);
+			dz->iparam[ECUT_ATT] = (int)round(dz->param[ECUT_ATT] * MS_TO_SECS * srate);
+		}
+		if(dz->iparam[ECUT_ATT] * 2 >= envlen[k]) {
+			sprintf(errstr,"Attack too long for envelope event at %lf secs.\n",time);
+			return DATA_ERROR;
+		}
+	}
+	return FINISHED;
+}
+
+/*************************** CREATE_ENVCUT_SNDBUFS1 **************************/
+
+int create_envcut_sndbufs1(dataptr dz)
+{
+	int framesize = F_SECSIZE;
+	int bigbufsize;
+	if(dz->sbufptr == 0 || dz->sampbuf==0) {
+		sprintf(errstr,"buffer pointers not allocated: create_sndbufs()\n");
+		return(PROGRAM_ERROR);
+	}
+	bigbufsize = framesize;	// SAFETY
+	dz->buflen = bigbufsize;
+	bigbufsize  *= sizeof(float);
+	if((dz->bigbuf = (float *)malloc(bigbufsize * sizeof(float))) == NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to create sound buffers.\n");
+		return(PROGRAM_ERROR);
+	}
+	dz->sbufptr[0] = dz->sampbuf[0] = dz->bigbuf;
+	dz->sampbuf[1] = dz->sampbuf[0] + dz->buflen;
+	return(FINISHED);
+}
+
+/*************************** CREATE_ENVCUT_SNDBUFS2 **************************/
+
+int create_envcut_sndbufs2(dataptr dz)
+{
+	int framesize = F_SECSIZE;
+	int bigbufsize;
+	bigbufsize = dz->ebuflen/framesize;	// SAFETY
+	if(bigbufsize * framesize != dz->ebuflen)
+		bigbufsize++;
+	bigbufsize *= framesize;
+	dz->buflen = bigbufsize;
+	bigbufsize += 16;	//	SAFETY
+	if((dz->sampbuf[1] = (float *)malloc(bigbufsize * sizeof(float))) == NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to create sound buffers.\n");
+		return(PROGRAM_ERROR);
+	}
+	dz->sbufptr[1] = dz->sampbuf[1];
+	dz->sampbuf[2] = dz->sampbuf[1] + dz->buflen;
+	return(FINISHED);
+}
+
+/*************************** ENVCUT **************************
+ *
+ *	Calculations are fone in sample-groups 1 for mono, 2 for stereo
+ */
+
+int envcut(dataptr dz)
+{
+	int exit_status, n, m, chans = dz->infile->channels;
+	int samptime, steps, k, decaylen;
+	float *buf = dz->sampbuf[1];
+	double ee, maxsamp, time = 0.0, srate = (double)dz->infile->srate;
+	int *envsize = dz->lparray[0], bufpos, *envstart = dz->lparray[1];
+	if(!dz->brksize[ECUT_ATT])
+		dz->iparam[ECUT_ATT] = (int)round(dz->param[ECUT_ATT] * MS_TO_SECS * srate);
+	dz->badfile = 0;
+	samptime = 0;											//	Start at start of sound;
+
+	for(n = 0;n < dz->itemcnt; n++) {						//	For every envelope-group needed
+		memset((char *)buf,0,dz->ebuflen * sizeof(float));	//	preset obuf to 0
+		if((sndseekEx(dz->ifd[0],samptime,0) < 0)) {		//	Seek to start of envelope group
+			sprintf(errstr,"sndseek failed\n");
+			return SYSTEM_ERROR;
+		}
+		dz->buflen = envsize[n] * chans;
+		if((exit_status = read_samps(buf,dz))<0)
+			return(exit_status);
+
+		if(dz->brksize[ECUT_ATT]) {
+			time = (double)samptime/srate;
+			if((exit_status = read_value_from_brktable(time,ECUT_ATT,dz))<0)
+				return(exit_status);
+			dz->iparam[ECUT_ATT] = (int)round(dz->param[ECUT_ATT] * MS_TO_SECS * srate);	//	Get value in samplegroups (1 mono, 2 stereo)
+		}
+		steps = dz->iparam[ECUT_ATT];
+		bufpos = 0;
+		for(k = 0;k < steps;k++) {							//	Envelope the samples attack
+			ee = (double)k/(double)steps; 			
+			for(m=0;m<chans;m++) {
+				buf[bufpos] = (float)(buf[bufpos] * ee);
+				bufpos++;
+			}
+		}
+		decaylen = dz->buflen - bufpos;
+		steps = decaylen/chans;
+		for(k=0;k < steps;k++) {							//	Envelope the samples decay
+			ee = 1.0 - ((double)k/(double)steps);
+			ee = pow(ee,dz->param[ECUT_EXP]);
+			for(m=0;m<chans;m++) {
+				buf[bufpos] = (float)(buf[bufpos] * ee);
+				bufpos++;
+			}
+		}													//	Write envelope-group to file
+		if(dz->zeroset) {
+			maxsamp = 0.0;
+			for(bufpos=0;bufpos < dz->buflen;bufpos++) {
+				if(fabs(buf[bufpos]) > maxsamp)
+					maxsamp = fabs(buf[bufpos]);
+			}
+			if(maxsamp < dz->param[ECUT_LIM]) {
+				dz->badfile = envsize[n] * chans;
+				continue;
+			}
+		}
+		dz->badfile = 0;
+		if((exit_status = write_samps(buf,dz->buflen,dz))<0)
+			return(exit_status);	
+		if(n < dz->itemcnt - 1) {
+			if((exit_status = open_next_outfile(dz))<0)			//	Get next file
+				return exit_status;
+		}
+		samptime = envstart[n+1];								//	Advance to next envelope-group of samples
+		if(dz->brksize[ECUT_EXP]) {
+			time = (double)samptime/srate;						//	If EXP varies, read brktable
+			if((exit_status = read_value_from_brktable(time,ECUT_EXP,dz))<0)
+				return(exit_status);
+		}
+	}
+	if(dz->badfile) {											//	If the last file opened was not written to (too low level)
+		if((exit_status = write_samps(buf,dz->badfile,dz))<0)	//	Write data to it: this allows sfsys to truncate the file in sndcloseEx
+			return(exit_status);								//	Then delete it
+		if(sndunlink(dz->ofd) < 0) {
+			fprintf(stdout,"WARNING: Can't set output soundfile %s for deletion.\n",dz->outfilename);
+			fflush(stdout);
+		}
+		if(sndcloseEx(dz->ofd) < 0) {
+			fprintf(stdout,"WARNING: Can't close output soundfile %s :%s\n",dz->outfilename,sferrstr());   //RWD sferrstr is a function
+			fflush(stdout);
+		}
+		dz->ofd = -1;
+	}
+	return FINISHED;
+}
+
+/****************************** GET_MODE *********************************/
+
+int get_the_mode_from_cmdline(char *str,dataptr dz)
+{
+	char temp[200], *p;
+	if(sscanf(str,"%s",temp)!=1) {
+		sprintf(errstr,"Cannot read mode of program.\n");
+		return(USAGE_ONLY);
+	}
+	p = temp + strlen(temp) - 1;
+	while(p >= temp) {
+		if(!isdigit(*p)) {
+			fprintf(stderr,"Invalid mode of program entered.\n");
+			return(USAGE_ONLY);
+		}
+		p--;
+	}
+	if(sscanf(str,"%d",&dz->mode)!=1) {
+		fprintf(stderr,"Cannot read mode of program.\n");
+		return(USAGE_ONLY);
+	}
+	if(dz->mode <= 0 || dz->mode > dz->maxmode) {
+		fprintf(stderr,"Program mode value [%d] is out of range [1 - %d].\n",dz->mode,dz->maxmode);
+		return(USAGE_ONLY);
+	}
+	dz->mode--;		/* CHANGE TO INTERNAL REPRESENTATION OF MODE NO */
+	return(FINISHED);
+}
+

+ 2678 - 0
dev/standnew/envspeak.c

@@ -0,0 +1,2678 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <tkglobals.h>
+#include <pnames.h>
+#include <filetype.h>
+#include <processno.h>
+#include <modeno.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <math.h>
+#include <mixxcon.h>
+#include <osbind.h>
+#include <standalone.h>
+#include <ctype.h>
+#include <sfsys.h>
+#include <string.h>
+#include <envlcon.h>
+#include <srates.h>
+
+#ifdef unix
+#define round(x) lround((x))
+#endif
+
+#define envcnt	wlength
+#define trofcnt rampbrksize
+#define ENV_FSECSIZE 256
+#define ENVSPEAK_PKSRCHWIDTH 3
+#define MINEVENTFRQ	50		//	generates the minimum possible event length for mode 7
+
+#define	ESPK_GATED	ESPK_REPET
+#define	ESPK_SEED	ESPK_OFFST
+#define	ESPK_NWISE	ESPK_OFFST
+#define	ESPK_RATIO	ESPK_WHICH
+#define	ESPK_RAND	ESPK_GAIN
+
+char errstr[2400];
+
+int anal_infiles = 1;
+int	sloom = 0;
+int sloombatch = 0;
+
+const char* cdp_version = "6.1.0";
+
+//CDP LIB REPLACEMENTS
+static int check_envspeak_param_validity_and_consistency(dataptr dz);
+static int setup_envspeak_application(dataptr dz);
+static int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+static int parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int setup_envspeak_param_ranges_and_defaults(dataptr dz);
+static int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int establish_application(dataptr dz);
+static int initialise_vflags(dataptr dz);
+static int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int mark_parameter_types(dataptr dz,aplptr ap);
+static int assign_file_data_storage(int infilecnt,dataptr dz);
+static int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+static int get_the_mode_from_cmdline(char *str,dataptr dz);
+static int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt);
+static int precalculate_peaks_array_and_splice(dataptr dz);
+static int envspeak(dataptr dz);
+static int getmaxattencnt(dataptr dz);
+static int windows_in_sndfile(dataptr dz);
+static int getenv_of_buffer(int samps_to_process,float **env,dataptr dz);
+static double getmaxsamp(int startsamp, int sampcnt,float *buffer);
+static int istrof(float *env,float *envend,float *q,int width);
+static int randvary_pklen(int peaklen,dataptr dz);
+static double dbtolevel(double val);
+static int getmaxwhich(dataptr dz);
+static int open_next_file(char *outfilename,int n,dataptr dz);
+static void randperm(int z,int setlen,dataptr dz);
+static void hinsert(int z,int m,int t,int setlen,dataptr dz);
+static void hprefix(int z,int m,int setlen,dataptr dz);
+static void hshuflup(int z,int k,int setlen,dataptr dz);
+static int getcutdata(int *cmdlinecnt,char ***cmdline,dataptr dz);
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status;
+	dataptr dz = NULL;
+	char **cmdline;
+	int  cmdlinecnt;
+	int n;
+	aplptr ap;
+	int is_launched = FALSE;
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+						/* CHECK FOR SOUNDLOOM */
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {					// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	dz->trofcnt = 0;
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc == 2) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+	}
+	if(!sloom) {
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		dz->maxmode = 24;
+		if((exit_status = get_the_mode_from_cmdline(cmdline[0],dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);
+		}
+		cmdline++;
+		cmdlinecnt--;
+		// setup_particular_application =
+		if((exit_status = setup_envspeak_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+
+	// parse_infile_and_hone_type() = 
+	if((exit_status = parse_infile_and_check_type(cmdline,dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// setup_param_ranges_and_defaults() =
+	if((exit_status = setup_envspeak_param_ranges_and_defaults(dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// open_first_infile		CDP LIB
+	if((exit_status = open_first_infile(cmdline[0],dz))<0) {	
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);	
+		return(FAILED);
+	}
+	cmdlinecnt--;
+	cmdline++;
+
+//	handle_extra_infiles() : redundant
+	// handle_outfile() = 
+	if((exit_status = handle_the_outfile(&cmdlinecnt,&cmdline,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+//	handle_formants()			redundant
+//	handle_formant_quiksearch()	redundant
+//	handle_special_data()		redundant
+ 
+	if(dz->mode >= 12) {
+		if((exit_status = getcutdata(&cmdlinecnt,&cmdline,dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	}
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	is_launched = TRUE;
+	dz->bufcnt = 4;
+	if((dz->sampbuf = (float **)malloc(sizeof(float *) * (dz->bufcnt+1)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->sbufptr = (float **)malloc(sizeof(float *) * dz->bufcnt))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffer pointers.\n");
+		return(MEMORY_ERROR);
+	}
+	for(n = 0;n <dz->bufcnt; n++)
+		dz->sampbuf[n] = dz->sbufptr[n] = (float *)0;
+	dz->sampbuf[n] = (float *)0;
+
+	//	1 double array for splice
+	if((dz->parray = (double **)malloc(sizeof(double *))) == NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to create splice buffer (1).\n");
+		return(MEMORY_ERROR);
+	}
+	//	2 float arrays for trofstore
+	if((dz->fptr=(float **)malloc(2 * sizeof(float *)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to store envelope (1).\n");
+		return(MEMORY_ERROR);
+	}
+//	create_sndbufs
+	if((exit_status = create_sndbufs_for_envel(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = precalculate_peaks_array_and_splice(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	dz->mode %= 12;
+//	check_param_validity_and_consistency....
+	if((exit_status = check_envspeak_param_validity_and_consistency(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//param_preprocess()						redundant
+	//spec_process_file =
+	if((exit_status = envspeak(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = complete_output(dz))<0) {										// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);		// CDP LIB
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc, brkcnt;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	brkcnt = tipc;
+	//THERE ARE NO INPUTFILE brktables USED IN THIS PROCESS
+	if(brkcnt>0) {
+		if((exit_status = setup_and_init_input_brktable_constants(dz,brkcnt))<0)			  
+			return(exit_status);
+	}
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+		return(exit_status);
+	
+	// establish_infile_constants() replaced by
+	dz->infilecnt = 1;
+	//establish_bufptrs_and_extra_buffers():
+	return(FINISHED);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}						 		/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_OUTFILE *********************/
+
+int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status;
+	char *filename = (*cmdline)[0], *nufilename;
+	char prefix_units[] = "_00";
+
+	if(filename[0]=='-' && filename[1]=='f') {
+		dz->floatsam_output = 1;
+		dz->true_outfile_stype = SAMP_FLOAT;
+		filename+= 2;
+	}
+	if(!sloom) {
+		if(file_has_invalid_startchar(filename) || value_is_numeric(filename)) {
+			sprintf(errstr,"Outfile name %s has invalid start character(s) or looks too much like a number.\n",filename);
+			return(DATA_ERROR);
+		}
+	}
+	if(dz->mode == 9 || dz->mode == 21) {
+		if((dz->wordstor = (char **)malloc(sizeof (char *)))==NULL) {
+			sprintf(errstr,"Cannot set up storage for infile name (1)\n");
+			return(MEMORY_ERROR);
+		}
+		if((dz->wordstor[0] = (char *)malloc((strlen(filename) + 12) * sizeof (char)))==NULL) {
+			sprintf(errstr,"Cannot set up storage for infile name (2)\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(dz->wordstor[0],filename);
+	}
+	if((dz->mode == 9 || dz->mode == 21) && !sloom) {
+		if((nufilename = (char *)malloc((strlen(filename) + 12) * sizeof (char)))==NULL) {
+			sprintf(errstr,"Cannot set up storage for infile name (2)\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(nufilename,filename);
+		insert_new_chars_at_filename_end(nufilename,prefix_units);
+		insert_new_number_at_filename_end(nufilename,0,0);
+		strcpy(dz->outfilename,nufilename);
+		if((exit_status = create_sized_outfile(nufilename,dz))<0)
+			return(exit_status);
+	} else {
+		strcpy(dz->outfilename,filename);
+		if((exit_status = create_sized_outfile(filename,dz))<0)
+			return(exit_status);
+	}
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/************************* SETUP_ENVSPEAK_APPLICATION *******************/
+
+int setup_envspeak_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	switch(dz->mode) {
+	case(4):	//	fall thro
+	case(5):	//	fall thro
+	case(0): exit_status = set_param_data(ap,0   ,6,5,"iiiID0");	break;	//	repet & repet-shrink
+	case(1): exit_status = set_param_data(ap,0   ,6,3,"iii000");	break;	//	reverse-repet
+	case(2):	//	fall thro
+	case(3): exit_status = set_param_data(ap,0   ,6,5,"iiiID0");	break;	//	atten "alternate"
+	case(6): exit_status = set_param_data(ap,0   ,6,6,"iiiIDI");	break;	//	repeat part-of
+	case(7):	//	fall thro
+	case(8): exit_status = set_param_data(ap,0   ,6,6,"iiiIDD");	break;	//	repeat but shrink
+	case(9): exit_status = set_param_data(ap,0   ,6,2,"ii0000");	break;	//	extract all
+	case(10): exit_status = set_param_data(ap,0  ,6,3,"iii000");	break;	//	permute randomly
+	case(11): exit_status = set_param_data(ap,0  ,6,3,"iiI000");	break;	//	permute N-wise
+	case(16):	//	fall thro
+	case(17):	//	fall thro
+	case(12): exit_status = set_param_data(ap,XSPK_CUTS  ,6,4,"0iiID0");	break;	//	repet & repet-shrink
+	case(13): exit_status = set_param_data(ap,XSPK_CUTS  ,6,2,"0ii000");	break;	//	reverse-repet
+	case(14):	//	fall thro
+	case(15): exit_status = set_param_data(ap,XSPK_CUTS  ,6,4,"0iiID0");	break;	//	atten "alternate"
+	case(18): exit_status = set_param_data(ap,XSPK_CUTS  ,6,5,"0iiIDI");	break;	//	repeat part-of
+	case(19):	//	fall thro
+	case(20): exit_status = set_param_data(ap,XSPK_CUTS  ,6,5,"0iiIDD");	break;	//	repeat but shrink
+	case(21): exit_status = set_param_data(ap,XSPK_CUTS  ,6,1,"0i0000");	break;	//	extract all
+	case(22): exit_status = set_param_data(ap,XSPK_CUTS  ,6,2,"0ii000");	break;	//	permute randomly
+	case(23): exit_status = set_param_data(ap,XSPK_CUTS  ,6,2,"0iI000");	break;	//	permute N-wise
+	}
+	if(exit_status < 0)
+		return(FAILED);
+	switch(dz->mode) {
+	case(6):	//	fall thro
+	case(18):
+		exit_status = set_vflgs(ap,"",0,"","z",1,0,"0");
+		break;
+	default:
+		exit_status = set_vflgs(ap,"",0,"","",0,0,"");
+		break;
+	}
+	if(exit_status < 0)
+		return(FAILED);
+	// set_legal_infile_structure -->
+	dz->has_otherfile = FALSE;
+	// assign_process_logic -->
+	dz->input_data_type = SNDFILES_ONLY;
+	if(dz->mode == 2 || dz->mode == 3 || dz->mode == 14 || dz->mode == 15)
+		dz->process_type	= EQUAL_SNDFILE;	
+	else
+		dz->process_type	= UNEQUAL_SNDFILE;	
+	dz->outfiletype  	= SNDFILE_OUT;
+	return application_init(dz);	//GLOBAL
+}
+
+/************************* PARSE_INFILE_AND_CHECK_TYPE *******************/
+
+int parse_infile_and_check_type(char **cmdline,dataptr dz)
+{
+	int exit_status;
+	infileptr infile_info;
+	if(!sloom) {
+		if((infile_info = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for infile structure to test file data.");
+			return(MEMORY_ERROR);
+		} else if((exit_status = cdparse(cmdline[0],infile_info))<0) {
+			sprintf(errstr,"Failed to parse input file %s\n",cmdline[0]);
+			return(PROGRAM_ERROR);
+		} else if(infile_info->filetype != SNDFILE)  {
+			sprintf(errstr,"File %s is not of correct type\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if((exit_status = copy_parse_info_to_main_structure(infile_info,dz))<0) {
+			sprintf(errstr,"Failed to copy file parsing information\n");
+			return(PROGRAM_ERROR);
+		}
+		free(infile_info);
+	}
+	return(FINISHED);
+}
+
+/************************* SETUP_ENVSPEAK_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_envspeak_param_ranges_and_defaults(dataptr dz)
+{
+	int exit_status;
+	int mode = dz->mode % 12;
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	// NB total_input_param_cnt is > 0 !!!
+	if((exit_status = setup_input_param_range_stores(ap->total_input_param_cnt,ap))<0)
+		return(FAILED);
+	ap->lo[ESPK_WINSZ]	= 5;				//	param 0
+	ap->hi[ESPK_WINSZ]	= 1000;
+	ap->default_val[ESPK_WINSZ]	= 50;
+	ap->lo[ESPK_SPLEN]	= 2;				//	param 1
+	ap->hi[ESPK_SPLEN]	= 100;
+	ap->default_val[ESPK_SPLEN]	= 5;
+	if(mode < 9) {
+		ap->lo[ESPK_OFFST]	= 0;				//	param 2
+		ap->hi[ESPK_OFFST]	= 100;
+		ap->default_val[ESPK_OFFST]	= 0;
+		switch(mode) {
+		case(2):	//	fall thro			//	SEGMENT DELETIONS
+		case(3):
+			ap->lo[ESPK_GAIN]	= -96;		//	param 4		//	attenuation of attenuated items
+			ap->hi[ESPK_GAIN]	= 0;
+			ap->default_val[ESPK_GAIN]	= -96;
+			//	fall thro
+		case(0):	//	fall thro			//	REPETITION OF SEGMENTS, OR GROUPSIZE IN SEGMENT DELETIONS
+		case(4):	//	fall thro
+		case(5):	//	fall thro
+		case(7):	//	fall thro
+		case(8):	//	fall thro
+		case(6):							//	NO OF REPETS OF DIVISION OF SEGMENT = GROUPSIZE TO ATTENUATE
+			ap->lo[ESPK_REPET]	= 1;		//	param 3		//	NB ESPK_REPET = ESPK_GATED
+			ap->hi[ESPK_REPET]	= 100;
+			ap->default_val[ESPK_REPET]	= 2;
+			break;
+		}
+		if(!(mode == 1 || mode == 2 || mode == 3)) {
+			ap->lo[ESPK_RAND]	= 0;		//	param 4
+			ap->hi[ESPK_RAND]	= 1;
+			ap->default_val[ESPK_RAND]	= 0;
+		}
+		switch(mode) {
+		case(6):
+			ap->lo[ESPK_WHICH]	= 1;		//	param 5		Which segment of each divided syllable is to be processed
+			ap->hi[ESPK_WHICH]	= 100;
+			ap->default_val[ESPK_WHICH]	= 1;
+			break;
+		case(7):	//	fall thro
+		case(8):
+			ap->lo[ESPK_RATIO]	= 0.1;		//	param 5		By what ratio does the length of repeated syllables decrease
+			ap->hi[ESPK_RATIO]	= 1.0;
+			ap->default_val[ESPK_RATIO]	= .5;
+			break;
+		}
+	}
+	switch(mode) {
+	case(10):
+		ap->lo[ESPK_SEED]	= 0;			//	param 3		Random seed for perms
+		ap->hi[ESPK_SEED]	= 64;
+		ap->default_val[ESPK_SEED]	= 0;
+		break;
+	case(11):
+		ap->lo[ESPK_NWISE]	= 1;			//	param 3		Group-size for reversal
+		ap->hi[ESPK_NWISE]	= 100;
+		ap->default_val[ESPK_NWISE]	= 2;
+		break;
+	}
+	dz->maxmode = 24;
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_envspeak_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int read_special_data(char *str,dataptr dz)	
+{
+	return(FINISHED);
+}
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+	usage2("envspeak");
+	return(USAGE_ONLY);
+}
+
+/**************************** CHECK_ENVSPEAK_PARAM_VALIDITY_AND_CONSISTENCY *****************************/
+
+int check_envspeak_param_validity_and_consistency(dataptr dz)
+{
+//	NEEDS TO BE DONE WHEN TROFCNT IS KNOWN AND SPLICELEN IN GPSAMPS KNOWN !!!!
+	int lastsamp = 0, n, k, sampsize, maxwhich;
+	int chans = dz->infile->channels;
+	int offset = dz->iparam[ESPK_OFFST];
+	int *trof = dz->lparray[0];
+	int splicelen, minseg, shorten, mintrofs_needed;
+	splicelen = dz->iparam[ESPK_SPLEN] * chans;
+	minseg = (splicelen * 2) + chans;
+	if(dz->trofcnt == 0) {
+		sprintf(errstr,"Trof array not established before testing parameters.\n");
+		return PROGRAM_ERROR;
+	}
+	if(offset >= dz->trofcnt - 2) {
+		sprintf(errstr,"ERROR: Offset (%d) too large for number of peaks found (%d).\n",offset,dz->trofcnt);
+		return DATA_ERROR;
+	}
+	shorten = 0;
+	for(n = 0; n <= dz->trofcnt; n++) {
+		sampsize = trof[n] - lastsamp;
+		if(sampsize < minseg) {
+			fprintf(stdout,"Splice Length too long for some of \"syllables\".\nsampsize = %d minseg = %d trof[%d] = %d\n",sampsize,minseg,n,trof[n]);
+			fprintf(stdout,"Atempting to delete too short \"syllables\".\n");
+			shorten = 1;
+			fflush(stdout);
+			break;
+		}
+		lastsamp = trof[n];
+	}
+	if(shorten) {
+		lastsamp = 0;
+		for(n = 0; n <= dz->trofcnt; n++) {
+			sampsize = trof[n] - lastsamp;
+			while(sampsize < minseg) {
+				if(n < dz->trofcnt) {
+					k = n + 1;			
+					while(n < dz->trofcnt)
+						trof[n] = trof[k];
+				} else
+					trof[dz->trofcnt - 1] = trof[dz->trofcnt];
+				dz->trofcnt--;		//	Delete times until intertrof size big enough : decreasing trofcnt accordingly
+				if(dz->trofcnt <= 0) {
+					sprintf(errstr,"No long-enough segments found, using this splicelength.\n");
+					return DATA_ERROR;
+				}
+			}
+			lastsamp = trof[n];
+		}
+	}
+	if(dz->mode == 2 || dz->mode == 3)
+		mintrofs_needed = 1 + offset + getmaxattencnt(dz);
+	else
+		mintrofs_needed = 1;
+	if(dz->trofcnt < mintrofs_needed) {
+		sprintf(errstr,"Too few trofs found (%d) for this process and offset (%d)\n",dz->trofcnt,mintrofs_needed);
+		return DATA_ERROR;
+	}
+	if(!(dz->mode == 10 || dz->mode == 11)) {
+		if(!dz->brksize[ESPK_REPET] && dz->iparam[ESPK_REPET] <= 1) {
+			switch(dz->mode) {
+			case(0):	//	fall thro
+			case(4):	//	fall thro
+			case(5):
+				fprintf(stdout, "WARNING: A repeat value of 1 or less will have no effect : only useful in a brkpoint file.\n");
+				break;
+			case(2):
+				fprintf(stdout, "WARNING: Attenuation count value of 1 or less  as no effect : only useful in a brkpoint file.\n");
+				break;
+			case(3):
+				fprintf(stdout, "WARNING: Attenuation count value of 1 or less will produce a silent file: only useful in a brkpoint file.\n");
+				break;
+			}
+			fflush(stdout);
+
+		}
+	}
+	switch(dz->mode) {
+	case(2):	//	fall thro
+	case(3):
+		dz->param[ESPK_GAIN] = dbtolevel(dz->param[ESPK_GAIN]);
+		break;
+	case(6):
+		maxwhich = getmaxwhich(dz);
+		if(maxwhich > dz->iparam[ESPK_REPET]) {
+			if(dz->brksize[ESPK_WHICH]) 
+				sprintf(errstr,"The (maximum) chosen segment (%d) cannot be beyond the number of divisions (%d)\n",maxwhich,dz->iparam[ESPK_REPET]);
+			else
+				sprintf(errstr,"The chosen segment (%d) cannot be greater than the number of divisions (%d)\n",maxwhich,dz->iparam[ESPK_REPET]);
+			return DATA_ERROR;
+		}
+		break;
+	}	
+	return FINISHED;
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if(!strcmp(prog_identifier_from_cmdline,"envspeak"))				dz->process = ENVSPEAK;
+	else {
+		sprintf(errstr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/******************************** SETUP_AND_INIT_INPUT_BRKTABLE_CONSTANTS ********************************/
+
+int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt)
+{	
+	int n;
+	if((dz->brk      = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<brkcnt;n++) {
+		dz->brk[n]     = NULL;
+		dz->brkptr[n]  = NULL;
+		dz->brkinit[n] = 0;
+		dz->brksize[n] = 0;
+	}
+	return(FINISHED);
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+	if(!strcmp(str,"envspeak")) {
+		fprintf(stderr,
+	    "USAGE:\n"
+	    "envspeak envspeak 1,5,6 infile outfile wsize splice offset repet rand\n"
+	    "envspeak envspeak 2     infile outfile wsize splice offset\n"
+	    "envspeak envspeak 3-4   infile outfile wsize splice offset attencnt dbatten\n"
+	    "envspeak envspeak 7     infile outfile wsize splice offset div rand which [-z]\n"
+	    "envspeak envspeak 8-9   infile outfile wsize splice offset repet rand ratio\n"
+	    "envspeak envspeak 10    infile outfile wsize splice\n"
+	    "envspeak envspeak 11    infile outfile wsize splice seed\n"
+	    "envspeak envspeak 12    infile outfile wsize splice Nwise\n"
+		"\n"
+		"envspeak envspeak 13-24 AS ABOVE BUT replace \"wsize\" by \"cutsfile\"\n"
+		"\n"
+		"Process speech \"syllables\".\n"
+		"\n"
+		"Mode 1:    Repeat each syllables, \"repet\" times.\n"
+		"Mode 2:    Reverse-repeat each syllable.\n"
+		"Modes 3/4: (3) Attenuate N in N+1 syllabs    (4) Attenuate all except.\n"
+		"Modes 5/6: (5) Repeat each syllab N times, shrinking from end  (6)  from start.\n"
+		"Mode 7:    Divide each syllable into N parts, and repeat one of these N times.\n"
+		"Mode 8:    For each syllab, Repeat, shortening each repetition, lopping-off end.\n"
+		"Mode 9:    ditto, lopping-off start.\n"
+		"Mode 10:   Extract all syllables.\n"
+		"Mode 11:   Randomly reorder syllables.\n"
+		"Mode 12:   Reverse order syllabs N-wise (e.g.for N=3 abc|def|ghi -> cba|fed|ihj).\n"
+		"\n"
+		"WSIZE     Size of envelope-search window in mS (default 50).\n"
+		"CUTSFILE  List of times (apart from 0 & end) where infile cut to create syllables.\n"
+		"SPLICE    Splice length in mS (default 15) \n"
+		"OFFSET    Number of initial peaks to output unchanged.\n"
+		"REPET     Number of repetitions of each syllable (Range 2 upwards).\n"
+		"ATTENCNT  Groupsize (N) of syllabs ...(Mode 3) to attenuate (4) to NOT attenuate.\n"
+		"          N means N in N+1 : so \"1\" means 1 in 2, \"3\" means 3 in 4 etc \n"
+		"DBATTEN   Reduce attenuated segments by ATTEN dB: Modes 3-4. (Range -96 to < 0)\n"
+		"DIV       Keep 1/DIVth part of syllable, to repeat DIV times.\n"
+		"WHICH     Which syllable-fraction to keep (Range 1 to DIV)\n"
+		"-z        Repeated elements do NOT grow in size (machine-like quality).\n"
+		"RATIO     length of repeated elements reduces by RATIO : Range (> 0.0 to 1)\n"
+		"RAND      Randomisation of lengths of repeated units.\n"
+		"NWISE     Reverse order in groups of N.\n"
+		"SEED      Intialisation for random order permutation (Modes 11 only).\n"
+		"          If Seed > 0, using same seed again, gives IDENTICAL random output.\n"
+		"\n"
+		"REPET, ATTENCNT, ATTEN and WHICH may vary over time.\n");
+	} else
+		fprintf(stdout,"Unknown option '%s'\n",str);
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	fprintf(stderr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/****************************** GET_MODE *********************************/
+
+int get_the_mode_from_cmdline(char *str,dataptr dz)
+{
+	char temp[200], *p;
+	if(sscanf(str,"%s",temp)!=1) {
+		sprintf(errstr,"Cannot read mode of program.\n");
+		return(USAGE_ONLY);
+	}
+	p = temp + strlen(temp) - 1;
+	while(p >= temp) {
+		if(!isdigit(*p)) {
+			fprintf(stderr,"Invalid mode of program entered.\n");
+			return(USAGE_ONLY);
+		}
+		p--;
+	}
+	if(sscanf(str,"%d",&dz->mode)!=1) {
+		fprintf(stderr,"Cannot read mode of program.\n");
+		return(USAGE_ONLY);
+	}
+	if(dz->mode <= 0 || dz->mode > dz->maxmode) {
+		fprintf(stderr,"Program mode value [%d] is out of range [1 - %d].\n",dz->mode,dz->maxmode);
+		return(USAGE_ONLY);
+	}
+	dz->mode--;		/* CHANGE TO INTERNAL REPRESENTATION OF MODE NO */
+	return(FINISHED);
+}
+
+/****************************** ENVSPEAK *********************************/
+
+int envspeak(dataptr dz) 
+{
+	int exit_status, chans = dz->infile->channels, srate = dz->infile->srate, isrand;
+	float *ibuf = dz->sampbuf[0], *obuf = dz->sampbuf[1], *ovflwbuf = dz->sampbuf[2], *rbuf = dz->sampbuf[3];
+	float temp;
+	int gpsplicelen = dz->iparam[ESPK_SPLEN];
+	int splicelen = gpsplicelen * chans, upsplice, mindur;
+	int obufpos = 0, lasttrofat = 0, thistrofat, peaklen, nupeaklen, splicend, rbufpos, upspliclen, thissplicelen;
+	int *trof = dz->lparray[0];
+	int mintrof, skipback, skipforward, trofdiv, offset, truepeaklen, truelasttrofat, origpeaklen, sttseg;
+	int gated = 0, n, m, i, j, k, z, nwise;
+	double *splicebuf = dz->parray[0], time = 0, roffset, ratio;	
+	double samps_per_sec = (double)srate * chans;
+	char *outfilename;
+	int namelen, numlen, *permm = NULL;
+	if(dz->param[ESPK_RAND] > 0.0)
+		initrand48();
+	mindur = (int)round((double)srate/MINEVENTFRQ) * chans;
+	switch(dz->mode) {
+	case(0):			//	Repeat	
+		mintrof = dz->iparam[ESPK_OFFST];
+		for(n = 0; n <= dz->trofcnt; n++)  {
+			thistrofat  = trof[n];
+			peaklen = thistrofat - lasttrofat;
+			splicend = splicelen - 1;
+			if(n < mintrof) {			//	We must be at start of file : therefore no obufpos baktrak & no upsplice
+				for(j = peaklen - 1, m = 0; m < thistrofat; m++,j--) {
+					if (j < splicelen) 
+						obuf[obufpos] = (float)(ibuf[m] * splicebuf[splicend--]);			//	do downslice
+					else																	
+						obuf[obufpos] = ibuf[m];											//  else copy input
+					if(++obufpos >= dz->buflen * 2) {
+						if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+							return(exit_status);
+						memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+						memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+						obufpos -= dz->buflen;
+					}
+				}
+			} else {
+				time = (double)thistrofat/(double)samps_per_sec;
+				if((exit_status = read_values_from_all_existing_brktables(time,dz))<0)
+					return PROGRAM_ERROR;
+				skipback = 0;
+				if(lasttrofat > 0) {				//	If we're NOT at file start	
+					obufpos -= splicelen;		//	baktrak to splice to end of last segment written
+					peaklen += splicelen;		//	and length of peak is therefore one splicelen longer
+					upsplice = splicelen;
+					skipback = splicelen;
+				} else
+					upsplice = 0;					//	Prevents initial splice on start of file-segment
+				splicend = splicelen - 1;
+				for(k = 0, j = peaklen - 1, m = lasttrofat - skipback; m < thistrofat; m++,k++,j--) {
+					if(k < upsplice) 
+						obuf[obufpos] = (float)(obuf[obufpos] + (ibuf[m] * splicebuf[k]));	//	do upslice
+					else if (j < splicelen) 
+						obuf[obufpos] = (float)(ibuf[m] * splicebuf[splicend--]);			//	do downslice
+					else
+						obuf[obufpos] = ibuf[m];											//	just copy
+					if(++obufpos >= dz->buflen * 2) {
+						if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+							return(exit_status);
+						memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+						memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+						obufpos -= dz->buflen;
+					}
+				}
+				obufpos -= splicelen;
+				origpeaklen = peaklen;
+				if(upsplice == 0)				//	If peaklen has not already been lengthened
+					origpeaklen += splicelen;		//  do it now
+				for(z = 0; z < dz->iparam[ESPK_REPET] - 1; z++) {
+					peaklen = origpeaklen;
+					thissplicelen = splicelen;
+					if(dz->param[ESPK_RAND] > 0.0) {		//	On each repet, reduce length of repet, at random (lopping bits off end)
+						do {
+							nupeaklen = randvary_pklen(origpeaklen - splicelen,dz);
+						}while (nupeaklen < 2*chans);
+						peaklen = nupeaklen + splicelen;
+						if(peaklen < splicelen * 2)
+							thissplicelen = peaklen/2;
+						else
+							thissplicelen = splicelen;
+						splicend = thissplicelen - 1;
+					}
+					splicend = splicelen - 1;
+					for(k = 0, j = peaklen - 1, m = lasttrofat - skipback; k < peaklen; m++,k++,j--) {
+						if(k < thissplicelen) 
+							obuf[obufpos] = (float)(obuf[obufpos] + (ibuf[m] * splicebuf[k]));	//	do upslice
+						else if (j < thissplicelen) 
+							obuf[obufpos] = (float)(obuf[obufpos] + (ibuf[m] * splicebuf[splicend--])); //	do downslice
+						else
+							obuf[obufpos] = ibuf[m];											// just copy
+						if(++obufpos >= dz->buflen * 2) {
+							if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+								return(exit_status);
+							memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+							memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+							obufpos -= dz->buflen;
+						}				
+					}
+				}
+			}
+			lasttrofat  = thistrofat;
+		}
+		break;
+	case(1):			//	Repeat-reversed
+		mintrof = dz->iparam[ESPK_OFFST];
+		for(n = 0; n <= dz->trofcnt; n++)  {
+			thistrofat  = trof[n];
+			peaklen = thistrofat - lasttrofat;
+			splicend = splicelen - 1;
+			if(n < mintrof) {			//	Copy infile if process has not yet started
+				peaklen = thistrofat;
+				for(j = peaklen - 1, m = 0; m < thistrofat; m++,j--) {
+					if (j < splicelen) 
+						obuf[obufpos] = (float)(ibuf[m] * splicebuf[splicend--]);			//	do downslice
+					else
+						obuf[obufpos] = ibuf[m];											// or just copy
+					if(++obufpos >= dz->buflen * 2) {
+						if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+							return(exit_status);
+						memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+						memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+						obufpos -= dz->buflen;
+					}
+				}
+			} else {
+				rbufpos = 0;
+				skipback = 0;
+				if(lasttrofat > 0) {
+					obufpos -= splicelen;
+					peaklen += splicelen;
+					upspliclen = splicelen;
+					skipback = splicelen;
+				} else
+					upspliclen = 0;						//	No initial splice
+		
+				splicend = splicelen - 1;
+				for(k = 0, j = peaklen - 1, m = lasttrofat - skipback; m < thistrofat; m++,k++,j--) {	//	Write to both outbuf and reversing-buf
+					rbuf[rbufpos++] = ibuf[m];						
+					if(k < upspliclen) 
+						obuf[obufpos] = (float)(obuf[obufpos] + (ibuf[m] * splicebuf[k]));	//	do upslice
+					else if (j < splicelen) 
+						obuf[obufpos] = (float)(obuf[obufpos] + (ibuf[m]  * splicebuf[splicend--]));			//	do downslice
+					else
+						obuf[obufpos] = ibuf[m];											//	just copy
+					if(++obufpos >= dz->buflen * 2) {
+						if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+							return(exit_status);
+						memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+						memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+						obufpos -= dz->buflen;
+					}				
+				}
+				if(chans > 1) {																//	Reverse channel groups in reversed buffer
+					for(m = 0; m < rbufpos; m += chans) {									//	IF NESS
+						for(i = 0,k = m, j = m+chans-1; i < chans/2; i++, k++,j--) {
+							temp = rbuf[j];
+							rbuf[j] = rbuf[k];
+							rbuf[k] = temp;
+						}
+					}
+				}
+				for(i = 0,m = 0, k = rbufpos - 1; i < rbufpos/2; i++, m++,k--) {					//	Reverse Entire reverse-buf
+					temp = rbuf[m];
+					rbuf[m] = rbuf[k];
+					rbuf[k] = temp;
+				}
+				obufpos -= splicelen;
+				if(upspliclen == 0)				//	If peaklen has not already been lengthened
+					peaklen += splicelen;		//  do it now
+				splicend = splicelen - 1;
+				for(m = 0, j = peaklen - 1; m < peaklen; m++,j--) {							//	Write reverse-buf to outbuf
+					if(m < splicelen) 
+						obuf[obufpos] = (float)(obuf[obufpos] + (rbuf[m] * splicebuf[m]));	//	do upslice
+					else if (j < splicelen) 
+						obuf[obufpos] = (float)(obuf[obufpos] + (rbuf[m] * splicebuf[splicend--]));		//	do downslice
+					else
+						obuf[obufpos] = rbuf[m];											// just copy
+					if(++obufpos >= dz->buflen * 2) {
+						if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+							return(exit_status);
+						memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+						memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+						obufpos -= dz->buflen;
+					}				
+				}
+			}
+			lasttrofat  = thistrofat;
+		}
+		break;
+	case(2):	//	fall thro			Drop out peaks, in a patterned way
+	case(3):
+	//	PREGROUPED THE GATED AND UNGATED MATERIAL
+		gated = 0;
+		lasttrofat = 0;
+		mintrof = dz->iparam[ESPK_OFFST];
+		for(n = 0; n <= dz->trofcnt; n++)  {
+			thistrofat = trof[n];
+			peaklen = thistrofat - lasttrofat;
+			splicend = splicelen - 1;
+			if(n < mintrof) {
+				for(j = peaklen - 1, m = 0; m < thistrofat; m++,j--) {
+					if (j < splicelen) 
+						obuf[obufpos] = (float)(ibuf[m] * splicebuf[splicend--]);			//	do downslice to attenuation level
+					else
+						obuf[obufpos] = ibuf[m];											// or just copy
+					if(++obufpos >= dz->buflen * 2) {
+						if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+							return(exit_status);
+						memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+						memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+						obufpos -= dz->buflen;
+					}
+				}
+			} else if((dz->mode == 2 && !gated) || (dz->mode == 3 && gated)) {
+				skipback = 0;
+				if(lasttrofat > 0) {				//	If we're NOT at file start	
+					obufpos -= splicelen;		//	baktrak to splice to end of last segment written
+					peaklen += splicelen;		//	and length of peak is therefore one splicelen longer
+					upsplice = splicelen;
+					skipback = splicelen;
+				} else
+					upsplice = 0;					//	Prevents initial splice on start of file-segment
+				splicend = splicelen - 1;
+				for(k = 0, j = peaklen - 1, m = lasttrofat - skipback; m < thistrofat; m++,k++,j--) {
+					if(k < upsplice) 
+						obuf[obufpos] = (float)(obuf[obufpos] + (ibuf[m] * splicebuf[k]));	//	do upslice
+					else if (j < splicelen) 
+						obuf[obufpos] = (float)(obuf[obufpos] + (ibuf[m] * splicebuf[splicend--]));	//	do downslice
+					else
+						obuf[obufpos] = ibuf[m];											//	just copy
+					if(++obufpos >= dz->buflen * 2) {
+						if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+							return(exit_status);
+						memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+						memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+						obufpos -= dz->buflen;
+					}				
+				}
+				gated = !gated;
+			} else {
+				skipback = 0;
+				if(lasttrofat > 0) {				//	If we're NOT at file start	
+					obufpos -= splicelen;		//	baktrak to splice to end of last segment written
+					peaklen += splicelen;		//	and length of peak is therefore one splicelen longer
+					upsplice = splicelen;
+					skipback = splicelen;
+				} else
+					upsplice = 0;				//	Prevents initial splice on start of file-segment
+				splicend = splicelen - 1;
+				for(k = 0, j = peaklen - 1, m = lasttrofat - skipback; m < thistrofat; m++,k++,j--) {
+					if(k < upsplice) 
+						obuf[obufpos] = (float)(obuf[obufpos] + (ibuf[m] *  dz->param[ESPK_GAIN] * splicebuf[k]));	//	do upslice with attenuate
+					else if (j < splicelen) 
+						obuf[obufpos] = (float)(obuf[obufpos] + (ibuf[m] *  dz->param[ESPK_GAIN] * splicebuf[splicend--]));	//	do downslice with attenuate
+					else
+						obuf[obufpos] = (float)(ibuf[m] * dz->param[ESPK_GAIN]);										// just attenuate										
+					if(++obufpos >= dz->buflen * 2) {								
+						if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+							return(exit_status);
+						memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+						memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+						obufpos -= dz->buflen;
+					}				
+				}
+				gated = !gated;
+			}
+			lasttrofat  = thistrofat;
+		}
+		break;
+	case(4):	//	fall thro			//	Repeat	: Shrink
+	case(5):
+		mintrof = dz->iparam[ESPK_OFFST];
+		for(n = 0; n <= dz->trofcnt; n++)  {
+			thistrofat  = trof[n];
+			peaklen = thistrofat - lasttrofat;
+			trofdiv = (int)round((double)(peaklen/chans)/(double)dz->iparam[ESPK_REPET]) * chans;
+			splicend = splicelen - 1;
+			if(n < mintrof) {			//	We must be at start of file : therefore no obufpos baktrak & no upsplice
+				for(j = peaklen - 1, m = 0; m < thistrofat; m++,j--) {
+					if (j < splicelen) 
+						obuf[obufpos] = (float)(ibuf[m] * splicebuf[splicend--]);			//	do downslice
+					else																	
+						obuf[obufpos] = ibuf[m];											//  else copy input
+					if(++obufpos >= dz->buflen * 2) {
+						if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+							return(exit_status);
+						memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+						memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+						obufpos -= dz->buflen;
+					}
+				}
+			} else {
+				time = (double)thistrofat/(double)samps_per_sec;
+				if((exit_status = read_values_from_all_existing_brktables(time,dz))<0)
+					return PROGRAM_ERROR;
+				skipback = 0;
+				if(lasttrofat > 0) {				//	If we're NOT at file start	
+					obufpos -= splicelen;		//	baktrak to splice to end of last segment written
+					peaklen += splicelen;		//	and length of peak is therefore one splicelen longer
+					upsplice = splicelen;
+					skipback = splicelen;
+				} else
+					upsplice = 0;					//	Prevents initial splice on start of file-segment
+				splicend = splicelen - 1;
+				for(k = 0, j = peaklen - 1, m = lasttrofat - skipback; m < thistrofat; m++,k++,j--) {
+					if(k < upsplice) 
+						obuf[obufpos] = (float)(obuf[obufpos] + (ibuf[m] * splicebuf[k]));	//	do upslice
+					else if (j < splicelen) 
+						obuf[obufpos] = (float)(ibuf[m] * splicebuf[splicend--]);			//	do downslice
+					else
+						obuf[obufpos] = ibuf[m];											//	just copy
+					if(++obufpos >= dz->buflen * 2) {
+						if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+							return(exit_status);
+						memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+						memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+						obufpos -= dz->buflen;
+					}
+				}
+				obufpos -= splicelen;
+				truepeaklen = peaklen;
+				truelasttrofat = lasttrofat;
+				switch(dz->mode) {
+				case(4):
+					for(z = 0; z < dz->iparam[ESPK_REPET] - 1; z++) {
+						peaklen = truepeaklen;
+						peaklen -= trofdiv;			//	On each repet, reduce length of repeat by loppibf bits of END of seg			
+						truepeaklen -= trofdiv;		//	Advance and Remember UNrandomised peaklen			
+						if(dz->param[ESPK_RAND] > 0.0) {
+							roffset = drand48() - 0.5;		//		Rand range max +- 1/2 peaklen;
+							roffset *= dz->param[ESPK_RAND];
+							offset = (int)round(roffset * ((peaklen - splicelen)/chans)) * chans;	//	offset is divisible by chans;
+							if(offset != 0)
+								peaklen += offset;
+						}
+						if(peaklen < splicelen * 2)
+							thissplicelen = peaklen/2;
+						else
+							thissplicelen = splicelen;
+						splicend = thissplicelen - 1;
+						for(k = 0, j = peaklen - 1, m = lasttrofat - skipback; k < peaklen; m++,k++,j--) {
+							if(k < thissplicelen) 
+								obuf[obufpos] = (float)(obuf[obufpos] + (ibuf[m] * splicebuf[k]));	//	do upslice
+							else if (j < thissplicelen) 
+								obuf[obufpos] = (float)(obuf[obufpos] + (ibuf[m] * splicebuf[splicend--])); //	do downslice
+							else
+								obuf[obufpos] = ibuf[m];											// just copy
+							if(++obufpos >= dz->buflen * 2) {
+								if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+									return(exit_status);
+								memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+								memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+								obufpos -= dz->buflen;
+							}				
+						}
+					}
+					break;
+				case(5):
+					for(z = 0; z < dz->iparam[ESPK_REPET] - 1; z++) {
+						peaklen = truepeaklen;
+						peaklen -= trofdiv;
+						truepeaklen -= trofdiv;
+						lasttrofat = thistrofat - peaklen;
+						lasttrofat += trofdiv;		//	On each repet, reduce length of repeat by lopping bits off start of seg
+						offset = 0;
+						if(dz->param[ESPK_RAND] > 0.0) {
+							while(peaklen < chans * 2) {				//	Avoid negative-length segments
+								roffset = drand48() - 0.5;				//	Rand range max +- 1/2 peaklen TIMES the entered rand param (0-1)
+								roffset *= dz->param[ESPK_RAND];		//	Offset is divisible by chans;
+								offset = (int)round(roffset * ((peaklen - splicelen)/2/chans)) * chans;
+								peaklen += offset;
+							}											//	If peaklen shorter than upsplive+ downsplice
+						}												//	Shorten "thisspilcelen"
+						if(peaklen < splicelen * 2)						//	This causes splice table to be read up to, and then down from
+							thissplicelen = peaklen/2;					//	ony a part of it, but still gives equivalent up and down splices
+						else
+							thissplicelen = splicelen;
+						lasttrofat = thistrofat - (peaklen - thissplicelen);
+						splicend = thissplicelen - 1;
+						for(k = 0, j = peaklen - 1, m = lasttrofat; k < peaklen; m++,k++,j--) {
+							if(k < thissplicelen) 
+								obuf[obufpos] = (float)(obuf[obufpos] + (ibuf[m] * splicebuf[k]));	//	do upslice
+							else if (j < thissplicelen)
+								obuf[obufpos] = (float)(obuf[obufpos] + (ibuf[m] * splicebuf[splicend--])); //	do downslice
+							else
+								obuf[obufpos] = ibuf[m];											// just copy
+							if(++obufpos >= dz->buflen * 2) {
+								if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+									return(exit_status);
+								memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+								memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+								obufpos -= dz->buflen;
+							}				
+						}
+					}
+					break;
+				}
+			}
+			lasttrofat  = thistrofat;
+		}
+		break;
+	case(6):							//	Repeat divided element of syllables
+		mintrof = dz->iparam[ESPK_OFFST];
+		isrand = 0;
+		for(n = 0; n <= dz->trofcnt; n++)  {
+			thistrofat  = trof[n];
+			peaklen = thistrofat - lasttrofat;
+			trofdiv = (int)round((double)(peaklen/chans)/(double)dz->iparam[ESPK_REPET]) * chans;
+			trofdiv = max(trofdiv,mindur);
+			splicend = splicelen - 1;
+			if(n < mintrof) {			//	We must be at start of file : therefore no obufpos baktrak & no upsplice
+				for(j = peaklen - 1, m = 0; m < thistrofat; m++,j--) {
+					if (j < splicelen) 
+						obuf[obufpos] = (float)(ibuf[m] * splicebuf[splicend--]);			//	do downslice
+					else																	
+						obuf[obufpos] = ibuf[m];											//  else copy input
+					if(++obufpos >= dz->buflen * 2) {
+						if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+							return(exit_status);
+						memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+						memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+						obufpos -= dz->buflen;
+					}
+				}
+			} else {
+				time = (double)thistrofat/(double)samps_per_sec;
+				if((exit_status = read_values_from_all_existing_brktables(time,dz))<0)
+					return PROGRAM_ERROR;
+				skipback = 0;
+				peaklen  = trofdiv;						//	1/Nth part of syllable only, to be repeated N times
+				origpeaklen = peaklen;
+				skipforward = (dz->iparam[ESPK_WHICH] - 1) * trofdiv;		//	Finds seg to repeat
+				for(z = 0; z < dz->iparam[ESPK_REPET]; z++) {
+					if(isrand)
+						peaklen = origpeaklen;
+					skipback = splicelen;
+					if((sttseg = lasttrofat + skipforward - skipback) >= 0) {
+						obufpos -= splicelen;			//	baktrak to splice to end of last segment written
+						if(dz->vflag[0]) {
+						/* HEREH */				
+							if(z == 0)
+								peaklen += splicelen;
+						} else {
+							peaklen += splicelen;		//	length of peaks increase
+							peaklen = min(peaklen,dz->insams[0]);
+						}
+						upsplice = splicelen;
+						lasttrofat = thistrofat - peaklen;
+					} else {
+						sttseg = 0;
+						upsplice = 0;					//	Prevents initial splice on start of 1st file-segment
+					}
+					origpeaklen = peaklen;
+					isrand = 0;
+					if(dz->param[ESPK_RAND] > 0.0) {
+						roffset = drand48() - 0.5;		//		Rand range max +- 1/2 peaklen;
+						roffset *= dz->param[ESPK_RAND];
+						offset = (int)round(roffset * ((peaklen - splicelen)/chans)) * chans;	//	offset is divisible by chans;
+						peaklen += offset;
+						isrand = 1;
+					}
+					if(peaklen < splicelen * 2) {		//	This causes splice table to be read up to, and then down from
+						thissplicelen = peaklen/2;		//	ony a part of it, but still gives equivalent up and down splices
+						if(upsplice > 0)
+							upsplice = thissplicelen;
+					} else {
+						thissplicelen = splicelen;
+						if(upsplice > 0)
+							upsplice = thissplicelen;
+					}
+					splicend = splicelen - 1;
+					for(k = 0, j = peaklen - 1, m = sttseg; k < peaklen; m++,k++,j--) {
+						if(k < upsplice) 
+							obuf[obufpos] = (float)(obuf[obufpos] + (ibuf[m] * splicebuf[k]));	//	do upslice
+						else if (j < thissplicelen) 
+							obuf[obufpos] = (float)(ibuf[m] * splicebuf[splicend--]);			//	do downslice
+						else
+							obuf[obufpos] = ibuf[m];											//	just copy
+						if(++obufpos >= dz->buflen * 2) {
+							if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+								return(exit_status);
+							memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+							memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+							obufpos -= dz->buflen;
+						}
+					}
+				}
+			}
+			lasttrofat  = thistrofat;
+		}
+		break;
+	case(7):							//	Repeat syllables, diminishing in length, lopping off end
+		mintrof = dz->iparam[ESPK_OFFST];
+		isrand = 0;
+		for(n = 0; n <= dz->trofcnt; n++)  {
+			thistrofat  = trof[n];
+			peaklen = thistrofat - lasttrofat;
+			origpeaklen = peaklen;
+			ratio = dz->param[ESPK_RATIO];
+			splicend = splicelen - 1;
+			if(n < mintrof) {			//	We must be at start of file : therefore no obufpos baktrak & no upsplice
+				for(j = peaklen - 1, m = 0; m < thistrofat; m++,j--) {
+					if (j < splicelen) 
+						obuf[obufpos] = (float)(ibuf[m] * splicebuf[splicend--]);			//	do downslice
+					else																	
+						obuf[obufpos] = ibuf[m];											//  else copy input
+					if(++obufpos >= dz->buflen * 2) {
+						if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+							return(exit_status);
+						memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+						memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+						obufpos -= dz->buflen;
+					}
+				}
+			} else {
+				time = (double)thistrofat/(double)samps_per_sec;
+				if((exit_status = read_values_from_all_existing_brktables(time,dz))<0)
+					return PROGRAM_ERROR;
+				for(z = 0; z < dz->iparam[ESPK_REPET]; z++) {
+					peaklen = origpeaklen;
+					if(lasttrofat > 0) {
+						obufpos -= splicelen;			//	baktrak to splice to end of last segment written
+						peaklen += splicelen;			//	include pre-splice
+						skipback = splicelen;
+						upsplice = splicelen;
+					} else {
+						upsplice = 0;					//	Prevents initial splice on start of 1st file-segment
+						skipback = 0;
+					}
+					isrand = 0;
+					if(dz->param[ESPK_RAND] > 0.0) {
+						roffset = drand48() - 0.5;		//		Rand range max +- 1/2 peaklen;
+						roffset *= dz->param[ESPK_RAND];
+						offset = (int)round(roffset * ((peaklen - splicelen)/chans)) * chans;	//	offset is divisible by chans;
+						peaklen += offset;
+						isrand = 1;
+					}
+					if(peaklen < splicelen * 2) {		//	This causes splice table to be read up to, and then down from
+						thissplicelen = peaklen/2;		//	ony a part of it, but still gives equivalent up and down splices
+						if(upsplice > 0)
+							upsplice = thissplicelen;
+					} else {
+						thissplicelen = splicelen;
+						if(upsplice > 0)
+							upsplice = thissplicelen;
+					}
+					splicend = splicelen - 1;
+					for(k = 0, j = peaklen - 1, m = lasttrofat - skipback; k < peaklen; m++,k++,j--) {
+						if(k < upsplice) 
+							obuf[obufpos] = (float)(obuf[obufpos] + (ibuf[m] * splicebuf[k]));	//	do upslice
+						else if (j < thissplicelen) 
+							obuf[obufpos] = (float)(ibuf[m] * splicebuf[splicend--]);			//	do downslice
+						else
+							obuf[obufpos] = ibuf[m];											//	just copy
+						if(++obufpos >= dz->buflen * 2) {
+							if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+								return(exit_status);
+							memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+							memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+							obufpos -= dz->buflen;
+						}
+					}
+					origpeaklen = (int)round((double)(origpeaklen/chans) * ratio) * chans;
+					origpeaklen = max(origpeaklen,mindur);
+				}
+			}
+			lasttrofat  = thistrofat;
+		}
+		break;
+	case(8):							//	Repeat syllables, diminishing in length, lopping off start
+		mintrof = dz->iparam[ESPK_OFFST];
+		isrand = 0;
+		for(n = 0; n <= dz->trofcnt; n++)  {
+			thistrofat  = trof[n];
+			peaklen = thistrofat - lasttrofat;
+			origpeaklen = peaklen;
+			ratio = dz->param[ESPK_RATIO];
+			splicend = splicelen - 1;
+			if(n < mintrof) {			//	We must be at start of file : therefore no obufpos baktrak & no upsplice
+				for(j = peaklen - 1, m = 0; m < thistrofat; m++,j--) {
+					if (j < splicelen) 
+						obuf[obufpos] = (float)(ibuf[m] * splicebuf[splicend--]);			//	do downslice
+					else																	
+						obuf[obufpos] = ibuf[m];											//  else copy input
+					if(++obufpos >= dz->buflen * 2) {
+						if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+							return(exit_status);
+						memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+						memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+						obufpos -= dz->buflen;
+					}
+				}
+			} else {
+				time = (double)thistrofat/(double)samps_per_sec;
+				if((exit_status = read_values_from_all_existing_brktables(time,dz))<0)
+					return PROGRAM_ERROR;
+				for(z = 0; z < dz->iparam[ESPK_REPET]; z++) {
+					peaklen = origpeaklen;
+					if(lasttrofat > 0) {
+						obufpos -= splicelen;			//	baktrak to splice to end of last segment written
+						peaklen += splicelen;			//	include pre-splice
+						skipback = splicelen;
+						upsplice = splicelen;
+					} else {
+						upsplice = 0;					//	Prevents initial splice on start of 1st file-segment
+						skipback = 0;
+					}
+					isrand = 0;
+					if(dz->param[ESPK_RAND] > 0.0) {
+						roffset = drand48() - 0.5;		//		Rand range max +- 1/2 peaklen;
+						roffset *= dz->param[ESPK_RAND];
+						offset = (int)round(roffset * ((peaklen - splicelen)/chans)) * chans;	//	offset is divisible by chans;
+						peaklen += offset;
+						isrand = 1;
+					}
+					if(peaklen < splicelen * 2) {		//	This causes splice table to be read up to, and then down from
+						thissplicelen = peaklen/2;		//	ony a part of it, but still gives equivalent up and down splices
+						if(upsplice > 0)
+							upsplice = thissplicelen;
+					} else {
+						thissplicelen = splicelen;
+						if(upsplice > 0)
+							upsplice = thissplicelen;
+					}
+					splicend = splicelen - 1;
+					for(k = 0, j = peaklen - 1, m = max(0,thistrofat - peaklen); k < peaklen; m++,k++,j--) {
+						if(k < upsplice) 
+							obuf[obufpos] = (float)(obuf[obufpos] + (ibuf[m] * splicebuf[k]));	//	do upslice
+						else if (j < thissplicelen) 
+							obuf[obufpos] = (float)(ibuf[m] * splicebuf[splicend--]);			//	do downslice
+						else
+							obuf[obufpos] = ibuf[m];											//	just copy
+						if(++obufpos >= dz->buflen * 2) {
+							if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+								return(exit_status);
+							memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+							memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+							obufpos -= dz->buflen;
+						}
+					}
+					origpeaklen = (int)round((double)(origpeaklen/chans) * ratio) * chans;
+					origpeaklen = max(origpeaklen,mindur);
+				}
+			}
+			lasttrofat  = thistrofat;
+		}
+		break;
+	case(9):				//	Extract syllables
+		namelen = strlen(dz->wordstor[0]);
+		numlen = 4;
+		if((outfilename = (char *)malloc((namelen + numlen + 1) * sizeof(char)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY to store outfilenames.\n");
+			return(MEMORY_ERROR);
+		}
+		for(n = 0; n <= dz->trofcnt; n++)  {
+			obufpos = 0;
+			if(n > 0) {
+				if((exit_status = open_next_file(outfilename,n,dz)) < 0)
+					return exit_status;
+			}
+			thistrofat  = trof[n];
+			peaklen = thistrofat - lasttrofat;
+			splicend = splicelen - 1;
+			if(lasttrofat > 0) {
+				peaklen += splicelen;			//	include pre-splice
+				upsplice = splicelen;
+			} else {
+				upsplice = 0;					//	Prevents initial splice on start of 1st file-segment
+			}
+			if(peaklen < splicelen * 2) {		//	This causes splice table to be read up to, and then down from
+				thissplicelen = peaklen/2;		//	ony a part of it, but still gives equivalent up and down splices
+				if(upsplice > 0)
+					upsplice = thissplicelen;
+			} else {
+				thissplicelen = splicelen;
+				if(upsplice > 0)
+					upsplice = thissplicelen;
+			}
+			dz->total_samps_written = 0;
+			dz->tempsize = peaklen;
+			splicend = splicelen - 1;
+			for(k = 0, j = peaklen - 1, m = thistrofat - peaklen; k < peaklen; m++,k++,j--) {
+				if(k < upsplice)
+					obuf[obufpos] = (float)(ibuf[m] * splicebuf[k]);	//	do upslice
+				else if (j < thissplicelen) 
+					obuf[obufpos] = (float)(ibuf[m] * splicebuf[splicend--]);			//	do downslice
+				else
+					obuf[obufpos] = ibuf[m];							//	just copy
+				if(++obufpos >= dz->buflen * 2) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+					memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+					obufpos -= dz->buflen;
+				}
+			}
+			if(obufpos) {
+				if((exit_status = write_samps(obuf,obufpos,dz))<0)
+					return(exit_status);
+			}
+			lasttrofat = thistrofat;
+		}
+		obufpos = 0;
+		break;
+	case(10):	//	fall thro					//	Randomise order
+	case(11):									//	N-wise permute order
+		switch(dz->mode) {
+		case(10):
+			if(dz->iparam[ESPK_SEED] > 0)
+				srand((int)dz->iparam[ESPK_SEED]);
+			else
+				initrand48();
+			randperm(0,dz->trofcnt+1,dz);
+			permm = dz->iparray[0];
+			break;
+		case(11):
+			permm = dz->iparray[0];
+			if(dz->brksize[ESPK_NWISE]) {
+				time = 0.0;
+				if((exit_status = read_value_from_brktable(time,ESPK_NWISE,dz))<0)
+					return exit_status;
+			}
+			i = 0;
+			for(k = 0; k <= dz->trofcnt; k += nwise) {
+				nwise = dz->iparam[ESPK_NWISE];
+				z = min(k + nwise,dz->trofcnt+1);
+				do {
+					z--;
+					permm[i++] = z;			//	Store reverse-ordered groups
+				} while(z > k);
+				if(dz->brksize[ESPK_NWISE]) {
+					time = (double)trof[k]/(double)samps_per_sec;
+					if((exit_status = read_value_from_brktable(time,ESPK_NWISE,dz))<0)
+						return exit_status;
+				}
+			}
+			break;
+		}
+		for(n = 0; n <= dz->trofcnt; n++)  {
+			k = permm[n];
+			thistrofat  = trof[k--];
+			if(k < 0)
+				lasttrofat = 0;
+			else
+				lasttrofat = trof[k];
+			peaklen = thistrofat - lasttrofat;
+			splicend = splicelen - 1;
+			if(lasttrofat > 0) {
+				obufpos -= splicelen;			//	baktrak to splice to end of last segment written
+				peaklen += splicelen;			//	include pre-splice
+				upsplice = splicelen;
+			} else
+				upsplice = 0;					//	Prevents initial splice on start of 1st file-segment
+			if(peaklen < splicelen * 2) {		//	This causes splice table to be read up to, and then down from
+				thissplicelen = peaklen/2;		//	ony a part of it, but still gives equivalent up and down splices
+				if(upsplice > 0)
+					upsplice = thissplicelen;
+			} else {
+				thissplicelen = splicelen;
+				if(upsplice > 0)
+					upsplice = thissplicelen;
+			}
+			splicend = splicelen - 1;
+			for(k = 0, j = peaklen - 1, m = max(0,thistrofat - peaklen); k < peaklen; m++,k++,j--) {
+				if(k < upsplice) 
+					obuf[obufpos] = (float)(obuf[obufpos] + (ibuf[m] * splicebuf[k]));	//	do upslice
+				else if (j < thissplicelen) 
+					obuf[obufpos] = (float)(ibuf[m] * splicebuf[splicend--]);			//	do downslice
+				else
+					obuf[obufpos] = ibuf[m];											//	just copy
+				if(++obufpos >= dz->buflen * 2) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+					memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+					obufpos -= dz->buflen;
+				}
+			}
+			lasttrofat  = thistrofat;
+		}
+		break;
+	}
+	 if(obufpos) {
+		if((exit_status = write_samps(obuf,obufpos,dz))<0)
+			return(exit_status);
+	}
+	return FINISHED;
+}
+
+/*************************************** EXTRACT_ENV_FROM_SNDFILE **************************/
+
+int extract_env_from_sndfile(dataptr dz)
+{
+	int exit_status;
+	float *envptr;
+	dz->envcnt = windows_in_sndfile(dz);
+	if((dz->fptr[0]=(float *)malloc((dz->envcnt+20) * sizeof(float)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to store envelope (2).\n");
+		return(MEMORY_ERROR);
+	}
+	envptr = dz->fptr[0];
+	dz->ssampsread = 1;
+	while(dz->ssampsread > 0)	{
+		if((dz->ssampsread = fgetfbufEx(dz->sampbuf[0], dz->buflen,dz->ifd[0],0)) < 0) {
+			sprintf(errstr,"Can't read samples from soundfile: extract_env_from_sndfile()\n");
+			return(SYSTEM_ERROR);
+		}
+		if(sloom)
+			display_virtual_time(dz->total_samps_read,dz);		
+		if((exit_status = getenv_of_buffer(dz->ssampsread,&envptr,dz))<0)
+			return exit_status;
+	}
+	dz->fptr[1] = envptr;		//	envend
+	if((exit_status = sndseekEx(dz->ifd[0],0,0))<0) {
+		sprintf(errstr,"Failed to return to start of file.\n");
+		return SYSTEM_ERROR;
+	}
+	dz->total_samps_read = 0;
+	return(FINISHED);
+}
+
+/************************* GETENV_OF_BUFFER [READENV] *******************************/
+
+int getenv_of_buffer(int samps_to_process,float **envptr,dataptr dz)
+{
+	int  start_samp = 0;
+	int envwindow_sampsize = dz->iparam[ESPK_WINSZ];
+	float *ibuf = dz->sampbuf[0];
+	float *env = *envptr;
+	double convertor = 1.0/F_ABSMAXSAMP;
+	while(samps_to_process >= envwindow_sampsize) {
+		*env++       = (float) (getmaxsamp(start_samp,envwindow_sampsize,ibuf) * convertor);
+		start_samp  += envwindow_sampsize;
+		samps_to_process -= envwindow_sampsize;
+	}
+	if(samps_to_process)	/* Handle any final short buffer */
+		*env++ = (float)(getmaxsamp(start_samp,samps_to_process,ibuf) * convertor);
+	*envptr = env;
+	return FINISHED;
+}
+
+/****************************** WINDOWS_IN_SNDFILE [GET_ENVSIZE] ******************************/
+ 
+int windows_in_sndfile(dataptr dz)
+{
+	int envcnt, winsize = dz->iparam[ESPK_WINSZ];
+	if(((envcnt = dz->insams[0]/winsize) * winsize)!=dz->insams[0])
+		envcnt++;
+	return envcnt;
+}
+
+/*************************** GETMAXSAMP *****************************/
+
+double getmaxsamp(int startsamp, int sampcnt,float *buffer)
+{
+	int  i, endsamp = startsamp + sampcnt;
+	double thisval, thismaxsamp = 0.0;
+	for(i = startsamp; i<endsamp; i++) {
+		if((thisval =  fabs(buffer[i]))>thismaxsamp)		   
+			thismaxsamp = thisval;
+	}
+	return thismaxsamp;
+}
+
+/*************************** ENVTROFSGET *************************/
+ 
+int envtrofsget(dataptr dz)
+{
+	int done, n, k, m;
+ 	int upwards, troffcnt = 0, thistrofat, lasttrofat, envcnt, peaklen, ovflw;
+	int *trof;
+ 	float *p, *q;
+	int envwindow_sampsize = dz->iparam[ESPK_WINSZ];
+	int minseglen = (dz->iparam[ESPK_SPLEN] * 2) * dz->infile->channels;		//	Minimum segment to cut is larger than 2 splices.
+	float *env, *envend;
+
+	env = dz->fptr[0];
+	envend = dz->fptr[1];
+					//	 2 gpsplices     * chans;
+	p = env+1;
+ 	q = env;    
+	if (*p > *q)
+ 		upwards = TRUE;
+ 	else
+ 		upwards = FALSE;
+	troffcnt  = 0;
+	lasttrofat = 0;
+	envcnt = 0;
+ 	while(p < envend) {
+ 		if(upwards) {
+ 			if(*p < *q) {
+ 				upwards = FALSE;
+ 			}
+ 		} else {
+			if(*p > *q) {												//	Peak-segments (separated by trofs)
+				if(istrof(env,envend,q,ENVSPEAK_PKSRCHWIDTH)) {
+					thistrofat = envcnt * envwindow_sampsize;
+					peaklen = thistrofat - lasttrofat;
+					if(peaklen > minseglen) {							//	Peak-segments must be longer than 2 splices
+						troffcnt++;										//	This also skips getting a trof AT 0 time
+						lasttrofat = thistrofat;
+					}
+				}
+ 				upwards = TRUE;
+ 			}
+		}
+ 		p++;
+ 		q++;
+		envcnt++;
+ 	}
+	if(dz->mode == 10 || dz->mode == 11) {
+		if((dz->iparray = (int **)malloc(sizeof(int *))) == NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY to store peak-locations.\n");
+			return(MEMORY_ERROR);
+		}
+		if((dz->iparray[0] = (int *)malloc((troffcnt + 1) * sizeof(int))) == NULL) {//	Storage for permed or swapped syllable order
+			sprintf(errstr,"INSUFFICIENT MEMORY to store peak-locations.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	trof = dz->lparray[0];
+	dz->trofcnt = troffcnt;
+	envcnt = 0;
+ 	p = env+1;
+ 	q = env;    
+	if (*p > *q)
+ 		upwards = TRUE;
+ 	else
+ 		upwards = FALSE;
+	troffcnt = 0;
+	lasttrofat = 0;
+	envcnt = 0;
+	while(envcnt < dz->envcnt) {
+ 		if(upwards) {
+ 			if(*p < *q) {
+ 				upwards = FALSE;
+ 			}
+ 		} else {
+			if(*p > *q) {												//	Peak-segments (separated by trofs)
+				if(istrof(env,envend,q,ENVSPEAK_PKSRCHWIDTH)) {
+					thistrofat = envcnt * envwindow_sampsize;
+					peaklen = thistrofat - lasttrofat;
+					if(peaklen > minseglen) {
+						trof[troffcnt++] = envcnt * dz->iparam[ESPK_WINSZ];	//	Peak-segments must be longer than 2 splices
+						lasttrofat = thistrofat;							//	This also skips getting a trof AT 0 time
+					}
+				}
+ 				upwards = TRUE;
+ 			}
+		}
+ 		p++;
+ 		q++;
+		envcnt++;
+ 	}
+	trof[troffcnt] = dz->insams[0];		//	Add trof at EOF
+
+	if(dz->mode == 2 || dz->mode == 3) {			//	PREGROUP (i.e. shuffle-down overwrite) THE SETS OF ATTENUATED SEGMENTS
+		done = 0;									//													Say we hape attenSTEP = 3
+		for(n = 0; n < dz->trofcnt; n+=2) {			//	At every trof value								To merge (for attenuating) N segments, Shuffle down N-1 times
+			if(n < dz->iparam[ESPK_OFFST])			//													(last time tx is EOF and is AT trofcnt) 
+				continue;							//	To delete N trofs, shuffle down N-1 timings		t0  t1  t2  t3  t4  t5  t6  t7  (tx)  
+			k = n + 1;								//													t0	MERGED	t3  t4  t5  t6  t7  (tx)  
+			m = n + dz->iparam[ESPK_GATED];			//													t0  t3  t4  t5  t6  t7 (tx)  REDUCE trofcnt by N-1 
+			if((ovflw = m - dz->trofcnt) >= 0) {	//																							
+				trof[k] = trof[dz->trofcnt];		//													If at array end 
+				dz->trofcnt -= (dz->iparam[ESPK_GATED] - ovflw);	//									t1  t2  t3  t4 (tx)	OR	t1  t2  t3	(tx)		OR	t1  t2 (tx)
+				done = 1;							//														n	k		m			n	k		  m			    n	k	 -  m	
+				break;								//													Copy(tx) into k :
+			} else {								//													OVFLW = m - End = 0		OVFLW = m - End = 1		OVFLW = m - End = 2
+				for(/* k, m */; m <= dz->trofcnt; k++,m++) {				//									Reduce trofcnt by 0		Reduce trofcnt by 1		Reduce trofcnt by 2
+					trof[k] = trof[m];        //RWD can hide unused vars above
+				}
+				dz->trofcnt -= dz->iparam[ESPK_GATED] - 1;		//	DEFAULT
+			}
+		}
+	}
+	if(dz->trofcnt <= 0) {
+		sprintf(errstr,"FAILED TO FIND ANY ENVELOPE TROUGHS IN THE FILE.\n");
+		return DATA_ERROR;
+	}
+	return(FINISHED);
+}
+
+/*************************** CREATE_SNDBUFS_FOR_ENVEL **************************
+ *
+ *	Only AFTER params have been read.
+ */
+
+int create_sndbufs_for_envel(dataptr dz)
+{
+	int bigbufsize;
+	int n;
+	/* All other cases */
+	if(dz->bufcnt < 4) {
+		sprintf(errstr,"bufcnt too low : must be at least 4.\n");
+		return(PROGRAM_ERROR);
+	}
+	if(dz->sbufptr == 0 || dz->sampbuf == 0) {
+		sprintf(errstr,"buffer pointers not allocated: create_sndbufs_for_envel()\n");
+		return(PROGRAM_ERROR);
+	}
+	dz->buflen = dz->insams[0];
+	bigbufsize = dz->buflen * dz->bufcnt * sizeof(float);
+
+	if((dz->bigbuf = (float *)malloc((bigbufsize))) == NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to create sound buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->bufcnt;n++)				//	Leave making reversing buf till max size assessed
+		dz->sbufptr[n] = dz->sampbuf[n] = dz->bigbuf + (dz->buflen * n);
+	dz->sbufptr[n] = dz->sampbuf[n] = dz->bigbuf + (dz->buflen * n);
+	return(FINISHED);
+}
+
+/*************************** ISTROF **********************************/
+ 
+int istrof(float *env,float *envend,float *q,int width)
+{
+ 	int up, down;
+ 	float *upq, *downq, *r;
+ 	if(width<2)
+ 		return(TRUE);
+ 	down = up = width/2;   
+	if(EVEN(width))
+ 		down = up - 1;		/* set search params above and below q */
+ 	downq = q - down;
+ 	upq   = q + up;
+ 	upq   = min(envend-1,upq);	/* allow for ends of envelope table */
+ 	downq = max(env,downq);
+ 	for(r = downq; r<=upq; r++) {
+ 		if(*q > *r)
+ 			return(FALSE);		
+ 	}
+ 	return(TRUE);			/* if r is minimum of all in peak, return 1 */
+ }
+ 
+/*************************** PRECALCULATE_PEAKS_ARRAY_AND_SPLICE **********************************/
+ 
+int precalculate_peaks_array_and_splice(dataptr dz)
+{
+	int exit_status, chans = dz->infile->channels;
+	int gpsplicelen, splicelen, n, m, k;
+	double splicincr, *splicebuf;
+	int srate = dz->infile->srate;
+
+	dz->iparam[ESPK_SPLEN] = (int)round(dz->param[ESPK_SPLEN] * MS_TO_SECS * (double)srate);
+	gpsplicelen = dz->iparam[ESPK_SPLEN];
+	splicelen = gpsplicelen * chans;
+	splicincr = 1.0/(double)gpsplicelen;
+	if((dz->parray[0] = (double *)malloc((splicelen * sizeof(double)))) == NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to create splice buffer (2).\n");
+		return(MEMORY_ERROR);
+	}
+	splicebuf = dz->parray[0];
+	for(n= 0, m = 0;n < gpsplicelen; n++, m += chans) {
+		for(k = 0; k < chans; k++)
+			splicebuf[m+k] = (double)n * splicincr;
+	}
+	if(dz->mode < 12) {
+		dz->iparam[ESPK_WINSZ] = (int)round(dz->param[ESPK_WINSZ] * MS_TO_SECS * (double)srate) * chans;
+		if((exit_status = extract_env_from_sndfile(dz))< 0)
+			return exit_status;
+		if((dz->lparray=(int **)malloc(sizeof(int *)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY to store peaks.\n");
+			return(MEMORY_ERROR);
+		}
+		if((dz->lparray[0]=(int *)malloc(dz->envcnt * sizeof(int)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY to store peaks (2).\n");
+			return(MEMORY_ERROR);
+		}
+		if((exit_status = envtrofsget(dz))< 0)
+			return exit_status;
+	} else {
+		dz->ssampsread = 1;
+		while(dz->ssampsread > 0)	{
+			if((dz->ssampsread = fgetfbufEx(dz->sampbuf[0], dz->buflen,dz->ifd[0],0)) < 0) {
+				sprintf(errstr,"Can't read samples from soundfile: getcutdata()\n");
+				return(SYSTEM_ERROR);
+			}
+		}
+	}
+	return FINISHED;
+}
+
+/*************************** GETMAXATTENCNT **********************************/
+ 
+int getmaxattencnt(dataptr dz)
+{
+	int n;
+	int maxatten = -1;
+	if(dz->brksize[ESPK_GATED] == 0)
+		return dz->iparam[ESPK_GATED];
+	else {
+		for(n = 0; n < dz->brksize[ESPK_GATED]; n++)
+			maxatten = max(maxatten,(int)round(dz->brk[ESPK_GATED][n]));
+	}
+	return maxatten;
+}
+
+/****************************** RANDVARY_PKLEN ******************************/
+
+int randvary_pklen(int peaklen,dataptr dz)
+
+{
+	int varyrange, variance;
+	int chans = dz->infile->channels;
+	varyrange = (int)round((double)(peaklen/chans) * dz->param[ESPK_RAND]); //
+	variance = (int)floor(drand48() * varyrange);		//
+	if(variance == 0)									//	|----------peaklen-------------|
+		return 0;										//						|--vrange--|
+	peaklen -= variance * chans;						//						    |-vnce-|
+	return peaklen;										//  |-------nupeaklen-------|
+}
+
+/******************************** DBTOLEVEL ***********************/
+
+double dbtolevel(double val)
+{
+	int isneg = 0;
+	if(flteq(val,0.0))
+		return(1.0);
+	if(val < 0.0) {
+		val = -val;
+		isneg = 1;
+	}
+	val /= 20.0;
+	val = pow(10.0,val);
+	if(isneg)
+		val = 1.0/val;
+	return(val);
+}	
+
+/*************************** GETMAXWHICH **********************************/
+ 
+int getmaxwhich(dataptr dz)
+{
+	int n;
+	int maxwhich = -1;
+	if(dz->brksize[ESPK_WHICH] == 0)
+		return dz->iparam[ESPK_WHICH];
+	else {
+		for(n = 0; n < dz->brksize[ESPK_WHICH]; n++)
+			maxwhich = max(maxwhich,(int)round(dz->brk[ESPK_WHICH][n]));
+	}
+	return maxwhich;
+}
+
+/*************************** OPEN_NEXT_FILE **********************************/
+ 
+int open_next_file(char *outfilename,int n,dataptr dz)
+{
+	int exit_status;
+	char prefix_units[]     = "_00";
+	char prefix_tens[]      = "_0";
+	char prefix_hundreds[]  = "_";
+	if(n > 0) {
+		if((exit_status = headwrite(dz->ofd,dz))<0) {
+			free(outfilename);
+			return(exit_status);
+		}
+	}
+	if(sndcloseEx(dz->ofd) < 0) {
+		fprintf(stdout,"WARNING: Can't close output soundfile %s\n",outfilename);
+		fflush(stdout);
+	}
+	dz->ofd = -1;
+	strcpy(outfilename,dz->wordstor[0]);
+	if(!sloom) {
+		if(n<10)
+			insert_new_chars_at_filename_end(outfilename,prefix_units);
+		else if(n<100)
+			insert_new_chars_at_filename_end(outfilename,prefix_tens);
+		else if(n<1000)
+			insert_new_chars_at_filename_end(outfilename,prefix_hundreds);
+		else {
+			sprintf(errstr,"Too many duplicates.\n");
+			return(PROGRAM_ERROR);
+		}
+		insert_new_number_at_filename_end(outfilename,n,0);
+	} else {
+		insert_new_number_at_filename_end(outfilename,n,1);
+	}
+	if((exit_status = create_sized_outfile(outfilename,dz))<0) {
+		sprintf(errstr, "Cannot open outfile Soundfile %s\n",outfilename);
+		return(SYSTEM_ERROR);
+	}
+	return FINISHED;
+}
+
+/********************************* RANDPERM *************************************/
+
+void randperm(int z,int setlen,dataptr dz)
+{
+	int n, t;
+	for(n=0;n<setlen;n++) {
+		t = (int)floor(drand48() * (n+1));
+		if(t>=n)
+			hprefix(z,n,setlen,dz);
+		else
+			hinsert(z,n,t,setlen,dz);
+	}
+}
+
+/***************************** HINSERT **********************************
+ *
+ * Insert the value m AFTER the T-th element in iparray[].
+ */
+
+void hinsert(int z,int m,int t,int setlen,dataptr dz)
+{   
+	hshuflup(z,t+1,setlen,dz);
+	dz->iparray[z][t+1] = m;
+}
+
+/***************************** HPREFIX ************************************
+ *
+ * Insert the value m at start of the permutation iparray[].
+ */
+
+void hprefix(int z,int m,int setlen,dataptr dz)
+{
+	hshuflup(z,0,setlen,dz);
+	dz->iparray[z][0] = m;
+}
+
+/****************************** HSHUFLUP ***********************************
+ *
+ * move set members in iparray[] upwards, starting from element k.
+ */
+
+void hshuflup(int z,int k,int setlen,dataptr dz)
+{   
+	int n, *i;
+	int y = setlen - 1;
+	i = (dz->iparray[z]+y);
+	for(n = y;n > k;n--) {
+		*i = *(i-1);
+		i--;
+	}
+}
+
+/******************************** GETCUTDATA ***********************/
+
+int getcutdata(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	aplptr ap = dz->application;
+	int troffcnt, linecnt, chans = dz->infile->channels, srate = dz->infile->srate;
+	char temp[2000], *q, *filename = (*cmdline)[0];
+	int *trof;
+	double *p, dummy;
+	ap->data_in_file_only = TRUE;
+	ap->special_range 	  = TRUE;
+	ap->min_special 	  = 0;
+	ap->max_special 	  = dz->duration;
+
+	if((dz->fp = fopen(filename,"r"))==NULL) {
+		sprintf(errstr,"Cannot open pattern datafile %s\n",filename);
+		return(DATA_ERROR);
+	}
+	p = &dummy;
+	linecnt = 0;
+	troffcnt = 0;
+	while(fgets(temp,200,dz->fp)!=NULL) {
+		q = temp;
+		if(is_an_empty_line_or_a_comment(temp)) {
+			linecnt++;
+			continue;
+		}
+		while(get_float_from_within_string(&q,p)) {
+			if(*p < ap->min_special || *p > ap->max_special) {
+				sprintf(errstr,"Cut position (%lf) out of range (%lf to %lf): file %s : line %d\n",
+					*p,ap->min_special,ap->max_special,filename,linecnt+1);
+				return(DATA_ERROR);
+			}
+			troffcnt++;
+		}
+		linecnt++;
+	}
+	if(troffcnt == 0) {
+		if(fclose(dz->fp)<0) {
+			fprintf(stdout,"WARNING: Failed to close input textfile %s.\n",filename);
+			fflush(stdout);
+		}
+		sprintf(errstr,"No data found in file %s\n",filename);
+		return(DATA_ERROR);
+	}
+	if((dz->lparray=(int **)malloc(sizeof(int *)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to store trofs (1).\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lparray[0] = (int *)malloc((troffcnt + 1) * sizeof(int))) == NULL) {		//	Storage for syllable edit-point data
+		sprintf(errstr,"INSUFFICIENT MEMORY to store trofs (2).\n");
+		return(MEMORY_ERROR);
+	}
+	if(fseek(dz->fp,0,0)< 0) {
+		sprintf(errstr,"Failed to return to start of file %s.\n",filename);
+		return SYSTEM_ERROR;
+	}
+	troffcnt = 0;
+	trof = dz->lparray[0];
+	while(fgets(temp,200,dz->fp)!=NULL) {
+		q = temp;
+		if(is_an_empty_line_or_a_comment(temp))
+			continue;
+		while(get_float_from_within_string(&q,p))
+			trof[troffcnt++] = (int)(*p * (double)srate) * chans;
+	}
+	if(fclose(dz->fp)<0) {
+		fprintf(stdout,"WARNING: Failed to close input textfile %s.\n",filename);
+		fflush(stdout);
+	}
+	if(trof[troffcnt - 1] >= dz->insams[0]-chans)	//	Ignore any splice at End-of-file
+		troffcnt--;									//	by moving it to the troffcnt spot
+	else
+		trof[troffcnt] = dz->insams[0];
+	dz->trofcnt = troffcnt;
+	(*cmdline)++;		
+	(*cmdlinecnt)--;
+	return FINISHED;
+}
+

+ 3463 - 0
dev/standnew/extspeak.c

@@ -0,0 +1,3463 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <tkglobals.h>
+#include <pnames.h>
+#include <filetype.h>
+#include <processno.h>
+#include <modeno.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <math.h>
+#include <mixxcon.h>
+#include <osbind.h>
+#include <standalone.h>
+#include <ctype.h>
+#include <sfsys.h>
+#include <string.h>
+#include <envlcon.h>
+#include <srates.h>
+#ifdef unix
+#include <aaio.h>
+#endif
+
+#ifdef unix
+#define round(x) lround((x))
+#endif
+
+#define envcnt	wlength
+#define trofcnt rampbrksize
+#define targetcnt ringsize
+#define NEGATION 45
+
+#define EXTSPEAK_PKSRCHWIDTH 3
+
+#define XSPK_MAXLEVEL	0.9
+char errstr[2400];
+
+#define	PATN_ARRAY	0
+#define	PERM_ARRAY	1
+#define	TRGT_ARRAY	2
+
+int anal_infiles = 1;
+int	sloom = 0;
+int sloombatch = 0;
+
+const char* cdp_version = "6.1.0";
+
+//CDP LIB REPLACEMENTS
+static int check_extspeak_param_validity_and_consistency(int XSPK_RRND,int XSPK_ORISZ,dataptr dz);
+static int setup_extspeak_application(dataptr dz);
+static int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+static int parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int setup_extspeak_param_ranges_and_defaults(dataptr dz);
+static int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int establish_application(dataptr dz);
+static int initialise_vflags(dataptr dz);
+static int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int mark_parameter_types(dataptr dz,aplptr ap);
+static int assign_file_data_storage(int infilecnt,dataptr dz);
+static int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+static int get_the_mode_from_cmdline(char *str,dataptr dz);
+static int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt);
+static int precalculate_peaks_array_and_splice(dataptr dz);
+static int extspeak(int XSPK_RRND,int XSPK_ORISZ,dataptr dz);
+static int windows_in_sndfile(dataptr dz);
+static int getenv_of_buffer(int samps_to_process,float **env,dataptr dz);
+static double getmaxsamp(int startsamp, int sampcnt,float *buffer);
+static int istrof(float *env,float *envend,float *q,int width);
+static void randperm(int z,int setlen,dataptr dz);
+static void hinsert(int z,int m,int t,int setlen,dataptr dz);
+static void hprefix(int z,int m,int setlen,dataptr dz);
+static void hshuflup(int z,int k,int setlen,dataptr dz);
+static int handle_the_extra_infiles(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int insert_new_syllable(int peaklen,int patno,int splicelen,double gain,double origlevel,double normaliser,
+							   int *obufpos,float *obuf,float *ovflwbuf,dataptr dz);
+static int store_patterndatafile_name(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int handle_pattern_data(int patternsize,dataptr dz);
+static int generate_xspk_pattern(int XSPK_RRND, int patternsize,dataptr dz);
+static int create_sndbufs_for_extspeak(dataptr dz);
+static int get_int_from_within_string(char **str,int *val, int minus_one_ok);
+static int open_checktype_getsize_and_compare_header(char *filename,int fileno,fileptr *fp2,dataptr dz);
+static int find_orig_syllab_maxima(int splicelen,dataptr dz);
+static int find_normaliser(double *normaliser,int samps_per_sec,int splicelen,dataptr dz);
+static double get_syllable_time(int thistrofat,int lasttrofat,int peaklen,int n,int samps_per_sec,dataptr dz);
+static double dbtolevel(double val);
+static int getcutdata(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int get_cutpat_data(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int expand_pattern_data(int patternsize,dataptr dz);
+static int get_cuttapa_data(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int get_cuttarg_data(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int exttargetspeak(int XSPK_RRND,int XSPK_ORISZ,dataptr dz);
+static int find_normaliser_target(double *normaliser,int samps_per_sec,int splicelen,dataptr dz);
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status;
+	dataptr dz = NULL;
+	char **cmdline;
+	int  cmdlinecnt, XSPK_RRND, XSPK_ORISZ;
+	int n;
+	aplptr ap;
+	int is_launched = FALSE;
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+						/* CHECK FOR SOUNDLOOM */
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {					// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	dz->trofcnt = 0;
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc == 2) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+	}
+	if(!sloom) {
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		dz->maxmode = 18;
+		if((exit_status = get_the_mode_from_cmdline(cmdline[0],dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);
+		}
+		cmdline++;
+		cmdlinecnt--;
+		// setup_particular_application =
+		if((exit_status = setup_extspeak_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+
+	// parse_infile_and_hone_type() = 
+	if((exit_status = parse_infile_and_check_type(cmdline,dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// setup_param_ranges_and_defaults() =
+	if((exit_status = setup_extspeak_param_ranges_and_defaults(dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// open_first_infile		CDP LIB
+	if((exit_status = open_first_infile(cmdline[0],dz))<0) {	
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);	
+		return(FAILED);
+	}
+	cmdlinecnt--;
+	cmdline++;
+
+	if((dz->iparray = (int **)malloc(3 * sizeof(int *))) == NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to store trof-locations and other data.\n");
+		return(MEMORY_ERROR);
+	}
+
+//	handle_extra_infiles
+	if((exit_status = handle_the_extra_infiles(&cmdlinecnt,&cmdline,dz))<0) {
+		fprintf(stdout,"\n **** May be TOO MANY PARAMS on commandline ****\n\n");
+		fflush(stdout);
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if(dz->infilecnt < 2) {
+		sprintf(errstr,"ERROR: At least TWO input files required for this process.\n");
+		exit_status = DATA_ERROR;
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+	// handle_outfile() = 
+	if((exit_status = handle_the_outfile(&cmdlinecnt,&cmdline,dz))<0) {
+		fprintf(stdout,"\n **** If the outfile does NOT already exist ****\n **** May be TOO FEW PARAMS on commandline ****\n\n");
+		fflush(stdout);
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+//	handle_formants()			redundant
+//	handle_formant_quiksearch()	redundant
+	switch(dz->mode) {
+	case(2):	//	fall thro
+	case(5):
+		if((exit_status = store_patterndatafile_name(&cmdlinecnt,&cmdline,dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		break;
+	case(6):	//	fall thro
+	case(7):	//	fall thro
+	case(9):	//	fall thro
+	case(10):
+		if((exit_status = getcutdata(&cmdlinecnt,&cmdline,dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		break;
+	case(8):	//	fall thro
+	case(11):
+		if((exit_status = get_cutpat_data(&cmdlinecnt,&cmdline,dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		break;
+	case(12):	//	fall thro
+	case(13):	//	fall thro
+	case(15):	//	fall thro
+	case(16):
+		if((exit_status = get_cuttarg_data(&cmdlinecnt,&cmdline,dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		break;
+	case(14):	//	fall thro
+	case(17):
+		if((exit_status = get_cuttapa_data(&cmdlinecnt,&cmdline,dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		break;
+	}
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if(dz->mode == 3 || dz->mode == 9)
+		XSPK_RRND =	3;
+	else if(dz->mode == 12)
+		XSPK_RRND =	3;
+	else if(dz->mode == 15)
+		XSPK_RRND =	2;
+	else
+		XSPK_RRND = XSPK_RAND;
+	if(dz->mode >=12 && dz->mode < 15)
+		XSPK_ORISZ = 2;
+	else
+		XSPK_ORISZ = XSPK_ORIGSZ;
+
+	is_launched = TRUE;
+	dz->bufcnt = dz->infilecnt + 2;
+	if((dz->sampbuf = (float **)malloc(sizeof(float *) * (dz->bufcnt+1)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->sbufptr = (float **)malloc(sizeof(float *) * dz->bufcnt))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffer pointers.\n");
+		return(MEMORY_ERROR);
+	}
+	for(n = 0;n <dz->bufcnt; n++)
+		dz->sampbuf[n] = dz->sbufptr[n] = (float *)0;
+	dz->sampbuf[n] = (float *)0;
+
+	//	1 double array for splice, 1 for maxlevels of orig syllables & 1 for maxlevels of new syllables
+	if((dz->parray = (double **)malloc(3 * sizeof(double *))) == NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to create splice buffer (1).\n");
+		return(MEMORY_ERROR);
+	}
+	//	2 float arrays for trofstore
+	if((dz->fptr=(float **)malloc(2 * sizeof(float *)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to store envelope (1).\n");
+		return(MEMORY_ERROR);
+	}
+//	create_sndbufs
+	if((exit_status = create_sndbufs_for_extspeak(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = precalculate_peaks_array_and_splice(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if(dz->vflag[XSPK_ENV] || (dz->mode >= 3 && dz->mode < 6) || (dz->mode >= 9 && dz->mode < 12) || dz->mode >= 15) {
+		if((dz->parray[2] = (double *)malloc(dz->infilecnt * sizeof(double))) == NULL) {//	Storage max levels of new input syllables
+			sprintf(errstr,"INSUFFICIENT MEMORY to maximum levels of input syllables.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	//	check_param_validity_and_consistency....
+	if((exit_status = check_extspeak_param_validity_and_consistency(XSPK_RRND,XSPK_ORISZ,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//param_preprocess()						redundant
+	//spec_process_file =
+	if(dz->mode >= 12)  {
+		if((exit_status = exttargetspeak(XSPK_RRND,XSPK_ORISZ,dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		if((exit_status = extspeak(XSPK_RRND,XSPK_ORISZ,dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	}
+	if((exit_status = complete_output(dz))<0) {										// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);		// CDP LIB
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc, brkcnt;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	brkcnt = tipc;
+	if(brkcnt>0) {
+		if((exit_status = setup_and_init_input_brktable_constants(dz,brkcnt))<0)			  
+			return(exit_status);
+	}
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+		return(exit_status);
+	
+	// establish_infile_constants() replaced by
+	dz->infilecnt = 1;
+	//establish_bufptrs_and_extra_buffers():
+	return(FINISHED);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}						 		/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_OUTFILE *********************/
+
+int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status;
+	char *filename = (*cmdline)[0];
+
+	if(filename[0]=='-' && filename[1]=='f') {
+		dz->floatsam_output = 1;
+		dz->true_outfile_stype = SAMP_FLOAT;
+		filename+= 2;
+	}
+	if(!sloom) {
+		if(file_has_invalid_startchar(filename) || value_is_numeric(filename)) {
+			sprintf(errstr,"Outfile name %s has invalid start character(s) or looks too much like a number.\n",filename);
+			return(DATA_ERROR);
+		}
+	}
+	strcpy(dz->outfilename,filename);
+	if((exit_status = create_sized_outfile(filename,dz))<0)
+		return(exit_status);
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/************************* SETUP_EXTSPEAK_APPLICATION *******************/
+
+int setup_extspeak_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	switch(dz->mode) {
+	case(9):	//	fall thro
+	case(10):	//	fall thro
+	case(6):	//	fall thro
+	case(7): exit_status = set_param_data(ap,XSPK_CUTS	  ,6,5,"0iiIDi");	break;
+	case(11):	//	fall thro
+	case(8): exit_status = set_param_data(ap,XSPK_CUTPAT  ,6,4,"0iiID0");	break;
+	case(3):	//	fall thro
+	case(4):	//	fall thro
+	case(0):	//	fall thro
+	case(1): exit_status = set_param_data(ap,0			  ,6,6,"iiiIDi");	break;
+	case(5):	//	fall thro
+	case(2): exit_status = set_param_data(ap,XSPK_PATTERN ,6,5,"iiiID0");	break;
+	case(12):	//	fall thro
+	case(13):	//	fall thro
+	case(15):	//	fall thro
+	case(16): exit_status = set_param_data(ap,XSPK_CUTARG ,6,3,"0i00Di");	break;
+	case(14):	//	fall thro
+	case(17): exit_status = set_param_data(ap,XSPK_CUPATA ,6,2,"0i00D0");	break;
+	}
+	if(exit_status < 0)
+		return(FAILED);
+	switch(dz->mode) {
+	case(6):	//	fall thro
+	case(0):
+		exit_status = set_vflgs(ap,"",0,"","tekior",6,0,"000000");
+		break;
+	case(7):	//	fall thro
+	case(8):	//	fall thro
+	case(1):	//	fall thro
+	case(2):
+		exit_status = set_vflgs(ap,"",0,"","tekio" ,5,0,"00000");
+		break;
+	case(9):	//	fall thro
+	case(3):
+		exit_status = set_vflgs(ap,"",0,"","tekr"   ,4,0,"0000");
+		break;
+	case(10):	//	fall thro
+	case(11):	//	fall thro
+	case(4):	//	fall thro
+	case(5):
+		exit_status = set_vflgs(ap,"",0,"","tek"    ,3,0,"000");
+		break;
+	case(12):
+		exit_status = set_vflgs(ap,"",0,"","teor"   ,4,0,"0000");
+		break;
+	case(15):	//	fall thro
+		exit_status = set_vflgs(ap,"",0,"","ter"    ,3,0,"000");
+		break;
+	case(13):	//	fall thro
+	case(14):
+		exit_status = set_vflgs(ap,"",0,"","teo"    ,3,0,"000");
+		break;
+	case(16):	//	fall thro 
+	case(17):
+		exit_status = set_vflgs(ap,"",0,"","te"     ,2,0,"00");
+		break;
+	}
+	if(exit_status < 0)
+		return(FAILED);
+	// set_legal_infile_structure -->
+	dz->has_otherfile = FALSE;
+	// assign_process_logic -->
+	dz->input_data_type = MANY_SNDFILES;
+	dz->process_type	= UNEQUAL_SNDFILE;	
+	dz->outfiletype  	= SNDFILE_OUT;
+	return application_init(dz);	//GLOBAL
+}
+
+/************************* PARSE_INFILE_AND_CHECK_TYPE *******************/
+
+int parse_infile_and_check_type(char **cmdline,dataptr dz)
+{
+	int exit_status;
+	infileptr infile_info;
+	if(!sloom) {
+		if((infile_info = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for infile structure to test file data.");
+			return(MEMORY_ERROR);
+		} else if((exit_status = cdparse(cmdline[0],infile_info))<0) {
+			sprintf(errstr,"Failed to parse input file %s\n",cmdline[0]);
+			return(PROGRAM_ERROR);
+		} else if(infile_info->filetype != SNDFILE)  {
+			sprintf(errstr,"File %s is not of correct type\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if((exit_status = copy_parse_info_to_main_structure(infile_info,dz))<0) {
+			sprintf(errstr,"Failed to copy file parsing information\n");
+			return(PROGRAM_ERROR);
+		}
+		free(infile_info);
+	}
+	return(FINISHED);
+}
+
+/************************* SETUP_EXTSPEAK_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_extspeak_param_ranges_and_defaults(dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	// NB total_input_param_cnt is > 0 !!!
+	if((exit_status = setup_input_param_range_stores(ap->total_input_param_cnt,ap))<0)
+		return(FAILED);
+	if(dz->mode < 6) {
+		ap->lo[XSPK_WINSZ]	= 5;			//	param 0
+		ap->hi[XSPK_WINSZ]	= 1000;
+		ap->default_val[XSPK_WINSZ]	= 50;
+	}
+	ap->lo[XSPK_SPLEN]	= 2;				//	param 1
+	ap->hi[XSPK_SPLEN]	= 100;
+	ap->default_val[XSPK_SPLEN]	= 5;
+	if(dz->mode < 12) {
+		ap->lo[XSPK_OFFST]	= 0;			//	param 2
+		ap->hi[XSPK_OFFST]	= 100;
+		ap->default_val[XSPK_OFFST]	= 0;
+		ap->lo[XSPK_N]	= 0;				//	param 3
+		ap->hi[XSPK_N]	= MAX_PATN;
+		ap->default_val[XSPK_N]	= 1;
+	}
+	ap->lo[XSPK_GAIN]	= -96;				//	param 4
+	ap->hi[XSPK_GAIN]	= 0;
+	ap->default_val[XSPK_GAIN]	= 0;
+	if(dz->mode != 2 && dz->mode != 5 && dz->mode != 8 && dz->mode != 11 && dz->mode != 14 && dz->mode != 17) {
+		ap->lo[XSPK_SEED]	= 0;			//	param 5
+		ap->hi[XSPK_SEED]	= 64;
+		ap->default_val[XSPK_SEED]	= 0;
+	}
+	dz->maxmode = 18;
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_extspeak_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int read_special_data(char *str,dataptr dz)	
+{
+	return(FINISHED);
+}
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+	usage2("extspeak");
+	return(USAGE_ONLY);
+}
+
+/**************************** CHECK_EXTSPEAK_PARAM_VALIDITY_AND_CONSISTENCY *****************************/
+
+int check_extspeak_param_validity_and_consistency(int XSPK_RRND,int XSPK_ORISZ,dataptr dz)
+{
+//	NEEDS TO BE DONE WHEN TROFCNT IS KNOWN AND SPLICELEN IN GPSAMPS KNOWN !!!!
+	int lastsamp = 0, n, k, sampsize;
+	int chans = dz->infile->channels, srate = dz->infile->srate;
+	int offset = dz->iparam[XSPK_OFFST];
+	int *trof = dz->lparray[0];
+	int splicelen, minseg, bad;
+	splicelen = dz->iparam[XSPK_SPLEN] * chans;
+	minseg = (splicelen * 2) + chans;
+	if(dz->trofcnt == 0) {
+		sprintf(errstr,"Trof array not established before testing parameters.\n");
+		return PROGRAM_ERROR;
+	}
+	if(offset >= dz->trofcnt - 2) {
+		sprintf(errstr,"ERROR: Offset (%d) too large for number of peaks found (%d).\n",offset,dz->trofcnt);
+		return DATA_ERROR;
+	}
+	bad = 0;
+	for(n = 0; n <= dz->trofcnt; n++) {
+		sampsize = trof[n] - lastsamp;
+		if(sampsize < minseg) {
+			bad = 1;
+			if(n == 0)
+				fprintf(stdout,"syllab %d too short (%d mS) for two Splices (%d mS)\nbetween times 0 and %lf\n",
+				n+1,(int)round(((double)(sampsize/chans)/(double)srate) * SECS_TO_MS),(int)round(dz->param[XSPK_SPLEN] * 2),(double)trof[n]/(double)(srate * chans));
+			else {
+				sampsize -= splicelen;
+				fprintf(stdout,"syllab %d too short (%d mS) for two Splices (%d mS)\nbetween times %lf and %lf\n",
+				n+1,(int)round(((double)(sampsize/chans)/(double)srate) * SECS_TO_MS),(int)round(dz->param[XSPK_SPLEN] * 2),(double)(trof[n-1]/chans)/(double)srate,(double)(trof[n]/chans)/(double)srate);
+			}
+		}
+		lastsamp = trof[n] - splicelen;
+	}
+	if(bad)
+		return DATA_ERROR;
+	if(dz->trofcnt <= 1) {
+		sprintf(errstr,"Too few trofs found (%d) for this process and offset (%d)\n",dz->trofcnt,dz->iparam[2]);
+		return DATA_ERROR;
+	}
+	if(dz->mode < 3 || (dz->mode >= 6  && dz->mode < 9)) {
+		if(dz->vflag[XSPK_INJECT]) {
+			if(dz->vflag[XSPK_ORISZ] || dz->vflag[XSPK_ENV] || dz->vflag[XSPK_TRANSPOSE] ) {
+				if(dz->vflag[XSPK_ORISZ]) {
+					if(dz->vflag[XSPK_ENV] && dz->vflag[XSPK_TRANSPOSE])
+						fprintf(stdout,"WARNING: \"Original Size\" flag redundant : \"Envelope\" & \"Transpose\" Flags not operational when INSERTING the original syllables.\n"); 
+					else if(dz->vflag[XSPK_ENV])
+						fprintf(stdout,"WARNING: \"Original Size\" flag redundant : \"Envelope\" Flag not operational when INSERTING the original syllables.\n"); 
+					else if(dz->vflag[XSPK_TRANSPOSE])
+						fprintf(stdout,"WARNING: \"Original Size\" flag redundant : \"Transpose\" Flag not operational when INSERTING the original syllables.\n");
+					else 
+						fprintf(stdout,"WARNING: \"Original Size\" flag redundant when INSERTING the original syllables.\n");
+				} else {
+					if(dz->vflag[XSPK_ENV] && dz->vflag[XSPK_TRANSPOSE])
+						fprintf(stdout,"WARNING: \"Envelope\" & \"Transpose\" Flags not operational when INSERTING the original syllables.\n"); 
+					else if(dz->vflag[XSPK_ENV])
+						fprintf(stdout,"WARNING: \"Envelope\" Flag not operational when INSERTING the original syllables.\n"); 
+					else
+						fprintf(stdout,"WARNING: \"Transpose\" Flag not operational when INSERTING the original syllables.\n"); 
+				}
+				fflush(stdout);
+			}
+			dz->vflag[XSPK_TRANSPOSE] = 0;
+			dz->vflag[XSPK_ENV]       = 0;
+			dz->vflag[XSPK_ORISZ]    = 1;
+		}	
+	}
+	if(dz->mode < 3 || (dz->mode >= 6  && dz->mode < 9) || (dz->mode >= 12  && dz->mode < 15)) {
+		if(dz->vflag[XSPK_ORISZ] && dz->vflag[XSPK_TRANSPOSE]) {
+			fprintf(stdout,"WARNING: \"Keep original size\" Flag makes \"Transposition\" Flag redundant.\n"); 
+			fflush(stdout);
+		}
+	}
+	if((dz->mode==0 || dz->mode==3 || dz->mode==6 || dz->mode==9) && dz->vflag[XSPK_RRND] && dz->infilecnt < 3) {
+		switch(dz->mode) {
+		case(10):	//	fall thro
+		case(7):	//	fall thro
+		case(4):	//	fall thro
+		case(1):
+			sprintf(errstr,"INFO: No randomisation possible with less than 2 (extra) input file.\n");
+			return DATA_ERROR;
+		case(9):	//	fall thro
+		case(6):	//	fall thro
+		case(3):	//	fall thro
+		case(0):
+			if(dz->infilecnt < 3) {
+				sprintf(errstr,"WARNING: No randomisation possible with only less than 2 (extra) input file.\n");
+				return DATA_ERROR;
+			}
+			break;
+		}
+	}
+	if(dz->brksize[XSPK_GAIN]) {
+		for(n = 0,k = 1; n < dz->brksize[XSPK_GAIN];n++,k+=2)
+			dz->brk[XSPK_GAIN][k] = dbtolevel(dz->brk[XSPK_GAIN][k]);
+	} else
+		dz->param[XSPK_GAIN] = dbtolevel(dz->param[XSPK_GAIN]);
+
+	return FINISHED;
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if(!strcmp(prog_identifier_from_cmdline,"extspeak"))				dz->process = EXTSPEAK;
+	else {
+		sprintf(errstr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/******************************** SETUP_AND_INIT_INPUT_BRKTABLE_CONSTANTS ********************************/
+
+int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt)
+{	
+	int n;
+	if((dz->brk      = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<brkcnt;n++) {
+		dz->brk[n]     = NULL;
+		dz->brkptr[n]  = NULL;
+		dz->brkinit[n] = 0;
+		dz->brksize[n] = 0;
+	}
+	return(FINISHED);
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+	if(!strcmp(str,"extspeak")) {
+		fprintf(stderr,
+	    "\nUSAGE:  extspeak extspeak 1-18 infile0 infile1 [infile2..] outfile params\n"
+		"PARAMS for each mode\n"
+	    "1)          wsize splice offset N gain seed [-t] [-e] [-k] [-i] [-o] [-r]\n"
+	    "2)          wsize splice offset N gain seed [-t] [-e] [-k] [-i] [-o] \n"
+	    "3)  pattern wsize splice offset N gain      [-t] [-e] [-k] [-i] [-o] \n"
+	    "4)          wsize splice offset N gain seed [-t] [-e] [-k]           [-r]\n"
+	    "5)          wsize splice offset N gain seed [-t] [-e] [-k]\n"
+	    "6)  pattern wsize splice offset N gain      [-t] [-e] [-k]\n"
+	    "7)  cuts          splice offset N gain seed [-t] [-e] [-k] [-i] [-o] [-r]\n"
+	    "8)  cuts          splice offset N gain seed [-t] [-e] [-k] [-i] [-o] \n"
+	    "9)  cutspat       splice offset N gain      [-t] [-e] [-k] [-i] [-o] \n"
+	    "10) cuts          splice offset N gain seed [-t] [-e] [-k]           [-r]\n"
+	    "11) cuts          splice offset N gain seed [-t] [-e] [-k]\n"
+	    "12) cutspat       splice offset N gain      [-t] [-e] [-k]\n"
+	    "13) cuts+targets  splice          gain seed [-t] [-e]           [-o] [-r]\n"
+	    "14) cuts+targets  splice          gain seed [-t] [-e]           [-o]\n"
+	    "15) cuts+tgts+pat splice          gain      [-t] [-e]           [-o]\n"
+	    "16) cuts+targets  splice          gain seed [-t] [-e]                [-r]\n"
+	    "17) cuts+targets  splice          gain seed [-t] [-e]\n"
+	    "18) cuts+tgts+pat splice          gain      [-t] [-e]\n"
+		"MODES 1-3,6-9   REPLACE  - or INJECT BETWEEN - syllabs of infile0 ...\n"
+		"MODES 12-15     REPLACE SPECIFIED syllabs of infile0 ...\n"
+		"MODES 4-6,10-12 MIX INTO selected syllabs of infile0 ...\n"
+		"MODES 16-18     MIX INTO SPECIFIED syllabs of infile0 ...\n"
+		"      ... NEW SYLLABLES, each taken from one of the other input files.\n"
+		"MODES 1/4/7/10/13/16  Select syllabs from each file in turn OR (-r) at random.\n"
+		"MODES 2/5/8/11/14/17  Rand-permute order of syllabs. Once ALL used, permute again.\n"
+		"MODES 3/6/9/12/15/18  Select infile following specified ordering-pattern.\n"
+		"\n"
+		"PATTERN Pattern in a Textfile : the specific sequence of syllables to be inserted.\n"
+		"        e.g. \"1 5 2\" means, use infile1 infile5 infile2 in that order (then repeat).\n"
+		"CUTS    Modes 7,8,10,11 List of Times, in a Textfile : location of syllable-starts\n"
+		"        in infile0 (zero time, and time at very end of file, not required).\n"
+		"CUTSPAT Modes 9 and 12 List of Times, in a Textfile : location of syllable-starts\n"
+		"        FOLLOWED BY single line with \"#\", followed by PATTERN Data (see above).\n"
+		"CUTS+TARGETS    List of Times, in a Textfile : location of syllable-starts\n"
+		"        FOLLOWED BY single line with \"#\", followed by SYLLABLES TO TARGET Data.\n"
+		"CUTS+TGTS+PAT   List of Times, in a Textfile : location of syllable-starts\n"
+		"        FOLLOWED BY single line with \"#\", followed by SYLLABLES TO TARGET Data\n"
+		"        FOLLOWED BY single line with \"#\", followed by PATTERN Data (see above).\n"
+		"If there is NO CUTS/CUTSPAT, infile0 divided into \"syllables\" by automatic process.\n"
+		"\n"
+		"FOR MORE INFORMATION ----- hit any key on keyboard\n");
+	} else {
+		fprintf(stdout,"Unknown option '%s'\n",str);
+		return USAGE_ONLY;
+	}
+	_getch();
+	while(!kbhit())
+		;
+	if(kbhit()) {
+		fprintf(stderr,
+		"\n"
+		"In \"Syllables to Target\" data, the COUNT OF SYLLABLES in infile0\n"
+		"is ONE MORE than the number of edit-points you have listed\n"
+		"(assuming there are no edits at zero or at the file end).\n"
+		"\n"
+		"       Each edit point marks the END of a syllable\n"
+		"       and the final syllable is AFTER the last edit.\n"
+		"\n"
+		"To ensure to target the VERY LAST syllable, the value \"-1\" can be used.\n"
+		"\n"
+		"\n"
+		"\n"
+		"\n" 
+		"PARAMETERS\n"
+		"\n"
+		"\n"
+		"WSIZE   Size of envelope-search window to AUTOfind syllabs in file0, in mS (try 50).\n"
+		"\n"
+		"SPLICE  Splice length for extracting and joining syllables (try 15).\n"
+		"\n"
+		"OFFSET  Number of syllables at start of infile0 to output unchanged.\n"
+		"\n" 
+		"N       N means write 1 original (file0) syllable for every N new syllabs inserted\n"
+		"\n" 
+		"        ...... EXCEPT IF flag \"-k\" is set, when ......\n"
+		"\n" 
+		"        N means KEEP N original (file0) syllables for every 1 new syllab inserted.\n"
+		"\n"
+		"GAIN    Gain of inserted syllables (Range -96dB to 0dB).\n"
+		"\n" 
+		"SEED    Initialisation for random reorderings, or permutations.\n"
+		"        If Seed > 0, using SAME seed AGAIN gives IDENTICAL random output.\n"
+		"\n" 
+		"Parameters N and GAIN may vary over time.\n"
+		"\n" 
+		"\n"
+		"\n"
+		"\n" 
+		"\n"
+		"\n"
+		"\n"
+		"FOR MORE INFORMATION ----- hit any key on keyboard\n"
+		"\n" 
+		"\n");
+	}
+	_getch();
+	while(!kbhit())
+		;
+	if(kbhit()) {
+		fprintf(stderr,
+		"\n"
+		"\n"
+		"EXAMPLE USAGE:\n"
+		"\n" 
+		"          For N=2 (i.e. REPLACE or KEEP 2 in 3 syllables)\n"
+		"          AND 9 Original Syllables =  ---------\n"
+		"\n" 
+		"No flags:      Keep 1, Replace (N=)2  -XX-XX-XX\n"
+		"\n" 
+		"-k flags:      Keep (N=)2, Replace 1  --X--X--X\n"
+		"\n" 
+		"-i flag:       Keep 1, Inject (N=)2   -XX-XX-XX-XX-XX-XX-XX-XX-XX\n"
+		"\n" 
+		"-i & -k flags: Keep (N=)2, Inject 1   --X--X--X--X-\n"
+		"\n" 
+		"\n" 
+		"FLAGS.\n"
+		"\n" 
+		"-r      RAND: Select next inserted syllable ENTIRELY at random.\n"
+		"\n" 
+		"-k      KEEP:  N becomes count of syllabs to KEEP rather than to REPLACE or INJECT.\n"
+		"\n" 
+		"-i      INJECT new syllable(s) BETWEEN existing infile0 syllables.\n"
+		"        Default : new syllabs OVERWRITE existing syllables, and are resized to fit.\n"
+		"\n" 
+		"FOLLOWING FLAG ONLY RELEVANT where you REPLACE the original syllables.\n"
+		"\n" 
+		"-o      ORIGINAL SIZE: Don't Resize new syllable to size of originals.\n"
+		"        (Output file will therefore not be same length/rhythm as infile0).\n"
+		"\n" 
+		"FOLLOWING FLAGS ONLY RELEVANT where you REPLACE or MIX INTO the original syllables.\n"
+		"\n" 
+		"-t      TRANSPOSE: If Resizing, Transpose/Time-stretch new syllab to adjust length.\n"
+		"        Default: Cut to Size or Pad with Silence.\n"
+		"\n" 
+		"-e      Follow the ENVELOPE of the the original syllables in file0\n"
+		"        by scaling level of inserted syllab to that of replaced/mixed-into syllable.\n"
+		"        This scaling is independent of the \"GAIN\" value (which is ALSO applied).\n" 
+		"\n" 
+		"\n" 
+		"\n" 
+		"\n" 
+			"FOR MORE INFORMATION ----- hit any key on keyboard\n"
+		"\n");
+	}
+	_getch();
+	while(!kbhit())
+		;
+	if(kbhit()) {
+		fprintf(stderr,
+		"CONTOUR TYPES.\n"
+		"\n"
+		"                                        _\n"
+		"                                     / | |    _\n"
+		"      _ ................ Add ..... /   |_|   | |\n"
+		"     | |                               | |   | |\n"
+		"     | |                     _         | |   | |\n"
+		"     | |    _               | |        | |   |_|\n"
+		"     | |_  | |         _    | |        | |_  | |\n"
+		"    _| | |_| |_   +   | |   | |   =   _| | |_| |_\n"	
+		"   | | | | | | |     _| |___| |_     | | | | | | |\n"
+		"\n"
+		"\n"
+		"\n"
+		"\n"
+		"                         Gain+          _\n"
+		"      _ ................ Add ..... ../ |_|\n"
+		"     | |                               | |    _\n"
+		"     | |                   .....       | |   | |\n"
+		"     | |    _                          | |   |_|\n"
+		"     | |_  | |       .....  ._.        | |_  | |\n"
+		"    _| | |_| |_   +   ._.   | |   =   _| | |_| |_\n"	
+		"   | | | | | | |     _| |___| |_     | | | | | | |\n"
+		"\n"
+		"\n"
+		"\n"
+		"\n"
+		"                                        _\n"
+		"                                     / | |\n"
+		"                                    /  | |\n"
+		"                                   /   | |\n"
+		"                                  /    | |\n"
+		"                                 /     | |\n"
+		"      _ .... -e ...... _ ..Add../      |_|    _\n"
+		"     | |  Envelope    |^|              | |   | |\n"
+		"     | |              |^|  .....       | |   | |\n"
+		"     | |    _ ........|^|... _ ...     | |   |_|\n"
+		"     | |_  | |        |^|   | |        | |_  | |\n"
+		"    _| | |_| |_  +    |_|   | |   =   _| | |_| |_\n"	
+		"   | | | | | | |     _| |___| |_     | | | | | | |\n"
+		"\n");
+	}
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	fprintf(stderr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/****************************** GET_MODE *********************************/
+
+int get_the_mode_from_cmdline(char *str,dataptr dz)
+{
+	char temp[200], *p;
+	if(sscanf(str,"%s",temp)!=1) {
+		sprintf(errstr,"Cannot read mode of program.\n");
+		return(USAGE_ONLY);
+	}
+	p = temp + strlen(temp) - 1;
+	while(p >= temp) {
+		if(!isdigit(*p)) {
+			fprintf(stderr,"Invalid mode of program entered.\n");
+			return(USAGE_ONLY);
+		}
+		p--;
+	}
+	if(sscanf(str,"%d",&dz->mode)!=1) {
+		fprintf(stderr,"Cannot read mode of program.\n");
+		return(USAGE_ONLY);
+	}
+	if(dz->mode <= 0 || dz->mode > dz->maxmode) {
+		fprintf(stderr,"Program mode value [%d] is out of range [1 - %d].\n",dz->mode,dz->maxmode);
+		return(USAGE_ONLY);
+	}
+	dz->mode--;		/* CHANGE TO INTERNAL REPRESENTATION OF MODE NO */
+	return(FINISHED);
+}
+
+/****************************** EXTSPEAK *********************************/
+
+int extspeak(int XSPK_RRND,int XSPK_ORISZ,dataptr dz) 
+{
+	int exit_status, chans = dz->infile->channels, srate = dz->infile->srate, orig, done;
+	float *ibuf = dz->sampbuf[0], *obuf = dz->sampbuf[dz->infilecnt], *ovflwbuf = dz->sampbuf[dz->infilecnt + 1];
+	int gpsplicelen = dz->iparam[XSPK_SPLEN];
+	int splicelen = gpsplicelen * chans, upsplice;
+	int obufpos = 0, lasttrofat = 0, thistrofat, peaklen, splicend;
+	int *trof = dz->lparray[0];
+	int mintrof;
+	int n, m, j, k, z;
+	double *splicebuf = dz->parray[0], time = 0, maxgain = 0.0, *origmax = dz->parray[1], *syllmax = dz->parray[2];
+	int samps_per_sec = srate * chans;
+	double val, gain, normaliser = 1.0;
+	int *pattern;
+	double Nmaxd, origlevel = 1.0;
+	int max_inserts_per_orig, patternsize, patterncnt, patno, syllread, q;
+	for(n = 1; n< dz->infilecnt;n++) {
+		if((syllread = fgetfbufEx(dz->sampbuf[n], dz->insams[n],dz->ifd[n],0)) < 0) {
+			sprintf(errstr,"Can't read samples from soundfile %d\n",n);      // RWD was %n
+			return(SYSTEM_ERROR);
+		}
+		if(syllread != dz->insams[n]) {
+			sprintf(errstr,"Fail to read all samples from soundfile %d\n",n);   // RWD ditto
+			return(SYSTEM_ERROR);
+		}
+		if(dz->vflag[XSPK_ENV] || (dz->mode >= 3 && dz->mode < 6) || (dz->mode >= 9 && dz->mode < 12)|| dz->mode >= 15) {
+			maxgain = 0.0;
+			for(q = 0; q < dz->insams[n]; q++)
+				maxgain = max(maxgain,fabs(dz->sampbuf[n][q]));
+			syllmax[n] = maxgain;
+		}
+	}
+	if(dz->mode != 2 && dz->mode != 5 && dz->mode != 8 && dz->mode != 11) {
+		if(dz->iparam[XSPK_SEED] > 0)
+			srand(dz->iparam[XSPK_SEED]);
+		else
+			initrand48();
+	}
+	mintrof = dz->iparam[XSPK_OFFST];
+	if(dz->brksize[XSPK_N])  {
+		if((exit_status = get_maxvalue_in_brktable(&Nmaxd,XSPK_N,dz))<0)
+			return exit_status;
+	} else
+		Nmaxd = dz->param[XSPK_N];
+	if(dz->vflag[XSPK_KEEP])								// One inserted item for every N origs
+		max_inserts_per_orig = 1;							//	Max possible 1 for every 1
+	else 
+		max_inserts_per_orig = (int)ceil(Nmaxd);			//	Max possible = max_inserts_per_orig
+	patternsize = (dz->trofcnt+1) * max_inserts_per_orig;	//	Max possible pattern size
+
+	if((exit_status = generate_xspk_pattern(XSPK_RRND,patternsize,dz))<0)
+		return exit_status;
+	if((dz->mode >= 3 && dz->mode < 6) || dz->mode >= 9) {
+		fprintf(stdout,"INFO: Calculating Normalisation.\n");
+		fflush(stdout);
+		if((exit_status = find_orig_syllab_maxima(splicelen,dz)) < 0)
+			return exit_status;
+		if((exit_status = find_normaliser(&normaliser,samps_per_sec,splicelen,dz)) < 0)
+			return exit_status;
+	}
+	pattern = dz->iparray[PATN_ARRAY];
+	orig = 0;
+	done = 0;
+	lasttrofat = 0;
+	splicend = splicelen - 1;
+	patterncnt = 0;
+	m = mintrof - 1;
+	if(m >= 0) {
+		thistrofat = trof[m];
+		peaklen = thistrofat;			//	We must be at start of file : therefore no obufpos baktrak & no upsplice
+		for(k = 0, j = peaklen - 1; k < thistrofat; k++,j--) {
+			if (j < splicelen) 
+				obuf[obufpos] = (float)(ibuf[k] * splicebuf[splicend--] * normaliser);	//	do downslice
+			else																	
+				obuf[obufpos] = (float)(ibuf[k] * normaliser);							//  else copy input
+			if(++obufpos >= dz->buflen * 2) {
+				if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+					return(exit_status);
+				memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+				memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+				obufpos -= dz->buflen;
+			}
+		}
+		lasttrofat = thistrofat;
+	}
+	m++;
+	for(n = m; n <= dz->trofcnt; n++)  {
+		if(n > 0)
+			lasttrofat = trof[n-1];
+		thistrofat  = trof[n];
+		peaklen = thistrofat - lasttrofat;
+		splicend = splicelen - 1;
+		time = get_syllable_time(thistrofat,lasttrofat,peaklen,n,samps_per_sec,dz);
+		if((exit_status = read_values_from_all_existing_brktables(time,dz))<0)
+			return exit_status;
+		gain = dz->param[XSPK_GAIN];
+		if(lasttrofat > 0) {			//	If we're NOT at file start	
+			obufpos -= splicelen;		//	baktrak to splice to end of last segment written
+			peaklen += splicelen;		//	and length of peak is therefore one splicelen longer
+			upsplice = splicelen;
+		} else
+			upsplice = 0;				//	Prevents initial splice on start of file-segment
+		splicend = splicelen - 1;
+		if(dz->vflag[XSPK_ENV])
+			origlevel = origmax[n];
+		switch(dz->vflag[XSPK_KEEP]) {
+		case(0):						//	N  = the number of syllables to insert
+										//	First Copy ONE original syllable
+			for(k = 0, j = peaklen - 1, m = thistrofat - peaklen; k < peaklen; k++,m++,j--) {
+				if(k < upsplice)
+					val = ibuf[m] * splicebuf[k];							//	do upslice
+				else if (j < splicelen) 
+					val = ibuf[m] * splicebuf[splicend--];					//	do downslice
+				else																	
+					val = ibuf[m];											//  else as is
+				obuf[obufpos] = (float)(obuf[obufpos] + (val * normaliser));//	then normalise and add to buffer
+				if(++obufpos >= dz->buflen * 2) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+					memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+					obufpos -= dz->buflen;
+				}
+			}
+
+			for(z = 0; z < dz->iparam[XSPK_N]; z++) {	//	Then Add N NEW syllables		
+				if((dz->mode >= 3 && dz->mode < 6) || dz->mode >= 9 || !dz->vflag[XSPK_INJECT]) {
+					if(++n > dz->trofcnt) {				//	Advance count of original syllables
+						done = 1;						//	and If out of original syllables, quit
+						break;
+					}
+					lasttrofat = thistrofat;
+					thistrofat  = trof[n];
+					peaklen = thistrofat - lasttrofat;
+					peaklen += splicelen;
+				}
+				obufpos -= splicelen;
+				upsplice = splicelen;
+				patno = pattern[patterncnt++];
+				if((dz->mode < 3 || (dz->mode >= 6 && dz->mode < 9)) && dz->vflag[XSPK_ORISZ])	//	IF not Resizing : write-in ALL of new syllable
+					peaklen = dz->insams[patno];			//	ELSE it's truncated/extended to size of original syllable
+				splicend = peaklen - 1; 
+				if((exit_status = insert_new_syllable(peaklen,patno,splicelen,gain,origlevel,normaliser,&obufpos,obuf,ovflwbuf,dz))<0)
+					return exit_status;
+			}
+			break;
+		case(1):					//	N  = the number of syllables to keep
+			if(orig < dz->iparam[XSPK_N]) {		//	Add an original syllable, Keeping count of how many added
+				for(k = 0, j = peaklen - 1, m = thistrofat - peaklen; k < peaklen; k++,m++,j--) {
+					if(k < upsplice)
+						val = ibuf[m] * splicebuf[k];							//	do upslice
+					else if (j < splicelen) 
+						val = ibuf[m] * splicebuf[splicend--];					//	do downslice
+					else																	
+						val = ibuf[m];											//  else as is
+					obuf[obufpos] = (float)(obuf[obufpos] + (val * normaliser));//	then normalise and add to buffer
+					if(++obufpos >= dz->buflen * 2) {
+						if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+							return(exit_status);
+						memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+						memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+						obufpos -= dz->buflen;
+					}
+				}
+				orig++;									//	Count how many orig syllabs added
+			} else {				//	If all N orig syllabs have already been added
+				patno = pattern[patterncnt++];		//	Add JUST 1 NEW syllable
+				if((dz->mode < 3 || (dz->mode >= 6 && dz->mode < 9)) && dz->vflag[XSPK_ORISZ])
+					peaklen = dz->insams[patno];
+				splicend = peaklen - 1;
+				if((exit_status = insert_new_syllable(peaklen,patno,splicelen,gain,origlevel,normaliser,&obufpos,obuf,ovflwbuf,dz))<0)
+					return exit_status;
+				orig = 0;							//	Reset orig-syllabs counter
+			}
+			break;
+		}				
+		if(done)
+			break;
+	}
+	if(obufpos) {
+		if((exit_status = write_samps(obuf,obufpos,dz))<0)
+			return(exit_status);
+	}
+	return FINISHED;
+}
+				
+/****************************** EXTTARGETSPEAK *********************************/
+
+int exttargetspeak(int XSPK_RRND,int XSPK_ORISZ,dataptr dz) 
+{
+	int exit_status, chans = dz->infile->channels, srate = dz->infile->srate;
+	float *ibuf = dz->sampbuf[0], *obuf = dz->sampbuf[dz->infilecnt], *ovflwbuf = dz->sampbuf[dz->infilecnt + 1];
+	int gpsplicelen = dz->iparam[XSPK_SPLEN];
+	int splicelen = gpsplicelen * chans, upsplice;
+	int obufpos = 0, lasttrofat = 0, thistrofat, peaklen, splicend;
+	int *trof = dz->lparray[0];
+	int n, m, j, k;
+	double *splicebuf = dz->parray[0], time = 0, maxgain = 0.0, *origmax = dz->parray[1], *syllmax = dz->parray[2];
+	int samps_per_sec = srate * chans;
+	double val, gain, normaliser = 1.0;
+	int *pattern, *target;
+	double origlevel = 1.0;
+	int patterncnt, target_cnt, patno, syllread, q;
+	for(n = 1; n< dz->infilecnt;n++) {
+		if((syllread = fgetfbufEx(dz->sampbuf[n], dz->insams[n],dz->ifd[n],0)) < 0) {
+			sprintf(errstr,"Can't read samples from soundfile %d\n",n);      // RWD was %n
+			return(SYSTEM_ERROR);
+		}
+		if(syllread != dz->insams[n]) {
+			sprintf(errstr,"Fail to read all samples from soundfile %d\n",n); // RWD ditto
+			return(SYSTEM_ERROR);
+		}
+		if(dz->vflag[XSPK_ENV] || dz->mode >= 15) {
+			maxgain = 0.0;
+			for(q = 0; q < dz->insams[n]; q++)
+				maxgain = max(maxgain,fabs(dz->sampbuf[n][q]));
+			syllmax[n] = maxgain;
+		}
+	}
+	if(dz->mode != 14 && dz->mode != 17) {
+		if(dz->iparam[XSPK_SEED] > 0)
+			srand(dz->iparam[XSPK_SEED]);
+		else
+			initrand48();
+		if((exit_status = generate_xspk_pattern(XSPK_RRND,dz->trofcnt+1,dz))<0)
+			return exit_status;
+	}
+	if(dz->mode >= 15) {
+		fprintf(stdout,"INFO: Calculating Normalisation.\n");
+		fflush(stdout);
+		if((exit_status = find_orig_syllab_maxima(splicelen,dz)) < 0)
+			return exit_status;
+		if((exit_status = find_normaliser_target(&normaliser,samps_per_sec,splicelen,dz)) < 0)
+			return exit_status;
+	}
+	target  = dz->iparray[TRGT_ARRAY];
+	pattern = dz->iparray[PATN_ARRAY];
+	lasttrofat = 0;
+	splicend = splicelen - 1;
+	patterncnt = 0;
+	target_cnt = 0;
+	for(n = 0; n <= dz->trofcnt; n++)  {
+		if(n > 0)
+			lasttrofat = trof[n-1];
+		thistrofat  = trof[n];
+		peaklen = thistrofat - lasttrofat;
+		splicend = splicelen - 1;
+		if(dz->brksize[XSPK_GAIN]) {
+			time = get_syllable_time(thistrofat,lasttrofat,peaklen,n,samps_per_sec,dz);
+			if((exit_status = read_value_from_brktable(time,XSPK_GAIN,dz))<0)
+				return exit_status;
+		}
+		gain = dz->param[XSPK_GAIN];
+		if(lasttrofat > 0) {			//	If we're NOT at file start	
+			obufpos -= splicelen;		//	baktrak to splice to end of last segment written
+			peaklen += splicelen;		//	and length of peak is therefore one splicelen longer
+			upsplice = splicelen;
+		} else
+			upsplice = 0;				//	Prevents initial splice on start of file-segment
+		splicend = splicelen - 1;
+		if(dz->vflag[XSPK_ENV])
+			origlevel = origmax[n];
+		if(target_cnt < dz->targetcnt && n == target[target_cnt]) {	
+			patno = pattern[patterncnt++];
+			if((dz->mode < 15) && dz->vflag[XSPK_ORISZ])	//	IF not Resizing : write-in ALL of new syllable
+				peaklen = dz->insams[patno];			//	ELSE it's truncated/extended to size of original syllable
+			splicend = peaklen - 1; 
+			if((exit_status = insert_new_syllable(peaklen,patno,splicelen,gain,origlevel,normaliser,&obufpos,obuf,ovflwbuf,dz))<0)
+				return exit_status;
+			target_cnt++;
+		} else {
+			for(k = 0, j = peaklen - 1, m = thistrofat - peaklen; k < peaklen; k++,m++,j--) {
+				if(k < upsplice)
+					val = ibuf[m] * splicebuf[k];							//	do upslice
+				else if (j < splicelen) 
+					val = ibuf[m] * splicebuf[splicend--];					//	do downslice
+				else																	
+					val = ibuf[m];											//  else as is
+				obuf[obufpos] = (float)(obuf[obufpos] + (val * normaliser));//	then normalise and add to buffer
+				if(++obufpos >= dz->buflen * 2) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+					memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+					obufpos -= dz->buflen;
+				}
+			}
+		}
+	}
+	if(obufpos) {
+		if((exit_status = write_samps(obuf,obufpos,dz))<0)
+			return(exit_status);
+	}
+	return FINISHED;
+}
+				
+/*************************************** EXTRACT_ENV_FROM_SNDFILE **************************/
+
+int extract_env_from_sndfile(dataptr dz)
+{
+	int exit_status;
+	float *envptr;
+	dz->envcnt = windows_in_sndfile(dz);
+	if((dz->fptr[0]=(float *)malloc((dz->envcnt+20) * sizeof(float)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to store envelope (2).\n");
+		return(MEMORY_ERROR);
+	}
+	envptr = dz->fptr[0];
+	dz->ssampsread = 1;
+	while(dz->ssampsread > 0)	{
+		if((dz->ssampsread = fgetfbufEx(dz->sampbuf[0], dz->insams[0],dz->ifd[0],0)) < 0) {
+			sprintf(errstr,"Can't read samples from soundfile 1: extract_env_from_sndfile()\n");
+			return(SYSTEM_ERROR);
+		}
+		if(sloom)
+			display_virtual_time(dz->total_samps_read,dz);		
+		if((exit_status = getenv_of_buffer(dz->ssampsread,&envptr,dz))<0)
+			return exit_status;
+	}
+	dz->fptr[1] = envptr;		//	envend
+	if((exit_status = sndseekEx(dz->ifd[0],0,0))<0) {
+		sprintf(errstr,"Failed to return to start of file.\n");
+		return SYSTEM_ERROR;
+	}
+	dz->total_samps_read = 0;
+	return(FINISHED);
+}
+
+/************************* GETENV_OF_BUFFER [READENV] *******************************/
+
+int getenv_of_buffer(int samps_to_process,float **envptr,dataptr dz)
+{
+	int  start_samp = 0;
+	int envwindow_sampsize = dz->iparam[XSPK_WINSZ];
+	float *ibuf = dz->sampbuf[0];
+	float *env = *envptr;
+	double convertor = 1.0/F_ABSMAXSAMP;
+	while(samps_to_process >= envwindow_sampsize) {
+		*env++       = (float) (getmaxsamp(start_samp,envwindow_sampsize,ibuf) * convertor);
+		start_samp  += envwindow_sampsize;
+		samps_to_process -= envwindow_sampsize;
+	}
+	if(samps_to_process)	/* Handle any final short buffer */
+		*env++ = (float)(getmaxsamp(start_samp,samps_to_process,ibuf) * convertor);
+	*envptr = env;
+	return FINISHED;
+}
+
+/****************************** WINDOWS_IN_SNDFILE [GET_ENVSIZE] ******************************/
+ 
+int windows_in_sndfile(dataptr dz)
+{
+	int envcnt, winsize = dz->iparam[XSPK_WINSZ];
+	if(((envcnt = dz->insams[0]/winsize) * winsize)!=dz->insams[0])
+		envcnt++;
+	return envcnt;
+}
+
+/*************************** GETMAXSAMP *****************************/
+
+double getmaxsamp(int startsamp, int sampcnt,float *buffer)
+{
+	int  i, endsamp = startsamp + sampcnt;
+	double thisval, thismaxsamp = 0.0;
+	for(i = startsamp; i<endsamp; i++) {
+		if((thisval =  fabs(buffer[i]))>thismaxsamp)		   
+			thismaxsamp = thisval;
+	}
+	return thismaxsamp;
+}
+
+/*************************** EXTTROFSGET *************************/
+ 
+int exttrofsget(dataptr dz)
+{
+ 	int upwards, troffcnt = 0, thistrofat, lasttrofat, env_cnt, peaklen;
+	int *trof;
+ 	float *p, *q, *ibuf = dz->sampbuf[0];
+	double *maxarray, maxlevel;
+	int envwindow_sampsize = dz->iparam[XSPK_WINSZ], n, k;
+	int minseglen = (dz->iparam[XSPK_SPLEN] * 2) * dz->infile->channels;		//	Minimum segment to cut is larger than 2 splices.
+	float *env, *envend;
+
+	env = dz->fptr[0];
+	envend = dz->fptr[1];
+					//	 2 gpsplices     * chans;
+	p = env+1;
+ 	q = env;    
+	if (*p > *q)
+ 		upwards = TRUE;
+ 	else
+ 		upwards = FALSE;
+	troffcnt  = 0;
+	lasttrofat = 0;
+	dz->envcnt = 0;
+ 	while(p < envend) {
+ 		if(upwards) {
+ 			if(*p < *q) {
+ 				upwards = FALSE;
+ 			}
+ 		} else {
+			if(*p > *q) {												//	Peak-segments (separated by trofs)
+				if(istrof(env,envend,q,EXTSPEAK_PKSRCHWIDTH)) {
+					thistrofat = dz->envcnt * envwindow_sampsize;
+					peaklen = thistrofat - lasttrofat;
+					if(peaklen > minseglen) {							//	Peak-segments must be longer than 2 splices
+						troffcnt++;										//	This also skips getting a trof AT 0 time
+						lasttrofat = thistrofat;
+					}
+				}
+ 				upwards = TRUE;
+ 			}
+		}
+ 		p++;
+ 		q++;
+		dz->envcnt++;
+ 	}
+	if((dz->lparray[0] = (int *)malloc((troffcnt + 1) * sizeof(int))) == NULL) {	//	Allow for trof at EOF
+		sprintf(errstr,"INSUFFICIENT MEMORY to store peak-locations.\n");
+		return(MEMORY_ERROR);
+	}
+	if(dz->mode == 1 || dz->mode == 4) {
+		if((dz->iparray[PERM_ARRAY] = (int *)malloc((dz->infilecnt - 1) * sizeof(int))) == NULL) {	//	Storage for permed syllable order
+			sprintf(errstr,"INSUFFICIENT MEMORY to store permutation array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	trof = dz->lparray[0];
+	dz->trofcnt = troffcnt;
+ 	p = env+1;
+ 	q = env;    
+	env_cnt = 0;
+	if (*p > *q)
+ 		upwards = TRUE;
+ 	else
+ 		upwards = FALSE;
+	troffcnt = 0;
+	lasttrofat = 0;
+	while(env_cnt < dz->envcnt) {
+ 		if(upwards) {
+ 			if(*p < *q) {
+ 				upwards = FALSE;
+ 			}
+ 		} else {
+			if(*p > *q) {													//	Peak-segments (separated by trofs)
+				if(istrof(env,envend,q,EXTSPEAK_PKSRCHWIDTH)) {
+					thistrofat = env_cnt * envwindow_sampsize;
+					peaklen = thistrofat - lasttrofat;
+					if(peaklen > minseglen) {
+						trof[troffcnt++] = env_cnt * dz->iparam[XSPK_WINSZ];//	Peak-segments must be longer than 2 splices
+						lasttrofat = thistrofat;							//	This also skips getting a trof AT 0 time
+					}
+				}
+ 				upwards = TRUE;
+ 			}
+		}
+ 		p++;
+ 		q++;
+		env_cnt++;
+ 	}
+	trof[troffcnt] = dz->insams[0];		//	Add trof at EOF
+													//Only get here if dz->mode < 6
+	if(dz->vflag[XSPK_ENV] || dz->mode >= 3) {					//	Get syllable maxima on infile0
+		if((dz->parray[1] = (double *)malloc((dz->trofcnt + 1) * sizeof(double))) == NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY to create splice buffer (2).\n");
+			return(MEMORY_ERROR);
+		}
+		maxarray = dz->parray[1];
+		n = 0;
+		lasttrofat = 0;
+		while(n <= dz->trofcnt) {
+			thistrofat = trof[n];
+			k = lasttrofat;
+			maxlevel = -HUGE;
+			while(k < thistrofat) {
+				maxlevel = max(maxlevel,fabs(ibuf[k]));
+				k++;
+			}
+			maxarray[n] = maxlevel;
+			lasttrofat = thistrofat;
+			n++;
+		}
+	}
+	return(FINISHED);
+}
+
+/*************************** CREATE_SNDBUFS_FOR_EXTSPEAK **************************
+ *
+ *	Only AFTER params have been read.
+ */
+
+int create_sndbufs_for_extspeak(dataptr dz)
+{
+	int bigbufsize, minobufsize, safety = 16;
+	int n, k,chans = dz->infile->channels;
+	double srate = (double)dz->infile->srate;
+	/* All other cases */
+	if(dz->bufcnt == dz->infilecnt + 3);		//	includes end-of-all bufs pointer
+	if(dz->sbufptr == 0 || dz->sampbuf == 0) {
+		sprintf(errstr,"buffer pointers not allocated: create_sndbufs_for_extspeak()\n");
+		return(PROGRAM_ERROR);
+	}
+	/* minobufsize = 2 * sizeof splice */
+	minobufsize = ((int)ceil((dz->param[XSPK_SPLEN] * MS_TO_SECS) * 2.0 * srate) + safety) * chans;
+	minobufsize = max(minobufsize,512 * chans); 
+	bigbufsize  = 0;
+	for(n = 0; n < dz->infilecnt; n++)
+		bigbufsize += dz->insams[n];
+	bigbufsize += minobufsize * 2;
+	bigbufsize *=  sizeof(float);
+	if((dz->bigbuf = (float *)malloc((bigbufsize))) == NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to create sound buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	dz->sbufptr[0] = dz->sampbuf[0] = dz->bigbuf;
+	for(n=0,k=1;n<dz->infilecnt;n++,k++)								//	Inbufs = size of infles
+		dz->sbufptr[k] = dz->sampbuf[k] = dz->sampbuf[n] + dz->insams[n];
+	dz->sbufptr[k] = dz->sampbuf[k] = dz->sampbuf[n] + minobufsize;		// outbuf and ovflwbuf are minobufsize length
+	k++;											
+	n++;
+	dz->sbufptr[k] = dz->sampbuf[k] = dz->sampbuf[n] + minobufsize;
+	dz->buflen = minobufsize;
+	return(FINISHED);
+}
+
+/*************************** ISTROF **********************************/
+ 
+int istrof(float *env,float *envend,float *q,int width)
+{
+ 	int up, down;
+ 	float *upq, *downq, *r;
+ 	if(width<2)
+ 		return(TRUE);
+ 	down = up = width/2;
+	if(EVEN(width))
+ 		down = up - 1;		/* set search params above and below q */
+ 	downq = q - down;
+ 	upq   = q + up;
+ 	upq   = min(envend-1,upq);	/* allow for ends of envelope table */
+ 	downq = max(env,downq);
+ 	for(r = downq; r<=upq; r++) {
+ 		if(*q > *r)
+ 			return(FALSE);		
+ 	}
+ 	return(TRUE);			/* if r is minimum of all in peak, return 1 */
+ }
+ 
+/*************************** PRECALCULATE_PEAKS_ARRAY_AND_SPLICE **********************************/
+ 
+int precalculate_peaks_array_and_splice(dataptr dz)
+{
+	int exit_status, chans = dz->infile->channels;
+	int gpsplicelen, splicelen, n, m, k;
+	double splicincr, *splicebuf;
+	int srate = dz->infile->srate;
+	int *trof;
+	double *maxarray, maxlevel;
+	int thistrofat, lasttrofat;
+	float *ibuf;
+
+	dz->iparam[XSPK_SPLEN] = (int)round(dz->param[XSPK_SPLEN] * MS_TO_SECS * (double)srate);
+	if(dz->mode < 6)
+		dz->iparam[XSPK_WINSZ] = (int)round(dz->param[XSPK_WINSZ] * MS_TO_SECS * (double)srate) * chans;
+	gpsplicelen = dz->iparam[XSPK_SPLEN];
+	splicelen = gpsplicelen * chans;
+	splicincr = 1.0/(double)gpsplicelen;
+	if((dz->parray[0] = (double *)malloc((splicelen * sizeof(double)))) == NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to create splice buffer (2).\n");
+		return(MEMORY_ERROR);
+	}
+	splicebuf = dz->parray[0];
+	for(n= 0, m = 0;n < gpsplicelen; n++, m += chans) {
+		for(k = 0; k < chans; k++)
+			splicebuf[m+k] = (double)n * splicincr;
+	}
+	if(dz->mode < 6) {
+		if((exit_status = extract_env_from_sndfile(dz))< 0)
+			return exit_status;
+		if((dz->lparray=(int **)malloc(2 * sizeof(int *)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY to store peaks.\n");
+			return(MEMORY_ERROR);
+		}
+		if((dz->lparray[0]=(int *)malloc(dz->envcnt * sizeof(int)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY to store peaks (2).\n");
+			return(MEMORY_ERROR);
+		}
+		trof = dz->lparray[0];
+
+		if((exit_status = exttrofsget(dz))< 0)
+			return exit_status;
+	} else {
+		trof = dz->lparray[0];		//	Array was created when special-data file "cuts" was read
+		ibuf = dz->sampbuf[0];
+		if((dz->ssampsread = fgetfbufEx(dz->sampbuf[0],dz->insams[0],dz->ifd[0],0)) < 0) {
+			sprintf(errstr,"Can't read samples from soundfile 1: precalculate_peaks_array_and_splice()\n");
+			return(SYSTEM_ERROR);
+		}
+		if(dz->vflag[XSPK_ENV] || (dz->mode >= 9 && dz->mode < 12) || dz->mode >= 15) {			//	Get syllable maxima on infile0
+			if((dz->parray[1] = (double *)malloc((dz->trofcnt + 1) * sizeof(double))) == NULL) {
+				sprintf(errstr,"INSUFFICIENT MEMORY to create splice buffer (2).\n");
+				return(MEMORY_ERROR);
+			}
+			maxarray = dz->parray[1];
+			n = 0;
+			lasttrofat = 0;
+			while(n <= dz->trofcnt) {
+				thistrofat = trof[n];
+				k = lasttrofat;
+				maxlevel = -HUGE;
+				while(k < thistrofat) {
+					maxlevel = max(maxlevel,fabs(ibuf[k]));
+					k++;
+				}
+				maxarray[n] = maxlevel;
+				lasttrofat = thistrofat;
+				n++;
+			}
+		}
+	}
+	return FINISHED;
+}
+
+/********************************* RANDPERM *************************************/
+
+void randperm(int z,int setlen,dataptr dz)
+{
+	int n, t;
+	for(n=0;n<setlen;n++) {
+		t = (int)floor(drand48() * (n+1));
+		if(t>=n)
+			hprefix(z,n,setlen,dz);
+		else
+			hinsert(z,n,t,setlen,dz);
+	}
+}
+
+/***************************** HINSERT **********************************
+ *
+ * Insert the value m AFTER the T-th element in iparray[].
+ */
+
+void hinsert(int z,int m,int t,int setlen,dataptr dz)
+{   
+	hshuflup(z,t+1,setlen,dz);
+	dz->iparray[z][t+1] = m;
+}
+
+/***************************** HPREFIX ************************************
+ *
+ * Insert the value m at start of the permutation iparray[].
+ */
+
+void hprefix(int z,int m,int setlen,dataptr dz)
+{
+	hshuflup(z,0,setlen,dz);
+	dz->iparray[z][0] = m;
+}
+
+/****************************** HSHUFLUP ***********************************
+ *
+ * move set members in iparray[] upwards, starting from element k.
+ */
+
+void hshuflup(int z,int k,int setlen,dataptr dz)
+{
+	int n, *i;
+	int y = setlen - 1;
+	i = (dz->iparray[z]+y);
+	for(n = y;n > k;n--) {
+		*i = *(i-1);
+		i--;
+	}
+}
+
+/****************************** GENERATE_XSPK_PATTERN ***********************************/
+
+int generate_xspk_pattern(int XSPK_RRND,int patternsize,dataptr dz)
+{
+	int exit_status, lastperm, firstperm, n, patterncnt, syllabcnt, done = 0;
+	int *pattern, *permm;
+	if(dz->mode != 8 && dz->mode != 11 && dz->mode != 14 && dz->mode != 17) {		//	In these modes, pattern has already been read
+		if((dz->iparray[PATN_ARRAY] = (int *)malloc(patternsize  * sizeof(int))) == NULL) {//	Storage for permed or swapped syllable order
+			sprintf(errstr,"INSUFFICIENT MEMORY to store pattern of new syllables.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	pattern = dz->iparray[PATN_ARRAY];
+	syllabcnt = dz->infilecnt - 1;	//	Count of files with syllables-for-insertion
+	patterncnt = 0;
+	switch(dz->mode) {
+	case(12):	//	fall thro
+	case(15):	//	fall thro
+	case(9):	//	fall thro
+	case(6):	//	fall thro
+	case(3):	//	fall thro
+	case(0):						//	Syllable pattern is in original order, or entirely random
+		if(dz->vflag[XSPK_RRND]) {	//	Entirely random
+			while(patterncnt < patternsize)
+				pattern[patterncnt++] = (int)floor(drand48() * syllabcnt) + 1;
+		} else {					//	No flags set : seq of infiles, (repeated) e.g. for 3 files 1 2 3 1 2 3 ....
+			while(patterncnt < patternsize) {
+				for(n = 0; n < syllabcnt; n++) {
+					pattern[patterncnt] = n + 1; 
+					if(++patterncnt >= patternsize) {
+							done = 1;
+							break;
+					}
+				}
+				if(done)
+					break;
+			}
+		}
+		break;
+	case(16):	//	fall thro
+	case(13):	//	fall thro
+	case(10):	//	fall thro
+	case(7):	//	fall thro
+	case(4):	//	fall thro
+	case(1):										//	Rand-permutation of ALL input syllables, then a different ditto, etc
+		permm = dz->iparray[PERM_ARRAY];
+		randperm(PERM_ARRAY,syllabcnt,dz);			//	For syllabcnt 3, perms values 0,1,2 into "permm"
+		lastperm = permm[syllabcnt - 1];
+		while(patterncnt < patternsize) {
+			for(n = 0; n < syllabcnt; n++) {
+				pattern[patterncnt] = permm[n] + 1;	//	Read permd value, but add 1 to index syllab buffers from 1 upwards
+				if(++patterncnt >= patternsize) {
+						done = 1;
+						break;
+				}
+			}
+			if(done)
+				break;
+			do {
+				randperm(1,syllabcnt,dz);
+				firstperm = permm[0];
+			} while(firstperm == lastperm);
+			lastperm = permm[syllabcnt - 1];		//	Ensure no syllable repeated betwren end of one perm & start of next
+		}
+		break;
+	case(5):	//	fall thro
+	case(2):						//	Syllable pattern is input as a file : read it, and expand to fill patternsize
+		if((exit_status = handle_pattern_data(patternsize,dz))<0)
+			return exit_status;
+		break;
+	case(8):	//	fall thro
+	case(11):						//	Syllable pattern HAS ALREADY BEEN input as a file : expand it to fill patternsize
+		if((exit_status = expand_pattern_data(patternsize,dz))<0)
+			return exit_status;
+		break;
+	}
+	return FINISHED;
+}
+
+/************************ HANDLE_PATTERN_DATA *********************/
+
+int handle_pattern_data(int patternsize,dataptr dz)
+{
+	aplptr ap = dz->application;
+	int patterncnt, linecnt, done, k, j;
+	char temp[2000], *q, *filename = dz->wordstor[0];
+	int *pattern = dz->iparray[PATN_ARRAY];
+	int *p;
+	ap->data_in_file_only = TRUE;
+	ap->special_range 	  = TRUE;
+	ap->min_special 	  = 1;
+	ap->max_special 	  = dz->infilecnt - 1;
+
+	if((dz->fp = fopen(filename,"r"))==NULL) {
+		sprintf(errstr,"Cannot open pattern datafile %s\n",filename);
+		return(DATA_ERROR);
+	}
+	p = pattern;
+	done = 0;
+	linecnt = 0;
+	patterncnt = 0;
+	while(fgets(temp,200,dz->fp)!=NULL) {
+		q = temp;
+		if(is_an_empty_line_or_a_comment(temp)) {
+			linecnt++;
+			continue;
+		}
+		while(get_int_from_within_string(&q,p,0)) {
+			if(*p < ap->min_special || *p > ap->max_special) {
+				sprintf(errstr,"Pattern number (%d) out of range (from %d to count of NEW syllables in infile list = %d) : file %s : line %d\n",
+					(int)round(*p),(int)round(ap->min_special),dz->infilecnt - 1,filename,linecnt+1);
+				return(DATA_ERROR);
+			}
+			if(++patterncnt >= patternsize) {
+				done = 1;
+				break;
+			}
+			p++;
+		}
+		if(done)
+			break;
+		linecnt++;
+	}
+	if(fclose(dz->fp)<0) {
+		fprintf(stdout,"WARNING: Failed to close input textfile %s.\n",filename);
+		fflush(stdout);
+	}
+	if(patterncnt == 0) {
+		sprintf(errstr,"No data found in file %s\n",filename);
+		return(DATA_ERROR);
+	}
+	if(patterncnt < patternsize) {			//	Repeat pattern to fill pattern array
+		for(k = patterncnt, j = 0; k < patternsize; k++,j++)
+			pattern[k] = pattern[j];
+	}
+	return(FINISHED);
+}
+
+/************************************ STORE_PATTERNDATAFILE_NAME ***************************
+ *
+ *	Store the NAME of the special-data file, to open later.
+ */
+
+int store_patterndatafile_name(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status;
+	char *filename = (*cmdline)[0];
+	if(!sloom) {
+		if(*cmdlinecnt <= 0) {
+			sprintf(errstr,"Insufficient parameters on command line.\n");
+			return(USAGE_ONLY);
+		}
+	}
+	if((dz->fp = fopen(filename,"r"))==NULL) {
+		sprintf(errstr,"Cannot open pattern datafile %s\n",filename);
+		return(DATA_ERROR);
+	}
+	fclose(dz->fp);
+	if(dz->wordstor!=NULL)
+		free_wordstors(dz);
+	dz->all_words = 0;
+	if((exit_status = store_filename(filename,dz))<0)
+		return(exit_status);
+	(*cmdline)++;		
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/************************************ INSERT_NEW_SYLLABLE ***************************/
+
+int insert_new_syllable(int peaklen,int patno,int splicelen,double gain,double origlevel,double normaliser,int *obufpos, float *obuf, float *ovflwbuf,dataptr dz)
+{
+	int exit_status, k, j, m, z, c, gpsmpcnt, chans = dz->infile->channels;
+	double frac, diff, flincr, flpos, val;
+	double *splicebuf = dz->parray[0];
+	float *ibuf = dz->sampbuf[patno], *origibuf, ival;
+	double *syllmax =  dz->parray[2];
+	int ibufpos;
+	int splicend = splicelen - 1;
+
+	if(dz->vflag[XSPK_ENV])				//	Scale to level of original syllable
+		gain *= origlevel/syllmax[patno];	//	pattern vals run from 1 (not from zero), and level also stored at 1 upwards
+
+	if((dz->mode >= 3 && dz->mode < 6) || (dz->mode >= 9 && dz->mode < 12) || dz->mode >= 15) {
+		origibuf = dz->sampbuf[0];
+		ibufpos = dz->total_samps_written + *obufpos;
+		switch(dz->vflag[XSPK_TRANSPOSE]) {
+		case(0):						//	CUT OR PAD WITH ZEROS
+			for(k = 0, j = peaklen - 1; k < peaklen; k++,j--) {
+				if(k >= dz->insams[patno])												// add normalised orig into existing buffer
+					ival = 0.0f;
+				else
+					ival = ibuf[k];
+				if(k < splicelen)														//	do upslice of new syllab BUT ADD ~~NO~~ old syllab (its already there in downsplice)
+					val = (origibuf[ibufpos++]  + (gain * ival)) * splicebuf[k];
+				else if (j < splicelen)													//	do downslice of new syllab
+					val = (origibuf[ibufpos++] + (gain * ival)) * splicebuf[splicend--];
+				else																	//	just add, and normalise
+					val = origibuf[ibufpos++] + (gain * ival);
+				obuf[*obufpos] = (float)(obuf[*obufpos] + (val * normaliser));
+				if(++(*obufpos) >= dz->buflen * 2) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+					memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+					*obufpos -= dz->buflen;
+				}				
+			}
+			break;
+		case(1):						//	TRANSPOSE
+			flpos = 0.0;															//	Flincr increments as GPsampcnt		
+			flincr = (double)(dz->insams[patno])/(double)peaklen;
+			flpos = 0.0;															//	Flincr increments as GPsampcnt		
+			for(k = 0,gpsmpcnt = 0,j = peaklen - chans;k < peaklen;gpsmpcnt++,k+=chans,j-=chans) { 
+				flpos = ((double)k/(double)peaklen) * (double)(dz->insams[patno]/chans);
+				m = (int)floor(flpos);											//	Find the fractional part of the GPchans-xnt
+				frac = flpos - (double)m;										//	Convert to the (channel-base) in the true sampcnt;
+				m *= chans;														
+				for(c = 0; c < chans; c++) {									//	Do interp between ALL channels
+					z = m + chans;
+					val = ibuf[m];
+					diff = ibuf[z] - ibuf[m];
+					val +=  diff * frac;
+					if(k < splicelen)											//	do upslice of new syllab
+						val = (origibuf[ibufpos++]  + (gain * val)) * splicebuf[k];
+					else if (j < splicelen)										//	do downslice of new syllab mixing with orig
+						val = (origibuf[ibufpos++] + (gain * val)) * splicebuf[splicend--];
+					else														//	just add, and normalise
+						val = origibuf[ibufpos++] + (gain * val);
+					obuf[*obufpos] = (float)(obuf[*obufpos] + (val * normaliser));
+					m++;														
+					(*obufpos)++;
+				}
+				if(*obufpos >= dz->buflen * 2) {
+					if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+						return(exit_status);
+					memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+					memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+					*obufpos -= dz->buflen;
+				}
+			}
+			break;
+		}
+		return FINISHED;
+	}
+	switch(dz->vflag[XSPK_TRANSPOSE]) {
+	case(0):						//	CUT OR PAD WITH ZEROS
+		for(k = 0, j = peaklen - 1; k < peaklen; k++,j--) {
+			if(k >= dz->insams[patno])												// add nothing into existing buffer
+				;															
+			else if(k < splicelen)													//	do upslice
+				obuf[*obufpos] = (float)(obuf[*obufpos] + (gain * (ibuf[k] * splicebuf[k])));
+			else if (j < splicelen)													//	do downslice
+				obuf[*obufpos] = (float)(obuf[*obufpos] + (gain * (ibuf[k] * splicebuf[splicend--])));
+			else																
+				obuf[*obufpos] = (float)(obuf[*obufpos] + (gain * ibuf[k]));		//	just copy
+			if(++(*obufpos) >= dz->buflen * 2) {
+				if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+					return(exit_status);
+				memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+				memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+				*obufpos -= dz->buflen;
+			}				
+		}
+		break;
+	case(1):						//	TRANSPOSE
+		for(k = 0,gpsmpcnt = 0,j = peaklen - chans;k < peaklen;gpsmpcnt++,k+=chans,j-=chans) { 
+			flpos = ((double)k/(double)peaklen) * (double)(dz->insams[patno]/chans);
+			m = (int)floor(flpos);											//	Find the fractional part of the GPchans-xnt
+			frac = flpos - (double)m;										//	Convert to the (channel-base) in the true sampcnt;
+			m *= chans;														
+			for(c = 0; c < chans; c++) {									//	Do interp between ALL channels
+				z = m + chans;
+				val = ibuf[m];
+				diff = ibuf[z] - ibuf[m];
+				val  += (diff * frac);
+				if(k < splicelen) 
+					obuf[*obufpos] = (float)(obuf[*obufpos] + (gain * val * splicebuf[k]));
+				else if (j < splicelen)										//	do upslice
+					obuf[*obufpos] = (float)(obuf[*obufpos] + (gain * val * splicebuf[splicend--]));
+				else														//	do downslice
+					obuf[*obufpos] = (float)(obuf[*obufpos] + (gain * val));
+				m++;														//	just add in
+				(*obufpos)++;
+			}
+			if(*obufpos >= dz->buflen * 2) {
+				if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+					return(exit_status);
+				memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+				memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+				*obufpos -= dz->buflen;
+			}
+		}
+		break;
+	}
+	return FINISHED;
+}
+
+/************************ HANDLE_EXTRA_INFILES *********************/
+
+int handle_the_extra_infiles(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+					/* OPEN ANY FURTHER INFILES, CHECK COMPATIBILITY, STORE DATA AND INFO */
+	int  exit_status;
+	int  n;
+	char *filename;
+	fileptr fp2 = NULL;
+	for(n=1;n<dz->infilecnt;n++) {
+		filename = (*cmdline)[0];
+		if((exit_status = open_checktype_getsize_and_compare_header(filename,n,&fp2,dz))<0)
+			return(exit_status);
+		(*cmdline)++;
+		(*cmdlinecnt)--;
+	}
+	return(FINISHED);
+}
+
+/************************** GET_INT_FROM_WITHIN_STRING **************************
+ * takes a pointer TO A POINTER to a string. If it succeeds in finding 
+ * aN INT it returns the int value (*val), and it's new position in the
+ * string (*str).
+ */
+
+int get_int_from_within_string(char **str,int *val,int minus_one_ok)
+{
+	char *p, *valstart;
+	int  has_digits = 0;
+	p = *str;
+	while(isspace(*p))
+		p++;
+	valstart = p;
+	if(minus_one_ok) {
+		if(*p == NEGATION) {
+			p++;
+			if(*p != 1 + INT_TO_ASCII)	//	Only neg number allowed is -1
+				return(FALSE);
+		}
+	}
+	if(!isdigit(*p))
+		return(FALSE);
+	has_digits = TRUE;
+	p++;	
+	while(!isspace(*p) && *p!=NEWLINE && *p!=ENDOFSTR) {
+		if(isdigit(*p))
+			has_digits = TRUE;
+		p++;
+	}
+	if(!has_digits || sscanf(valstart,"%d",val)!=1)
+		return(FALSE);
+	*str = p;
+	return(TRUE);
+}
+
+/************************** OPEN_CHECKTYPE_GETSIZE_AND_COMPARE_HEADER *****************************/
+
+int open_checktype_getsize_and_compare_header(char *filename,int fileno,fileptr *fp2,dataptr dz)
+{
+	int exit_status;
+	infileptr ifp;
+	double maxamp, maxloc;
+	int maxrep;
+	int getmax = 0, getmaxinfo = 0;
+	fileptr fp1 = dz->infile; 
+
+	if((dz->ifd[fileno] = sndopenEx(filename,0,CDP_OPEN_RDONLY)) < 0) {
+		sprintf(errstr,"cannot open input file %s to read data.\n",filename);
+		return(DATA_ERROR);
+	}
+	if((ifp = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to store data on later infile. (1)\n");
+		return(MEMORY_ERROR);
+	}
+	if((*fp2 = (fileptr)malloc(sizeof(struct fileprops)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to store data on later infile. (2)\n");
+		return(MEMORY_ERROR);
+	}
+	if((exit_status = readhead(ifp,dz->ifd[fileno],filename,&maxamp,&maxloc,&maxrep,getmax,getmaxinfo))<0)
+		return(exit_status);
+	copy_to_fileptr(ifp,*fp2);
+	if((*fp2)->filetype != SNDFILE) {
+		sprintf(errstr,"%s is not a sound file.\n",filename);
+		return(DATA_ERROR);
+	}
+	if((*fp2)->filetype != fp1->filetype) {
+		sprintf(errstr,"Incompatible file type in input file %s.\n",filename);
+		return(DATA_ERROR);
+	}
+	if((*fp2)->srate != fp1->srate) {
+		sprintf(errstr,"Incompatible sample-rate in input file %s.\n",filename);
+		return(DATA_ERROR);
+	}
+	if((*fp2)->channels != fp1->channels) {
+		sprintf(errstr,"Incompatible channel-count in input file %s.\n",filename);
+		return(DATA_ERROR);
+	}
+	if((dz->insams[fileno] = sndsizeEx(dz->ifd[fileno]))<0) {	    /* FIND SIZE OF FILE */
+		sprintf(errstr, "Can't read size of input file %s.\n");
+		return(PROGRAM_ERROR);
+	}
+	return(FINISHED);
+}
+
+/***************************************** FIND_ORIG_SYLLAB_MAXIMA *******************************/
+
+int find_orig_syllab_maxima(int splicelen,dataptr dz)
+{
+	int thistrofat, lasttrofat, n, k;
+	int *trof = dz->lparray[0];
+	double maxlevel, *origmax = dz->parray[1];
+	float *ibuf = dz->sampbuf[0];
+	lasttrofat = 0;
+	for(n = 0; n <= dz->trofcnt;n++) {
+		thistrofat = trof[n];
+		lasttrofat = max(0,lasttrofat - splicelen);
+		maxlevel = 0.0;
+		for(k = lasttrofat; k < thistrofat; k++)
+			maxlevel = max(maxlevel,ibuf[k]);
+		origmax[n] = maxlevel;
+		lasttrofat = thistrofat;
+	}
+	return FINISHED;
+}
+
+/***************************************** FIND_NORMALISER *******************************/
+
+int find_normaliser(double *normaliser,int samps_per_sec,int splicelen,dataptr dz)
+{
+	int exit_status, patterncnt, patno, z, n, done, orig;
+	double newmaxlevel, time = 0.0;
+	int lasttrofat, thistrofat, peaklen;
+	int *trof = dz->lparray[0];
+	int  *pattern = dz->iparray[PATN_ARRAY];
+	double thislevel, *origlevel = dz->parray[1], *syllmax = dz->parray[2];
+	done = 0;
+	orig = 0;
+	patterncnt = 0;
+	lasttrofat = 0;
+	newmaxlevel = 0.0;
+	z = 0;
+	while(z < dz->iparam[XSPK_OFFST]) {
+		newmaxlevel = max(newmaxlevel,origlevel[z]);
+		z++;
+	}
+	for(n = z; n <= dz->trofcnt; n++)  {
+		if(n > 0)
+			lasttrofat = trof[n-1];
+		lasttrofat = max(0,lasttrofat - splicelen);
+		thistrofat = trof[n];
+		peaklen = thistrofat - lasttrofat;
+		time = get_syllable_time(thistrofat,lasttrofat,peaklen,n,samps_per_sec,dz);
+		if((exit_status = read_values_from_all_existing_brktables(time,dz))<0)
+			return exit_status;
+		switch(dz->vflag[XSPK_KEEP]) {
+		case(0):					//	N  = the number of syllables to insert
+			newmaxlevel = max(newmaxlevel,origlevel[n]);	//	Just read level of file0 syllable
+			for(z = 0; z < dz->iparam[XSPK_N]; z++) {		//	Then Consider N NEW syllables
+				if(++n >= dz->trofcnt) {					//	Advance count of original syllables
+					done = 1;								//	and If out of original syllables, quit
+					break;
+				}
+				if(dz->brksize[XSPK_GAIN]) {
+					lasttrofat = thistrofat;			//	Reset time to read any gain table
+					thistrofat = trof[n];
+					time = get_syllable_time(thistrofat,lasttrofat,peaklen,n,samps_per_sec,dz);
+					if((exit_status = read_value_from_brktable(time,XSPK_GAIN,dz))<0)
+						return exit_status;
+				}
+				patno = pattern[patterncnt++];
+				if(dz->vflag[XSPK_ENV]) 
+					thislevel = origlevel[n] + (origlevel[n] * dz->param[XSPK_GAIN]);					//	File0-level + (scaled fileN-level X gain)
+				else
+					thislevel = origlevel[n] + (syllmax[patno] * dz->param[XSPK_GAIN]);					//	File0-level + (fileN-level X gain)
+				newmaxlevel = max(newmaxlevel,thislevel);
+			}
+			break;
+		case(1):					//	N  = the number of syllables to keep
+			if(orig < dz->iparam[XSPK_N]) {			//	Add an original syllable, Keeping count of how many added
+				newmaxlevel = max(newmaxlevel,origlevel[n]);
+				orig++;								//	Count how many orig syllabs added
+			} else {								//	If all N orig syllabs have already been added
+				if(++n >= dz->trofcnt) {			//	Advance count of original syllables
+					done = 1;						//	and If out of original syllables, quit
+					break;
+				}
+				if(dz->brksize[XSPK_GAIN]) {
+					lasttrofat = thistrofat;
+					thistrofat = trof[n];
+					time = get_syllable_time(thistrofat,lasttrofat,peaklen,n,samps_per_sec,dz);
+					if((exit_status = read_value_from_brktable(time,XSPK_GAIN,dz))<0)
+						return exit_status;
+				}
+				patno = pattern[patterncnt++];		//	Add JUST 1 NEW syllable
+				if(dz->vflag[XSPK_ENV]) 
+					thislevel = origlevel[n] + (origlevel[n] * dz->param[XSPK_GAIN]);				//	File0-level + (scaled fileN-level X gain)
+				else
+					thislevel = origlevel[n] + (syllmax[patno] * dz->param[XSPK_GAIN]);				//	File0-level + (fileN-level X gain)
+				newmaxlevel = max(newmaxlevel,thislevel);
+				orig = 0;							//	Reset orig-syllabs counter
+			}
+			break;
+		}				
+		if(done)
+			break;
+	}
+	if(newmaxlevel > XSPK_MAXLEVEL)
+		*normaliser = XSPK_MAXLEVEL/newmaxlevel;
+	return FINISHED;
+}
+
+/***************************************** FIND_NORMALISER_TARGET *******************************/
+
+int find_normaliser_target(double *normaliser,int samps_per_sec,int splicelen,dataptr dz)
+{
+	int exit_status, patterncnt, patno, n;
+	double newmaxlevel, time = 0.0;
+	int lasttrofat, thistrofat, peaklen;
+	int *trof = dz->lparray[0];
+	int  target_cnt, *pattern = dz->iparray[PATN_ARRAY], *target = dz->iparray[TRGT_ARRAY];
+	double thislevel, *origlevel = dz->parray[1], *syllmax = dz->parray[2];
+	lasttrofat = 0;
+	target_cnt = 0;
+	patterncnt = 0;
+	newmaxlevel = 0.0;
+	for(n = 0; n <= dz->trofcnt; n++)  {
+		if(n > 0)
+			lasttrofat = trof[n-1];
+		lasttrofat = max(0,lasttrofat - splicelen);
+		thistrofat = trof[n];
+		peaklen = thistrofat - lasttrofat;
+		if(target_cnt < dz->targetcnt &&  n == target[target_cnt]) {
+			if(dz->brksize[XSPK_GAIN]) {
+				time = get_syllable_time(thistrofat,lasttrofat,peaklen,n,samps_per_sec,dz);
+				if((exit_status = read_value_from_brktable(time,XSPK_GAIN,dz))<0)
+					return exit_status;
+			}
+			patno = pattern[patterncnt++];
+			if(dz->vflag[XSPK_ENV]) 
+				thislevel = origlevel[n] + (origlevel[n] * dz->param[XSPK_GAIN]);					//	File0-level + (scaled fileN-level X gain)
+			else
+				thislevel = origlevel[n] + (syllmax[patno] * dz->param[XSPK_GAIN]);					//	File0-level + (fileN-level X gain)
+			newmaxlevel = max(newmaxlevel,thislevel);
+			target_cnt++;
+		} else
+			newmaxlevel = max(newmaxlevel,origlevel[n]);
+	}
+	if(newmaxlevel > XSPK_MAXLEVEL)
+		*normaliser = XSPK_MAXLEVEL/newmaxlevel;
+	return FINISHED;
+}
+
+/*************************************** GET_SYLLABLE_TIME ****************************************/
+
+double get_syllable_time(int thistrofat,int lasttrofat,int peaklen,int n,int samps_per_sec,dataptr dz)
+{
+	double time;
+	if(lasttrofat == 0)				//	time is zero at first syllab of file0
+		time = 0,0;
+	else if(n == dz->trofcnt)		//	time is EOF at last syllab of file0
+		time = (double)thistrofat/(double)samps_per_sec;
+	else							//	ELSE time is mid-point of syllable
+		time = (double)(thistrofat + (peaklen/2))/(double)samps_per_sec;
+	return time;
+}
+
+/******************************** DBTOLEVEL ***********************/
+
+double dbtolevel(double val)
+{
+	int isneg = 0;
+	if(flteq(val,0.0))
+		return(1.0);
+	if(val < 0.0) {
+		val = -val;
+		isneg = 1;
+	}
+	val /= 20.0;
+	val = pow(10.0,val);
+	if(isneg)
+		val = 1.0/val;
+	return(val);
+}	
+
+/******************************** GETCUTDATA ***********************/
+
+int getcutdata(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	aplptr ap = dz->application;
+	int troffcnt, linecnt, chans = dz->infile->channels, srate = dz->infile->srate;
+	char temp[2000], *q, *filename = (*cmdline)[0];
+	int *trof;
+	double *p, dummy;
+	ap->data_in_file_only = TRUE;
+	ap->special_range 	  = TRUE;
+	ap->min_special 	  = 0;
+	ap->max_special 	  = dz->duration;
+
+	if((dz->fp = fopen(filename,"r"))==NULL) {
+		sprintf(errstr,"Cannot open pattern datafile %s\n",filename);
+		return(DATA_ERROR);
+	}
+	p = &dummy;
+	linecnt = 0;
+	troffcnt = 0;
+	while(fgets(temp,200,dz->fp)!=NULL) {
+		q = temp;
+		if(is_an_empty_line_or_a_comment(temp)) {
+			linecnt++;
+			continue;
+		}
+		while(get_float_from_within_string(&q,p)) {
+			if(*p < ap->min_special || *p > ap->max_special) {
+				sprintf(errstr,"Cut position (%lf) out of range (%lf to %lf): file %s : line %d\n",
+					*p,ap->min_special,ap->max_special,filename,linecnt+1);
+				return(DATA_ERROR);
+			}
+			troffcnt++;
+		}
+		linecnt++;
+	}
+	if(troffcnt == 0) {
+		if(fclose(dz->fp)<0) {
+			fprintf(stdout,"WARNING: Failed to close input textfile %s.\n",filename);
+			fflush(stdout);
+		}
+		sprintf(errstr,"No data found in file %s\n",filename);
+		return(DATA_ERROR);
+	}
+	if((dz->lparray=(int **)malloc(2 * sizeof(int *)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to store trofs (1).\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lparray[0] = (int *)malloc((troffcnt + 1) * sizeof(int))) == NULL) {		//	Storage for syllable edit-point data
+		sprintf(errstr,"INSUFFICIENT MEMORY to store trofs (2).\n");
+		return(MEMORY_ERROR);
+	}
+	if(dz->mode == 7 || dz->mode == 10) {
+		if((dz->iparray[PERM_ARRAY] = (int *)malloc((dz->infilecnt - 1) * sizeof(int))) == NULL) {	//	Storage for permed syllable order
+			sprintf(errstr,"INSUFFICIENT MEMORY to store permutation array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(fseek(dz->fp,0,0)< 0) {
+		sprintf(errstr,"Failed to return to start of file %s.\n",filename);
+		return SYSTEM_ERROR;
+	}
+	troffcnt = 0;
+	trof = dz->lparray[0];
+	while(fgets(temp,200,dz->fp)!=NULL) {
+		q = temp;
+		if(is_an_empty_line_or_a_comment(temp))
+			continue;
+		while(get_float_from_within_string(&q,p))
+			trof[troffcnt++] = (int)(*p * (double)srate) * chans;
+	}
+	if(fclose(dz->fp)<0) {
+		fprintf(stdout,"WARNING: Failed to close input textfile %s.\n",filename);
+		fflush(stdout);
+	}
+	if(trof[troffcnt - 1] >= dz->insams[0]-chans)	//	Ignore any splice at End-of-file
+		troffcnt--;									//	by moving it to the troffcnt spot
+	else
+		trof[troffcnt] = dz->insams[0];
+	dz->trofcnt = troffcnt;
+	(*cmdline)++;		
+	(*cmdlinecnt)--;
+	return FINISHED;
+}
+
+/************************ GET_CUTPAT_DATA *********************/
+
+int get_cutpat_data(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	aplptr ap = dz->application;
+	int troffcnt, patterncnt, linecnt, gottrof, chans = dz->infile->channels, srate = dz->infile->srate;
+	char temp[2000], *q, *filename = (*cmdline)[0];
+	int maxpatternsize, *trof;
+	double *dp, ddummy;
+	int *ip, idummy, *pattern;
+	ap->data_in_file_only = TRUE;
+	ap->special_range 	  = TRUE;
+	ap->min_special 	  = 0;
+	ap->max_special		  = dz->duration;
+	ap->min_special2	  = 1;
+	ap->max_special2	  = dz->infilecnt - 1;
+
+	if((dz->fp = fopen(filename,"r"))==NULL) {
+		sprintf(errstr,"Cannot open splicing & pattern datafile %s\n",filename);
+		return(DATA_ERROR);
+	}
+	dp = &ddummy;
+	ip = &idummy;
+	gottrof = 0;
+	linecnt = 1;
+	troffcnt = 0;
+	patterncnt = 0;
+	while(fgets(temp,200,dz->fp)!=NULL) {
+		q = temp;
+		if(temp[0] == '#') {
+			if(gottrof) {
+				sprintf(errstr,"Too many  \"#\" lines in the file\n");
+				return(DATA_ERROR);
+			}
+			if(strlen(temp) != 1) {
+				q++;
+				while(*q != ENDOFSTR) {			//	Catch error like #1 1 2 3 4, with pattern item(s) on same line as #
+					if(!isspace(*q)) {
+						sprintf(errstr,"Spurious characters found on \"#\" line in file %s\n",filename);
+						if(fclose(dz->fp)<0) {
+							fprintf(stdout,"WARNING: Failed to close input textfile %s.\n",filename);
+							fflush(stdout);
+						}
+						return DATA_ERROR;
+					}
+					q++;
+				}
+			}
+			gottrof = 1;
+			linecnt++;
+			continue;
+		}
+		else if(is_an_empty_line_or_a_comment(temp)) {
+			linecnt++;
+			continue;
+		}
+		if(gottrof) {		//	Looking for pattern numbers
+			while(get_int_from_within_string(&q,ip,0)) {
+				if(*ip < ap->min_special2 || *ip > ap->max_special2) {
+					sprintf(errstr,"Pattern number (%d) out of range (from %d to count of NEW syllables in infile list = %d) : file %s : line %d\n",
+					*ip,(int)round(ap->min_special2),(int)round(ap->max_special2),filename,linecnt);
+					return(DATA_ERROR);
+				}
+				patterncnt++;
+			}
+		} else {		//	Looking for file edit times
+ 			while(get_float_from_within_string(&q,dp)) {
+				if(*dp < ap->min_special || *dp > ap->max_special) {
+					sprintf(errstr,"Cut position (%lf) out of range (%lf to %lf): file %s : line %d\n",
+						*dp,ap->min_special,ap->max_special,filename,linecnt);
+					return(DATA_ERROR);
+				}
+				troffcnt++;
+			}
+		}
+		linecnt++;
+	}
+	if(troffcnt == 0 || patterncnt == 0) {
+		if(fclose(dz->fp)<0) {
+			fprintf(stdout,"WARNING: Failed to close input textfile %s.\n",filename);
+			fflush(stdout);
+		}
+		if(troffcnt == 0 && patterncnt == 0) {
+			sprintf(errstr,"No data found in file %s\n",filename);
+			return(DATA_ERROR);
+		} else if(troffcnt == 0) {
+			sprintf(errstr,"No file edit times found in file %s\n",filename);
+			return(DATA_ERROR);
+		} else {
+			if(!gottrof) {
+				sprintf(errstr,"No separator \"#\" found in file %s\n",filename);
+				return(DATA_ERROR);
+			} else {
+				sprintf(errstr,"No pattern data found in file %s\n",filename);
+				return(DATA_ERROR);
+			}
+		}
+	}
+	if((dz->lparray=(int **)malloc(2 * sizeof(int *)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to store cut times (1).\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lparray[0] = (int *)malloc((troffcnt + 1) * sizeof(int))) == NULL) {		//	Storage for syllable edit-point data
+		sprintf(errstr,"INSUFFICIENT MEMORY to store source cut times (2).\n");
+		return(MEMORY_ERROR);
+	}
+	if(dz->mode == 7 || dz->mode == 10) {
+		if((dz->iparray[PERM_ARRAY] = (int *)malloc((dz->infilecnt - 1) * sizeof(int))) == NULL) {	//	Storage for permed syllable order
+			sprintf(errstr,"INSUFFICIENT MEMORY to store permutation array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	maxpatternsize = (troffcnt+1) * (1 + MAX_PATN);
+	if((dz->iparray[PATN_ARRAY] = (int *)malloc(maxpatternsize  * sizeof(int))) == NULL) {	//	Storage for pattern of syllables
+		sprintf(errstr,"INSUFFICIENT MEMORY to store pattern of new syllables.\n");
+		return(MEMORY_ERROR);
+	}
+	if(fseek(dz->fp,0,0)< 0) {
+		sprintf(errstr,"Failed to return to start of file %s.\n",filename);
+		return SYSTEM_ERROR;
+	}
+	dp = &ddummy;
+	ip = &idummy;
+	gottrof = 0;
+	linecnt = 0;
+	trof = dz->lparray[0];
+	pattern = dz->iparray[PATN_ARRAY];
+	troffcnt = 0;
+	patterncnt = 0;
+	while(fgets(temp,200,dz->fp)!=NULL) {
+		q = temp;
+		if(temp[0] == '#') {
+			gottrof = 1;
+			continue;
+		}
+		if(is_an_empty_line_or_a_comment(temp))
+			continue;
+		if(gottrof) {		//	Looking for pattern numbers
+			while(get_int_from_within_string(&q,ip,0))
+				pattern[patterncnt++] = *ip;
+		} else {		//	Looking for file edit times
+ 			while(get_float_from_within_string(&q,dp))
+				trof[troffcnt++] = (int)(*dp * (double)srate) * chans;
+		}
+	}
+	if(fclose(dz->fp)<0) {
+		fprintf(stdout,"WARNING: Failed to close input textfile %s.\n",filename);
+		fflush(stdout);
+	}
+	if(trof[troffcnt - 1] >= dz->insams[0]-chans)	//	Ignore any splice at End-of-file
+		troffcnt--;									//	by moving it to the troffcnt spot
+	else
+		trof[troffcnt] = dz->insams[0];
+	dz->trofcnt = troffcnt;
+	dz->itemcnt = patterncnt;
+	(*cmdline)++;		
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/************************ EXPAND_PATTERN_DATA *********************/
+
+int expand_pattern_data(int patternsize,dataptr dz)
+{
+	int k, j;
+	int *pattern = dz->iparray[PATN_ARRAY];
+	if(dz->itemcnt < patternsize) {			//	Repeat pattern to fill pattern array : Array already has max possible size for patterns
+		for(k = dz->itemcnt, j = 0; k < patternsize; k++,j++)
+			pattern[k] = pattern[j % dz->itemcnt];
+	}
+	return FINISHED;
+}
+
+/************************ GET_CUTTARG_DATA *********************/
+
+int get_cuttarg_data(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	aplptr ap = dz->application;
+	int troffcnt, target_cnt, linecnt, gottrof, chans = dz->infile->channels, srate = dz->infile->srate;
+	char temp[2000], *q, *filename = (*cmdline)[0];
+	int *trof;
+	double *dp, ddummy;
+	int *ip, idummy, *target, n, m, k;
+	ap->data_in_file_only = TRUE;
+	ap->special_range 	  = TRUE;
+	ap->min_special 	  = 0;
+	ap->max_special		  = dz->duration;
+	ap->min_special2	  = 1;
+	ap->max_special2	  = dz->infilecnt - 1;
+
+	if((dz->fp = fopen(filename,"r"))==NULL) {
+		sprintf(errstr,"Cannot open splicing & target datafile %s\n",filename);
+		return(DATA_ERROR);
+	}
+	dp = &ddummy;
+	ip = &idummy;
+	gottrof = 0;
+	linecnt = 1;
+	troffcnt = 0;
+	target_cnt = 0;
+	while(fgets(temp,200,dz->fp)!=NULL) {
+		q = temp;
+		if(temp[0] == '#') {
+			if(gottrof) {
+				sprintf(errstr,"Too many  \"#\" lines in the file\n");
+				return(DATA_ERROR);
+			}
+			if(strlen(temp) != 1) {
+				q++;
+				while(*q != ENDOFSTR) {			//	Catch error like #1 1 2 3 4, with target item(s) on same line as #
+					if(!isspace(*q)) {
+						sprintf(errstr,"Spurious characters found on \"#\" line in file %s\n",filename);
+						if(fclose(dz->fp)<0) {
+							fprintf(stdout,"WARNING: Failed to close input textfile %s.\n",filename);
+							fflush(stdout);
+						}
+						return DATA_ERROR;
+					}
+					q++;
+				}
+			}
+			gottrof = 1;
+			linecnt++;
+			continue;
+		}
+		else if(is_an_empty_line_or_a_comment(temp)) {
+			linecnt++;
+			continue;
+		}
+		if(gottrof) {		//	Looking for target numbers
+			while(get_int_from_within_string(&q,ip,1)) {
+				if((*ip != -1) && (*ip == 0 || *ip > troffcnt+1)) {
+					sprintf(errstr,"Target number (%d) out of range (from 1 to count of syllabs within file0 (%d)  = %d) OR -1 (for last syllab)le: file %s : line %d\n",
+					*ip,troffcnt+1,filename,linecnt);
+					return(DATA_ERROR);
+				}
+				target_cnt++;
+			}
+		} else {		//	Looking for file edit times
+ 			while(get_float_from_within_string(&q,dp)) {
+				if(*dp < ap->min_special || *dp > ap->max_special) {
+					sprintf(errstr,"Cut position (%lf) out of range (%lf to %lf): file %s : line %d\n",
+						*dp,ap->min_special,ap->max_special,filename,linecnt);
+					return(DATA_ERROR);
+				}
+				troffcnt++;
+			}
+		}
+		linecnt++;
+	}
+	if(troffcnt == 0 || target_cnt == 0) {
+		if(fclose(dz->fp)<0) {
+			fprintf(stdout,"WARNING: Failed to close input textfile %s.\n",filename);
+			fflush(stdout);
+		}
+		if(troffcnt == 0 && target_cnt == 0) {
+			sprintf(errstr,"No data found in file %s\n",filename);
+			return(DATA_ERROR);
+		} else if(troffcnt == 0) {
+			sprintf(errstr,"No file edit times found in file %s\n",filename);
+			return(DATA_ERROR);
+		} else {
+			if(!gottrof) {
+				sprintf(errstr,"No separator \"#\" found in file %s\n",filename);
+				return(DATA_ERROR);
+			} else {
+				sprintf(errstr,"No target data found in file %s\n",filename);
+				return(DATA_ERROR);
+			}
+		}
+	}
+	if((dz->lparray=(int **)malloc(2 * sizeof(int *)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to store source cut times (1).\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lparray[0] = (int *)malloc((troffcnt + 1) * sizeof(int))) == NULL) {		//	Storage for syllable edit-point data
+		sprintf(errstr,"INSUFFICIENT MEMORY to store source cut times (2).\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparray[TRGT_ARRAY] = (int *)malloc((troffcnt+1) * sizeof(int))) == NULL) {	//	Storage for targeted syllables
+		sprintf(errstr,"INSUFFICIENT MEMORY to store target syllables.\n");
+		return(MEMORY_ERROR);
+	}
+	if(dz->mode == 13 || dz->mode == 16) {
+		if((dz->iparray[PERM_ARRAY] = (int *)malloc((dz->infilecnt - 1) * sizeof(int))) == NULL) {	//	Storage for permed syllable order
+			sprintf(errstr,"INSUFFICIENT MEMORY to store permutation array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(fseek(dz->fp,0,0)< 0) {
+		sprintf(errstr,"Failed to return to start of file %s.\n",filename);
+		return SYSTEM_ERROR;
+	}
+	dp = &ddummy;
+	ip = &idummy;
+	gottrof = 0;
+	linecnt = 0;
+	trof = dz->lparray[0];
+	target  = dz->iparray[TRGT_ARRAY];
+	troffcnt = 0;
+	target_cnt = 0;
+	while(fgets(temp,200,dz->fp)!=NULL) {
+		q = temp;
+		if(temp[0] == '#') {
+			gottrof = 1;
+			continue;
+		}
+		if(is_an_empty_line_or_a_comment(temp))
+			continue;
+		if(gottrof) {		//	Looking for target numbers
+			while(get_int_from_within_string(&q,ip,1)) {
+				if(*ip < 0)
+					*ip = troffcnt + 1;
+				target[target_cnt++] = *ip;
+			}
+		} else {		//	Looking for file edit times
+ 			while(get_float_from_within_string(&q,dp))
+				trof[troffcnt++] = (int)(*dp * (double)srate) * chans;
+		}
+	}
+	if(fclose(dz->fp)<0) {
+		fprintf(stdout,"WARNING: Failed to close input textfile %s.\n",filename);
+		fflush(stdout);
+	}
+	if(trof[troffcnt - 1] >= dz->insams[0]-chans)	//	Ignore any splice at End-of-file
+		troffcnt--;									//	by moving it to the troffcnt spot
+	else
+		trof[troffcnt] = dz->insams[0];
+	dz->trofcnt = troffcnt;
+	for(n = 0; n < target_cnt-1;n++) {				//	Sort targets to ascending order, and erase duplicates
+		for(m = n+1; m < target_cnt; m++) {
+			if(target[n] == target[m]) {
+				fprintf(stdout,"syllable %d targeted more than once.\n",target[n]);
+				fflush(stdout);
+				if(m < target_cnt - 1) {
+					for(k = m+1;k < target_cnt;k++)
+						target[k-1] = target[k];	//	Erase by shufldown
+				}
+				target_cnt--;
+				m--;
+			} else if(target[m] < target[n]) {
+				k = target[m];
+				target[m] = target[n];
+				target[n] = k;
+			}
+		}
+	}
+	for(n = 0; n < target_cnt;n++)					//	Make targets count from zero
+		target[n]--;
+	dz->targetcnt = target_cnt;
+	(*cmdline)++;		
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/************************ GET_CUTTAPA_DATA *********************/
+
+int get_cuttapa_data(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	aplptr ap = dz->application;
+	int troffcnt, target_cnt, patterncnt, linecnt, gothash, chans = dz->infile->channels, srate = dz->infile->srate;
+	char temp[2000], *q, *filename = (*cmdline)[0];
+	int *trof;
+	double *dp, ddummy;
+	int *ip, idummy, *pattern, *target, n, m, k;
+	ap->data_in_file_only = TRUE;
+	ap->special_range 	  = TRUE;
+	ap->min_special 	  = 0;
+	ap->max_special		  = dz->duration;
+	ap->min_special2	  = 1;
+	ap->max_special2	  = dz->infilecnt - 1;
+
+	if((dz->fp = fopen(filename,"r"))==NULL) {
+		sprintf(errstr,"Cannot open splicing,pattern and targeting datafile %s\n",filename);
+		return(DATA_ERROR);
+	}
+	dp = &ddummy;
+	ip = &idummy;
+	gothash = 0;
+	linecnt = 1;
+	troffcnt = 0;
+	target_cnt = 0;
+	patterncnt = 0;
+	while(fgets(temp,200,dz->fp)!=NULL) {
+		q = temp;
+		if(temp[0] == '#') {
+			if(gothash == 2) {
+				sprintf(errstr,"Too many \"#\" signs in datafile %s\n",filename);
+				return(DATA_ERROR);
+			}
+			if(strlen(temp) != 1) {
+				q++;
+				while(*q != ENDOFSTR) {			//	Catch error like #1 1 2 3 4, with pattern item(s) on same line as #
+					if(!isspace(*q)) {
+						if(gothash)
+							sprintf(errstr,"Spurious characters found on second \"#\" line in file %s\n",filename);
+						else 
+							sprintf(errstr,"Spurious characters found on first \"#\" line in file %s\n",filename);
+						if(fclose(dz->fp)<0) {
+							fprintf(stdout,"WARNING: Failed to close input textfile %s.\n",filename);
+							fflush(stdout);
+						}
+						return DATA_ERROR;
+					}
+					q++;
+				}
+			}
+			gothash++;
+			linecnt++;
+			continue;
+		}
+		else if(is_an_empty_line_or_a_comment(temp)) {
+			linecnt++;
+			continue;
+		}
+		if(gothash == 2) {		//	Looking for target numbers
+			while(get_int_from_within_string(&q,ip,1)) {
+				if((*ip != -1) && (*ip == 0 || *ip > troffcnt+1)) {
+					sprintf(errstr,"Target number (%d) out of range (from 1 to count of syllabs within file0 = %d) OR -1 for last syllable: file %s : line %d\n",
+					*ip,troffcnt+1,filename,linecnt);
+					return(DATA_ERROR);
+				}
+				target_cnt++;
+			}
+		} else if(gothash == 1) {		//	Looking for pattern
+			while(get_int_from_within_string(&q,ip,0)) {
+				if(*ip < ap->min_special2 || *ip > ap->max_special2) {
+					sprintf(errstr,"Pattern number (%d) out of range (from %d to count of NEW syllables (%d) in infile list = %d) : file %s : line %d\n",
+					*ip,dz->infilecnt-1,(int)round(ap->min_special2),(int)round(ap->max_special2),filename,linecnt);
+					return(DATA_ERROR);
+				}
+				patterncnt++;
+			}
+		} else {		//	Looking for file edit times
+ 			while(get_float_from_within_string(&q,dp)) {
+				if(*dp < ap->min_special || *dp > ap->max_special) {
+					sprintf(errstr,"Cut position (%lf) out of range (%lf to %lf): file %s : line %d\n",
+						*dp,ap->min_special,ap->max_special,filename,linecnt);
+					return(DATA_ERROR);
+				}
+				troffcnt++;
+			}
+		}
+		linecnt++;
+	}
+	if(troffcnt == 0 || patterncnt == 0 || target_cnt == 0) {
+		if(fclose(dz->fp)<0) {
+			fprintf(stdout,"WARNING: Failed to close input textfile %s.\n",filename);
+			fflush(stdout);
+		}
+		if(troffcnt == 0 && patterncnt == 0 && target_cnt == 0) {
+			sprintf(errstr,"No data found in file %s\n",filename);
+			return(DATA_ERROR);
+		} else if(troffcnt == 0) {
+			sprintf(errstr,"No file edit times found in file %s\n",filename);
+			return(DATA_ERROR);
+		} else {
+			if(gothash == 0) {
+				sprintf(errstr,"No separator \"#\" found in file %s\n",filename);
+				return(DATA_ERROR);
+			} else if(gothash == 1) {
+				sprintf(errstr,"No 2nd separator \"#\" found in file %s\n",filename);
+				return(DATA_ERROR);
+			} else if(target_cnt == 0) {
+				sprintf(errstr,"No target data found in file %s\n",filename);
+				return(DATA_ERROR);
+			} else {
+				sprintf(errstr,"No pattern data found in file %s\n",filename);
+				return(DATA_ERROR);
+			}
+		}
+	}
+	if((dz->lparray=(int **)malloc(2 * sizeof(int *)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to store cut times (1).\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lparray[0] = (int *)malloc((troffcnt + 1) * sizeof(int))) == NULL) {		//	Storage for syllable edit-point data
+		sprintf(errstr,"INSUFFICIENT MEMORY to store source cut times (2).\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparray[PATN_ARRAY] = (int *)malloc((troffcnt+1) * sizeof(int))) == NULL) {	//	Storage for pattern of syllables
+		sprintf(errstr,"INSUFFICIENT MEMORY to store target syllables.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparray[TRGT_ARRAY] = (int *)malloc((troffcnt+1) * sizeof(int))) == NULL) {	//	Storage for target syllables
+		sprintf(errstr,"INSUFFICIENT MEMORY to store target syllables.\n");
+		return(MEMORY_ERROR);
+	}
+	if(fseek(dz->fp,0,0)< 0) {
+		sprintf(errstr,"Failed to return to start of file %s.\n",filename);
+		return SYSTEM_ERROR;
+	}
+	dp = &ddummy;
+	ip = &idummy;
+	gothash = 0;
+	linecnt = 0;
+	trof = dz->lparray[0];
+	pattern = dz->iparray[PATN_ARRAY];
+	target  = dz->iparray[TRGT_ARRAY];
+	troffcnt = 0;
+	patterncnt = 0;
+	target_cnt = 0;
+	while(fgets(temp,200,dz->fp)!=NULL) {
+		q = temp;
+		if(temp[0] == '#') {
+			gothash++;
+			continue;
+		}
+		if(is_an_empty_line_or_a_comment(temp))
+			continue;
+		if(gothash == 2) {			//	Looking for target list
+			while(get_int_from_within_string(&q,ip,1)) {
+				if(*ip < 0)
+					*ip = troffcnt+1;
+				target[target_cnt++] = *ip;
+			}
+		} else if(gothash == 1) {		//	Looking for pattern numbers
+			while(get_int_from_within_string(&q,ip,0))
+				pattern[patterncnt++] = *ip;
+		} else {		//	Looking for file edit times
+ 			while(get_float_from_within_string(&q,dp))
+				trof[troffcnt++] = (int)(*dp * (double)srate) * chans;
+		}
+	}
+	if(fclose(dz->fp)<0) {
+		fprintf(stdout,"WARNING: Failed to close datafile %s.\n",filename);
+		fflush(stdout);
+	}
+	if(trof[troffcnt - 1] >= dz->insams[0]-chans)	//	Ignore any splice at End-of-file
+		troffcnt--;									//	by moving it to the troffcnt spot
+	else
+		trof[troffcnt] = dz->insams[0];
+	dz->trofcnt = troffcnt;
+	for(n = 0; n < target_cnt-1;n++) {				//	Sort targets to ascending order, and erase duplicates
+		for(m = n+1; m < target_cnt; m++) {
+			if(target[n] == target[m]) {
+				fprintf(stdout,"syllable %d targeted more than once.\n",target[n]);
+				fflush(stdout);
+				if(m < target_cnt - 1) {
+					for(k = m+1;k < target_cnt;k++)
+						target[k-1] = target[k];	//	Erase by shufldown
+				}
+				target_cnt--;
+				m--;
+			} else if(target[m] < target[n]) {		//	Swap out-of-order targets
+				k = target[m];
+				target[m] = target[n];
+				target[n] = k;
+			}
+		}
+	}
+	for(n = 0; n < target_cnt;n++)					//	Make targets count from zero
+		target[n]--;
+	dz->targetcnt = target_cnt;
+	if(patterncnt < dz->trofcnt + 1) {				//	Expand pattern to max possible size
+		for(n = 0, k = patterncnt; k < dz->trofcnt+1;n++,k++)
+			pattern[k] = pattern[n % patterncnt];
+	}
+	(*cmdline)++;		
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}

+ 1337 - 0
dev/standnew/fractal.c

@@ -0,0 +1,1337 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <tkglobals.h>
+#include <pnames.h>
+#include <filetype.h>
+#include <processno.h>
+#include <modeno.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <math.h>
+#include <mixxcon.h>
+#include <osbind.h>
+#include <standalone.h>
+#include <ctype.h>
+#include <sfsys.h>
+#include <string.h>
+#include <srates.h>
+
+
+#ifdef unix
+#define round(x) lround((x))
+#endif
+#define maxfraccnt rampbrksize
+
+char errstr[2400];
+
+int anal_infiles = 1;
+int	sloom = 0;
+int sloombatch = 0;
+
+const char* cdp_version = "6.1.0";
+
+//CDP LIB REPLACEMENTS
+static int check_fractal_param_validity_and_consistency(dataptr dz);
+static int setup_fractal_application(dataptr dz);
+static int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+static int parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int setup_fractal_param_ranges_and_defaults(dataptr dz);
+static int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int establish_application(dataptr dz);
+static int initialise_vflags(dataptr dz);
+static int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int mark_parameter_types(dataptr dz,aplptr ap);
+static int assign_file_data_storage(int infilecnt,dataptr dz);
+static int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+static int get_the_mode_from_cmdline(char *str,dataptr dz);
+static int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt);
+static int float_array_for_fractal(int nnn,int n, float **ptr);
+static int generate_fractal_pattern(dataptr dz);
+static int create_fractal_sndbufs(dataptr dz);
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status;
+	dataptr dz = NULL;
+	char **cmdline;
+	int  cmdlinecnt;
+	int n;
+	aplptr ap;
+	int is_launched = FALSE;
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+						/* CHECK FOR SOUNDLOOM */
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {					// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc == 2) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+	}
+	if(!sloom) {
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		dz->maxmode = 0;
+		// get_the_mode_from_cmdline
+		// setup_particular_application =
+		if((exit_status = setup_fractal_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+
+	// parse_infile_and_hone_type() = 
+	if((exit_status = parse_infile_and_check_type(cmdline,dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// setup_param_ranges_and_defaults() =
+	if((exit_status = setup_fractal_param_ranges_and_defaults(dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// open_first_infile		CDP LIB
+	if((exit_status = open_first_infile(cmdline[0],dz))<0) {	
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);	
+		return(FAILED);
+	}
+	cmdlinecnt--;
+	cmdline++;
+
+//	handle_extra_infiles() : redundant
+	// handle_outfile() = 
+	if((exit_status = handle_the_outfile(&cmdlinecnt,&cmdline,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+//	handle_formants()			redundant
+//	handle_formant_quiksearch()	redundant
+//	handle_special_data()		redundant
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+//	check_param_validity_and_consistency....
+	if((exit_status = check_fractal_param_validity_and_consistency(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	is_launched = TRUE;
+	dz->bufcnt = 3;
+	if((dz->sampbuf = (float **)malloc(sizeof(float *) * (dz->bufcnt+1)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->sbufptr = (float **)malloc(sizeof(float *) * dz->bufcnt))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffer pointers.\n");
+		return(MEMORY_ERROR);
+	}
+	for(n = 0;n <dz->bufcnt; n++)
+		dz->sampbuf[n] = dz->sbufptr[n] = (float *)0;
+	dz->sampbuf[n] = (float *)0;
+
+	if((exit_status = create_fractal_sndbufs(dz))<0) {							// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//param_preprocess()						redundant
+	//spec_process_file =
+	if((exit_status = generate_fractal_pattern(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = complete_output(dz))<0) {										// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);		// CDP LIB
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc, brkcnt;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	brkcnt = tipc;
+	//THERE ARE NO INPUTFILE brktables USED IN THIS PROCESS
+	if(brkcnt>0) {
+		if((exit_status = setup_and_init_input_brktable_constants(dz,brkcnt))<0)			  
+			return(exit_status);
+	}
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+		return(exit_status);
+	
+	// establish_infile_constants() replaced by
+	dz->infilecnt = 1;
+	//establish_bufptrs_and_extra_buffers():
+	return(FINISHED);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}						 		/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_OUTFILE *********************/
+
+int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status;
+	char *filename = (*cmdline)[0];
+	if(filename[0]=='-' && filename[1]=='f') {
+		dz->floatsam_output = 1;
+		dz->true_outfile_stype = SAMP_FLOAT;
+		filename+= 2;
+	}
+	if(!sloom) {
+		if(file_has_invalid_startchar(filename) || value_is_numeric(filename)) {
+			sprintf(errstr,"Outfile name %s has invalid start character(s) or looks too much like a number.\n",filename);
+			return(DATA_ERROR);
+		}
+	}
+	strcpy(dz->outfilename,filename);	   
+	if((exit_status = create_sized_outfile(filename,dz))<0)
+		return(exit_status);
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/************************* SETUP_FRACTAL_APPLICATION *******************/
+
+int setup_fractal_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	// SEE parstruct FOR EXPLANATION of next 2 functions
+	if((exit_status = set_param_data(ap,0   ,1,1,"i"))<0)
+		return(FAILED);
+	if((exit_status = set_vflgs(ap,"s",1,"i","",0,0,""))<0)
+		return(FAILED);
+	// set_legal_infile_structure -->
+	dz->has_otherfile = FALSE;
+	// assign_process_logic -->
+	dz->input_data_type = SNDFILES_ONLY;
+	dz->process_type	= UNEQUAL_SNDFILE;	
+	dz->outfiletype  	= SNDFILE_OUT;
+	return application_init(dz);	//GLOBAL
+}
+
+/************************* PARSE_INFILE_AND_CHECK_TYPE *******************/
+
+int parse_infile_and_check_type(char **cmdline,dataptr dz)
+{
+	int exit_status;
+	infileptr infile_info;
+	if(!sloom) {
+		if((infile_info = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for infile structure to test file data.");
+			return(MEMORY_ERROR);
+		} else if((exit_status = cdparse(cmdline[0],infile_info))<0) {
+			sprintf(errstr,"Failed to parse input file %s\n",cmdline[0]);
+			return(PROGRAM_ERROR);
+		} else if(infile_info->filetype != SNDFILE)  {
+			sprintf(errstr,"File %s is not of correct type\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if((exit_status = copy_parse_info_to_main_structure(infile_info,dz))<0) {
+			sprintf(errstr,"Failed to copy file parsing information\n");
+			return(PROGRAM_ERROR);
+		}
+		free(infile_info);
+	}
+	return(FINISHED);
+}
+
+/************************* SETUP_FRACTAL_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_fractal_param_ranges_and_defaults(dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	// NB total_input_param_cnt is > 0 !!!
+	if((exit_status = setup_input_param_range_stores(ap->total_input_param_cnt,ap))<0)
+		return(FAILED);
+	// get_param_ranges()
+	ap->lo[0]	= 2;
+	ap->hi[0]	= 100;
+	ap->default_val[0]	= 8;
+	ap->lo[1]	= 2;
+	ap->hi[1]	= 50;
+	ap->default_val[1] = 15;
+	dz->maxmode = 0;
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_fractal_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int read_special_data(char *str,dataptr dz)	
+{
+	return(FINISHED);
+}
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+	usage2("fractal");
+	return(USAGE_ONLY);
+}
+
+/**************************** CHECK_FRACTAL_PARAM_VALIDITY_AND_CONSISTENCY *****************************/
+
+int check_fractal_param_validity_and_consistency(dataptr dz)
+{
+	int gpsamplen, minfracsize, maxsegcnt, maxcutcnt;
+	gpsamplen = dz->insams[0]/dz->infile->channels;					//	Length of file in sample-groups
+	dz->iparam[FRACSPLICE] = (int)round(dz->param[FRACSPLICE] * MS_TO_SECS * dz->infile->srate);
+	minfracsize = dz->iparam[FRACSPLICE] * 3;						//	Assume splicelen is in groupsamples
+																	//	Assume min size = 3 X splicelen
+	maxsegcnt = (int)floor((double)gpsamplen/(double)(minfracsize));//	Number of segments obtained by cutting file into minlength chunks
+	maxcutcnt = 1;
+	dz->maxfraccnt = 2;												//	Count how many successive cuts-in-half are needed
+	while(dz->maxfraccnt < maxsegcnt) {									//	To generate NO MORE THAN maxfraccnt segments.
+		dz->maxfraccnt *= 2;
+		maxcutcnt++;												//	calculate the maximum number of divisions by 2
+	}																//	which will fit INSIDE the maxsegcnt
+	dz->maxfraccnt /= 2;
+	maxcutcnt--;
+	if(dz->iparam[FRACDEPTH] > maxcutcnt) {
+		sprintf(errstr,"INFO: Maximum number of fractal cuts for this file = %d\n",maxcutcnt);
+		return DATA_ERROR;
+	}
+	return FINISHED;
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if(!strcmp(prog_identifier_from_cmdline,"fractal"))				dz->process = FRACTAL;
+	else {
+		sprintf(errstr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/******************************** SETUP_AND_INIT_INPUT_BRKTABLE_CONSTANTS ********************************/
+
+int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt)
+{	
+	int n;
+	if((dz->brk      = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<brkcnt;n++) {
+		dz->brk[n]     = NULL;
+		dz->brkptr[n]  = NULL;
+		dz->brkinit[n] = 0;
+		dz->brksize[n] = 0;
+	}
+	return(FINISHED);
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+	if(!strcmp(str,"fractal")) {
+		fprintf(stderr,
+	    "USAGE:\n"
+	    "fractal fractal infile outfile layers [-ssplicelen]\n"
+		"\n"
+		"Create fractalised version of sound.\n"
+		"\n"
+		"SPLICELEN Length of splices in mS.\n"
+		"\n"
+		"LAYERS    Number of fractal layers in the output sound.\n"
+		"          Note that the maximum number of layers possible\n"
+		"          depends on the duration of the input sound\n"
+		"          and the size of splices used\n"
+		"          and cannot be easily predicted in advance\n"
+		"\n"
+		"WARNINGS\n"
+		"(1) Specifying many layers will produce very long output sounds.\n"
+		"(2) Don't use very long input sounds, or you will run out of memory,\n"
+		"\n");
+	} else
+		fprintf(stdout,"Unknown option '%s'\n",str);
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	fprintf(stderr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/************************** GENERATE_FRACTAL_PATTERN *************************/
+
+int generate_fractal_pattern(dataptr dz)
+{
+	int exit_status, chans, segcnt, grpcnt, fracdepth, tailsize, cutcnt, splicelen;
+	int gpsamplen, patterncnt, segsize, total_used_len, obufpos, endfilestt, bufsize, starttail, origbuflen;
+	int n, j, m, z, c, thiscut, cutstt, cutend, thissegsize, patcnt, segno, insams;
+	double spliceincr;
+	float *ibuf = dz->sampbuf[0], *obuf = dz->sampbuf[1], *ovflwbuf = dz->sampbuf[2];
+	float *splicebuf, *tailbuf, **buf;
+	int *patterna, *patternb, *pattern1, *pattern2, *cutsegsize;
+
+	chans	  = dz->infile->channels;
+	gpsamplen = dz->insams[0]/chans;
+	fracdepth = dz->iparam[FRACDEPTH];
+	splicelen = dz->iparam[FRACSPLICE];
+	obufpos = 0;
+
+	//	CREATE SPLICE VALUES IN BUFFER
+
+	memset((char *)obuf,0,dz->buflen * 2 * sizeof(float));				//	Initialise obuf, and ovflwbuf to zero
+	origbuflen = dz->buflen;
+	dz->buflen = dz->insams[0];
+	if((exit_status = read_samps(ibuf,dz))<0)							//	Fill the input buffer
+		return(exit_status);
+	dz->buflen = origbuflen;
+
+	if((exit_status = float_array_for_fractal(splicelen,-2,&splicebuf)) < 0)
+		return exit_status;												//	Create buffer to store splice values
+	spliceincr = 1.0/(double)splicelen;									//	Fill the splice buffer
+	for(m = 0; m < splicelen; m++)
+		splicebuf[m] = (float)((double)m * spliceincr);
+
+	//	FIND HOW MANY SEGMENTS NEEDED (segcnt) AND THEIR SIZE (segsize) in gpsamples
+	//	For cut-stage 0 need  2^0 = 1 segment
+	//	For cut-stage 1 need  2^1 = 2 segments
+	//	For cut-stage 2 need  2^2 = 4 segments
+	//	For cut N need  2^N segments.
+
+	segcnt = 1;
+	for(n = 1;n < fracdepth; n++)
+		segcnt *= 2;
+
+	//	HOW int ARE THE SEGMENTS, IN SAMPLES : WHAT IS THE BUFFER SIZE REQUIRED
+	
+	segsize = gpsamplen/segcnt;					//	Sizeof segments (truncated)
+	bufsize = (segsize + splicelen) * chans;
+
+	//	STORE UNUSED TAIL OF FILE IN ITS OWN BUFFER
+
+	total_used_len = segcnt * segsize * chans;				//	How much of file used in making fractal
+	tailsize = dz->insams[0] - total_used_len;				//	How much is left
+	tailsize += splicelen * chans;							//	Add room for upsplice
+	starttail = total_used_len - (splicelen * chans);		//	Find start of portion extended-tail-portion to copy
+	if((exit_status = float_array_for_fractal(tailsize,-1,&tailbuf)) < 0)
+		return exit_status;									//	Create buffer to store tail
+	for(n = 0, m = starttail;n < tailsize; n++,m++)			//	Copy tail into buffer
+		tailbuf[n] = ibuf[m];
+	for(m = 0; m < splicelen; m++) {						//	Put upsplice on tail
+		j = m * 2;
+		for(c = 0; c < chans; c++) {
+			tailbuf[j] = (float)(tailbuf[j] * splicebuf[m]);
+			j++;
+		}
+		if(j == tailsize)									//	Break, if tail is shorter than full splice
+			break;
+	}
+
+	//	SET UP ARRAY OF BUFFERS TO STORE SEGMENTS
+	
+	if((buf = (float **)malloc(segcnt * sizeof(float *)))==NULL) {
+		sprintf(errstr,"Insufficient memory to store cut segments 1.\n");
+		return(MEMORY_ERROR);
+	}
+	for(n = 0; n < segcnt; n++) {
+		if((exit_status = float_array_for_fractal(bufsize,-1,&buf[n])) < 0)	//	Create buffers to store segments
+			return exit_status;
+	}
+
+	//	FIND FINAL SIZE OF FRACTAL PATTERN, AND SET UP ARRAYS TO STORE (GROWING) PATTERN
+	//	At every cut, the initial_pattern of segments is copied (and reversed), and appended, to make pattern twice as int
+	//	So total pattern of segments doubles in size at every cut
+	
+	patterncnt = segcnt;
+	for(n = 0;n < fracdepth; n++)
+		patterncnt *= 2; 
+	if((patterna = (int *)malloc(patterncnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"Insufficient memory to store pattern array 1.\n");
+		return(MEMORY_ERROR);
+	}
+	if((patternb = (int *)malloc(patterncnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"Insufficient memory to store pattern array 2.\n");
+		return(MEMORY_ERROR);
+	}
+
+	//	CREATE ARRAY TO STORE SIZES OF STORED SEGMENTS
+	
+	if((cutsegsize = (int *)malloc(segcnt * sizeof(int)))==NULL) {		//	Stores lengths of cut-segs, after splices added (or not)
+		sprintf(errstr,"Insufficient memory to store gating points.\n");
+		return(MEMORY_ERROR);
+	}
+
+	//	FILL THE PATTERN ARRAY
+
+	pattern1 = patterna;
+	pattern2 = patternb;
+
+	for(n = 0; n < segcnt; n++)									//	Initiate pattern : put all (numbered) segments in numeric order	
+		pattern1[n] = n;
+	grpcnt = segcnt;											//	Start off repatterning all existing segments
+	cutcnt = 1;
+	patcnt = 0;
+	for(n = 0;n < fracdepth; n++) {								//	For every cut-stage : loop-n
+		thiscut = 0;											//	Specify start and end of first-cut of cutcnt repatternings
+		cutend  = grpcnt;
+		patcnt = 0;												//	Initialise pattern counter at start of every repatterning
+
+		for(j = 0; j < cutcnt;j ++) {							//	For the number of cuts to be made at this stage : loop-j
+			if(patcnt + (grpcnt * 2) > patterncnt) {
+				sprintf(errstr,"ERROR: Error in pattern generation counting.\n");
+				return PROGRAM_ERROR;
+			}
+			for(m = thiscut; m <cutend;m++)						//	Copy pattern to new array   abcd
+				pattern2[patcnt++] = pattern1[m];				
+			for(m = cutend-1; m >= thiscut;m--)					//	Then copy it in reverse		abcddbca
+				pattern2[patcnt++] = pattern1[m];
+			thiscut += grpcnt;								
+			cutend  += grpcnt;									//	Advance start and end of cut in j-loop	
+		}
+		if(EVEN(n)) {
+			pattern1 = patternb;								//	Swap pattern pointers
+			pattern2 = patterna;
+		} else {												//	Final pattern always ends up as pattern1	
+			pattern1 = patterna;
+			pattern2 = patternb;
+		}														//	ONCE ALL segs at this level are reverse-copied and abutted
+		grpcnt /= 2;											//	Gpsize to Cut gets smaller (by 1/2) BUT the total pattern has doubled in size
+		cutcnt *= 4;											//	SO The number of cuts goes up by 2 X 2 !!	
+	}
+
+	//	TRANSFER SEGMENTS TO BUFFERS, EXTENDING BACKWARDS FOR UPSPLICE, AND DO START AND END SPLICES
+
+	//		Segments extended backwards by splicelen, but not forwards
+	//			|_______  |
+	//		 | /|		\ | 
+	//		 |/	|		 \|
+	//		 |	|		  |
+	//		add	|		  |
+	//		for | length  |
+	//	  splice|specified|
+	//			|_________|
+	//					  |_______	|
+	//					 /|		  \ |
+	//					/ |  next  \|
+	//					  | segment |
+	//					  |
+
+	for(n = 0; n < segcnt; n++) {									
+		cutstt = ((n * segsize) - splicelen) * chans;			//	Startcut is segment-index in pattern X segsize, MINUS room for splice
+		cutstt = max(cutstt,0);
+		cutend = (n + 1) * segsize * chans;						//	Startcut is segment-index+1 
+		cutend = min(cutend,dz->insams[0]);
+		for(m = cutstt,thissegsize = 0; m < cutend; m++,thissegsize++)	//	Copy segment to Relevant buffer
+			buf[n][thissegsize] = ibuf[m];								//  Counting the segment size with thissegsize
+		z = thissegsize - 1;
+		for(m = 0; m < splicelen; m++) {
+			if( n == 0) {											//	Start segment has no upsplice	
+				for(c = 0; c < chans; c++) {
+					buf[n][z] = (float)(buf[n][z] * splicebuf[m]);
+					z--;
+				}
+			} else {
+				j = m*2;											//	Otherwise : do start and end splices simultaneously
+				for(c = 0; c < chans; c++) {
+					buf[n][j] = (float)(buf[n][j] * splicebuf[m]);
+					j++;
+					buf[n][z] = (float)(buf[n][z] * splicebuf[m]);
+					z--;
+				}
+			}
+		}
+		cutsegsize[n] = thissegsize;
+	}
+
+	dz->tempsize = segsize * patcnt;									//	Approximate size of output
+
+	//	JOIN SEGMENTS TOGETHER IN OUTBUF, IN ORDER OF PATTERN
+
+	obufpos = splicelen * chans;										//	Preset ensures baktrak for splice doesn't run off start of infile
+	for(n = 0; n < patterncnt; n++) {
+		obufpos -= splicelen * chans;									//	baktrak to do splice
+		segno = pattern1[n];											//	Find segment indicated at position "n" in pattern
+																		//	and therefore get its buffer number (segno)
+		for(m = 0; m < cutsegsize[segno]; m++) {
+			obuf[obufpos] = (float)(obuf[obufpos] + buf[segno][m]);		//	Add-Copy segment to obuf (automatically overlapping splices)
+			if(++obufpos >= dz->buflen * 2) {
+				insams = dz->insams[0];									//	These two lines ensure that
+				dz->insams[0] = dz->tempsize;							//	time-reports when program runs are correct
+				if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+					return(exit_status);
+				dz->insams[0] = insams;
+				memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+				memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+				obufpos -= dz->buflen;
+			}
+		}
+	}
+	//	ADD TAIL OF SOUND
+
+	endfilestt = ((segcnt * segsize) - splicelen) * chans;
+	tailsize = dz->insams[0] - endfilestt;
+	obufpos -= splicelen * chans;
+	for(m = 0; m < tailsize; m++) {
+		obuf[obufpos] = (float)(obuf[obufpos] + ibuf[m]);
+		if(++obufpos >= dz->buflen * 2) {
+			insams = dz->insams[0];
+			dz->insams[0] = dz->tempsize;
+			if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+				return(exit_status);
+			dz->insams[0] = insams;
+			memcpy((char *)obuf,(char *)ovflwbuf,dz->buflen * sizeof(float));
+			memset((char *)ovflwbuf,0,dz->buflen * sizeof(float));
+			obufpos -= dz->buflen;
+		}
+	}
+	if(obufpos) {
+		insams = dz->insams[0];
+		dz->insams[0] = dz->tempsize;
+		if((exit_status = write_samps(obuf,obufpos,dz))<0)
+			return(exit_status);
+		dz->insams[0] = insams;
+	}
+	return FINISHED;
+}
+
+/****************************** FLOAT_ARRAY ******************************/
+
+int float_array_for_fractal(int nnn,int n, float **ptr)
+{	/* set up a floating point array length nnn. */
+	*ptr = (float *) calloc(nnn,sizeof(float));
+	if(*ptr==NULL){
+		if(n == -2) {
+			sprintf(errstr,"pvoc: insufficient memory to store splice values.\n");
+			return(MEMORY_ERROR);
+		} else if(n == -1) {
+			sprintf(errstr,"pvoc: insufficient memory to store end-segment of sound\n");
+			return(MEMORY_ERROR);
+		} else {
+			sprintf(errstr,"pvoc: insufficient memory for segment-of-pattern %d\n",n+1);
+			return(MEMORY_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/****************************** CREATE_FRACTAL_SNDBUFS ******************************/
+
+int create_fractal_sndbufs(dataptr dz)
+{
+	int bigbufsize, splicelen;
+	int framesize;
+	framesize = F_SECSIZE * dz->infile->channels;
+	if(dz->sbufptr == 0 || dz->sampbuf==0) {
+		sprintf(errstr,"buffer pointers not allocated: create_sndbufs()\n");
+		return(PROGRAM_ERROR);
+	}
+	splicelen = (int)round(1.0 * MS_TO_SECS * (double)dz->infile->srate) * dz->infile->channels;
+	dz->buflen = max(2 * splicelen,4096);
+	dz->buflen = (dz->buflen / framesize)  * framesize;
+
+	bigbufsize = dz->insams[0] + (2 * dz->buflen);
+	bigbufsize *= sizeof(float);
+	if((dz->bigbuf = (float *)malloc(bigbufsize)) == NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to create sound buffers. Don't use very big infiles\n");
+		return(PROGRAM_ERROR);
+	}
+	dz->sbufptr[0] = dz->sampbuf[0] = dz->bigbuf;
+	dz->sbufptr[1] = dz->sampbuf[1] = dz->sampbuf[0] + dz->insams[0];
+	dz->sbufptr[2] = dz->sampbuf[2] = dz->sampbuf[1] + dz->buflen;
+	dz->sbufptr[3] = dz->sampbuf[3] = dz->sampbuf[2] + dz->buflen;
+	return(FINISHED);
+}

+ 90 - 0
dev/standnew/headview.c

@@ -0,0 +1,90 @@
+#include <stdio.h>
+#ifdef unix
+#include <unistd.h>
+#endif
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include <fcntl.h>
+#ifdef WIN32
+#include <io.h>
+#endif
+
+#define BUFLEN 64
+#define ENDOFSTR ('\0')
+
+static void showbytes(int thisbuflen, int thisstart,char *buffer);
+
+int main(int argc,char *argv[])
+{
+	int fh;
+	int buflen = BUFLEN, bufcnt, bytescnt, partsect, n, thisbuflen, thisstart;
+	char buffer[BUFLEN];
+	if(argc != 3) {
+		fprintf(stderr,"USAGE: headview filename bytescnt\n");
+		return 0;
+	}
+	if(sscanf(argv[2],"%d",&bytescnt) < 1) {
+		fprintf(stderr,"Cannot read bytescnt\n");
+		return 0;
+	}
+	if(bytescnt <= 0) {
+		fprintf(stderr,"Invalid bytescnt\n");
+		return 0;
+	}
+#ifdef WIN32
+	if((fh = open(argv[1],O_RDONLY|O_RAW,0))<0) {
+#else
+    if((fh = open(argv[1],O_RDONLY,0))<0) {    
+#endif
+		fprintf(stderr,"Cannot open file %s\n",argv[1]);
+		return 0;
+	}
+	bufcnt = bytescnt/buflen;
+	partsect = bytescnt - (bufcnt * buflen);
+	thisstart = 0;
+	for(n=0;n<bufcnt;n++) {
+		thisbuflen = read(fh,buffer,BUFLEN);
+		if(thisbuflen < 0) {
+			fprintf(stderr,"Cannot read buffer %d\n",n+1);
+			return 0;
+		}
+		showbytes(thisbuflen,thisstart,buffer);
+		thisstart += thisbuflen;
+		if(thisbuflen < BUFLEN) {
+			partsect = 0;
+			break;
+		}
+	}
+	if(partsect > 0)
+		showbytes(partsect,thisstart,buffer);
+	return 1;
+}
+
+void showbytes(int thisbuflen, int thisstart,char *buffer)
+{
+	int thisend = thisstart + thisbuflen;
+	int m = 0;
+	char *p = buffer;
+	char temp1[2000], temp2[2000], temp3[2], temp4[64];
+	temp1[0] = ENDOFSTR;
+	temp2[0] = ENDOFSTR;
+	temp3[1] = ENDOFSTR;
+	while(m < thisbuflen) {
+		sprintf(temp4,"%d",*p);
+		strcat(temp2,temp4);
+		strcat(temp2," ");
+		if(isprint(*p))
+			temp3[0] = *p;
+		else
+			temp3[0] = '~';
+		strcat(temp1,temp3);
+		strcat(temp1," ");
+		p++;
+		m++;
+	}
+	fprintf(stdout,"CHARS %d to %d\n",thisstart + 1,thisend);
+	fprintf(stdout,"%s\n",temp1);
+	fprintf(stdout,"%s\n",temp2);
+	fflush(stdout);
+}

+ 1392 - 0
dev/standnew/hover2.c

@@ -0,0 +1,1392 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <tkglobals.h>
+#include <pnames.h>
+#include <filetype.h>
+#include <processno.h>
+#include <modeno.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <math.h>
+#include <mixxcon.h>
+#include <osbind.h>
+#include <standalone.h>
+#include <ctype.h>
+#include <sfsys.h>
+#include <string.h>
+#include <srates.h>
+
+#ifdef unix
+#define round(x) lround((x))
+#endif
+
+char errstr[2400];
+
+int anal_infiles = 1;
+int	sloom = 0;
+int sloombatch = 0;
+
+const char* cdp_version = "6.1.0";
+
+//CDP LIB REPLACEMENTS
+static int check_hover_param_validity_and_consistency(int *maxtraverse,dataptr dz);
+static int setup_hover_application(dataptr dz);
+static int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+static int parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int setup_hover_param_ranges_and_defaults(dataptr dz);
+static int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int establish_application(dataptr dz);
+static int initialise_vflags(dataptr dz);
+static int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int mark_parameter_types(dataptr dz,aplptr ap);
+static int assign_file_data_storage(int infilecnt,dataptr dz);
+static int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+static int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt);
+static int hover2(dataptr dz);
+static int create_hover2_sndbufs(int maxtraverse,dataptr dz);
+static int stepread_value_from_brktable(double thistime,int paramno,dataptr dz);
+
+#define HOVER_FRQ	0
+#define HOVER_LOC	1
+#define HOVER_FRQR	2
+#define HOVER_LOCR	3
+#define HOVER_DUR2	4
+
+#define TRAVERSE	0
+
+#define HOVER_SPLIC .015 
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status;
+	dataptr dz = NULL;
+	char **cmdline;
+	int  cmdlinecnt;
+	int n, maxtraverse = 0;
+	aplptr ap;
+	int is_launched = FALSE;
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+						/* CHECK FOR SOUNDLOOM */
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {					// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc == 2) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+	}
+	if(!sloom) {
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		// setup_particular_application =
+		if((exit_status = setup_hover_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+
+	// parse_infile_and_hone_type() = 
+	if((exit_status = parse_infile_and_check_type(cmdline,dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// setup_param_ranges_and_defaults() =
+	if((exit_status = setup_hover_param_ranges_and_defaults(dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// open_first_infile		CDP LIB
+	if((exit_status = open_first_infile(cmdline[0],dz))<0) {	
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);	
+		return(FAILED);
+	}
+	cmdlinecnt--;
+	cmdline++;
+
+//	handle_extra_infiles() : redundant
+	// handle_outfile() = 
+	if((exit_status = handle_the_outfile(&cmdlinecnt,&cmdline,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+//	handle_formants()			redundant
+//	handle_formant_quiksearch()	redundant
+//	handle_special_data()		redundant
+ 
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+//	check_param_validity_and_consistency....
+	if((exit_status = check_hover_param_validity_and_consistency(&maxtraverse,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	is_launched = TRUE;
+	dz->bufcnt = 3;
+	if((dz->sampbuf = (float **)malloc(sizeof(float *) * (dz->bufcnt+1)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->sbufptr = (float **)malloc(sizeof(float *) * dz->bufcnt))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffer pointers.\n");
+		return(MEMORY_ERROR);
+	}
+	for(n = 0;n <dz->bufcnt; n++)
+		dz->sampbuf[n] = dz->sbufptr[n] = (float *)0;
+	dz->sampbuf[n] = (float *)0;
+
+	if((exit_status = create_hover2_sndbufs(maxtraverse,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//param_preprocess()						redundant
+	//spec_process_file =
+	if((exit_status = hover2(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = complete_output(dz))<0) {										// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);		// CDP LIB
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc, brkcnt;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	brkcnt = tipc;
+	//THERE ARE NO INPUTFILE brktables USED IN THIS PROCESS
+	if(brkcnt>0) {
+		if((exit_status = setup_and_init_input_brktable_constants(dz,brkcnt))<0)			  
+			return(exit_status);
+	}
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+		return(exit_status);
+	
+	// establish_infile_constants() replaced by
+	dz->infilecnt = 1;
+	//establish_bufptrs_and_extra_buffers():
+	return(FINISHED);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}						 		/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_OUTFILE *********************/
+
+int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status;
+	char *filename = (*cmdline)[0];
+	if(filename[0]=='-' && filename[1]=='f') {
+		dz->floatsam_output = 1;
+		dz->true_outfile_stype = SAMP_FLOAT;
+		filename+= 2;
+	}
+	if(!sloom) {
+		if(file_has_invalid_startchar(filename) || value_is_numeric(filename)) {
+			sprintf(errstr,"Outfile name %s has invalid start character(s) or looks too much like a number.\n",filename);
+			return(DATA_ERROR);
+		}
+	}
+	strcpy(dz->outfilename,filename);	   
+	if((exit_status = create_sized_outfile(filename,dz))<0)
+		return(exit_status);
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/************************* SETUP_HOVER_APPLICATION *******************/
+
+int setup_hover_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	// SEE parstruct FOR EXPLANATION of next 2 functions
+	if((exit_status = set_param_data(ap,0   ,5,5,"DDDDd"))<0)
+		return(FAILED);
+	if((exit_status = set_vflgs(ap,"",0,"","sn",2,0,"00"))<0)
+		return(FAILED);
+	// set_legal_infile_structure -->
+	dz->has_otherfile = FALSE;
+	// assign_process_logic -->
+	dz->input_data_type = SNDFILES_ONLY;
+	dz->process_type	= UNEQUAL_SNDFILE;	
+	dz->outfiletype  	= SNDFILE_OUT;
+	return application_init(dz);	//GLOBAL
+}
+
+/************************* PARSE_INFILE_AND_CHECK_TYPE *******************/
+
+int parse_infile_and_check_type(char **cmdline,dataptr dz)
+{
+	int exit_status;
+	infileptr infile_info;
+	if(!sloom) {
+		if((infile_info = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for infile structure to test file data.");
+			return(MEMORY_ERROR);
+		} else if((exit_status = cdparse(cmdline[0],infile_info))<0) {
+			sprintf(errstr,"Failed to parse input file %s\n",cmdline[0]);
+			return(PROGRAM_ERROR);
+		} else if(infile_info->filetype != SNDFILE)  {
+			sprintf(errstr,"File %s is not of correct type\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if(infile_info->channels != 1)  {
+			sprintf(errstr,"File %s is not of correct type (must be mono)\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if((exit_status = copy_parse_info_to_main_structure(infile_info,dz))<0) {
+			sprintf(errstr,"Failed to copy file parsing information\n");
+			return(PROGRAM_ERROR);
+		}
+		free(infile_info);
+	}
+	return(FINISHED);
+}
+
+/************************* SETUP_HOVER_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_hover_param_ranges_and_defaults(dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	// NB total_input_param_cnt is > 0 !!!
+	if((exit_status = setup_input_param_range_stores(ap->total_input_param_cnt,ap))<0)
+		return(FAILED);
+	// get_param_ranges()
+	ap->lo[0]	= 1.0 / (dz->duration * 2.0);
+	ap->hi[0]	= dz->nyquist;
+	ap->default_val[0]	= 440.0;
+	ap->lo[1]	= 0.0;
+	ap->hi[1]	= dz->duration;
+	ap->default_val[1] = dz->duration / 2.0;
+	ap->lo[2]	= 0.0;
+	ap->hi[2]	= 1.0;
+	ap->default_val[2] = 0.1;
+	ap->lo[3]	= 0.0;
+	ap->hi[3]	= 1.0;
+	ap->default_val[3] = 0.1;
+	ap->lo[4]	= 0.0;
+	ap->hi[4]	= 100.0;
+	ap->default_val[4] = 1.0;
+
+	dz->maxmode = 0;
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_hover_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int read_special_data(char *str,dataptr dz)	
+{
+	return(FINISHED);
+}
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+	usage2("hover2");
+	return(USAGE_ONLY);
+}
+
+/**************************** CHECK_HOVER_PARAM_VALIDITY_AND_CONSISTENCY *****************************/
+
+int check_hover_param_validity_and_consistency(int *maxtraverse,dataptr dz)
+{
+	int exit_status;
+	double minval;
+	if(dz->brksize[HOVER_FRQ] == 0) {
+		dz->iparam[TRAVERSE] = (int)round(dz->infile->srate/dz->param[HOVER_FRQ]);
+		*maxtraverse = dz->iparam[TRAVERSE];
+	} else {
+		if((exit_status = get_minvalue_in_brktable(&minval,0,dz)) < 0)
+			return(exit_status);
+		*maxtraverse = (int)round((double)dz->infile->srate/minval);
+	}
+	if(dz->brksize[HOVER_LOC] == 0)
+		dz->iparam[HOVER_LOC] = (int)round(dz->infile->srate * dz->param[HOVER_LOC]);
+	dz->iparam[HOVER_DUR2] = (int)round(dz->infile->srate * dz->param[HOVER_DUR2]);
+
+	return FINISHED;
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if(!strcmp(prog_identifier_from_cmdline,"hover2"))				dz->process = HOVER2;
+	else {
+		sprintf(errstr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/******************************** SETUP_AND_INIT_INPUT_BRKTABLE_CONSTANTS ********************************/
+
+int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt)
+{	
+	int n;
+	if((dz->brk      = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<brkcnt;n++) {
+		dz->brk[n]     = NULL;
+		dz->brkptr[n]  = NULL;
+		dz->brkinit[n] = 0;
+		dz->brksize[n] = 0;
+	}
+	return(FINISHED);
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+	if(!strcmp(str,"hover2")) {
+		fprintf(stdout,
+	    "USAGE:\n"
+	    "hover2 hover2 infile outfile frq loc frqrand locrand dur [-s] [-n]\n"
+		"\n"
+		"move through a file, zigzag reading it at a given frequency,\n"
+		"reading back and forth from a zero-crossing,\n"
+		"then outputting same data inverted,\n"
+		"to form symmetrical zero-centred waveforms at each read.\n"
+		"\n"
+		"FRQ      rate of reading source-samples (in Hz).\n"
+		"         determines samplewidth of zigzag-read. e.g. at srate 44100,\n"
+		"         frq 1 Hz, reads 22050 samps forward, & 22050 samps back.\n"
+		"         frq 10 Hz, reads 2205 samps forward, & 2205 samps back.\n"
+		"LOC      Time in sourcefile near which samples are read.\n"
+		"FRQRAND  Random variation of frequency, (0-1).\n"
+		"LOCRAND  Random variation of location, (0-1).\n"
+		"DUR      total output duration.\n"
+		"-s       STEP between locations at times specified in any brkpnt file\n"
+		"         (rather than interpolating between the locations as time progresses).\n"
+		"-n       NORMALISE the loudness of all wavecycles generated.\n"
+		"\n"
+		"frq and loc (frqrand and locrand) may vary through time.\n"
+		"time in any brkpoint files is time in output-file.\n"
+		"\n");
+	} else
+		fprintf(stdout,"Unknown option '%s'\n",str);
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	fprintf(stderr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/******************************** HOVER2 ********************************/
+
+int hover2(dataptr dz)
+{
+	int exit_status, done, warned = 0, hover_splicelen = 0;
+	double randvar, time, srate = (double)dz->infile->srate, maxsamp, normaliser;
+	int samptime, randvarsamps;
+	float *ibuf = dz->sampbuf[0];
+	float *obuf = dz->sampbuf[1];
+	float *kbuf = dz->sampbuf[2];
+	int ibufpos, obufpos, abs_startreadbuf, abs_endreadbuf, readlimit;
+	int traverse, location, quarter_cycle;
+	int n, m;
+	double splincr = 0.0, spliceval = 0.0;
+	int splicelen = 0;
+
+	hover_splicelen = (int)round(HOVER_SPLIC * dz->infile->srate); 
+	obufpos = 0;
+
+	memset((char *)obuf,0,dz->buflen * sizeof(float));
+	if((exit_status = read_samps(ibuf,dz))<0)
+		return(exit_status);
+	samptime = 0;
+	time = 0.0;
+	abs_startreadbuf = 0;
+	abs_endreadbuf = dz->ssampsread;
+
+	/* No point in attempting to read buffers too close to end of file */	
+
+	if(dz->insams[0] < dz->buflen)
+		readlimit = 0;
+	else {
+		readlimit = (dz->insams[0] - dz->buflen)/F_SECSIZE;
+		readlimit *= F_SECSIZE;
+		if(dz->insams[0] - readlimit > dz->buflen)
+			readlimit += F_SECSIZE;
+	}
+	while(samptime < dz->iparam[HOVER_DUR2]) {
+	/* Initialise process by finding first frq, first location, (including randomisings) */
+
+		if(dz->vflag[0]) {
+			for(n=0;n<4;n++) {
+				if(n==HOVER_LOC) {
+					if(dz->brksize[HOVER_LOC]) {
+						if((exit_status = stepread_value_from_brktable(time,HOVER_LOC,dz))<0)
+							return(exit_status);
+					}
+				} else {
+					if(dz->brksize[n]) {
+						if((exit_status = read_value_from_brktable(time,n,dz))<0)
+							return(exit_status);
+					}
+				}
+			}
+		} else {
+			if((exit_status = read_values_from_all_existing_brktables(time,dz))<0)
+				return(exit_status);
+		}
+
+		/* TRAVERSE = TOTAL zig+zag read, in samples */
+
+		if(dz->brksize[HOVER_FRQ] > 0)
+			dz->iparam[TRAVERSE] = (int)round(srate/dz->param[HOVER_FRQ]);
+		traverse = dz->iparam[TRAVERSE];
+
+				/* LOCATION */
+
+		if(dz->brksize[HOVER_LOC] > 0)
+			dz->iparam[HOVER_LOC] = (int)round(srate * dz->param[HOVER_LOC]);
+		location = dz->iparam[HOVER_LOC];
+
+			/* RANDVAR of LOCATION */
+
+		if(dz->param[HOVER_LOCR] > 0.0) {
+			randvar =  (drand48() * 2.0) - 1.0;		/* range -1 to +1 */
+			randvar *= dz->param[HOVER_LOCR];		/* range -HOVER_LOCR to +HOVER_LOCR */
+			randvarsamps = (int)round(traverse * randvar);
+				/* random variation in location is random relative width of current hover-traverse */
+				/* rather than random relative to the total file duration */
+			location += randvarsamps;
+		}
+		if(location < 0)
+			location = 0;
+		if(location >= dz->insams[0])
+			location = dz->insams[0] - 1;
+
+		/* TRAVERSE, RAND VARIATION */
+
+		if(dz->param[HOVER_FRQR] > 0.0) {
+			randvar =  (drand48() * 2.0) - 1.0;		/* range -1 to +1 */
+			randvar *= dz->param[HOVER_FRQR];		/* range -HOVER_FRQR to +HOVER_FRQR */
+			randvarsamps = (int)round(traverse * randvar);
+			traverse = traverse + randvarsamps;
+		}
+		traverse = (int)round(traverse/4);
+		traverse *= 4;
+		if(traverse <4)
+			traverse = 4;
+		quarter_cycle = traverse/4;
+
+		time += (double)traverse/srate;
+		samptime += traverse;
+
+		if(location >= abs_endreadbuf || location < abs_startreadbuf) {
+			abs_startreadbuf = location/F_SECSIZE;
+			abs_startreadbuf *= F_SECSIZE;	/* align new read with sector size */
+			if(abs_startreadbuf > readlimit)
+				abs_startreadbuf = readlimit;
+			if((sndseekEx(dz->ifd[0],abs_startreadbuf,0)<0)){
+				sprintf(errstr,"sndseek() failed\n");
+				return SYSTEM_ERROR;
+			}
+			if((exit_status = read_samps(ibuf,dz))<0)
+				return exit_status;
+			abs_endreadbuf = abs_startreadbuf + dz->ssampsread;
+		}
+		ibufpos = location - abs_startreadbuf;
+
+		//	FIND DOWNWARD ZERO-CROSSING
+
+		done = 0;
+		while(ibuf[ibufpos] <= 0.0) {
+			ibufpos++;
+			if(abs_startreadbuf + ibufpos >= dz->insams[0]) {
+				if(!warned) {
+					sprintf(errstr,"WARNING: Location too close to end of file at time %lf\n",time);
+					fflush(stdout);
+				}
+				warned = 1;
+				done = 1;
+				break;
+			}
+			if(ibufpos >= dz->buflen) {
+				abs_startreadbuf = abs_endreadbuf;
+				if((exit_status = read_samps(ibuf,dz))<0)
+					return exit_status;
+				abs_endreadbuf = abs_startreadbuf + dz->ssampsread;
+			}
+		}
+		if(done)
+			continue;
+		while(ibuf[ibufpos] > 0.0) {
+			ibufpos++;
+			if(abs_startreadbuf + ibufpos >= dz->insams[0]) {
+				if(!warned) {
+					sprintf(errstr,"WARNING: Location too close to end of file at time %lf\n",time);
+					fflush(stdout);
+				}
+				warned = 1;
+				done = 1;
+				break;
+			}
+			if(ibufpos >= dz->buflen) {
+				abs_startreadbuf = abs_endreadbuf;
+				if((exit_status = read_samps(ibuf,dz))<0)
+					return exit_status;
+				abs_endreadbuf = abs_startreadbuf + dz->ssampsread;
+			}
+		}
+		if(done)
+			continue;
+
+		//	DO THE CYCLE
+		for(n = 0;n <= quarter_cycle;n++) {
+			kbuf[n] = ibuf[ibufpos++];
+			if(abs_startreadbuf + ibufpos >= dz->insams[0]) {
+				if(!warned) {
+					sprintf(errstr,"WARNING: Location too close to end of file at time %lf\n",time);
+					fflush(stdout);
+				}
+				warned = 1;
+				done = 1;
+				break;
+			}
+			if(ibufpos >= dz->buflen) {
+				abs_startreadbuf = abs_endreadbuf;
+				if((exit_status = read_samps(ibuf,dz))<0)
+					return exit_status;
+				abs_endreadbuf = abs_startreadbuf + dz->ssampsread;
+			}
+		}
+		if(done)
+			continue;
+		if(dz->vflag[1]) {
+			maxsamp = 0.0;
+			for(m = 0;m <= quarter_cycle;m++)
+				maxsamp = max(fabs(kbuf[m]),maxsamp);
+			if(maxsamp > 0.0) {
+				normaliser = 0.9/maxsamp;
+				for(m = 0;m <= quarter_cycle;m++)
+					kbuf[m] =  (float)(kbuf[m] * normaliser);
+			}
+		}
+//	SMOOTHING INTRODUCED
+		splicelen = min(quarter_cycle/2,hover_splicelen);
+		splincr = 1.0/(double)splicelen;
+		spliceval = 0.0;
+		for(n = 0;n <= splicelen;n++) {
+			kbuf[n] =  (float)(kbuf[n] * spliceval);
+			spliceval = min(spliceval + splincr,1.0);
+		}
+		spliceval = 0;
+		for(n = 0, m = quarter_cycle;n < splicelen;n++,m--) {
+			kbuf[m] =  (float)(kbuf[m] * spliceval);
+			spliceval = min(spliceval + splincr,1.0);
+		}
+		for(n = 0;n <= quarter_cycle;n++) {
+			obuf[obufpos++] = kbuf[n];
+			if(obufpos >= dz->buflen) {
+				if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+					return(exit_status);
+				obufpos = 0;
+			}
+		}
+		n-=2;
+		for(/*n*/; n > 0;n--) {     //RWD don't need to state n here
+			obuf[obufpos++] = kbuf[n];
+			if(obufpos >= dz->buflen) {
+				if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+					return(exit_status);
+				obufpos = 0;
+			}
+		}
+		for(n = 0;n <= quarter_cycle;n++) {
+			obuf[obufpos++] = -kbuf[n];
+			if(obufpos >= dz->buflen) {
+				if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+					return(exit_status);
+				obufpos = 0;
+			}
+		}
+		n-=2;
+		for(/* n */; n > 0;n--) {           //RWD as above
+			obuf[obufpos++] = -kbuf[n];
+			if(obufpos >= dz->buflen) {
+				if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+					return(exit_status);
+				obufpos = 0;
+			}
+		}
+	}
+	if(obufpos > 0) {
+		if((exit_status = write_samps(obuf,obufpos,dz))<0)
+			return(exit_status);
+	}
+	return FINISHED;
+}	
+
+/*************************** CREATE_HOVER2_SNDBUFS **************************/
+
+/* 2009 MULTICHANNEL */
+
+int create_hover2_sndbufs(int maxtraverse,dataptr dz)
+{
+	int n;
+	int bigbufsize;
+	int framesize;
+	framesize = F_SECSIZE * dz->infile->channels;
+	if(dz->sbufptr == 0 || dz->sampbuf==0) {
+		sprintf(errstr,"buffer pointers not allocated: create_sndbufs()\n");
+		return(PROGRAM_ERROR);
+	}
+	bigbufsize = (int)Malloc(-1);
+	bigbufsize /= dz->bufcnt;
+	if(bigbufsize <=0)
+		bigbufsize  = framesize * sizeof(float);
+
+	dz->buflen = bigbufsize / sizeof(float);	
+	dz->buflen = (dz->buflen / framesize) * framesize;
+	if(dz->buflen < maxtraverse) {
+		n = maxtraverse/framesize;
+		if(n * framesize < maxtraverse)
+			n++;
+		dz->buflen = framesize * n;
+	}
+	bigbufsize = dz->buflen * sizeof(float);
+	if(bigbufsize  < 0) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to create sound buffers (minimum Hover rate too low).\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->bufcnt;n++) {
+		if((dz->sampbuf[n] = (float *)malloc(bigbufsize)) == NULL) {
+			switch(n) {
+			case(0):	sprintf(errstr,"INSUFFICIENT MEMORY to create input sound buffer (minimum Hover rate too low).\n");			break;
+			case(1):	sprintf(errstr,"INSUFFICIENT MEMORY to create output sound buffer (minimum Hover rate too low).\n");		break;
+			case(2):	sprintf(errstr,"INSUFFICIENT MEMORY to create calculation sound buffer (minimum Hover rate too low).\n");	break;
+			}
+			return(MEMORY_ERROR);
+		}
+		dz->sbufptr[n] = dz->sampbuf[n];
+	}
+	dz->sampbuf[n] = dz->sampbuf[n-1] + dz->buflen;
+	return(FINISHED);
+}
+
+/**************************** STEPREAD_VALUE_FROM_BRKTABLE *****************************/
+
+int stepread_value_from_brktable(double thistime,int paramno,dataptr dz)
+{
+    double *p;
+	int n;
+	p = dz->brk[paramno];
+	n = 0;
+	while(thistime > *p) {
+		p +=2;
+		n++;
+		if(n >= dz->brksize[paramno])
+			break;
+	}
+	if(n > 0)
+		n--;
+	n *= 2;
+	n++;
+	dz->param[paramno] = dz->brk[paramno][n];
+    return(FINISHED);
+}
+

+ 1059 - 0
dev/standnew/onset.c

@@ -0,0 +1,1059 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <tkglobals.h>
+#include <pnames.h>
+#include <filetype.h>
+#include <processno.h>
+#include <modeno.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <math.h>
+#include <mixxcon.h>
+#include <osbind.h>
+#include <standalone.h>
+#include <ctype.h>
+#include <sfsys.h>
+#include <string.h>
+#include <srates.h>
+
+
+#ifdef unix
+#define round(x) lround((x))
+#endif
+
+char errstr[2400];
+
+int anal_infiles = 1;
+int	sloom = 0;
+int sloombatch = 0;
+
+const char* cdp_version = "6.1.0";
+
+//CDP LIB REPLACEMENTS
+static int setup_onset_application(dataptr dz);
+static int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+static int parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int setup_onset_param_ranges_and_defaults(dataptr dz);
+static int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int establish_application(dataptr dz);
+static int initialise_vflags(dataptr dz);
+static int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int mark_parameter_types(dataptr dz,aplptr ap);
+static int assign_file_data_storage(int infilecnt,dataptr dz);
+static int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+static int get_the_mode_from_cmdline(char *str,dataptr dz);
+static int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt);
+static int onset(dataptr dz);
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status;
+	dataptr dz = NULL;
+	char **cmdline;
+	int  cmdlinecnt;
+	int n;
+	aplptr ap;
+	int is_launched = FALSE;
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+						/* CHECK FOR SOUNDLOOM */
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {					// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc == 2) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+	}
+	if(!sloom) {
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		dz->maxmode = 0;
+		// setup_particular_application =
+		if((exit_status = setup_onset_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+
+	// parse_infile_and_hone_type() = 
+	if((exit_status = parse_infile_and_check_type(cmdline,dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// setup_param_ranges_and_defaults() =
+	if((exit_status = setup_onset_param_ranges_and_defaults(dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// open_first_infile		CDP LIB
+	if((exit_status = open_first_infile(cmdline[0],dz))<0) {	
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);	
+		return(FAILED);
+	}
+	cmdlinecnt--;
+	cmdline++;
+
+//	handle_extra_infiles() : redundant
+	// handle_outfile() = 
+	if((exit_status = handle_the_outfile(&cmdlinecnt,&cmdline,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+//	handle_formants()			redundant
+//	handle_formant_quiksearch()	redundant
+//	handle_special_data()		redundant
+ 
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+//	check_param_validity_and_consistency()	redundant
+	is_launched = TRUE;
+	dz->bufcnt = 1;
+	if((dz->sampbuf = (float **)malloc(sizeof(float *) * (dz->bufcnt+1)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->sbufptr = (float **)malloc(sizeof(float *) * dz->bufcnt))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffer pointers.\n");
+		return(MEMORY_ERROR);
+	}
+	for(n = 0;n <dz->bufcnt; n++)
+		dz->sampbuf[n] = dz->sbufptr[n] = (float *)0;
+	dz->sampbuf[n] = (float *)0;
+
+	if((exit_status = create_sndbufs(dz))<0) {							// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//param_preprocess()						redundant
+	//spec_process_file =
+	if((exit_status = onset(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = complete_output(dz))<0) {										// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);		// CDP LIB
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc, brkcnt;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	brkcnt = tipc;
+	//THERE ARE NO INPUTFILE brktables USED IN THIS PROCESS
+	if(brkcnt>0) {
+		if((exit_status = setup_and_init_input_brktable_constants(dz,brkcnt))<0)			  
+			return(exit_status);
+	}
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+		return(exit_status);
+	
+	// establish_infile_constants() replaced by
+	dz->infilecnt = 1;
+	//establish_bufptrs_and_extra_buffers():
+	return(FINISHED);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}						 		/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_OUTFILE *********************/
+
+int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status;
+	char *filename = (*cmdline)[0];
+	if(!sloom) {
+		if(file_has_invalid_startchar(filename) || value_is_numeric(filename)) {
+			sprintf(errstr,"Outfile name %s has invalid start character(s) or looks too much like a number.\n",filename);
+			return(DATA_ERROR);
+		}
+	}
+	strcpy(dz->outfilename,filename);	   
+	if((exit_status = create_sized_outfile(filename,dz))<0)
+		return(exit_status);
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/************************* SETUP_ONSET_APPLICATION *******************/
+
+int setup_onset_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	// SEE parstruct FOR EXPLANATION of next 2 functions
+	if((exit_status = set_param_data(ap,0   ,1,1,"d"))<0)
+		return(FAILED);
+	if((exit_status = set_vflgs(ap,"",0,"","",0,0,""))<0)
+		return(FAILED);
+	// set_legal_infile_structure -->
+	dz->has_otherfile = FALSE;
+	// assign_process_logic -->
+	dz->input_data_type = SNDFILES_ONLY;
+	dz->process_type	= TO_TEXTFILE;	
+	dz->outfiletype  	= TEXTFILE_OUT;
+	return application_init(dz);	//GLOBAL
+}
+
+/************************* PARSE_INFILE_AND_CHECK_TYPE *******************/
+
+int parse_infile_and_check_type(char **cmdline,dataptr dz)
+{
+	int exit_status;
+	infileptr infile_info;
+	if(!sloom) {
+		if((infile_info = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for infile structure to test file data.");
+			return(MEMORY_ERROR);
+		} else if((exit_status = cdparse(cmdline[0],infile_info))<0) {
+			sprintf(errstr,"Failed to parse input file %s\n",cmdline[0]);
+			return(PROGRAM_ERROR);
+		} else if(infile_info->filetype != SNDFILE)  {
+			sprintf(errstr,"File %s is not of correct type\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if(infile_info->channels < 2)  {
+			sprintf(errstr,"File %s is not of correct type (must be multichannel)\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if((exit_status = copy_parse_info_to_main_structure(infile_info,dz))<0) {
+			sprintf(errstr,"Failed to copy file parsing information\n");
+			return(PROGRAM_ERROR);
+		}
+		free(infile_info);
+	}
+	return(FINISHED);
+}
+
+/************************* SETUP_ONSET_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_onset_param_ranges_and_defaults(dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	// NB total_input_param_cnt is > 0 !!!
+	if((exit_status = setup_input_param_range_stores(ap->total_input_param_cnt,ap))<0)
+		return(FAILED);
+	// get_param_ranges()
+	ap->lo[0]	= FLTERR;
+	ap->hi[0]	= 0.9;
+	ap->default_val[0]	= FLTERR;
+	dz->maxmode = 0;
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_onset_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int read_special_data(char *str,dataptr dz)	
+{
+	return(FINISHED);
+}
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+	usage2("onset");
+	return(USAGE_ONLY);
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if(!strcmp(prog_identifier_from_cmdline,"onset"))				dz->process = ONSET;
+	else {
+		fprintf(stderr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/******************************** SETUP_AND_INIT_INPUT_BRKTABLE_CONSTANTS ********************************/
+
+int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt)
+{	
+	int n;
+	if((dz->brk      = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<brkcnt;n++) {
+		dz->brk[n]     = NULL;
+		dz->brkptr[n]  = NULL;
+		dz->brkinit[n] = 0;
+		dz->brksize[n] = 0;
+	}
+	return(FINISHED);
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+	if(!strcmp(str,"onset")) {
+		fprintf(stderr,
+	    "USAGE:\n"
+	    "onset onset infile outtextfile\n"
+		"\n"
+		"Return the succession of sound-onsets in each channel of a multichannel file.\n"
+		"\n"
+		"ONSETLEVEL  level at which sound onset is recognised.\n"
+		"\n");
+	} else
+		fprintf(stdout,"Unknown option '%s'\n",str);
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	fprintf(stderr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/******************************** ONSET ********************************/
+
+int onset(dataptr dz)
+{
+	int exit_status, chans = dz->infile->channels, k;
+	float *ibuf = dz->sampbuf[0];
+	int n, m, total_samps_read;
+	double found[16], minonset, srate = dz->infile->srate;
+	int minlocation[16], minloc;
+	total_samps_read = 0;
+	for(n = 0; n < chans; n++)
+		found[n] = -1.0;
+	if((exit_status = read_samps(ibuf,dz))<0)
+		return(exit_status);
+	while(dz->ssampsread > 0) {
+		for(n=0;n<dz->ssampsread;n+=chans) {
+			for(k=0;k<chans;k++) {
+				if(found[k] < 0.0) {
+					if(fabs(ibuf[n+k]) > dz->param[0])
+						found[k] = ((double)((total_samps_read + n)/chans)/srate);
+				}
+			}
+		}
+		total_samps_read += dz->ssampsread;
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+	}
+	m = 0;
+	for(n = 0;n < chans; n++) {
+		minonset = HUGE;
+		minloc = -1;
+		for(k=0;k<chans;k++) {
+			if(found[k] >= 0.0) {					//	If an onset has been found in this channel
+				if(found[k] < minonset) {			//	If less than current minonset
+					minonset  = found[k];			//	set minonset to this found-time
+					minloc    = k;					//	note which channel this is on
+				}
+			}
+		}
+		if(minloc >= 0) {							//	If minonset exists 
+			minlocation[m++] = minloc;				//	Store its location
+			found[minloc] = -1.0;					//	and set found for the relevant channel to -1.0
+		}											//	so it is not used in next search for minonset
+	}
+	if(m == 0)
+		fprintf(dz->fp,"NO SIGNAL DETECTED AT ONSET LEVEL %lf\n",dz->param[0]);
+	else {
+		for(n=0;n<m;n++)
+			fprintf(dz->fp,"%d\n",minlocation[n]);
+	}
+	return FINISHED;
+}

+ 1119 - 0
dev/standnew/pairex.c

@@ -0,0 +1,1119 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <tkglobals.h>
+#include <pnames.h>
+#include <filetype.h>
+#include <processno.h>
+#include <modeno.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <math.h>
+#include <mixxcon.h>
+#include <osbind.h>
+#include <standalone.h>
+#include <ctype.h>
+#include <sfsys.h>
+#include <string.h>
+#include <srates.h>
+
+
+#ifdef unix
+#define round(x) lround((x))
+#endif
+
+char errstr[2400];
+
+int anal_infiles = 1;
+int	sloom = 0;
+int sloombatch = 0;
+
+const char* cdp_version = "7.0.0";
+
+//CDP LIB REPLACEMENTS
+static int check_pairex_param_validity_and_consistency(dataptr dz);
+static int setup_pairex_application(dataptr dz);
+static int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+static int parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int setup_pairex_param_ranges_and_defaults(dataptr dz);
+static int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int establish_application(dataptr dz);
+static int initialise_vflags(dataptr dz);
+static int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int mark_parameter_types(dataptr dz,aplptr ap);
+static int assign_file_data_storage(int infilecnt,dataptr dz);
+static int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+static int get_the_mode_from_cmdline(char *str,dataptr dz);
+static int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt);
+static int pairex(dataptr dz);
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status;
+	dataptr dz = NULL;
+	char **cmdline;
+	int  cmdlinecnt, origchans;
+	int n;
+	aplptr ap;
+	int is_launched = FALSE;
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+						/* CHECK FOR SOUNDLOOM */
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {					// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc == 2) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+	}
+	if(!sloom) {
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		// setup_particular_application =
+		if((exit_status = setup_pairex_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+
+	// parse_infile_and_hone_type() = 
+	if((exit_status = parse_infile_and_check_type(cmdline,dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// setup_param_ranges_and_defaults() =
+	if((exit_status = setup_pairex_param_ranges_and_defaults(dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// open_first_infile		CDP LIB
+	if((exit_status = open_first_infile(cmdline[0],dz))<0) {	
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);	
+		return(FAILED);
+	}
+	cmdlinecnt--;
+	cmdline++;
+
+//	handle_extra_infiles() : redundant
+	// handle_outfile() = 
+	origchans = dz->infile->channels;
+	dz->infile->channels = STEREO;
+	if((exit_status = handle_the_outfile(&cmdlinecnt,&cmdline,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	dz->infile->channels = origchans;
+
+//	handle_formants()			redundant
+//	handle_formant_quiksearch()	redundant
+//	handle_special_data()		redundant
+ 
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+//	check_param_validity_and_consistency....
+	if((exit_status = check_pairex_param_validity_and_consistency(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	is_launched = TRUE;
+	dz->bufcnt = 2;
+	if((dz->sampbuf = (float **)malloc(sizeof(float *) * (dz->bufcnt+1)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->sbufptr = (float **)malloc(sizeof(float *) * dz->bufcnt))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffer pointers.\n");
+		return(MEMORY_ERROR);
+	}
+	for(n = 0;n <dz->bufcnt; n++)
+		dz->sampbuf[n] = dz->sbufptr[n] = (float *)0;
+	dz->sampbuf[n] = (float *)0;
+
+	if((exit_status = create_sndbufs(dz))<0) {							// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//param_preprocess()						redundant
+	//spec_process_file =
+	if((exit_status = pairex(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = complete_output(dz))<0) {										// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);		// CDP LIB
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc, brkcnt;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	brkcnt = tipc;
+	//THERE ARE NO INPUTFILE brktables USED IN THIS PROCESS
+	if(brkcnt>0) {
+		if((exit_status = setup_and_init_input_brktable_constants(dz,brkcnt))<0)			  
+			return(exit_status);
+	}
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+		return(exit_status);
+	
+	// establish_infile_constants() replaced by
+	dz->infilecnt = 1;
+	//establish_bufptrs_and_extra_buffers():
+	return(FINISHED);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}						 		/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_OUTFILE *********************/
+
+int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status;
+	char *filename = (*cmdline)[0];
+	if(filename[0]=='-' && filename[1]=='f') {
+		dz->floatsam_output = 1;
+		dz->true_outfile_stype = SAMP_FLOAT;
+		filename+= 2;
+	}
+	if(!sloom) {
+		if(file_has_invalid_startchar(filename) || value_is_numeric(filename)) {
+			sprintf(errstr,"Outfile name %s has invalid start character(s) or looks too much like a number.\n",filename);
+			return(DATA_ERROR);
+		}
+	}
+	strcpy(dz->outfilename,filename);	   
+	if((exit_status = create_sized_outfile(filename,dz))<0)
+		return(exit_status);
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/************************* SETUP_PAIREX_APPLICATION *******************/
+
+int setup_pairex_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	// SEE parstruct FOR EXPLANATION of next 2 functions
+	if((exit_status = set_param_data(ap,0   ,1,1,"i"))<0)
+		return(FAILED);
+	if((exit_status = set_vflgs(ap,"",0,"","",0,0,""))<0)
+		return(FAILED);
+	// set_legal_infile_structure -->
+	dz->has_otherfile = FALSE;
+	// assign_process_logic -->
+	dz->input_data_type = SNDFILES_ONLY;
+	dz->process_type	= UNEQUAL_SNDFILE;	
+	dz->outfiletype  	= SNDFILE_OUT;
+	return application_init(dz);	//GLOBAL
+}
+
+/************************* PARSE_INFILE_AND_CHECK_TYPE *******************/
+
+int parse_infile_and_check_type(char **cmdline,dataptr dz)
+{
+	int exit_status;
+	infileptr infile_info;
+	if(!sloom) {
+		if((infile_info = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for infile structure to test file data.");
+			return(MEMORY_ERROR);
+		} else if((exit_status = cdparse(cmdline[0],infile_info))<0) {
+			sprintf(errstr,"Failed to parse input file %s\n",cmdline[0]);
+			return(PROGRAM_ERROR);
+		} else if(infile_info->filetype != SNDFILE)  {
+			sprintf(errstr,"File %s is not of correct type\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if(infile_info->channels < 3)  {
+			sprintf(errstr,"File %s is not of correct type (must have more than two channels)\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if((exit_status = copy_parse_info_to_main_structure(infile_info,dz))<0) {
+			sprintf(errstr,"Failed to copy file parsing information\n");
+			return(PROGRAM_ERROR);
+		}
+		free(infile_info);
+	}
+	return(FINISHED);
+}
+
+/************************* SETUP_PAIREX_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_pairex_param_ranges_and_defaults(dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	// NB total_input_param_cnt is > 0 !!!
+	if((exit_status = setup_input_param_range_stores(ap->total_input_param_cnt,ap))<0)
+		return(FAILED);
+	// get_param_ranges()
+	ap->lo[0]	= 12;
+	ap->hi[0]	= 87;
+	ap->default_val[0]	= 12;
+	dz->maxmode = 0;
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_pairex_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int read_special_data(char *str,dataptr dz)	
+{
+	return(FINISHED);
+}
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+	usage2("pairex");
+	return(USAGE_ONLY);
+}
+
+/**************************** CHECK_PAIREX_PARAM_VALIDITY_AND_CONSISTENCY *****************************/
+
+int check_pairex_param_validity_and_consistency(dataptr dz)
+{
+	int chan1 = 0, chan2 = 0;
+	switch(dz->iparam[0]) {
+		case(12):	chan1 = 1;	chan2 = 2;	break;
+		case(13):	chan1 = 1;	chan2 = 3;	break;
+		case(14):	chan1 = 1;	chan2 = 4;	break;
+		case(15):	chan1 = 1;	chan2 = 5;	break;
+		case(16):	chan1 = 1;	chan2 = 6;	break;
+		case(17):	chan1 = 1;	chan2 = 7;	break;
+		case(18):	chan1 = 1;	chan2 = 8;	break;
+		case(21):	chan1 = 2;	chan2 = 1;	break;
+		case(23):	chan1 = 2;	chan2 = 3;	break;
+		case(24):	chan1 = 2;	chan2 = 4;	break;
+		case(25):	chan1 = 2;	chan2 = 5;	break;
+		case(26):	chan1 = 2;	chan2 = 6;	break;
+		case(27):	chan1 = 2;	chan2 = 7;	break;
+		case(28):	chan1 = 2;	chan2 = 8;	break;
+		case(31):	chan1 = 3;	chan2 = 1;	break;
+		case(32):	chan1 = 3;	chan2 = 2;	break;
+		case(34):	chan1 = 3;	chan2 = 4;	break;
+		case(35):	chan1 = 3;	chan2 = 5;	break;
+		case(36):	chan1 = 3;	chan2 = 6;	break;
+		case(37):	chan1 = 3;	chan2 = 7;	break;
+		case(38):	chan1 = 3;	chan2 = 8;	break;
+		case(41):	chan1 = 4;	chan2 = 1;	break;
+		case(42):	chan1 = 4;	chan2 = 2;	break;
+		case(43):	chan1 = 4;	chan2 = 3;	break;
+		case(45):	chan1 = 4;	chan2 = 5;	break;
+		case(46):	chan1 = 4;	chan2 = 6;	break;
+		case(47):	chan1 = 4;	chan2 = 7;	break;
+		case(48):	chan1 = 4;	chan2 = 8;	break;
+		case(51):	chan1 = 5;	chan2 = 1;	break;
+		case(52):	chan1 = 5;	chan2 = 2;	break;
+		case(53):	chan1 = 5;	chan2 = 3;	break;
+		case(54):	chan1 = 5;	chan2 = 4;	break;
+		case(56):	chan1 = 5;	chan2 = 6;	break;
+		case(57):	chan1 = 5;	chan2 = 7;	break;
+		case(58):	chan1 = 5;	chan2 = 8;	break;
+		case(61):	chan1 = 6;	chan2 = 1;	break;
+		case(62):	chan1 = 6;	chan2 = 2;	break;
+		case(63):	chan1 = 6;	chan2 = 3;	break;
+		case(64):	chan1 = 6;	chan2 = 4;	break;
+		case(65):	chan1 = 6;	chan2 = 5;	break;
+		case(67):	chan1 = 6;	chan2 = 7;	break;
+		case(68):	chan1 = 6;	chan2 = 8;	break;
+		case(71):	chan1 = 7;	chan2 = 1;	break;
+		case(72):	chan1 = 7;	chan2 = 2;	break;
+		case(73):	chan1 = 7;	chan2 = 3;	break;
+		case(74):	chan1 = 7;	chan2 = 4;	break;
+		case(75):	chan1 = 7;	chan2 = 5;	break;
+		case(76):	chan1 = 7;	chan2 = 6;	break;
+		case(78):	chan1 = 7;	chan2 = 8;	break;
+		case(81):	chan1 = 8;	chan2 = 1;	break;
+		case(82):	chan1 = 8;	chan2 = 2;	break;
+		case(83):	chan1 = 8;	chan2 = 3;	break;
+		case(84):	chan1 = 8;	chan2 = 4;	break;
+		case(85):	chan1 = 8;	chan2 = 5;	break;
+		case(86):	chan1 = 8;	chan2 = 6;	break;
+		case(87):	chan1 = 8;	chan2 = 7;	break;
+		default:
+			sprintf(errstr,"INVALID CHANNEL PAIR %d\n",dz->iparam[0]);
+			return(DATA_ERROR);
+	}
+	if((chan1 > dz->infile->channels) || (chan1 > dz->infile->channels)) { 
+		sprintf(errstr,"INVALID CHANNEL PAIR %d FOR A FILE WITH ONLY %d CHANNELS\n",dz->iparam[0],dz->infile->channels);
+		return(DATA_ERROR);
+	}
+	dz->iparam[0] = chan1 - 1;
+	dz->itemcnt   = chan2 - 1;
+	return(FINISHED);
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if(!strcmp(prog_identifier_from_cmdline,"pairex"))				dz->process = PAIREX;
+	else {
+		sprintf(errstr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/******************************** SETUP_AND_INIT_INPUT_BRKTABLE_CONSTANTS ********************************/
+
+int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt)
+{	
+	int n;
+	if((dz->brk      = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<brkcnt;n++) {
+		dz->brk[n]     = NULL;
+		dz->brkptr[n]  = NULL;
+		dz->brkinit[n] = 0;
+		dz->brksize[n] = 0;
+	}
+	return(FINISHED);
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+	if(!strcmp(str,"pairex")) {
+		fprintf(stderr,
+	    "USAGE:\n"
+	    "pairex pairex infile outfile pair\n"
+		"\n"
+		"Extract any pair of channels from a multichannel sound.\n"
+		"\n"
+		"PAIR : the channel numbers of the 2 channels to be extracted as a stereo pair.\n"
+		"\n");
+	} else
+		fprintf(stdout,"Unknown option '%s'\n",str);
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	fprintf(stderr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/******************************** PAIREX ********************************/
+
+int pairex(dataptr dz)
+{
+	int exit_status, chans = dz->infile->channels;
+	int chan1 = dz->iparam[0], chan2 = dz->itemcnt, n, L, R;
+	float *ibuf = dz->sampbuf[0], *obuf = dz->sampbuf[1];
+
+	if((exit_status = read_samps(ibuf,dz))<0)
+		return(exit_status);
+	while(dz->ssampsread > 0) {
+		n = 0;
+		chan1 = dz->iparam[0];
+		chan2 = dz->itemcnt;
+		for(n=0,L=0,R=1;n<dz->ssampsread;n+=chans,L+=2,R+=2) {
+			obuf[L] = ibuf[n + chan1];
+			obuf[R] = ibuf[n + chan2];
+		}
+		if((exit_status = write_samps(obuf,L,dz))<0)
+			return(exit_status);
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+	}
+	return FINISHED;
+}

+ 1343 - 0
dev/standnew/partition.c

@@ -0,0 +1,1343 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <tkglobals.h>
+#include <pnames.h>
+#include <filetype.h>
+#include <processno.h>
+#include <modeno.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <math.h>
+#include <mixxcon.h>
+#include <osbind.h>
+#include <standalone.h>
+#include <ctype.h>
+#include <sfsys.h>
+#include <string.h>
+#include <srates.h>
+
+#define PARTITION_SPLEN	(3)	// mS
+
+#define IN_READ		(1)
+#define IN_UPSPLICE	(2)
+#define IN_DNSPLICE	(3)
+#define IN_SKIP		(4)
+
+#ifdef unix
+#define round(x) lround((x))
+#endif
+
+char errstr[2400];
+
+int anal_infiles = 1;
+int	sloom = 0;
+int sloombatch = 0;
+
+const char* cdp_version = "7.0.0";
+
+//CDP LIB REPLACEMENTS
+static int check_partition_param_validity_and_consistency(dataptr dz);
+static int setup_partition_application(dataptr dz);
+static int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+static int parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int setup_partition_param_ranges_and_defaults(dataptr dz);
+static int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int establish_application(dataptr dz);
+static int initialise_vflags(dataptr dz);
+static int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int mark_parameter_types(dataptr dz,aplptr ap);
+static int assign_file_data_storage(int infilecnt,dataptr dz);
+static int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+static int get_the_mode_from_cmdline(char *str,dataptr dz);
+static int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt);
+static int partition(dataptr dz);
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status;
+	dataptr dz = NULL;
+	char **cmdline;
+	int  cmdlinecnt;
+	int n;
+	aplptr ap;
+	int is_launched = FALSE;
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+						/* CHECK FOR SOUNDLOOM */
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {					// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc == 2) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+	}
+	if(!sloom) {
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		dz->maxmode = 2;
+		if((exit_status = get_the_mode_from_cmdline(cmdline[0],dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);
+		}
+		cmdline++;
+		cmdlinecnt--;
+		// setup_particular_application =
+		if((exit_status = setup_partition_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+
+	// parse_infile_and_hone_type() = 
+	if((exit_status = parse_infile_and_check_type(cmdline,dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// setup_param_ranges_and_defaults() =
+	if((exit_status = setup_partition_param_ranges_and_defaults(dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// open_first_infile		CDP LIB
+	if((exit_status = open_first_infile(cmdline[0],dz))<0) {	
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);	
+		return(FAILED);
+	}
+	cmdlinecnt--;
+	cmdline++;
+
+//	handle_extra_infiles() : redundant
+	// handle_outfile() = 
+	if((exit_status = handle_the_outfile(&cmdlinecnt,&cmdline,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+//	handle_formants()			redundant
+//	handle_formant_quiksearch()	redundant
+//	handle_special_data()		redundant
+ 
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+//	check_param_validity_and_consistency....
+	if((exit_status = check_partition_param_validity_and_consistency(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	is_launched = TRUE;
+	dz->bufcnt = 2;
+	if((dz->sampbuf = (float **)malloc(sizeof(float *) * (dz->bufcnt+1)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->sbufptr = (float **)malloc(sizeof(float *) * dz->bufcnt))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffer pointers.\n");
+		return(MEMORY_ERROR);
+	}
+	for(n = 0;n <dz->bufcnt; n++)
+		dz->sampbuf[n] = dz->sbufptr[n] = (float *)0;
+	dz->sampbuf[n] = (float *)0;
+
+	if((exit_status = create_sndbufs(dz))<0) {							// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//param_preprocess()						redundant
+	//spec_process_file =
+	if((exit_status = partition(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = complete_output(dz))<0) {										// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);		// CDP LIB
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc, brkcnt;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	brkcnt = tipc;
+	//THERE ARE NO INPUTFILE brktables USED IN THIS PROCESS
+	if(brkcnt>0) {
+		if((exit_status = setup_and_init_input_brktable_constants(dz,brkcnt))<0)			  
+			return(exit_status);
+	}
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+		return(exit_status);
+	
+	// establish_infile_constants() replaced by
+	dz->infilecnt = 1;
+	//establish_bufptrs_and_extra_buffers():
+	return(FINISHED);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}						 		/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_OUTFILE *********************/
+
+int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status, n;
+	char *filename = (*cmdline)[0], temp[200], *p;
+	if(filename[0]=='-' && filename[1]=='f') {
+		dz->floatsam_output = 1;
+		dz->true_outfile_stype = SAMP_FLOAT;
+		filename+= 2;
+	}
+	if(!sloom) {
+		if(file_has_invalid_startchar(filename) || value_is_numeric(filename)) {
+			sprintf(errstr,"Outfile name %s has invalid start character(s) or looks too much like a number.\n",filename);
+			return(DATA_ERROR);
+		}
+	}
+	strcpy(dz->outfilename,filename);
+	p = dz->outfilename;
+	while(*p != ENDOFSTR) {
+		if(*p == '.') {
+			*p = ENDOFSTR;
+			break;
+		}
+		p++;
+	}
+	strcpy(temp,dz->outfilename);
+	if(!sloom)
+		strcat(temp,"0");
+	else {
+		n = strlen(dz->outfilename);
+		n--;
+		dz->outfilename[n] = ENDOFSTR;
+	}
+	strcat(temp,".wav");
+	if((exit_status = create_sized_outfile(temp,dz))<0)
+		return(exit_status);
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/************************* SETUP_PARTITION_APPLICATION *******************/
+
+int setup_partition_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	// SEE parstruct FOR EXPLANATION of next 2 functions
+	switch(dz->mode) {
+	case(0):
+		if((exit_status = set_param_data(ap,0   ,2,2,"ii"))<0)
+				return(FAILED);
+		if((exit_status = set_vflgs(ap,"",0,"","",0,0,""))<0)
+			return(FAILED);
+		break;
+	case(1):
+		if((exit_status = set_param_data(ap,0   ,2,2,"id"))<0)
+				return(FAILED);
+		if((exit_status = set_vflgs(ap,"",0,"","rs",2,2,"dd"))<0)
+			return(FAILED);
+		break;
+	}
+	// set_legal_infile_structure -->
+	dz->has_otherfile = FALSE;
+	// assign_process_logic -->
+	dz->input_data_type = SNDFILES_ONLY;
+	dz->process_type	= EQUAL_SNDFILE;	
+	dz->outfiletype  	= SNDFILE_OUT;
+	return application_init(dz);	//GLOBAL
+}
+
+/************************* PARSE_INFILE_AND_CHECK_TYPE *******************/
+
+int parse_infile_and_check_type(char **cmdline,dataptr dz)
+{
+	int exit_status;
+	infileptr infile_info;
+	if(!sloom) {
+		if((infile_info = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for infile structure to test file data.");
+			return(MEMORY_ERROR);
+		} else if((exit_status = cdparse(cmdline[0],infile_info))<0) {
+			sprintf(errstr,"Failed to parse input file %s\n",cmdline[0]);
+			return(PROGRAM_ERROR);
+		} else if(infile_info->filetype != SNDFILE)  {
+			sprintf(errstr,"File %s is not of correct type\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if(infile_info->channels != 1)  {
+			sprintf(errstr,"File %s is not of correct type (must be mono)\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if((exit_status = copy_parse_info_to_main_structure(infile_info,dz))<0) {
+			sprintf(errstr,"Failed to copy file parsing information\n");
+			return(PROGRAM_ERROR);
+		}
+		free(infile_info);
+	}
+	return(FINISHED);
+}
+
+/************************* SETUP_PARTITION_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_partition_param_ranges_and_defaults(dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	// NB total_input_param_cnt is > 0 !!!
+	if((exit_status = setup_input_param_range_stores(ap->total_input_param_cnt,ap))<0)
+		return(FAILED);
+	// get_param_ranges()
+	ap->lo[0]	= 2;
+	ap->hi[0]	= 256;
+	ap->default_val[0] = 8;
+	switch(dz->mode) {
+	case(0):
+		ap->lo[1]	= 1;
+		ap->hi[1]	= 1024;
+		ap->default_val[1]	= 1;
+		break;
+	case(1):
+		ap->lo[1]	= 0.01;
+		ap->hi[1]	= dz->duration;
+		ap->default_val[1]	= 0.1;
+		ap->lo[2]	= 0.0;
+		ap->hi[2]	= 1.0;
+		ap->default_val[2]	= 0.0;
+		ap->lo[3]	= 0.0;
+		ap->hi[3]	= 50.0;
+		ap->default_val[3]	= 3.0;
+		break;
+	}
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_partition_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int read_special_data(char *str,dataptr dz)	
+{
+	return(FINISHED);
+}
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+	usage2("partition");
+	return(USAGE_ONLY);
+}
+
+/**************************** CHECK_PARTITION_PARAM_VALIDITY_AND_CONSISTENCY *****************************/
+
+int check_partition_param_validity_and_consistency(dataptr dz)
+{
+	int maxblock;
+	if(dz->mode == 1) {
+		dz->iparam[1] = (int)round(dz->param[1] * (double)dz->infile->srate);
+		maxblock = (int)floor(dz->insams[0]/dz->iparam[0]);
+		dz->iparam[0] = min(dz->iparam[0],maxblock);
+	}
+	return FINISHED;
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if(!strcmp(prog_identifier_from_cmdline,"partition"))				dz->process = PARTITION;
+	else {
+		sprintf(errstr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/******************************** SETUP_AND_INIT_INPUT_BRKTABLE_CONSTANTS ********************************/
+
+int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt)
+{	
+	int n;
+	if((dz->brk      = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<brkcnt;n++) {
+		dz->brk[n]     = NULL;
+		dz->brkptr[n]  = NULL;
+		dz->brkinit[n] = 0;
+		dz->brksize[n] = 0;
+	}
+	return(FINISHED);
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+	if(!strcmp(str,"partition")) {
+		fprintf(stdout,
+	    "USAGE:\n"
+	    "partition partition 1 infile outnam outcnt groupcnt\n"
+		"\n"
+		"Partition mono sound file into disjunct files\n"
+		"in blocks defined by groups of wavesets.\n"
+		"\n"
+		"OR\n"
+	    "partition partition 2 infile outnam outcnt dur [-rrand] [-ssplice]\n"
+		"\n"
+		"Partition mono sound file into disjunct files\n"
+		"in blocks defined by duration.\n"
+		"\n"
+		"For input file \"abcdefghijklmno....\" and 3 output files\n"
+		"(where \"a\",\"b\" etc are successive blocks), we produce\n"
+		"\n"
+		"Outfile1 \"a--d--g--j--m--...\n"
+		"Outfile2 \"-b--e--h--k--n-...\n"
+		"Outfile3 \"--c--f--i--l--o...\n"
+		"\n"
+		"where \"-\" is silence replacing the missing blocks.\n"
+		"\n"
+		"OUTNAM   is generic name of the output files.\n"
+		"OUTCNT   is the number of output files.\n"
+		"\n"
+		"The duration of the blocks sent to the outfiles is either\n"
+		"\n"
+		"GROUPCNT Number of wavesets per block, OR\n"
+		"DUR      Duration, in seconds, per block, where\n"
+		"         block-duration must be short enough to allow\n"
+		"         at least 1 block to be sent to every output file.\n"
+		"         (if too large, dur will be reduced appropriately).\n"
+		"\n"
+		"RAND     is randomsation of durations (only) (range 0-1).\n" 
+		"SPLICE   Splice length in mS: default 3mS.\n" 
+		"\n");
+	} else
+		fprintf(stdout,"Unknown option '%s'\n",str);
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	fprintf(stderr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/******************************** PARTITION ********************************
+ *
+ * Logic of splices in mode 1:
+ *
+ *			 s			  s
+ *			 p			  p
+ *			|l|			 |l|
+ *  readlen |e|	skiplen	 |e|
+ *	________ n			  n	________	Skiplen = 2 * readlen (for the 2 other files)
+ *	        \			   /		\	minus splen(down)
+ *	         \			  /			 \	minus splen (up)
+ *	        ________
+ *	       /		\					BUT: as there's no upsplice at file start
+ *        /			 \					Initial skiplen (ONLY) is shorter by 1 skiplen.
+ *			        ________
+ *				   /		\
+ *				 /			 \
+ */
+ 
+int partition(dataptr dz)
+{
+	int exit_status, outfileno, initphase = 0, phase = 0, wavcnt = 0, gpcnt = 0, sampcnt;
+	int splen = 0, readlen = 0, skiplen = 0, start = 1, sampgpcnt = 0, edflag = IN_SKIP;
+	double splincr = 0.0, rr;
+	int chunkcnt = 0, n = 0, readcnt = 0;
+	int outfilecnt = dz->iparam[0], wavgrpcnt  = dz->iparam[1];
+	char filename[200], thisnum[8];
+	float *ibuf = dz->sampbuf[0];
+	float *obuf = dz->sampbuf[1];
+	int *read_len = NULL;
+	if(dz->mode == 1) {
+		splen = (int)floor(dz->param[3] * MS_TO_SECS * (double)dz->infile->srate);
+		splincr = 1.0/(double)splen;
+		readlen = dz->iparam[1];
+		skiplen = (dz->iparam[0] - 1) * readlen;	/* skip over any blocks going to other outfiles */
+		skiplen -= (2 * splen);						/* skip back over endsplice and startsplice */
+		readcnt = dz->insams[0]/dz->iparam[1];
+		readcnt *= 3;	// SAFETY
+		if((read_len = (int *)malloc(readcnt * sizeof(double)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for read lengths store.\n");
+			return(MEMORY_ERROR);
+		}
+		if(dz->param[2] > 0.0) {
+			for(chunkcnt = 0; chunkcnt < readcnt; chunkcnt++) {
+				rr = ((drand48() * 2) - 1.0) * 0.5;								/* range -1/2 to 1/2	 */
+				rr *= dz->param[2];												/* range <= -1/2 to +1/2 */
+				read_len[chunkcnt] = (int)ceil((double)readlen * (1.0 + rr));	/* range <= readlen/2 to [readlen + readlen/2] */
+			}
+		} else {
+			for(chunkcnt = 0; chunkcnt < readcnt; chunkcnt++)
+				read_len[chunkcnt] = readlen;
+		}
+
+	}
+	for(outfileno = 0;outfileno < outfilecnt;outfileno++) {
+		if(outfileno > 0) {
+			if(sndcloseEx(dz->ofd) < 0) {
+				sprintf(errstr,"Failed to close output file %d\n",outfileno+1);
+				return(SYSTEM_ERROR);
+			}
+			strcpy(filename,dz->outfilename);
+			sprintf(thisnum,"%d",outfileno);
+			strcat(filename,thisnum);
+			strcat(filename,".wav");
+			if((exit_status = create_sized_outfile(filename,dz))<0)
+				return(exit_status);
+			sndseekEx(dz->ifd[0],0,0);
+			reset_filedata_counters(dz);
+		}
+		switch(dz->mode) {
+		case(0):
+			initphase = 0;
+			phase = 0;
+			wavcnt = 0;
+			gpcnt = 0;
+			break;
+		case(1):
+			start = 1;		//	Flag we're at start of outfile
+			if(outfileno == 0)
+				edflag = IN_READ;
+			else
+				edflag = IN_SKIP;
+			sampgpcnt = 0;
+			chunkcnt = 0;			//	Reads through array of cut lengths
+			break;
+		}
+		while(dz->total_samps_read < dz->insams[0]) {
+			memset((char *)(obuf),0,dz->buflen * sizeof(float));
+			if((exit_status = read_samps(ibuf,dz)) < 0) 
+				return(exit_status);
+			if(dz->ssampsread == 0)
+				break;
+			switch(dz->mode) {
+			case(0):
+				for(sampcnt = 0; sampcnt < dz->ssampsread; sampcnt++) {
+					if(gpcnt % outfilecnt == outfileno)		/* if count of waveset groups is %= to output file no, write input to output */
+						obuf[sampcnt] = ibuf[sampcnt];
+					if(initphase == 0) {
+						if(ibuf[sampcnt] == 0.0)			/* Search for initial phase of signal */
+							continue;
+						else if(ibuf[sampcnt] <= 0.0) {
+							initphase = -1;					/* Note initial_phase, and set phase */
+							phase     = -1;
+						} else {
+							initphase = 1;
+							phase     = 1;
+						}
+					}										/* How wavesets are counted depends on initial phase */	
+					switch(initphase) {
+					case(-1):								/* with initial phase -ve */
+						switch(phase) {
+						case(-1):
+							if(ibuf[sampcnt] > 0.0)			/* If wave crosses zero, change phase */
+								phase = 1;
+							break;
+						case(1):
+							if(ibuf[sampcnt] <= 0.0) {		/* if phase recrosses zero, count the waveset */
+								phase = -1;
+								wavcnt++;
+							}
+							break;
+						}
+						break;
+					case(1):								/* Similarly for initial phase +ve */
+						switch(phase) {
+						case(1):
+							if(ibuf[sampcnt] <= 0.0)
+								phase = -1;
+							break;
+						case(-1):
+							if(ibuf[sampcnt] > 0.0) {
+								phase = 1;
+								wavcnt++;
+							}
+							break;
+						}
+						break;
+					}
+					if(wavcnt == wavgrpcnt) {				/* if counted a group-full of wavesets */
+						gpcnt++;							/* increment the groupcount */
+						wavcnt = 0;
+					}
+				}
+				break;
+			case(1):
+				if(start == 1) {				/* At start of each file */
+					skiplen = 0;				/* set initial skiplen */
+					for(n=0;n<outfileno;n++)	/* by adding lengths of all files to be skipped */
+						skiplen += read_len[n]; 
+					skiplen -= splen;			/* then backtrack by length of upsplice (pre full-level-read) */
+					start = 0;					/* and avoid doing this again by zeroing flag!! */
+				}								/* Note that file 0 gets a skip of -splen, BUT it starts in IN_READ mode */
+												/* so NO initial skip required: its 1st skip is set AFTER 1st read done */
+				for(sampcnt = 0; sampcnt < dz->ssampsread; sampcnt++) {
+					switch(edflag) {
+					case(IN_UPSPLICE):
+						obuf[sampcnt] = (float)((double)sampgpcnt * splincr * ibuf[sampcnt]);
+						if(++sampgpcnt >= splen) {
+							sampgpcnt = 0;
+							edflag = IN_READ;
+						}
+						break;
+					case(IN_READ):
+						obuf[sampcnt] = ibuf[sampcnt];
+						if(++sampgpcnt >= read_len[chunkcnt]) {	/* after any read completed */
+							skiplen = 0;						/* SET THE NEXT SKIPLEN */
+							for(n=1;n<outfilecnt;n++) {			/* add together successive read_lens to be skipped */
+								chunkcnt++;
+								skiplen += read_len[chunkcnt];
+							}									/* then backtrack by the length of downsplice on end of last read */
+							skiplen -= 2 * splen;				/* and by length of upsplice, as start upsplice is before read onset. */
+							chunkcnt++;							/* Finally go to next read_len to be used. */
+							sampgpcnt = 0;
+							edflag = IN_DNSPLICE;
+						}
+						break;
+					case(IN_DNSPLICE):
+						obuf[sampcnt] = (float)((1.0 - ((double)sampgpcnt * splincr)) * ibuf[sampcnt]);
+						if(++sampgpcnt >= splen) {
+							sampgpcnt = 0;
+							edflag = IN_SKIP;
+						}
+						break;
+					case(IN_SKIP):
+						if(++sampgpcnt >= skiplen) {
+							sampgpcnt = 0;
+							edflag = IN_UPSPLICE;
+						}
+						break;
+					}
+				}
+				break;
+			}
+			if((exit_status = write_samps(obuf,dz->ssampsread,dz))<0)
+				return(exit_status);
+		}
+	}
+	return FINISHED;
+}
+
+/****************************** GET_MODE *********************************/
+
+int get_the_mode_from_cmdline(char *str,dataptr dz)
+{
+	char temp[200], *p;
+	if(sscanf(str,"%s",temp)!=1) {
+		sprintf(errstr,"Cannot read mode of program.\n");
+		return(USAGE_ONLY);
+	}
+	p = temp + strlen(temp) - 1;
+	while(p >= temp) {
+		if(!isdigit(*p)) {
+			fprintf(stderr,"Invalid mode of program entered.\n");
+			return(USAGE_ONLY);
+		}
+		p--;
+	}
+	if(sscanf(str,"%d",&dz->mode)!=1) {
+		fprintf(stderr,"Cannot read mode of program.\n");
+		return(USAGE_ONLY);
+	}
+	if(dz->mode <= 0 || dz->mode > dz->maxmode) {
+		fprintf(stderr,"Program mode value [%d] is out of range [1 - %d].\n",dz->mode,dz->maxmode);
+		return(USAGE_ONLY);
+	}
+	dz->mode--;		/* CHANGE TO INTERNAL REPRESENTATION OF MODE NO */
+	return(FINISHED);
+}
+

+ 1497 - 0
dev/standnew/phasor.c

@@ -0,0 +1,1497 @@
+/* GO TO HEREH
+ *
+ * The write procedure not quite correct when there is offset.
+ * Need to write to obuf UP to the "maxoffset"
+ * BUT advance the obufotr only up to end of "towrite" WITHOUT the offset.
+ * and ONLY WRITE TO FILE when obfptr is AT or BEYOND buflen AT ~START~ OF THE WRITE
+ * (not simply when the write itself will overflow the buflen)
+ *
+ * Probably also need to extend obuf by another buflen.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <tkglobals.h>
+#include <pnames.h>
+#include <filetype.h>
+#include <processno.h>
+#include <modeno.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <math.h>
+#include <mixxcon.h>
+#include <osbind.h>
+#include <standalone.h>
+#include <ctype.h>
+#include <sfsys.h>
+#include <string.h>
+#include <srates.h>
+
+#ifdef unix
+#define round(x) lround((x))
+#endif
+
+char errstr[2400];
+
+#define ibuflen itemcnt
+
+int anal_infiles = 1;
+int	sloom = 0;
+int sloombatch = 0;
+
+const char* cdp_version = "6.1.0";
+
+#define MAXOUTLEVEL (0.95)
+#define WRAP (16)					//	wraparound extension of input buffer to allow for interpolated reading of last sample
+#define SAFETY (64)					//	Avoid overwriting end of arrays
+
+#define SIGNAL_TO_LEFT  (0)
+#define SIGNAL_TO_RIGHT (1)
+#define ROOT2		(1.4142136)
+
+#define maxoffset	total_windows	//	max time-offset of streams
+#define outchinfo	is_mapping		//	lowest array number holding output-channel-info for each stream
+
+//CDP LIB REPLACEMENTS
+static int check_phasor_param_validity_and_consistency(double *maxoffset,dataptr dz);
+static int setup_phasor_application(dataptr dz);
+static int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+static int parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int setup_phasor_param_ranges_and_defaults(dataptr dz);
+static int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int open_the_outfile(dataptr dz);
+static int setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int establish_application(dataptr dz);
+static int initialise_vflags(dataptr dz);
+static int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int mark_parameter_types(dataptr dz,aplptr ap);
+static int assign_file_data_storage(int infilecnt,dataptr dz);
+static int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+static int get_the_mode_from_cmdline(char *str,dataptr dz);
+static int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt);
+static int create_phasor_sndbufs(int maxshiftslen,double maxoffset,int *offsetwrap,dataptr dz);
+static int create_phaseshift_and_outchan_data_arrays(int *maxshiftslen, dataptr dz);
+static int calculate_phase_shifts(double time, int *phaseshiftcnt, dataptr dz);
+static int calculate_streams(double time,int phaseshiftcnt, int *obufpos, int *ibufpos, int passno, double normaliser, double *maxsamp,int offsetwrap,int * absolute_endofwrite,dataptr dz);
+static void pancalc(double position,double *leftgain,double *rightgain);
+static int phasor(int offsetwrap,dataptr dz);
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status;
+	dataptr dz = NULL;
+	char **cmdline;
+	int  cmdlinecnt;
+	int n, maxshiftslen = 0, offsetwrap = 0;
+	double maxoffset = 0.0;
+	aplptr ap;
+	int is_launched = FALSE;
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+						/* CHECK FOR SOUNDLOOM */
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {					// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc == 2) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+	}
+	if(!sloom) {
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		dz->maxmode = 0;
+		// setup_particular_application =
+		if((exit_status = setup_phasor_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+
+	// parse_infile_and_hone_type() = 
+	if((exit_status = parse_infile_and_check_type(cmdline,dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// setup_param_ranges_and_defaults() =
+	if((exit_status = setup_phasor_param_ranges_and_defaults(dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// open_first_infile		CDP LIB
+	if((exit_status = open_first_infile(cmdline[0],dz))<0) {	
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);	
+		return(FAILED);
+	}
+	cmdlinecnt--;
+	cmdline++;
+	dz->duration = (double)dz->insams[0]/(double)dz->infile->srate;
+
+//	handle_extra_infiles() : redundant
+	// handle_outfile() = 
+	if((exit_status = handle_the_outfile(&cmdlinecnt,&cmdline,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+//	handle_formants()			redundant
+//	handle_formant_quiksearch()	redundant
+//	handle_special_data()		redundant
+ 
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+//	check_param_validity_and_consistency....
+	if((exit_status = check_phasor_param_validity_and_consistency(&maxoffset,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = open_the_outfile(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = create_phaseshift_and_outchan_data_arrays(&maxshiftslen,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	is_launched = TRUE;
+	dz->bufcnt = 3;
+	if((dz->sampbuf = (float **)malloc(sizeof(float *) * (dz->bufcnt+1)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->sbufptr = (float **)malloc(sizeof(float *) * dz->bufcnt))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffer pointers.\n");
+		return(MEMORY_ERROR);
+	}
+	for(n = 0;n <dz->bufcnt; n++)
+		dz->sampbuf[n] = dz->sbufptr[n] = (float *)0;
+	dz->sampbuf[n] = (float *)0;
+
+	if((exit_status = create_phasor_sndbufs(maxshiftslen,maxoffset,&offsetwrap,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//param_preprocess()						redundant
+	//spec_process_file =
+	if((exit_status = phasor(offsetwrap,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = complete_output(dz))<0) {										// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);		// CDP LIB
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc, brkcnt;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	brkcnt = tipc;
+	//THERE ARE NO INPUTFILE brktables USED IN THIS PROCESS
+	if(brkcnt>0) {
+		if((exit_status = setup_and_init_input_brktable_constants(dz,brkcnt))<0)			  
+			return(exit_status);
+	}
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+		return(exit_status);
+	
+	// establish_infile_constants() replaced by
+	dz->infilecnt = 1;
+	//establish_bufptrs_and_extra_buffers():
+	return(FINISHED);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}						 		/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_OUTFILE *********************/
+
+int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	char *filename = (*cmdline)[0];
+	if(filename[0]=='-' && filename[1]=='f') {
+		dz->floatsam_output = 1;
+		dz->true_outfile_stype = SAMP_FLOAT;
+		filename+= 2;
+	}
+	if(!sloom) {
+		if(file_has_invalid_startchar(filename) || value_is_numeric(filename)) {
+			sprintf(errstr,"Outfile name %s has invalid start character(s) or looks too much like a number.\n",filename);
+			return(DATA_ERROR);
+		}
+	}
+	strcpy(dz->outfilename,filename);	   
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/************************ OPEN_THE_OUTFILE *********************/
+
+int open_the_outfile(dataptr dz)
+{
+	int exit_status, origchans;
+	origchans = dz->infile->channels;
+	dz->infile->channels = dz->iparam[PHASOR_OCHANS];
+	if((exit_status = create_sized_outfile(dz->outfilename,dz))<0)
+		return(exit_status);
+	dz->infile->channels = origchans;
+	dz->outfile->channels = dz->iparam[PHASOR_OCHANS];
+	return(FINISHED);
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/************************* SETUP_PHASOR_APPLICATION *******************/
+
+int setup_phasor_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	// SEE parstruct FOR EXPLANATION of next 2 functions
+	if((exit_status = set_param_data(ap,0   ,4,4,"iDDi"))<0)
+		return(FAILED);
+	if((exit_status = set_vflgs(ap,"o",1,"d","se",2,0,"00"))<0)
+		return(FAILED);
+	// set_legal_infile_structure -->
+	dz->has_otherfile = FALSE;
+	// assign_process_logic -->
+	dz->input_data_type = SNDFILES_ONLY;
+	dz->process_type	= UNEQUAL_SNDFILE;	
+	dz->outfiletype  	= SNDFILE_OUT;
+	return application_init(dz);	//GLOBAL
+}
+
+/************************* PARSE_INFILE_AND_CHECK_TYPE *******************/
+
+int parse_infile_and_check_type(char **cmdline,dataptr dz)
+{
+	int exit_status;
+	infileptr infile_info;
+	if(!sloom) {
+		if((infile_info = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for infile structure to test file data.");
+			return(MEMORY_ERROR);
+		} else if((exit_status = cdparse(cmdline[0],infile_info))<0) {
+			sprintf(errstr,"Failed to parse input file %s\n",cmdline[0]);
+			return(PROGRAM_ERROR);
+		} else if(infile_info->filetype != SNDFILE)  {
+			sprintf(errstr,"File %s is not of correct type\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if(infile_info->channels != 1)  {
+			sprintf(errstr,"File %s is not of correct type (must be mono)\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if((exit_status = copy_parse_info_to_main_structure(infile_info,dz))<0) {
+			sprintf(errstr,"Failed to copy file parsing information\n");
+			return(PROGRAM_ERROR);
+		}
+		free(infile_info);
+	}
+	return(FINISHED);
+}
+
+/************************* SETUP_GATE_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_phasor_param_ranges_and_defaults(dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	// NB total_input_param_cnt is > 0 !!!
+	if((exit_status = setup_input_param_range_stores(ap->total_input_param_cnt,ap))<0)
+		return(FAILED);
+	// get_param_ranges()
+	
+	ap->lo[PHASOR_STREAMS]	= 2;
+	ap->hi[PHASOR_STREAMS]	= 8;
+	ap->default_val[PHASOR_STREAMS]	= 2;
+	
+	ap->lo[PHASOR_FRQ]	= .01;
+	ap->hi[PHASOR_FRQ]	= 100;
+	ap->default_val[PHASOR_FRQ]	= 1;
+	
+	ap->lo[PHASOR_SHIFT]	= 0;
+	ap->hi[PHASOR_SHIFT]	= 12;
+	ap->default_val[PHASOR_SHIFT] = .5;
+	
+	ap->lo[PHASOR_OCHANS]	= 1;
+	ap->hi[PHASOR_OCHANS]	= 8;
+	ap->default_val[PHASOR_OCHANS] = 1;
+	
+	ap->lo[PHASOR_OFFSET]	= 0;
+	ap->hi[PHASOR_OFFSET]	= 500;
+	ap->default_val[PHASOR_OFFSET] = 0;
+
+	dz->maxmode = 0;
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_phasor_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int read_special_data(char *str,dataptr dz)	
+{
+	return(FINISHED);
+}
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+	usage2("phasor");
+	return(USAGE_ONLY);
+}
+
+/**************************** CHECK_GATE_PARAM_VALIDITY_AND_CONSISTENCY *****************************/
+
+int check_phasor_param_validity_and_consistency(double *maxoffset,dataptr dz)
+{
+	int exit_status;
+	if(dz->iparam[PHASOR_OCHANS] > dz->iparam[PHASOR_STREAMS]) {
+		sprintf(errstr,"Number of output channels exceeds number of streams.\n");
+		return(DATA_ERROR);
+	}
+	if(dz->brksize[PHASOR_OFFSET]) {
+		if((exit_status = get_maxvalue_in_brktable(maxoffset,PHASOR_OFFSET,dz))<0)
+			return exit_status;
+	} else
+		*maxoffset = dz->param[PHASOR_OFFSET];
+	if(dz->vflag[0] && (dz->iparam[PHASOR_OCHANS] <= 2)) {
+		sprintf(errstr,"NO SOUND-SURROUND POSSIBLE WITH %d OUTPUT CHANNELS\n",dz->iparam[PHASOR_OCHANS]); 
+		return DATA_ERROR;
+	}
+	return FINISHED;
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if(!strcmp(prog_identifier_from_cmdline,"phasor"))				dz->process = PHASOR;
+	else {
+		fprintf(stderr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/******************************** SETUP_AND_INIT_INPUT_BRKTABLE_CONSTANTS ********************************/
+
+int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt)
+{	
+	int n;
+	if((dz->brk      = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<brkcnt;n++) {
+		dz->brk[n]     = NULL;
+		dz->brkptr[n]  = NULL;
+		dz->brkinit[n] = 0;
+		dz->brksize[n] = 0;
+	}
+	return(FINISHED);
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+	if(!strcmp(str,"phasor")) {
+		fprintf(stderr,
+	    "USAGE:\n"
+	    "phasor phasor infile outfile streams phasfrq shift ochans [-ooffset] [-s] [-e]\n"
+		"\n"
+		"Introduce phasing into signal : Takes a MONO input file.\n"
+		"\n"
+		"STREAMS  Number of output streams that phase-interact (Range 2 - 8)\n"
+		"PHASFRQ  Frequency of packets (phase shifts forward then back in a single packet).\n"
+		"SHIFT    Maximum phaseshift with packet: (Range 0 - 12 semitones).\n"
+		"OCHANS   Number of output channels (not greater than number of streams).\n"
+		"OFFSET   The streams may be time-offset from one another..\n"
+		"        \"Offset\" is time-offset of the most-offset stream (Range 0 - 500 mS).\n"
+		"         The other streams are offset by intermediate amounts.\n"
+		"\n"
+		"-s       Output chans (lspkrs) encircle audience : only with more than 2 ochans.\n"       
+		"-e       Prints warnings re rounding-errors in calculating time-shifted streams.\n"       
+		"\n"
+		"\"shift\" and \"phasfrq\" can vary through time,\n"
+		"but extreme phasfrq changes or reversals will produce anomalous output.\n"
+		"\n");
+	} else
+		fprintf(stdout,"Unknown option '%s'\n",str);
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	fprintf(stderr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/******************************** CREATE_PHASESHIFT_AND_OUTCHAN_DATA_ARRAYS ********************************/
+
+int create_phaseshift_and_outchan_data_arrays(int *maxshiftslen, dataptr dz)
+{
+	int exit_status, n, m, chan;
+	double time = 0, srate = (double)dz->infile->srate, leftgain = 0.0, rightgain = 0.0, chanpos, pos;
+	*maxshiftslen = 0;
+	while(time < dz->duration) {
+		if((exit_status = read_values_from_all_existing_brktables(time,dz))<0)
+			return exit_status;
+		*maxshiftslen = max(*maxshiftslen,(int)ceil(srate/dz->param[PHASOR_FRQ]));
+		time += 1.0/dz->param[PHASOR_FRQ];
+	}
+	while(((*maxshiftslen)/4) * 4 != *maxshiftslen)
+		(*maxshiftslen)++;							//	phaseshift arrays must have a multiple-of-4 entries
+	*maxshiftslen += WRAP;							//	Allow for wraparound point and accumulation (of samp-pointer position) errors
+	dz->outchinfo = dz->iparam[PHASOR_STREAMS] - 1;
+	if((dz->parray = (double **)malloc((dz->outchinfo + dz->iparam[PHASOR_STREAMS]) * sizeof(double *)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to store phaseshift data arrays.\n");
+		return(MEMORY_ERROR);
+	}
+	for(n = 0; n < dz->outchinfo; n++) {
+		if((dz->parray[n] = (double *)malloc(((*maxshiftslen) + SAFETY) * sizeof(double)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY to store phaseshift data, stream %d.\n",n+1);
+			return(MEMORY_ERROR);
+		}
+	}
+	for(n = dz->outchinfo; n < dz->outchinfo + dz->iparam[PHASOR_STREAMS]; n++) {
+		if((dz->parray[n] = (double *)malloc(4 * sizeof(double)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY to store phaseshift data, stream %d.\n",n+1);
+			return(MEMORY_ERROR);
+		}
+	}
+	if(dz->iparam[PHASOR_STREAMS] == dz->iparam[PHASOR_OCHANS]) {
+		for(n=0,m = dz->outchinfo;n < dz->iparam[PHASOR_OCHANS]; n++,m++) {
+			dz->parray[m][0] = (double)n;
+			dz->parray[m][1] = 1.0;
+			dz->parray[m][2] = (double)((n+1)%dz->iparam[PHASOR_OCHANS]);
+			dz->parray[m][3] = 0.0;
+		}
+	} else {
+		if(dz->vflag[0]) {		/* Sound surround, 5 streams on 4 chans are positioned at 0  4/5  1+3/5  2+2/5  3+1/5 */
+			for(n=0,m = dz->outchinfo;n < dz->iparam[PHASOR_STREAMS]; n++,m++) {
+				chanpos = ((double)n/(double)dz->iparam[PHASOR_STREAMS]) * (double)dz->iparam[PHASOR_OCHANS];	//	e.g. 3.7
+				chan = (int)floor(chanpos);																		//	3
+				pos = chanpos - (double)chan;																	//	0.7 in range 0 to 1
+				pos = (2.0 * pos) - 1.0;																		//	0.4 in range -1 to 0
+				pancalc(pos,&leftgain,&rightgain);
+				dz->parray[m][0] = (double)chan;
+				dz->parray[m][1] = leftgain;
+				dz->parray[m][2] = (double)((chan+1)%dz->iparam[PHASOR_OCHANS]);
+				dz->parray[m][3] = rightgain;
+			}				
+		} else {				/* Linear array, 5 streams on 4 chans are positioned at   0  3/4  1+1/2  2+3/4   3   */
+			for(n=0,m = dz->outchinfo;n < dz->iparam[PHASOR_STREAMS]; n++,m++) {
+				chanpos = (double)n/(double)(dz->iparam[PHASOR_STREAMS] - 1) * (double)(dz->iparam[PHASOR_OCHANS] - 1);
+				chan = (int)floor(chanpos);
+				pos = chanpos - (double)chan;
+				pos = (2.0 * pos) - 1.0;
+				pancalc(pos,&leftgain,&rightgain);
+				dz->parray[m][0] = (double)chan;
+				dz->parray[m][1] = leftgain;
+				dz->parray[m][2] = (double)((chan+1)%dz->iparam[PHASOR_OCHANS]);
+				dz->parray[m][3] = rightgain;
+			}				
+		}
+	}
+	return FINISHED;
+}
+
+/******************************** CREATE_PHASOR_SNDBUFS ********************************/
+
+int create_phasor_sndbufs(int maxshiftslen,double maxoffset,int *offsetwrap,dataptr dz)
+{
+	int bigbufsize, seccnt;
+	int framesize = F_SECSIZE;
+	double srate = (double)dz->infile->srate;
+	if(maxoffset > 0.0) {										//	Additional buffer space, if streams are offset from one another
+		dz->maxoffset = (int)ceil(maxoffset * MS_TO_SECS * srate);
+		*offsetwrap = dz->maxoffset * dz->iparam[PHASOR_OCHANS];
+		*offsetwrap += WRAP;
+		seccnt = (*offsetwrap)/framesize;
+		if(seccnt * framesize < *offsetwrap)
+			seccnt++;
+		*offsetwrap = seccnt * framesize;
+	}
+	seccnt = maxshiftslen/framesize;
+	if(seccnt * framesize < maxshiftslen)
+		seccnt++;
+	bigbufsize = seccnt * framesize;
+	dz->buflen = bigbufsize;
+	dz->ibuflen = dz->buflen;	//	Input buffer size
+	bigbufsize *= (1 + (3 * dz->iparam[PHASOR_OCHANS]));		//	1 mono and 1 multichan (pbuf), + 1 dopuble-size outbuf
+	if(maxoffset > 0.0)
+		bigbufsize += 2 * *offsetwrap;							//	once for pbuf, and once for overflowbuf
+	if((dz->bigbuf = (float *)malloc(bigbufsize * sizeof(float))) == NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to create sound buffers.\n");
+		return(PROGRAM_ERROR);
+	}
+	dz->sbufptr[0] = dz->sampbuf[0] = dz->bigbuf;
+	dz->sbufptr[1] = dz->sampbuf[1] = dz->bigbuf + dz->buflen;								//	Input buffer (mono)
+	dz->buflen *= dz->iparam[PHASOR_OCHANS];												//  Buflen used in calculation is size of multichan buffers
+	dz->sbufptr[2] = dz->sampbuf[2] = dz->sampbuf[1] + dz->buflen + *offsetwrap;			//	Packet buffer (multichan) + its possible overflow + offset-extension
+	dz->sampbuf[3]					= dz->sampbuf[2] + dz->buflen + dz->buflen + *offsetwrap;//	Output buffer (multichan) + overflow buffer + offset-extension to overflow
+	return FINISHED;
+}
+
+/******************************** PHASOR ********************************/
+
+int phasor(int offsetwrap,dataptr dz)
+{
+	int exit_status, passno;
+	double time, normaliser = 1.0, maxsamp = 0.0;
+	float *ibuf = dz->sampbuf[0], *obuf = dz->sampbuf[2];
+	int phaseshiftcnt, ibufpos, obufpos, n, origbuflen = 0, absolute_endofwrite = 0;
+	for(passno = 0; passno < 2; passno++) {
+		dz->total_samps_read = 0;
+		dz->samps_left = dz->insams[0];
+		time = 0.0;
+		ibufpos = 0;
+		obufpos = 0;
+		memset((char *)ibuf,0,dz->ibuflen * sizeof(float));
+		memset((char *)obuf,0,((dz->buflen * 2) + offsetwrap) * sizeof(float));
+		sndseekEx(dz->ifd[0],0,0);
+		origbuflen = dz->buflen;
+		dz->buflen = dz->ibuflen;
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+		dz->buflen = origbuflen;
+		while(time < dz->duration) {
+			if((exit_status = calculate_phase_shifts(time,&phaseshiftcnt,dz))<0)
+				return exit_status;
+			if((exit_status = calculate_streams(time,phaseshiftcnt,&obufpos,&ibufpos,passno,normaliser,&maxsamp,offsetwrap,&absolute_endofwrite,dz))<0)
+				return exit_status;
+			if(exit_status == FINISHED)
+				break;
+			time += 1.0/dz->param[PHASOR_FRQ];
+		}
+		if(passno == 0) {
+			if(absolute_endofwrite > 0) {
+				for(n=0;n<absolute_endofwrite;n++)
+					maxsamp = max(maxsamp,fabs(obuf[n]));
+			}
+			if(maxsamp > MAXOUTLEVEL)
+				normaliser = MAXOUTLEVEL/maxsamp;
+		} else {
+			if(absolute_endofwrite > 0) {
+				for(n=0;n<absolute_endofwrite;n++)
+					obuf[n] = (float)(obuf[n] * normaliser);
+				if((exit_status = write_samps(obuf,absolute_endofwrite,dz))<0)
+					return(exit_status);
+			}
+		}
+	}
+	return FINISHED;
+}
+
+/******************************** CALCULATE_PHASE_SHIFTS ********************************/
+
+int calculate_phase_shifts(double time, int *phaseshiftcnt, dataptr dz)
+{
+	int exit_status;
+	double srate = (double)dz->infile->srate, maxphaseshift, minphaseshift, thismax, posoffset, sum, error;
+	double *sampincr;
+	int midway, quartway, threequartway, n, k, j;
+	if((exit_status = read_values_from_all_existing_brktables(time,dz))<0)
+		return exit_status;
+	maxphaseshift = dz->param[PHASOR_SHIFT];
+	minphaseshift = maxphaseshift/(dz->iparam[PHASOR_STREAMS] - 1);
+	*phaseshiftcnt = (int)floor(srate/dz->param[PHASOR_FRQ]);
+	while((*phaseshiftcnt/4) * 4 != *phaseshiftcnt)
+		(*phaseshiftcnt)++;								//	phaseshift arrays must have a multiple-of-4 entries
+	midway = (*phaseshiftcnt)/2;						//	midpoint of arrays
+	quartway = midway/2;
+	threequartway = midway + quartway;
+	for(n = 0; n < dz->iparam[PHASOR_STREAMS]-1;n++) {	//	Set max-shift for this stream
+		sum = 0.0;
+		thismax = min(maxphaseshift,(n+1) * minphaseshift);
+		thismax = thismax/SEMITONES_PER_OCTAVE;			//	Convert to octaves
+		posoffset = thismax/(double)quartway;			//	semitone-displacement per sample.
+															/*	If 8 samps to midway, midway = 8, quartway = 4 : midway-2 = 6	*/
+		sampincr = dz->parray[n];							/*																	*/
+		for(k = 0; k < quartway; k++)						/*	Rising		   A/\B				e.g. k=0  1   2   3				*/
+			sampincr[k] = min((k+1) * posoffset,thismax);	/*	portion	A	  /	   \				 +1  +2  +3  +4				*/
+															/* 						 \C	 D/			 j=6  5   4	 				*/
+		for(k = 0,j = midway - 2; k < quartway-1; k++,j--)	/*	Falling				   \/			 j=7 gets 0					*/
+			sampincr[j] = sampincr[k];						/*	portion B														*/
+
+		sampincr[midway-1] = 0.0;
+
+		for(k = 0,j = midway; k < midway; k++,j++)			/*	Falling & Rising portions C & D			*/
+			sampincr[j] = -sampincr[k];						/*	Every +ve sampincr in A+B				*/
+															/*	compensated for by equal -ve sampincr	*/ 
+															/*	in C+D, so signals should resync!		*/
+		for(k=0;k < *phaseshiftcnt;k++)
+			sampincr[k] = pow(2.0,sampincr[k]);				/*	semitones-->frqratio = sampincr			*/
+		sum = 0.0;
+		for(k=0;k < *phaseshiftcnt;k++)						/*  check error in summing all increments	*/
+			sum += sampincr[k];
+		error = (sum - (double)*phaseshiftcnt)/(double)(*phaseshiftcnt);
+		for(k=0;k < *phaseshiftcnt;k++)						/*	adjust increments to eliminate error	*/
+			sampincr[k] -= error;
+	}
+	return FINISHED;
+}
+
+/******************************** CALCULATE_STREAMS ********************************/
+
+int calculate_streams(double time,int phaseshiftcnt, int *obufpos, int *ibufpos, int passno, double normaliser, double *maxsamp, int offsetwrap, int *absolute_endofwrite, dataptr dz)
+{
+	int exit_status;
+	float *ibuf = dz->sampbuf[0];
+	float *pbuf = dz->sampbuf[1];
+	float *obuf = dz->sampbuf[2];
+	double ibufposd, srate = (double)dz->infile->srate, ch1lev = 0.0, ch2lev = 0.0;
+	double loval, valdiff, timefrac, val, val1, val2;
+	double *outchan_info, *sampincr;
+	int n, origbuflen, offset[8], bufadjust, thisoffset, k, ibufpos_for_each_stream = 0, lopos, hipos, ovflow;
+	int pbufpos = 0, advance_to_next_write = 0, pbufpos1 = 0, pbufpos2 = 0, endibufpos = 0, xmaxoffset, position_of_next_write, samps_to_write, xobufpos;
+	int warning = 0, streamcnt = dz->iparam[PHASOR_STREAMS], ochan1, ochan2;
+	memset((char *)pbuf,0, (dz->buflen + offsetwrap) * sizeof(float));
+	if(*ibufpos + phaseshiftcnt + 1 >= dz->ibuflen) {		//	Ensure all of read will go into the input buffer
+		bufadjust = dz->ssampsread - *ibufpos;
+		sndseekEx(dz->ifd[0],dz->total_samps_read - bufadjust,0);
+		dz->total_samps_read -= bufadjust;
+		memset((char *)ibuf,0,dz->ibuflen * sizeof(float));
+		origbuflen = dz->buflen;
+		dz->buflen = dz->ibuflen;							//	input buffer size
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+		dz->buflen = origbuflen;							//	Restore dz->buflen for calcs in output buffer		
+		if(dz->ssampsread <= 0)
+			return FINISHED;
+		*ibufpos = 0;
+	}
+
+	/* CALCULATE ANY STREAM TIME-OFFSETS */
+
+	thisoffset = (int)round(dz->param[PHASOR_OFFSET] * MS_TO_SECS * srate);				//	With 4 streams, offsets go ...
+	offset[0] = 0;																			//
+	xmaxoffset = 0;																			//		|----------------------------
+	for(k = 1; k < streamcnt-1;k++) {														//		| 	|----------------------------
+		offset[k] = (int)round(((double)k/(double)(streamcnt - 1)) * (double)thisoffset);	//		|	|	|----------------------------
+		xmaxoffset = max(xmaxoffset,offset[k]);												//		|	|	|	|----------------------------
+	}																						//		0  1/3 2/3	thisoffset
+	offset[k] = thisoffset;
+	xmaxoffset = max(xmaxoffset,offset[k]);
+	for(k = 0; k < streamcnt; k++) {
+		if(k==0)
+			ibufpos_for_each_stream = *ibufpos;				//	Current read-position in input
+		else if(k==1) {
+			endibufpos = ibufpos_for_each_stream;			//	ibufpos_for_each_stream has advanced from initial ibufpos , while writing stream 0 : 
+															//	and now tells us where we've reached in the input buffer.
+			advance_to_next_write = pbufpos;				//	pbufpos has advanced from zero, while writing stream 0 : 
+															//	It now tells us how many samples to advance, in output-buf, for next set-of-streams to be written to output
+		}
+		pbufpos = offset[k] * dz->iparam[PHASOR_OCHANS];	//	Initial time-offset of this stream (as a whole number of channel-groups), default is zero 
+		ibufposd = (double)(*ibufpos);						//	Ditto as a floatval which can be fractionally incremented
+
+		outchan_info = dz->parray[dz->outchinfo + k];		//	Output channel information for this stream
+
+		ochan1 = (int)round(outchan_info[0]);					
+		ch1lev = outchan_info[1];
+		ochan2 = (int)round(outchan_info[2]);
+		ch2lev = outchan_info[3];
+		pbufpos1 = pbufpos + ochan1;						//	Actual start sample for this particular stream feeding particular output channel
+		pbufpos2 = pbufpos + ochan2;						//	Actual start sample for this particular stream feeding adjacent output channel
+
+		for(n = 0; n < phaseshiftcnt; n++) {
+			if(k==0) {
+				pbuf[pbufpos] = (float)(pbuf[pbufpos] + ibuf[ibufpos_for_each_stream]);	//	Stream 0 always goes entirely to channel 0
+				pbufpos += dz->iparam[PHASOR_OCHANS];									//	Step to next output-channel-group
+				ibufpos_for_each_stream++;												//	Advance at normal rate in input
+			} else {
+				sampincr = dz->parray[k-1];
+				ibufposd += sampincr[n];												//	Advance in input by timewarp value stored in array
+				lopos = (int)round(ibufposd);
+				if(lopos >= phaseshiftcnt) {
+					warning++;
+					lopos = phaseshiftcnt;
+				}
+				hipos = lopos + 1;
+				loval = ibuf[lopos];
+				valdiff = ibuf[hipos] - loval;
+				timefrac = ibufposd - (double)lopos;
+				val = loval + (valdiff * timefrac);				//	Value obtained by interpolating in input sound
+				val1 = val * ch1lev;							//	Distribute this between the 2 appropriate output channels
+				pbuf[pbufpos1] = (float)(pbuf[pbufpos1] + val1);
+				val2 = val * ch2lev;
+				pbuf[pbufpos2] = (float)(pbuf[pbufpos2] + val2);
+				pbufpos1 += dz->iparam[PHASOR_OCHANS];			//	Step to appropriate-chan-positions in next output-channel-group
+				pbufpos2 += dz->iparam[PHASOR_OCHANS];
+			}
+		}
+	}
+	*ibufpos = endibufpos;										//	Reset final ibufpos - at end of loop through input samps.
+
+	position_of_next_write = *obufpos + advance_to_next_write;	//	Calculate position of NEXT write, from outbuf
+																//	Calculate absolute end of current write, in outbuf
+	*absolute_endofwrite = position_of_next_write + (dz->iparam[PHASOR_OCHANS] * xmaxoffset);
+	ovflow = *absolute_endofwrite - dz->buflen;
+	if(ovflow >= dz->buflen + offsetwrap) {						//	check that any overflow of principal output buffer does not exceed length of overflow-buffer
+		sprintf(errstr,"Buffer size underestimated,\n");
+		return PROGRAM_ERROR;
+	}
+													//	Write samples into the output buffer (even if they  overflow), as far as absolute end of write
+	samps_to_write = *absolute_endofwrite - *obufpos;
+	xobufpos = *obufpos;
+	for(n = 0; n < samps_to_write; n++) {
+		obuf[xobufpos] = (float)(obuf[xobufpos] + pbuf[n]);
+		xobufpos++;
+	}
+	*obufpos = position_of_next_write;				//	Reset output buffer write position, ready for next pass
+
+	if(position_of_next_write >= dz->buflen) {		//	If no further samples will be added to the current buffer (because next write is beyond its end)
+		if(passno == 0) {							//	We can process-or-write the complete current buffer
+			for(n=0;n<dz->buflen;n++)
+				*maxsamp = max(*maxsamp,fabs(obuf[n]));
+		} else {
+			for(n=0;n<dz->buflen;n++)
+				obuf[n] = (float)(obuf[n] * normaliser);
+			if((exit_status = write_samps(obuf,dz->buflen,dz))<0)
+				return(exit_status);
+		}
+		memset((char *)obuf,0,dz->buflen * sizeof(float));
+		memcpy((char *)obuf,(char *)(obuf + dz->buflen), dz->buflen * sizeof(float));	//  Wrap-around any overflow in output buffer.
+		memset((char *)(obuf + dz->buflen),0,dz->buflen * sizeof(float));				//	re-zero the overflow buffer.
+		if(offsetwrap > 0) {															//	Wrap around any data in the offsetwrap extension of the overflow buffer		
+			memcpy((char *)(obuf + dz->buflen),(char *)(obuf + (dz->buflen * 2)), offsetwrap * sizeof(float));
+			memset((char *)(obuf + (dz->buflen * 2)),0,offsetwrap * sizeof(float));		//	re-zero the offsetwrap buffer.
+		}
+		*obufpos -= dz->buflen;															//	Reset outbuf pointer.
+		*absolute_endofwrite -= dz->buflen; 
+	}
+	if(dz->vflag[1] && warning) {
+		fprintf(stdout,"WARNING: %d rounding errors at time %lf\n",warning,time);
+		fflush(stdout);
+	}
+	return CONTINUE;
+}	
+
+/************************************ PANCALC *******************************/
+
+void pancalc(double position,double *leftgain,double *rightgain)
+{
+	int dirflag;
+	double temp;
+	double relpos;
+	double reldist, invsquare;
+
+	if(position < 0.0)
+		dirflag = SIGNAL_TO_LEFT;		/* signal on left */
+	else
+		dirflag = SIGNAL_TO_RIGHT;
+
+	if(position < 0) 
+		relpos = -position;
+	else 
+		relpos = position;
+	if(relpos <= 1.0){		/* between the speakers */
+		temp = 1.0 + (relpos * relpos);
+		reldist = ROOT2 / sqrt(temp);
+		temp = (position + 1.0) / 2.0;
+		*rightgain = temp * reldist;
+		*leftgain = (1.0 - temp ) * reldist;
+	} else {				/* outside the speakers */
+		temp = (relpos * relpos) + 1.0;
+		reldist  = sqrt(temp) / ROOT2;   /* relative distance to source */
+		invsquare = 1.0 / (reldist * reldist);
+		if(dirflag == SIGNAL_TO_LEFT){
+			*leftgain = invsquare;
+			*rightgain = 0.0;
+		} else {   /* SIGNAL_TO_RIGHT */
+			*rightgain = invsquare;
+			*leftgain = 0;
+		}
+	}
+}
+

+ 1324 - 0
dev/standnew/quirk.c

@@ -0,0 +1,1324 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <tkglobals.h>
+#include <pnames.h>
+#include <filetype.h>
+#include <processno.h>
+#include <modeno.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <math.h>
+#include <mixxcon.h>
+#include <osbind.h>
+#include <standalone.h>
+#include <ctype.h>
+#include <sfsys.h>
+#include <string.h>
+#include <srates.h>
+
+
+#ifdef unix
+#define round(x) lround((x))
+#endif
+
+char errstr[2400];
+
+int anal_infiles = 1;
+int	sloom = 0;
+int sloombatch = 0;
+
+const char* cdp_version = "7.0.0";
+
+//CDP LIB REPLACEMENTS
+static int quirk_param_preprocess(dataptr dz);
+static int setup_quirk_application(dataptr dz);
+static int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+static int parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int setup_quirk_param_ranges_and_defaults(dataptr dz);
+static int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int establish_application(dataptr dz);
+static int initialise_vflags(dataptr dz);
+static int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int mark_parameter_types(dataptr dz,aplptr ap);
+static int assign_file_data_storage(int infilecnt,dataptr dz);
+static int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+static int get_the_mode_from_cmdline(char *str,dataptr dz);
+static int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt);
+static int quirk(dataptr dz);
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status;
+	dataptr dz = NULL;
+	char **cmdline;
+	int  cmdlinecnt;
+	int n;
+	aplptr ap;
+	int is_launched = FALSE;
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+						/* CHECK FOR SOUNDLOOM */
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {					// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc == 2) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+	}
+	if(!sloom) {
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		dz->maxmode = 2;
+		if((exit_status = get_the_mode_from_cmdline(cmdline[0],dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);
+		}
+		cmdline++;
+		cmdlinecnt--;
+		// setup_particular_application =
+		if((exit_status = setup_quirk_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+
+	// parse_infile_and_hone_type() = 
+	if((exit_status = parse_infile_and_check_type(cmdline,dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// setup_param_ranges_and_defaults() =
+	if((exit_status = setup_quirk_param_ranges_and_defaults(dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// open_first_infile		CDP LIB
+	if((exit_status = open_first_infile(cmdline[0],dz))<0) {	
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);	
+		return(FAILED);
+	}
+	cmdlinecnt--;
+	cmdline++;
+
+//	handle_extra_infiles() : redundant
+	// handle_outfile() = 
+	if((exit_status = handle_the_outfile(&cmdlinecnt,&cmdline,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+//	handle_formants()			redundant
+//	handle_formant_quiksearch()	redundant
+//	handle_special_data()		redundant
+ 
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	is_launched = TRUE;
+	dz->bufcnt = 1;
+	if((dz->sampbuf = (float **)malloc(sizeof(float *) * (dz->bufcnt+1)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->sbufptr = (float **)malloc(sizeof(float *) * dz->bufcnt))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffer pointers.\n");
+		return(MEMORY_ERROR);
+	}
+	for(n = 0;n <dz->bufcnt; n++)
+		dz->sampbuf[n] = dz->sbufptr[n] = (float *)0;
+	dz->sampbuf[n] = (float *)0;
+
+	if((exit_status = create_sndbufs(dz))<0) {							// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+//	check_param_validity_and_consistency....
+	if((exit_status = quirk_param_preprocess(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//param_preprocess()						redundant
+	//spec_process_file =
+	if((exit_status = quirk(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = complete_output(dz))<0) {										// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);		// CDP LIB
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc, brkcnt;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	brkcnt = tipc;
+	//THERE ARE NO INPUTFILE brktables USED IN THIS PROCESS
+	if(brkcnt>0) {
+		if((exit_status = setup_and_init_input_brktable_constants(dz,brkcnt))<0)			  
+			return(exit_status);
+	}
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+		return(exit_status);
+	
+	// establish_infile_constants() replaced by
+	dz->infilecnt = 1;
+	//establish_bufptrs_and_extra_buffers():
+	return(FINISHED);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}						 		/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_OUTFILE *********************/
+
+int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status;
+	char *filename = (*cmdline)[0];
+	if(filename[0]=='-' && filename[1]=='f') {
+		dz->floatsam_output = 1;
+		dz->true_outfile_stype = SAMP_FLOAT;
+		filename+= 2;
+	}
+	if(!sloom) {
+		if(file_has_invalid_startchar(filename) || value_is_numeric(filename)) {
+			sprintf(errstr,"Outfile name %s has invalid start character(s) or looks too much like a number.\n",filename);
+			return(DATA_ERROR);
+		}
+	}
+	strcpy(dz->outfilename,filename);	   
+	if((exit_status = create_sized_outfile(filename,dz))<0)
+		return(exit_status);
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/************************* SETUP_QUIRK_APPLICATION *******************/
+
+int setup_quirk_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	// SEE parstruct FOR EXPLANATION of next 2 functions
+	if((exit_status = set_param_data(ap,0   ,1,1,"d"))<0)
+		return(FAILED);
+	if((exit_status = set_vflgs(ap,"",0,"","",0,0,""))<0)
+		return(FAILED);
+	// set_legal_infile_structure -->
+	dz->has_otherfile = FALSE;
+	// assign_process_logic -->
+	dz->input_data_type = SNDFILES_ONLY;
+	dz->process_type	= EQUAL_SNDFILE;	
+	dz->outfiletype  	= SNDFILE_OUT;
+	return application_init(dz);	//GLOBAL
+}
+
+/************************* PARSE_INFILE_AND_CHECK_TYPE *******************/
+
+int parse_infile_and_check_type(char **cmdline,dataptr dz)
+{
+	int exit_status;
+	infileptr infile_info;
+	if(!sloom) {
+		if((infile_info = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for infile structure to test file data.");
+			return(MEMORY_ERROR);
+		} else if((exit_status = cdparse(cmdline[0],infile_info))<0) {
+			sprintf(errstr,"Failed to parse input file %s\n",cmdline[0]);
+			return(PROGRAM_ERROR);
+		} else if(infile_info->filetype != SNDFILE)  {
+			sprintf(errstr,"File %s is not of correct type\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if(infile_info->channels != 1)  {
+			sprintf(errstr,"File %s is not of correct type (must be mono)\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if((exit_status = copy_parse_info_to_main_structure(infile_info,dz))<0) {
+			sprintf(errstr,"Failed to copy file parsing information\n");
+			return(PROGRAM_ERROR);
+		}
+		free(infile_info);
+	}
+	return(FINISHED);
+}
+
+/************************* SETUP_QUIRK_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_quirk_param_ranges_and_defaults(dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	// NB total_input_param_cnt is > 0 !!!
+	if((exit_status = setup_input_param_range_stores(ap->total_input_param_cnt,ap))<0)
+		return(FAILED);
+	// get_param_ranges()
+	ap->lo[0]	= 0.01;
+	ap->hi[0]	= 100;
+	ap->default_val[0]	= 1;
+	dz->maxmode = 2;
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_quirk_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int read_special_data(char *str,dataptr dz)	
+{
+	return(FINISHED);
+}
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+	usage2("quirk");
+	return(USAGE_ONLY);
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if(!strcmp(prog_identifier_from_cmdline,"quirk"))				dz->process = QUIRK;
+	else {
+		sprintf(errstr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/******************************** SETUP_AND_INIT_INPUT_BRKTABLE_CONSTANTS ********************************/
+
+int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt)
+{	
+	int n;
+	if((dz->brk      = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<brkcnt;n++) {
+		dz->brk[n]     = NULL;
+		dz->brkptr[n]  = NULL;
+		dz->brkinit[n] = 0;
+		dz->brksize[n] = 0;
+	}
+	return(FINISHED);
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+	if(!strcmp(str,"quirk")) {
+		fprintf(stderr,
+	    "USAGE:\n"
+	    "quirk quirk 1-2 infile outfile powfac\n"
+		"\n"
+		"Distort signal by raising sample values to a power.\n"
+		"\n"
+		"POWFAC  Range 0.01 to 100.\n"
+		"             < 1: exaggerates signal contour.\n"
+		"             > 1: smooths signal contour.\n"
+		"\n"
+		"MODE 1  Applies power factor over amplitude range of individual half-wavesets.\n"
+		"MODE 2  Applies power factor over amplitude range of entire signal.\n"
+		"\n");
+	} else
+		fprintf(stdout,"Unknown option '%s'\n",str);
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	fprintf(stderr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/****************************** QUIRK_PARAM_PREPROCESS *********************************/
+
+int quirk_param_preprocess(dataptr dz)
+{
+	int exit_status;
+	int n, cnt = 0;
+	float *ibuf = dz->sampbuf[0], maxsamp;
+	int halfwaveset_cnt = 0;
+	int phase, initial_phase = 0;
+	int *wavesetsampcnt;
+	float *wavesetmaxsamp;
+	dz->samps_left = dz->insams[0];
+
+	//	DETERMINE INITIAL PHASE
+	
+	while(dz->samps_left > 0) {
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+		n = 0;
+		while(n < dz->ssampsread) {
+			if(ibuf[n] > 0.0) {
+				initial_phase = 1;
+				break;
+			} else if(ibuf[n] < 0.0) {
+				initial_phase = -1;
+				break;
+			}
+			n++;
+		}
+		if(initial_phase != 0)
+			break;
+	}
+	if(initial_phase == 0) {
+		fprintf(stderr,"No signal found in soundfile: Cannot proceed\n");
+		return DATA_ERROR;
+	}
+	phase = initial_phase;
+	if((sndseekEx(dz->ifd[0],0,0) < 0)){
+        sprintf(errstr,"sndseek failed\n");
+        return SYSTEM_ERROR;
+    }
+	dz->samps_left = dz->insams[0];
+	dz->total_samps_read = 0;
+	while(dz->samps_left > 0) {
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+		n = 0;
+		while(n < dz->ssampsread) {
+			switch(initial_phase) {
+			case(1):
+				if(phase == initial_phase) {
+					if(ibuf[n] < 0.0) {		//	i.e. phase has changed from 1 (initial_phase) to -1
+						halfwaveset_cnt++;	//	Count half-waveset
+						phase = -phase;		//	Switch phase
+					}
+				} else {
+					if(ibuf[n] >= 0.0) {	//	i.e. phase has changed from -1 to 1
+						halfwaveset_cnt++;	//	Count half-waveset
+						phase = -phase;		//	Switch phase
+					}
+				}
+				break;
+			case(-1): 
+				if(phase == initial_phase) {
+					if(ibuf[n] >= 0.0) {	//	i.e. phase has changed from -1 (initial_phase) to 1
+						halfwaveset_cnt++;	//	Count half-waveset
+						phase = -phase;		//	Switch phase
+					}
+				} else {
+					if(ibuf[n] < 0.0) {		//	i.e. phase has changed from 1 to -1
+						halfwaveset_cnt++;	//	Count half-waveset
+						phase = -phase;		//	Switch phase
+					}
+				}
+				break;
+			}
+			n++;
+		}
+	}
+	if(cnt > 0)
+		halfwaveset_cnt++;	//	Include any partial waveset at file end (i.e. signal doesn't go to zero)
+
+	dz->itemcnt = halfwaveset_cnt;
+	if((sndseekEx(dz->ifd[0],0,0) < 0)){
+        sprintf(errstr,"sndseek failed\n");
+        return SYSTEM_ERROR;
+    }
+	dz->samps_left = dz->insams[0];
+	dz->total_samps_read = 0;
+	dz->total_samps_written = 0;
+
+	//	establish array to store waveset sizes and maxsamples
+	
+	if((dz->iparray = (int **)malloc(sizeof(int *)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for waveset samplecnts storage.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparray[0] = (int *)malloc(dz->itemcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for waveset samplecnts storage.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->fptr = (float **)malloc(sizeof(float *)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for waveset maxamps store.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->fptr[0] = (float *)malloc(dz->itemcnt * sizeof(float)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for waveset maxamps store.\n");
+		return(MEMORY_ERROR);
+	}
+	wavesetsampcnt = dz->iparray[0];
+	wavesetmaxsamp = dz->fptr[0];
+	halfwaveset_cnt = 0;
+	maxsamp = 0.0;
+	phase = initial_phase;
+	while(dz->samps_left > 0) {
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+		n = 0;
+		while(n < dz->ssampsread) {
+			switch(initial_phase) {
+			case(1):
+				if(phase == initial_phase) {
+					if(ibuf[n] >= 0.0) {
+						if(ibuf[n] > maxsamp)
+							maxsamp = ibuf[n];
+						cnt++;
+					}
+					else {					//	i.e. phase has changed from 1 (initial_phase) to -1
+						wavesetsampcnt[halfwaveset_cnt] = cnt;
+						wavesetmaxsamp[halfwaveset_cnt] = maxsamp;
+						cnt = 1;
+						maxsamp = ibuf[n];
+						halfwaveset_cnt++;
+						phase = -phase;		//	Switch phase
+					}
+				} else {
+					if(ibuf[n] < 0.0) {
+						if(ibuf[n] < maxsamp)
+							maxsamp = ibuf[n];
+						cnt++;
+					} else {				//	i.e. phase has changed from -1 to 1
+						wavesetsampcnt[halfwaveset_cnt] = cnt;					
+						wavesetmaxsamp[halfwaveset_cnt] = maxsamp;
+						cnt = 1;
+						maxsamp = ibuf[n];
+						halfwaveset_cnt++;
+						phase = -phase;		//	Switch phase
+					}
+				}
+				break;
+			case(-1): 
+				if(phase == initial_phase) {
+					if(ibuf[n] < 0.0) {
+						if(ibuf[n] < maxsamp)
+							maxsamp = ibuf[n];
+						cnt++;
+					} else {					//	i.e. phase has changed from -1 (initial_phase) to 1
+						wavesetsampcnt[halfwaveset_cnt] = cnt;					
+						wavesetmaxsamp[halfwaveset_cnt] = maxsamp;
+						cnt = 1;
+						maxsamp = ibuf[n];
+						halfwaveset_cnt++;
+						phase = -phase;		//	Switch phase
+					}
+				} else {
+					if(ibuf[n] >= 0.0) {
+						if(ibuf[n] > maxsamp)
+							maxsamp = ibuf[n];
+						cnt++;
+				} else {					//	i.e. phase has changed from 1 to -1
+						wavesetsampcnt[halfwaveset_cnt] = cnt;					
+						wavesetmaxsamp[halfwaveset_cnt] = maxsamp;
+						cnt = 1;
+						maxsamp = ibuf[n];
+						halfwaveset_cnt++;
+						phase = -phase;		//	Switch phase
+					}
+				}
+				break;
+			}
+			n++;
+		}
+	}
+	if(cnt > 0) {
+		wavesetsampcnt[halfwaveset_cnt] = cnt;					
+		wavesetmaxsamp[halfwaveset_cnt] = maxsamp;
+	}
+	if((sndseekEx(dz->ifd[0],0,0) < 0)){
+        sprintf(errstr,"sndseek failed\n");
+        return SYSTEM_ERROR;
+    }
+	dz->samps_left = dz->insams[0];
+	dz->total_samps_read = 0;
+	dz->total_samps_written = 0;
+	
+	return FINISHED;
+}
+
+/****************************** QUIRK *********************************/
+
+int quirk(dataptr dz)
+{
+	int exit_status;
+	float *buf = dz->sampbuf[0];
+	int *wavesetsampcnt = dz->iparray[0];
+	float *wavesetmaxsamp  = dz->fptr[0], localmaxsamp;
+	double powfac = dz->param[0], samp, maxsamp;
+	int bufpos = 0, thiscnt, k, n;
+	switch(dz->mode) {
+	case(0):								//	Power factor applied over amplitude range of halfcycle
+		if((exit_status = read_samps(buf,dz))<0)
+			return(exit_status);
+		for(k = 0; k < dz->itemcnt;k++) {
+			thiscnt = wavesetsampcnt[k];
+			localmaxsamp = wavesetmaxsamp[k];
+			for(n = 0; n < thiscnt; n++) {
+				if(localmaxsamp != 0.0) {
+					samp = buf[bufpos]/localmaxsamp;	//	+ve/+ve = +ve OR -ve/-ve = +ve : Range 0 to 1
+					samp = pow(samp,powfac);			//	Range 0 to 1
+					samp *= localmaxsamp;				//	Range 0 to local-maxsamp(+ve or -ve)
+					buf[bufpos] = (float)samp;
+				}
+				if(++bufpos >= dz->buflen) {
+					if((exit_status = write_samps(buf,dz->buflen,dz))<0)
+						return(exit_status);
+					if((exit_status = read_samps(buf,dz))<0)
+						return(exit_status);
+					bufpos = 0;
+				}
+			}
+		}
+		break;
+	case(1):								//	Power factor applied over maximum range of entire sound
+		maxsamp = 0.0;
+		for(k = 0; k < dz->itemcnt;k++) {
+			if(fabs(wavesetmaxsamp[k]) > maxsamp)
+				maxsamp = fabs(wavesetmaxsamp[k]);	//	Find maxsamp in file
+		}
+		if((exit_status = read_samps(buf,dz))<0)
+			return(exit_status);
+		for(k = 0; k < dz->itemcnt;k++) {
+			thiscnt = wavesetsampcnt[k];
+			localmaxsamp = wavesetmaxsamp[k];
+			for(n = 0; n < thiscnt; n++) {
+				samp = fabs(buf[bufpos])/maxsamp;	//	range minsamp to maxsamp --> range 0 to 1
+				samp = pow(samp,powfac);			//	range 0 to 1
+				samp *= maxsamp;					//  range 0 to maxsamp
+				if(localmaxsamp < 0.0)
+					samp = -samp;
+				buf[bufpos] = (float)samp;
+				if(++bufpos >= dz->buflen) {
+					if((exit_status = write_samps(buf,dz->buflen,dz))<0)
+						return(exit_status);
+					if((exit_status = read_samps(buf,dz))<0)
+						return(exit_status);
+					bufpos = 0;
+				}
+			}
+		}
+		break;
+	}
+	if(bufpos > 0) {
+		if((exit_status = write_samps(buf,bufpos,dz))<0)
+			return(exit_status);
+	}
+	return FINISHED;
+}
+
+/****************************** GET_MODE *********************************/
+
+int get_the_mode_from_cmdline(char *str,dataptr dz)
+{
+	char temp[200], *p;
+	if(sscanf(str,"%s",temp)!=1) {
+		sprintf(errstr,"Cannot read mode of program.\n");
+		return(USAGE_ONLY);
+	}
+	p = temp + strlen(temp) - 1;
+	while(p >= temp) {
+		if(!isdigit(*p)) {
+			fprintf(stderr,"Invalid mode of program entered.\n");
+			return(USAGE_ONLY);
+		}
+		p--;
+	}
+	if(sscanf(str,"%d",&dz->mode)!=1) {
+		fprintf(stderr,"Cannot read mode of program.\n");
+		return(USAGE_ONLY);
+	}
+	if(dz->mode <= 0 || dz->mode > dz->maxmode) {
+		fprintf(stderr,"Program mode value [%d] is out of range [1 - %d].\n",dz->mode,dz->maxmode);
+		return(USAGE_ONLY);
+	}
+	dz->mode--;		/* CHANGE TO INTERNAL REPRESENTATION OF MODE NO */
+	return(FINISHED);
+}

+ 1186 - 0
dev/standnew/repair.c

@@ -0,0 +1,1186 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <tkglobals.h>
+#include <pnames.h>
+#include <filetype.h>
+#include <processno.h>
+#include <modeno.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <math.h>
+#include <mixxcon.h>
+#include <osbind.h>
+#include <standalone.h>
+#include <ctype.h>
+#include <sfsys.h>
+#include <string.h>
+#include <srates.h>
+
+
+#ifdef unix
+#define round(x) lround((x))
+#endif
+
+char errstr[2400];
+
+int anal_infiles = 1;
+int	sloom = 0;
+int sloombatch = 0;
+
+const char* cdp_version = "7.0.0";
+
+//CDP LIB REPLACEMENTS
+static int check_repair_param_validity_and_consistency(dataptr dz);
+static int setup_repair_application(dataptr dz);
+static int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+static int parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int setup_repair_param_ranges_and_defaults(dataptr dz);
+static int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int establish_application(dataptr dz);
+static int initialise_vflags(dataptr dz);
+static int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int mark_parameter_types(dataptr dz,aplptr ap);
+static int assign_file_data_storage(int infilecnt,dataptr dz);
+static int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+static int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt);
+static int handle_the_extra_infiles(char ***cmdline,int *cmdlinecnt,dataptr dz);
+static int create_repair_sndbufs(dataptr dz);
+static int repair(dataptr dz);
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status;
+	dataptr dz = NULL;
+	char **cmdline;
+	int  cmdlinecnt;
+	int n;
+	aplptr ap;
+	int is_launched = FALSE;
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+						/* CHECK FOR SOUNDLOOM */
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {					// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc == 2) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+	}
+	if(!sloom) {
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		dz->maxmode = 2;
+		// setup_particular_application =
+		if((exit_status = setup_repair_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+
+	// parse_infile_and_hone_type() = 
+	if((exit_status = parse_infile_and_check_type(cmdline,dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// setup_param_ranges_and_defaults() =
+	if((exit_status = setup_repair_param_ranges_and_defaults(dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// open_first_infile		CDP LIB
+	if((exit_status = open_first_infile(cmdline[0],dz))<0) {	
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);	
+		return(FAILED);
+	}
+	cmdlinecnt--;
+	cmdline++;
+
+//	handle_extra_infiles()
+	if((exit_status = handle_the_extra_infiles(&cmdline,&cmdlinecnt,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);		
+		return(FAILED);
+	}
+	// handle_outfile() = 
+	if((exit_status = handle_the_outfile(&cmdlinecnt,&cmdline,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+//	handle_formants()			redundant
+//	handle_formant_quiksearch()	redundant
+//	handle_special_data()		redundant
+ 
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+//	check_param_validity_and_consistency....
+	if((exit_status = check_repair_param_validity_and_consistency(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	is_launched = TRUE;
+	dz->bufcnt = dz->iparam[0] + 1;
+	if((dz->sampbuf = (float **)malloc(sizeof(float *) * (dz->bufcnt+1)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->sbufptr = (float **)malloc(sizeof(float *) * dz->bufcnt))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffer pointers.\n");
+		return(MEMORY_ERROR);
+	}
+	for(n = 0;n <dz->bufcnt; n++)
+		dz->sampbuf[n] = dz->sbufptr[n] = (float *)0;
+	dz->sampbuf[n] = (float *)0;
+
+	if((exit_status = create_repair_sndbufs(dz))<0) {							// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//param_preprocess()						redundant
+	//spec_process_file =
+	if((exit_status = repair(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = complete_output(dz))<0) {										// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);		// CDP LIB
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc, brkcnt;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	brkcnt = tipc;
+	//THERE ARE NO INPUTFILE brktables USED IN THIS PROCESS
+	if(brkcnt>0) {
+		if((exit_status = setup_and_init_input_brktable_constants(dz,brkcnt))<0)			  
+			return(exit_status);
+	}
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+		return(exit_status);
+	
+	// establish_infile_constants() replaced by
+	dz->infilecnt = -2;
+	//establish_bufptrs_and_extra_buffers():
+	return(FINISHED);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}						 		/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_OUTFILE *********************/
+
+int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status;
+	char *filename = (*cmdline)[0];
+	if(filename[0]=='-' && filename[1]=='f') {
+		dz->floatsam_output = 1;
+		dz->true_outfile_stype = SAMP_FLOAT;
+		filename+= 2;
+	}
+	if(!sloom) {
+		if(file_has_invalid_startchar(filename) || value_is_numeric(filename)) {
+			sprintf(errstr,"Outfile name %s has invalid start character(s) or looks too much like a number.\n",filename);
+			return(DATA_ERROR);
+		}
+	}
+	dz->all_words = 0;
+	if((exit_status = store_filename(filename,dz))<0)
+		return exit_status;
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/************************ OPEN_THE_OUTFILE *********************/
+
+int open_the_outfile(char **outfilename,int n,dataptr dz)
+{
+	int exit_status;
+	strcpy(*outfilename,dz->wordstor[0]);
+	if(!sloom) {
+		insert_new_chars_at_filename_end(*outfilename,"_");
+		insert_new_number_at_filename_end(*outfilename,n,0);
+	} else {
+		insert_new_number_at_filename_end(*outfilename,n,1);
+	}
+	dz->infile->channels = dz->iparam[0];
+	if((exit_status = create_sized_outfile(*outfilename,dz))<0)
+		return(exit_status);
+	dz->infile->channels = 1;
+	return(FINISHED);
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/************************* SETUP_REPAIR_APPLICATION *******************/
+
+int setup_repair_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	// SEE parstruct FOR EXPLANATION of next 2 functions
+	if((exit_status = set_param_data(ap,0   ,1,1,"i"))<0)
+		return(FAILED);
+	if((exit_status = set_vflgs(ap,"",0,"","",0,0,""))<0)
+		return(FAILED);
+	// set_legal_infile_structure -->
+	dz->has_otherfile = FALSE;
+	// assign_process_logic -->
+	dz->input_data_type = MANY_SNDFILES;
+	dz->process_type	= UNEQUAL_SNDFILE;	
+	dz->outfiletype  	= SNDFILE_OUT;
+	return application_init(dz);	//GLOBAL
+}
+
+/************************* PARSE_INFILE_AND_CHECK_TYPE *******************/
+
+int parse_infile_and_check_type(char **cmdline,dataptr dz)
+{
+	int exit_status;
+	infileptr infile_info;
+	if(!sloom) {
+		if((infile_info = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for infile structure to test file data.");
+			return(MEMORY_ERROR);
+		} else if((exit_status = cdparse(cmdline[0],infile_info))<0) {
+			sprintf(errstr,"Failed to parse input file %s\n",cmdline[0]);
+			return(PROGRAM_ERROR);
+		} else if(infile_info->filetype != SNDFILE)  {
+			sprintf(errstr,"File %s is not of correct type\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if(infile_info->channels != 1)  {
+			sprintf(errstr,"File %s is not of correct type (must be mono)\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if((exit_status = copy_parse_info_to_main_structure(infile_info,dz))<0) {
+			sprintf(errstr,"Failed to copy file parsing information\n");
+			return(PROGRAM_ERROR);
+		}
+		free(infile_info);
+	}
+	return(FINISHED);
+}
+
+/************************* SETUP_REPAIR_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_repair_param_ranges_and_defaults(dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	// NB total_input_param_cnt is > 0 !!!
+	if((exit_status = setup_input_param_range_stores(ap->total_input_param_cnt,ap))<0)
+		return(FAILED);
+	// get_param_ranges()
+	ap->lo[0]	= 2;
+	ap->hi[0]	= 16;
+	ap->default_val[0]	= 2;
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_repair_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int read_special_data(char *str,dataptr dz)	
+{
+	return(FINISHED);
+}
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+	usage2("repair");
+	return(USAGE_ONLY);
+}
+
+/**************************** CHECK_REPAIR_PARAM_VALIDITY_AND_CONSISTENCY *****************************/
+
+int check_repair_param_validity_and_consistency(dataptr dz)
+{
+	int n, k, gpcnt, chans = dz->iparam[0];
+	int sampcnt;
+	if(!(chans == 2 || chans == 4 || chans == 5 || chans == 7 || chans == 8 || chans == 16)) {
+		sprintf(errstr,"INVALID CHANNEL COUNT (2,4,5,7,8,16 only)\n");
+		return DATA_ERROR;
+	}
+	gpcnt = dz->infilecnt/chans;
+	if(gpcnt * chans != dz->infilecnt) {
+		sprintf(errstr,"NUMBER OF INPUT FILES IS NOT A MULTIPLE OF %d",chans);
+		return DATA_ERROR;
+	}
+	for(n = 0; n < gpcnt; n++) {
+		sampcnt = dz->insams[n];
+		for(k = n+gpcnt;k < dz->infilecnt;k += gpcnt) {
+			if(dz->insams[k] != sampcnt) {
+				sprintf(errstr,"FILES %d AND %d ARE NOT THE SAME SIZE\n",n,k);
+				return DATA_ERROR;
+			}
+		}
+	}
+	return FINISHED;
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if(!strcmp(prog_identifier_from_cmdline,"repair"))				dz->process = REPAIR;
+	else {
+		sprintf(errstr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/******************************** SETUP_AND_INIT_INPUT_BRKTABLE_CONSTANTS ********************************/
+
+int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt)
+{	
+	int n;
+	if((dz->brk      = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<brkcnt;n++) {
+		dz->brk[n]     = NULL;
+		dz->brkptr[n]  = NULL;
+		dz->brkinit[n] = 0;
+		dz->brksize[n] = 0;
+	}
+	return(FINISHED);
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+	if(!strcmp(str,"repair")) {
+		fprintf(stderr,
+	    "USAGE:\n"
+	    "repair repair infiles generic-outfilename channels\n"
+		"\n"
+		"Join a list of mono sounds into stereo, 4-channel or etc outputs.\n"
+		"\n"
+		"CHANNELS   No of channels in output files.\n"
+		"\n"
+		"Input files must be listed with all channel 1 sources in order, first,\n"
+		"then all channel 2 sources in order, etc.\n"
+		"\n");
+	} else
+		fprintf(stdout,"Unknown option '%s'\n",str);
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	fprintf(stderr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/******************************** REPAIR ********************************/
+
+int repair(dataptr dz)
+{
+	int exit_status, n, ch;
+	int k, obufpos,samps_read;
+	int chans = dz->iparam[0];
+	float *obuf = dz->sampbuf[chans];
+	int gpsize = dz->infilecnt/chans;
+	char *outfilename;
+	if((outfilename = (char *)malloc((strlen(dz->wordstor[0]) + 12) * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for output filenames\n");
+		return(MEMORY_ERROR);
+	}
+	dz->outfile->channels = chans;
+	dz->total_samps_written = 0;
+	dz->tempsize = 0;
+	for(n = 0; n < gpsize; n++)
+		dz->tempsize += dz->insams[n] * chans;	//	Set size for progress-bar display = sum of lengths of chan1 srcs
+	for(n = 0; n < gpsize; n++) {
+		if((exit_status = open_the_outfile(&outfilename,n,dz))< 0)
+			return exit_status;
+		dz->samps_left = dz->insams[n];
+		obufpos = 0;
+		while(dz->samps_left) {
+			for(ch = 0,k = n; k < dz->infilecnt; ch++,k += gpsize) {
+				if((samps_read = fgetfbufEx(dz->sampbuf[ch],dz->buflen,dz->ifd[k],0)) < 0) {
+					sprintf(errstr,"Can't read samples from input soundfile %d.\n",k+1);
+					return(SYSTEM_ERROR);
+				}
+			}
+			dz->ssampsread = samps_read;
+			dz->samps_left -= samps_read;
+			dz->total_samps_read += samps_read;
+			for(k = 0; k < dz->ssampsread; k++) {
+				for(ch = 0; ch < chans; ch++)
+					obuf[obufpos++] = dz->sampbuf[ch][k];
+			}
+			if((exit_status = write_samps(obuf,dz->ssampsread * chans,dz))<0)
+				return(exit_status);
+			obufpos = 0;
+		}
+		if((exit_status = headwrite(dz->ofd,dz))<0) {
+			free(outfilename);
+			return(exit_status);
+		}
+		if(n < gpsize - 1) {
+			if((exit_status = reset_peak_finder(dz))<0)
+				return(exit_status);
+			if(sndcloseEx(dz->ofd) < 0) {
+				fprintf(stdout,"WARNING: Can't close output soundfile %s\n",outfilename);
+				fflush(stdout);
+			}
+			dz->ofd = -1;
+		}
+	}
+	return FINISHED;
+}
+
+/*************************** CREATE_REPAIR_SNDBUFS **************************/
+
+/* MONO TO MULTICHAN */
+
+int create_repair_sndbufs(dataptr dz)
+{
+	int n, chans = dz->iparam[0];
+	int bigbufsize;
+	int framesize;
+	framesize = F_SECSIZE;
+	if(dz->sbufptr == 0 || dz->sampbuf==0) {
+		sprintf(errstr,"buffer pointers not allocated: create_sndbufs()\n");
+		return(PROGRAM_ERROR);
+	}
+	bigbufsize = (int)Malloc(-1);
+	bigbufsize /= chans * 2;
+	if(bigbufsize <=0)
+		bigbufsize  = framesize * sizeof(float);
+
+	dz->buflen = bigbufsize / sizeof(float);	
+	dz->buflen = (dz->buflen / framesize)  * framesize;
+	bigbufsize = dz->buflen * sizeof(float);
+	if((dz->bigbuf = (float *)malloc(bigbufsize  * chans * 2)) == NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to create sound buffers.\n");
+		return(PROGRAM_ERROR);
+	}
+	for(n = 0; n < chans; n++) 
+		dz->sbufptr[n] = dz->sampbuf[n] = dz->bigbuf + (dz->buflen * n);	//	Buffers for each channel
+	dz->sbufptr[n] = dz->sampbuf[n] = dz->bigbuf + (dz->buflen * n);		//	Buffer for joined outfile
+	n++;
+	dz->sampbuf[n] = dz->bigbuf + (dz->buflen * (2 + chans));				//	End of final long buffer
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_EXTRA_INFILES *********************/
+
+int handle_the_extra_infiles(char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+					/* OPEN ANY FURTHER INFILES, CHECK COMPATIBILITY, STORE DATA AND INFO */
+	int  exit_status, n;
+	char *filename;
+
+	if(dz->infilecnt > 1) {
+		for(n=1;n<dz->infilecnt;n++) {
+			filename = (*cmdline)[0];
+			if((exit_status = handle_other_infile(n,filename,dz))<0)
+				return(exit_status);
+			(*cmdline)++;
+			(*cmdlinecnt)--;
+		}
+	} else {
+		sprintf(errstr,"Insufficient input files for this process\n");
+		return(DATA_ERROR);
+	}
+	return(FINISHED);
+}
+

+ 62 - 0
dev/standnew/scales.c

@@ -0,0 +1,62 @@
+/*
+ *	SETHARES: The spectrum of an individual tone determines what notes (forming a scale)
+ *	will sound in-tune or consonant, and which not. e.g. in tempered or just intonation,
+ *	the octave sounds in tune because of the harmonic structure of the spectra of tones,
+ *	but we can construct spectra such that a minor-9th sounds less harsh than an octave.
+ *
+ *	Naive solution
+ *
+ *	(1) m scale-tones -> (m-1) interval ratios r[1],r[2],r[3] .....r[m-1]
+ *	(2) Choose a set of n partials f[1],f[2]....f[n], and amplitudes a[1],a[2]...a[n]
+ *		to minimise the sum of the dissonance over all the (m-1) intervals.
+ *
+ *	Constraints required
+ *
+ *	(1) a[k] all set to zero always give minimal dissonance
+ *	(2)	r[k] all very large also minimises dissonance
+ *
+ *	so we want to avoid these special cases.
+ *
+ *
+ *	INTRINSIC OR INHERENT DISSONANCE
+ *
+ *	Dissonance of a spectrum (the intrinsic or inherent dissonance - within one tone)
+ *
+ *	Df = 1/2 Z(j=1 to n)Z(k=1 to n)d(f[j],f[k],l[a],l[k])
+ *
+ *	where d(f[j],f[k],l[a],l[k]) = dissonance between partials f[j],f[k] with loudnesses l[j],l[k].
+ *
+ *	and "Z" = Sigma (i.e. sum over all values from j = 1 to j = n)
+ *
+ * (see accompanying text document)
+ *
+ *	Dissonance is defined in terms of SENSORY DISSONANCE.
+ *
+ *	If we play two sine tones of the same frequency together we hear 1 tone.
+ *	If we then gradually increase the frequency of the 2nd tone ..
+ *	(1) When tones are very close, we hear one pitch, with slow beating, relatively pleasant
+ *		(resolution of the ear cannot distinguish the two tones)
+ *	(2) The beating then becomes rapid and "rough" or "gritty", the peak of sensory dissonance.
+ *	(3) The two tones then gradually become distinguishable and dissonance fades away,
+ *		until we hear 2 clear tones.
+ *
+ *	The shape of the dissonance curve varies with the frequency chosen for the FIXED tone.
+ * (see accompanying text document)
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ */

+ 1373 - 0
dev/standnew/specenv.c

@@ -0,0 +1,1373 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <tkglobals.h>
+#include <pnames.h>
+#include <filetype.h>
+#include <processno.h>
+#include <modeno.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <math.h>
+#include <mixxcon.h>
+#include <osbind.h>
+#include <standalone.h>
+#include <speccon.h>
+#include <ctype.h>
+#include <sfsys.h>
+#include <string.h>
+#include <srates.h>
+
+#ifdef unix
+#define round(x) lround((x))
+#else
+#define round(x) cdp_round((x))
+#endif
+
+char errstr[2400];
+
+int anal_infiles = 1;
+int	sloom = 0;
+int sloombatch = 0;
+
+#define SE_IBUF1	0
+#define SE_IBUF2	1
+#define SE_OBUF		2
+#define SE_BUFEND	3
+
+#define CHAN_SRCHRANGE_F	(4)
+
+#define spececentrfrq specenvpch
+
+#define MINSPECAMP	
+
+const char* cdp_version = "7.1.0";
+
+/* CDP LIBRARY FUNCTIONS TRANSFERRED HERE */
+
+static int 	set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist);
+static int  set_vflgs(aplptr ap,char *optflags,int optcnt,char *optlist,
+				char *varflags,int vflagcnt, int vparamcnt,char *varlist);
+static int 	setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int	initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int	mark_parameter_types(dataptr dz,aplptr ap);
+static int  establish_application(dataptr dz);
+static int  application_init(dataptr dz);
+static int  initialise_vflags(dataptr dz);
+static int  setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int  setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int  get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int  assign_file_data_storage(int infilecnt,dataptr dz);
+
+/* CDP LIB FUNCTION MODIFIED TO AVOID CALLING setup_particular_application() */
+
+static int  parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+
+/* SIMPLIFICATION OF LIB FUNC TO APPLY TO JUST THIS FUNCTION */
+
+static int  parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int	handle_the_extra_infile(char ***cmdline,int *cmdlinecnt,dataptr dz);
+static int  handle_the_outfile(int *cmdlinecnt,char ***cmdline,int is_launched,dataptr dz);
+static int  setup_specenv_application(dataptr dz);
+static int  setup_specenv_param_ranges_and_defaults(dataptr dz);
+static int	check_specenv_param_validity_and_consistency(dataptr dz);
+static int  get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+static int  setup_and_init_input_brktable_constants(dataptr dz,int brkcnt);
+
+/* BYPASS LIBRARY GLOBAL FUNCTION TO GO DIRECTLY TO SPECIFIC APPLIC FUNCTIONS */
+
+static int do_specenv(dataptr dz);
+static int allocate_specenv_buffer(dataptr dz);
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status;
+	dataptr dz = NULL;
+	char **cmdline;
+	int  cmdlinecnt;
+	aplptr ap;
+	int is_launched = FALSE;
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+						/* CHECK FOR SOUNDLOOM */
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {					// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+					  
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc == 2) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		// setup_particular_application =
+		if((exit_status = setup_specenv_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+
+	// parse_infile_and_hone_type() = 
+	if((exit_status = parse_infile_and_check_type(cmdline,dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// setup_param_ranges_and_defaults() =
+	if((exit_status = setup_specenv_param_ranges_and_defaults(dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// open_first_infile		CDP LIB
+	if((exit_status = open_first_infile(cmdline[0],dz))<0) {	
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);	
+		return(FAILED);
+	}
+	cmdlinecnt--;
+	cmdline++;
+
+//	handle_extra_infiles() =
+	if((exit_status = handle_the_extra_infile(&cmdline,&cmdlinecnt,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// handle_outfile() = 
+	if((exit_status = handle_the_outfile(&cmdlinecnt,&cmdline,is_launched,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+//	handle_formants()			redundant
+//	handle_formant_quiksearch()	redundant
+//	handle_special_data()		redundant
+ 
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//check_param_validity_and_consistency .....
+	if((exit_status = check_specenv_param_validity_and_consistency(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	is_launched = TRUE;
+
+	//allocate_large_buffers() ... replaced by
+	dz->extra_bufcnt =  0; 
+	dz->bptrcnt = 3;
+	
+	if((exit_status = establish_spec_bufptrs_and_extra_buffers(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = allocate_specenv_buffer(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//param_preprocess()						redundant
+	//spec_process_file =
+	if((exit_status = do_specenv(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+	if((exit_status = complete_output(dz))<0) {										// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);		// CDP LIB
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+/************************ HANDLE_THE_EXTRA_INFILE *********************/
+
+int handle_the_extra_infile(char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+					/* OPEN ONE EXTRA ANALFILE, CHECK COMPATIBILITY */
+	int  exit_status;
+	char *filename;
+	fileptr fp2;
+	int fileno = 1;
+	double maxamp, maxloc;
+	int maxrep;
+	int getmax = 0, getmaxinfo = 0;
+	infileptr ifp;
+	fileptr fp1 = dz->infile; 
+	filename = (*cmdline)[0];
+	if((dz->ifd[fileno] = sndopenEx(filename,0,CDP_OPEN_RDONLY)) < 0) {
+		sprintf(errstr,"cannot open input file %s to read data.\n",filename);
+		return(DATA_ERROR);
+	}	
+	if((ifp = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to store data on later infile. (1)\n");
+		return(MEMORY_ERROR);
+	}
+	if((fp2 = (fileptr)malloc(sizeof(struct fileprops)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to store data on later infile. (2)\n");
+		return(MEMORY_ERROR);
+	}
+	if((exit_status = readhead(ifp,dz->ifd[1],filename,&maxamp,&maxloc,&maxrep,getmax,getmaxinfo))<0)
+		return(exit_status);
+	copy_to_fileptr(ifp,fp2);
+	if(fp2->filetype != ANALFILE) {
+		sprintf(errstr,"%s is not an analysis file.\n",filename);
+		return(DATA_ERROR);
+	}
+	if(fp2->origstype != fp1->origstype) {
+		sprintf(errstr,"Incompatible original-sample-type in input file %s.\n",filename);
+		return(DATA_ERROR);
+	}
+	if(fp2->origrate != fp1->origrate) {
+		sprintf(errstr,"Incompatible original-sample-rate in input file %s.\n",filename);
+		return(DATA_ERROR);
+	}
+	if(fp2->arate != fp1->arate) {
+		sprintf(errstr,"Incompatible analysis-sample-rate in input file %s.\n",filename);
+		return(DATA_ERROR);
+	}
+	if(fp2->Mlen != fp1->Mlen) {
+		sprintf(errstr,"Incompatible analysis-window-length in input file %s.\n",filename);
+		return(DATA_ERROR);
+	}
+	if(fp2->Dfac != fp1->Dfac) {
+		sprintf(errstr,"Incompatible decimation factor in input file %s.\n",filename);
+		return(DATA_ERROR);
+	}
+	if(fp2->channels != fp1->channels) {
+		sprintf(errstr,"Incompatible channel-count in input file %s.\n",filename);
+		return(DATA_ERROR);
+	}
+	if((dz->insams[fileno] = sndsizeEx(dz->ifd[fileno]))<0) {	    /* FIND SIZE OF FILE */
+		sprintf(errstr, "Can't read size of input file %s.\n"
+		"open_checktype_getsize_and_compareheader()\n",filename);
+		return(PROGRAM_ERROR);
+	}
+	if(dz->insams[fileno]==0) {
+		sprintf(errstr, "File %s contains no data.\n",filename);
+		return(DATA_ERROR);
+	}
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc, brkcnt;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	brkcnt = tipc;
+	//THERE ARE NO INPUTFILE brktables USED IN THIS PROCESS
+	if(brkcnt>0) {
+		if((exit_status = setup_and_init_input_brktable_constants(dz,brkcnt))<0)			  
+			return(exit_status);
+	}
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+			return(exit_status);
+	
+	// establish_infile_constants() replaced by
+	dz->infilecnt = ONE_NONSND_FILE;
+	//establish_bufptrs_and_extra_buffers():
+	dz->array_cnt=2;
+	if((dz->parray  = (double **)malloc(dz->array_cnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for internal double arrays.\n");
+		return(MEMORY_ERROR);
+	}
+	dz->parray[0] = NULL;
+	dz->parray[1] = NULL;
+	return(FINISHED);
+}
+
+/******************************** SETUP_AND_INIT_INPUT_BRKTABLE_CONSTANTS ********************************/
+
+int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt)
+{	
+	int n;
+	if((dz->brk      = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<brkcnt;n++) {
+		dz->brk[n]     = NULL;
+		dz->brkptr[n]  = NULL;
+		dz->brkinit[n] = 0;
+		dz->brksize[n] = 0;
+	}
+	return(FINISHED);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}						 		/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/***************************** HANDLE_THE_OUTFILE **************************/
+
+int handle_the_outfile(int *cmdlinecnt,char ***cmdline,int is_launched,dataptr dz)
+{
+	int exit_status;
+	char *filename = NULL;
+	filename = (*cmdline)[0];
+	strcpy(dz->outfilename,filename);	   
+	if((exit_status = create_sized_outfile(filename,dz))<0)
+		return(exit_status);
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/************************* SETUP_SPECENV_APPLICATION *******************/
+
+int setup_specenv_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	// SEE parstruct FOR EXPLANATION of next 2 functions
+	if((exit_status = set_param_data(ap,0   ,1,1,"i"      ))<0)
+		return(FAILED);
+	if((exit_status = set_vflgs(ap,"b",1,"d","pik",3,0,"000"))<0)
+		return(FAILED);
+	// set_legal_infile_structure -->
+	dz->has_otherfile = FALSE;
+	// assign_process_logic -->
+	dz->input_data_type = TWO_ANALFILES;
+	dz->process_type	= MIN_ANALFILE;	
+	dz->outfiletype  	= ANALFILE_OUT;
+	return application_init(dz);	//GLOBAL
+}
+
+/************************* PARSE_INFILE_AND_CHECK_TYPE *******************/
+
+int parse_infile_and_check_type(char **cmdline,dataptr dz)
+{
+	int exit_status;
+	infileptr infile_info;
+	if(!sloom) {
+		if((infile_info = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for infile structure to test file data.");
+			return(MEMORY_ERROR);
+		} else if((exit_status = cdparse(cmdline[0],infile_info))<0) {
+			sprintf(errstr,"Failed tp parse input file %s\n",cmdline[0]);
+			return(PROGRAM_ERROR);
+		} else if(infile_info->filetype != ANALFILE)  {
+			sprintf(errstr,"File %s is not of correct type\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if((exit_status = copy_parse_info_to_main_structure(infile_info,dz))<0) {
+			sprintf(errstr,"Failed to copy file parsing information\n");
+			return(PROGRAM_ERROR);
+		}
+		free(infile_info);
+	}
+	dz->clength		= dz->wanted / 2;
+	dz->chwidth 	= dz->nyquist/(double)(dz->clength-1);
+	dz->halfchwidth = dz->chwidth/2.0;
+	return(FINISHED);
+}
+
+/************************* SETUP_SPECENV_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_specenv_param_ranges_and_defaults(dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	// NB total_input_param_cnt is > 0 !!!s
+	if((exit_status = setup_input_param_range_stores(ap->total_input_param_cnt,ap))<0)
+		return(FAILED);
+	// get_param_ranges()
+	ap->lo[0]			= 1;
+	ap->hi[0]			= dz->clength;
+	ap->default_val[0]	= 60;
+	ap->lo[1]			= -1;
+	ap->hi[1]			= 1;
+	ap->default_val[1]	= 0;
+	dz->maxmode = 0;
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_specenv_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+/*********************** CHECK_SPECENV_PARAM_VALIDITY_AND_CONSISTENCY *********************/
+
+int check_specenv_param_validity_and_consistency(dataptr dz)
+{
+	int n, m;
+	double nextfrq, frqstep, jj, jj1, jj2;
+	if(dz->insams[0] > dz->insams[1]) {
+		sprintf(errstr,"First file is longer than 2nd: cannot proceed.\n");
+		return(GOAL_FAILED);
+	}
+	if(dz->vflag[0]) {		//	IF PITCHWISE
+		if(dz->iparam[0] > 4) {
+			sprintf(errstr,"For octave-wise spectral envelope, max octaves-per-window is 4.\n");
+			return(DATA_ERROR);
+		}
+	}
+	if(dz->param[1] == 1.0) {
+		sprintf(errstr,"Input file1 is not affected, if balance is set at 1.\n");
+		return(DATA_ERROR);
+	}
+	if(dz->param[1] == -1.0) {
+		sprintf(errstr,"Input file1 is merely replace by file2, if balance is set at -1.\n");
+		return(DATA_ERROR);
+	}
+	if((dz->specenvfrq = (float *)malloc(dz->wanted * sizeof(float)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for spectral envelope lower frequency boundaries.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->specenvtop = (float *)malloc(dz->wanted * sizeof(float)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for spectral envelope upper frequency boundaries.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->specenvamp = (float *)malloc(dz->wanted * sizeof(float)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for 1st spectral envelope amplitudes.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->specenvamp2 = (float *)malloc(dz->wanted * sizeof(float)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for 2nd spectral envelope amplitudes.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->spececentrfrq = (float *)malloc((dz->wanted + 1) * sizeof(float)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for 2nd spectral envelope amplitudes.\n");
+		return(MEMORY_ERROR);
+	}
+	n = 0;
+	dz->specenvfrq[n] = 0.0;
+	nextfrq = dz->halfchwidth;
+	dz->specenvtop[n] = (float)nextfrq;
+	n++;
+	if(dz->vflag[0])							//	octave-wise envelopes
+		frqstep = pow(2.0,dz->iparam[0]);		//	N-octave frq multiplier
+	else										//	frequency-wise envelopes
+		frqstep = dz->chwidth * dz->iparam[0];	//	equal frequency steps
+	while(nextfrq < dz->nyquist) {
+		if(n >= dz->clength) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for spectral envelope data.\n");
+			return(PROGRAM_ERROR);
+		}
+		dz->specenvfrq[n] = (float)nextfrq;
+		if(dz->vflag[0])
+			nextfrq *= frqstep;
+		else
+			nextfrq += frqstep;
+		dz->specenvtop[n] = (float)nextfrq;
+		n++;
+	}
+	dz->specenvcnt = n;
+	dz->spececentrfrq[0] = 0.0; 
+	if(dz->vflag[0]) {
+		for(n = 0, m= 1; n < dz->specenvcnt; n++,m++) {
+			hztomidi(&jj1,dz->specenvtop[n]);
+			hztomidi(&jj2,dz->specenvfrq[n]);
+			jj = (jj1 + jj2)/2.0;
+			dz->spececentrfrq[m] = (float)miditohz(jj);			//	NB THESE ARE STORED AS FREQUENCIES
+		}
+	} else {
+		for(n = 0, m= 1; n < dz->specenvcnt; n++,m++)
+			dz->spececentrfrq[m] = (float)((dz->specenvtop[n] + dz->specenvfrq[n])/2.0);
+	}
+	return FINISHED;
+}
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int read_special_data(char *str,dataptr dz)	
+{
+	return(FINISHED);
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if      (!strcmp(prog_identifier_from_cmdline,"specenv"))			dz->process = SPECENV;
+	else {
+		sprintf(errstr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/**************************** allocate_specenv_buffer ******************************/
+
+int allocate_specenv_buffer(dataptr dz)
+{
+	unsigned int buffersize;
+	buffersize = dz->wanted * (dz->bptrcnt + 1);
+	dz->buflen = dz->wanted;
+	if((dz->bigfbuf	= (float*) malloc(buffersize * sizeof(float)))==NULL) {  
+		sprintf(errstr,"INSUFFICIENT MEMORY for sound buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	dz->flbufptr[SE_IBUF1]	= dz->bigfbuf;							//	inbuf1
+	dz->flbufptr[SE_IBUF2]	= dz->flbufptr[SE_IBUF1] + dz->wanted;	//	inbuf2
+	dz->flbufptr[SE_OBUF]	= dz->flbufptr[SE_IBUF2] + dz->wanted;	//	obuf
+	dz->flbufptr[SE_BUFEND]	= dz->flbufptr[SE_OBUF]  + dz->wanted;	//	end of bufs
+	return(FINISHED);
+}
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+	return(usage2("specenv"));
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+	if(!strcmp(str,"specenv")) {
+		fprintf(stderr,
+	    "USAGE:\n"
+		"specenv specenv inanalfil1 inanalfil2 outanalfil windowsize [-bbal] [-p] [-i] [-k]\n"
+		"\n"
+		"Get the spectral envelope of file 2 and apply it to file 1.\n"
+		"(File 2 must be at least as long as file 1).\n"
+		"\n"
+		"BAL  proportion of original files in output.\n"
+		"     bal > 1 : balance of shaped-file to infile1 = (1-bal) : bal\n"
+		"               (Higher balance keeps more of the original file1)\n" 
+		"     bal < 1 : balance of shaped-file to infile2 = (1+bal) : -bal\n"
+		"               (Lower balance keeps more of the imposed file2)\n" 
+		"     default 0.0 (none of the original files in the output).\n"
+		"\n"
+		"-p : windowsize counted in octave steps.\n"
+		"     Default: counted in analysis-channel-widths (srate/anal-chans).\n"
+		"\n"
+		"-i : IMPOSE spectral envelope (default, REPLACE spectral envelope)\n"	
+		"\n"
+		"-k : KEEP the loudness contour of the imposed file.\n"	
+		"     Default: keep the loudness contour of the original file.\n"
+		"\n"
+		"Process equivalent to format extraction + formant impose/replace\n"
+		"but allows for larger spectral windows.\n"
+		"\n");
+	} else {
+		fprintf(stderr,
+		"Unknown option '%s'\n"
+	    "USAGE:\n"
+		"specenv specenv inanalfil1 inanalfil2 outanalfil windowsize [-f] [-i]\n",str);
+	}	
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	fprintf(stderr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/*********************** INNER_LOOP ***************************/
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return FINISHED;
+}
+
+/**************************** DO_SPECENV ****************************/
+
+int do_specenv(dataptr dz)
+{
+	int exit_status, cc, vc, cnt, botchan, topchan, bwidth_in_chans;
+	int n, samps_read1, samps_read2, wcnt;
+	float *ibuf1, *ibuf2, *obuf;
+	float topfreq, botfreq, frq, specfrq, up_specfrq, dn_specfrq, loamp, hiamp, amp1 = 0.0, amp2;
+	double diff, ratio, pch, up_specpch, dn_specpch, ampdiff, ampstep, maxiamp = 0.0, maxiamp2 = 0.0, maxoamp = 0.0;
+	double balance = dz->param[1];
+
+	ibuf1 = dz->flbufptr[SE_IBUF1];
+	ibuf2 = dz->flbufptr[SE_IBUF2];
+	obuf  = dz->flbufptr[SE_OBUF];
+
+	//	READ A WINDOW FROM EACH FILE
+	wcnt = 0;
+	while((samps_read1 = fgetfbufEx(ibuf1, dz->buflen,dz->ifd[0],0)) > 0) {
+		if(samps_read1 < 0) {
+			sprintf(errstr,"Failed to read data from first input file.\n");
+			return(SYSTEM_ERROR);
+		}
+		samps_read2 = fgetfbufEx(ibuf2, dz->buflen,dz->ifd[1],0);
+		if(samps_read2 < 0) {
+			sprintf(errstr,"Failed to read data from second input file.\n");
+			return(SYSTEM_ERROR);
+		}
+		topfreq = 0.0f;
+		n = 0;
+		while(n < dz->specenvcnt) {		//	Extract spectral envelope of both files
+			botfreq  = topfreq;
+			botchan  = (int)floor(botfreq/dz->chwidth); /* TRUNCATE */
+			botchan -= CHAN_SRCHRANGE_F;
+			botchan  =  max(botchan,0);
+			topfreq  = dz->specenvtop[n];
+			topchan  = (int)floor(topfreq/dz->chwidth); /* TRUNCATE */
+			topchan += CHAN_SRCHRANGE_F;
+			topchan  =  min(topchan,dz->clength);
+			for(cc = botchan,vc = botchan * 2; cc < topchan; cc++,vc += 2) {
+				if(fabs(ibuf1[FREQ]) >= botfreq && fabs(ibuf1[FREQ]) < topfreq)
+					dz->specenvamp[n] = (float)(dz->specenvamp[n] + ibuf1[AMPP]);
+				if(fabs(ibuf2[FREQ]) >= botfreq && fabs(ibuf2[FREQ]) < topfreq)
+					dz->specenvamp2[n] = (float)(dz->specenvamp2[n] + ibuf2[AMPP]);
+			}
+			bwidth_in_chans    = max(1,(int)round((topfreq - botfreq)/dz->chwidth));
+			dz->specenvamp[n]  = (float)(dz->specenvamp[n]/bwidth_in_chans);
+			dz->specenvamp2[n] = (float)(dz->specenvamp2[n]/bwidth_in_chans);
+			n++;
+		}
+		if(!dz->vflag[2]) {
+			maxiamp  = 0.0;
+			maxiamp2 = 0.0;
+			maxoamp  = 0.0;
+		}
+		for(cc = 0,vc = 0; cc < dz->clength; cc++,vc += 2) {
+			//	FOR EACH FREQUNCY IN THE SPECTRUM ....
+			
+			frq = (float)fabs(ibuf1[FREQ]);
+
+			//	FIND THE SPECTRAL ENVELOPE LEVELS (amp1 & amp2) corresponding TO THIS FRQ
+			
+			cnt = 1;											//	speccentrecnt counts 0 to n	| |	  |	  |		centre frqs of bands + val at 0Hz
+																//	specenv boundaries 0 to n-1	|___|___|___	bottom frqs of bands
+			specfrq = 	dz->spececentrfrq[cnt];					//	specamp vals 0 to n-1		  |	  |	  |		average amplitudes of bands
+			while(frq > specfrq) {
+				cnt++;											//	Search envelope bands until envband-frq is > input frq
+				specfrq = dz->spececentrfrq[cnt];
+			}
+			if(dz->vflag[0]) {	// PITCHWISE					
+				hztomidi(&pch,frq);
+				hztomidi(&up_specpch,specfrq);
+				cnt--;
+				hztomidi(&dn_specpch,dz->spececentrfrq[cnt]);
+				diff = up_specpch - dn_specpch;	
+				ratio = (pch - dn_specpch)/diff;
+			} else {			//	FRQWISE						//	thisfrq = *					0   1   2*  3   4   
+				up_specfrq = specfrq;							//	specenv boundaries			|___|___|*__|___|___	bottom frqs of bands
+				cnt--;											//	speccentrefrq-hi			x x	  x	 *|	  x	  x		cnt = 3
+				dn_specfrq = dz->spececentrfrq[cnt];			//	speccentrefrq-lo			x x	  |	 *x	  x	  x		cnt = 2
+				diff = up_specfrq - dn_specfrq;					//	cnt of centres				0 1	 ~2~ ~3~  4	  5     
+				ratio = (frq - dn_specfrq)/diff;				//										\
+																//	count of HIampval (below)	  0	  1  ~2~  3	  4
+																//	HIamp						  a	  a	  A	  a	  a		cnt = 2 (for hiamp)
+			}
+
+			//	INTERPOLATE FOR SPECTRAL ENVELOPE AMPLITUDE AT THIS PARTICULAR FREQUENCY, IN BOTH ENVELOPES (if ness)
+		
+			if(!dz->vflag[1]) {		//	i.e. IMPOSE rather than REPLACE
+				hiamp = dz->specenvamp[cnt];					//	count of ampvals			  0	  1	 ~2~  3	  4
+				loamp = dz->specenvamp[cnt - 1];				//	hiamp						  a	  a	  A	  a	  a
+				ampdiff = hiamp - loamp;						//	loamp						  a	  A	  a	  a	  a
+				ampstep = ampdiff * ratio;						//	count of ampvals			  0	 ~1~  2   3	  4
+				amp1 = (float)(loamp + ampstep);
+			}
+			hiamp = dz->specenvamp2[cnt];
+			loamp = dz->specenvamp2[cnt - 1];
+			ampdiff = hiamp - loamp;
+			ampstep = ampdiff * ratio;
+			amp2 = (float)(loamp + ampstep);
+
+			if(dz->vflag[1])	//	IMPOSE
+				obuf[AMPP] = (float)(ibuf1[AMPP] * amp2);
+			else {				//	REPLACE
+				if(amp1 > MINAMP)
+					obuf[AMPP] = (float)(ibuf1[AMPP] * amp2/amp1);
+				else
+					obuf[AMPP] = ibuf1[AMPP];
+			}
+			obuf[FREQ] = ibuf1[FREQ];
+			if(!dz->vflag[2]) {
+				maxiamp  = max(maxiamp,ibuf1[AMPP]);
+				maxiamp2 = max(maxiamp2,ibuf2[AMPP]);
+				maxoamp  = max(maxoamp,obuf[AMPP]);
+			}
+		}	
+		if(!dz->vflag[2]) {
+			if((maxiamp2 < MINAMP) && maxiamp > MINAMP) {				//	If the superimposed spectrum level is (almost) zero, and the orig spectrum isn't
+				for(cc = 0,vc = 0; cc <dz->clength; cc++, vc +=2)		//	Keep the orig spectrum
+					obuf[AMPP] = ibuf1[AMPP];
+			} else if(maxoamp > MINAMP) {								//	Else (if the maxoutput spectrum is not almost zero)
+				for(cc = 0,vc = 0; cc <dz->clength; cc++, vc +=2)		//	adjust output level to level of input
+					obuf[AMPP] = (float)(obuf[AMPP] * maxiamp/maxoamp);
+			} else if(maxiamp > MINAMP) {								//	else, if input is not (nearly) zero, replace output by input
+				for(cc = 0,vc = 0; cc <dz->clength; cc++, vc +=2)
+					obuf[AMPP] = ibuf1[AMPP];
+			}
+		}
+		if(balance > 0.0) {
+			for(cc = 0,vc = 0; cc <dz->clength; cc++, vc +=2)
+				obuf[AMPP] = (float)((obuf[AMPP] * (1.0 - balance)) + (ibuf1[AMPP] * balance));
+		} else if(balance < 0.0) {
+			for(cc = 0,vc = 0; cc <dz->clength; cc++, vc +=2)
+				obuf[AMPP] = (float)((obuf[AMPP] * (1.0 + balance)) - (ibuf2[AMPP] * balance));
+		}
+		if((exit_status = write_samps(obuf,dz->wanted,dz))<0)
+			return(exit_status);
+		wcnt++;
+	}
+	return FINISHED;
+}

+ 1261 - 0
dev/standnew/speculation.c

@@ -0,0 +1,1261 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <tkglobals.h>
+#include <pnames.h>
+#include <filetype.h>
+#include <processno.h>
+#include <modeno.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <math.h>
+#include <mixxcon.h>
+#include <osbind.h>
+#include <standalone.h>
+#include <speccon.h>
+#include <ctype.h>
+#include <sfsys.h>
+#include <string.h>
+#include <srates.h>
+
+#ifdef unix
+#define round lround
+#endif
+
+char errstr[2400];
+
+int anal_infiles = 1;
+int	sloom = 0;
+int sloombatch = 0;
+
+const char* cdp_version = "7.0.0";
+
+/* CDP LIBRARY FUNCTIONS TRANSFERRED HERE */
+
+static int 	set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist);
+static int  set_vflgs(aplptr ap,char *optflags,int optcnt,char *optlist,
+				char *varflags,int vflagcnt, int vparamcnt,char *varlist);
+static int 	setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int	initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int	mark_parameter_types(dataptr dz,aplptr ap);
+static int  establish_application(dataptr dz);
+static int  application_init(dataptr dz);
+static int  initialise_vflags(dataptr dz);
+static int  setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int  setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int  get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int  assign_file_data_storage(int infilecnt,dataptr dz);
+
+/* CDP LIB FUNCTION MODIFIED TO AVOID CALLING setup_particular_application() */
+
+static int  parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+
+/* SIMPLIFICATION OF LIB FUNC TO APPLY TO JUST THIS FUNCTION */
+
+static int  parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int  handle_the_outfile(int *cmdlinecnt,char ***cmdline,int is_launched,dataptr dz);
+static int  setup_the_application(dataptr dz);
+static int  setup_the_param_ranges_and_defaults(dataptr dz);
+static int	check_the_param_validity_and_consistency(dataptr dz);
+static int  get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+static int  setup_and_init_input_brktable_constants(dataptr dz,int brkcnt);
+static void insert_newnumber_at_filename_end(char *filename,int num,int overwrite_last_char);
+
+/* BYPASS LIBRARY GLOBAL FUNCTION TO GO DIRECTLY TO SPECIFIC APPLIC FUNCTIONS */
+
+static int create_next_outfile(dataptr dz);
+static int allocate_speculation_buffer(dataptr dz);
+static int swap_chans(int startchan,int endchan,int windows_in_buf,dataptr dz);
+static int speculate(dataptr dz);
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status;
+	dataptr dz = NULL;
+	char **cmdline;
+	int  cmdlinecnt;
+	aplptr ap;
+	int is_launched = FALSE;
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+						/* CHECK FOR SOUNDLOOM */
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {					// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+					  
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc == 2) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		dz->maxmode = 0;
+		if((exit_status = setup_the_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+	// parse_infile_and_hone_type() = 
+	if((exit_status = parse_infile_and_check_type(cmdline,dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// setup_param_ranges_and_defaults() =
+	if((exit_status = setup_the_param_ranges_and_defaults(dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// open_first_infile		CDP LIB
+	if((exit_status = open_first_infile(cmdline[0],dz))<0) {	
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);	
+		return(FAILED);
+	}
+	cmdlinecnt--;
+	cmdline++;
+
+	if((exit_status = handle_the_outfile(&cmdlinecnt,&cmdline,is_launched,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+//	handle_formants()			redundant
+//	handle_formant_quiksearch()	redundant
+//	handle_special_data()		redundant except
+
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//check_param_validity_and_consistency .....
+	if((exit_status = check_the_param_validity_and_consistency(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	is_launched = TRUE;
+	dz->extra_bufcnt =  0;	
+	dz->bptrcnt = 1;
+	if((exit_status = establish_spec_bufptrs_and_extra_buffers(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = allocate_speculation_buffer(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//param_preprocess()						redundant
+	//spec_process_file =
+	if((exit_status = speculate(dz))< 0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+	if((exit_status = complete_output(dz))<0) {										// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);		// CDP LIB
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc, brkcnt;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	brkcnt = tipc;
+	if(brkcnt>0) {
+		if((exit_status = setup_and_init_input_brktable_constants(dz,brkcnt))<0)			  
+			return(exit_status);
+	}
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+			return(exit_status);
+	
+	// establish_infile_constants() replaced by
+	dz->infilecnt = 1;
+	return(FINISHED);
+}
+
+/******************************** SETUP_AND_INIT_INPUT_BRKTABLE_CONSTANTS ********************************/
+
+int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt)
+{	
+	int n;
+	if((dz->brk      = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<brkcnt;n++) {
+		dz->brk[n]     = NULL;
+		dz->brkptr[n]  = NULL;
+		dz->brkinit[n] = 0;
+		dz->brksize[n] = 0;
+	}
+	return(FINISHED);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}						 		/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/***************************** HANDLE_THE_OUTFILE **************************/
+
+int handle_the_outfile(int *cmdlinecnt,char ***cmdline,int is_launched,dataptr dz)
+{
+	int exit_status;
+	char *p, *q;
+	if(dz->wordstor!=NULL)
+		free_wordstors(dz);
+	dz->all_words = 0;
+	if((exit_status = store_filename((*cmdline)[0],dz))<0)
+		return(exit_status);
+	p = dz->wordstor[0];
+	q = p;
+	p += strlen(dz->wordstor[0]);
+	p--;
+	while(p > q) {				//	Strip file extension
+		if(*p == '.') {
+			*p = ENDOFSTR;
+			break;
+		}
+		p--;
+	}
+	strcpy(dz->outfilename,dz->wordstor[0]);
+	dz->itemcnt = 0;
+	if(sloom)
+		insert_newnumber_at_filename_end(dz->outfilename,dz->itemcnt,1);
+	else
+		insert_newnumber_at_filename_end(dz->outfilename,dz->itemcnt,0);
+	if((exit_status = create_sized_outfile(dz->outfilename,dz))<0)
+		return(exit_status);
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/***************************** CREATE_NEXT_OUTFILE **************************/
+
+int create_next_outfile(dataptr dz)
+{
+	int exit_status;
+	dz->itemcnt++;
+	strcpy(dz->outfilename,dz->wordstor[0]);
+	if(sloom)
+		insert_newnumber_at_filename_end(dz->outfilename,dz->itemcnt,1);
+	else
+		insert_newnumber_at_filename_end(dz->outfilename,dz->itemcnt,0);
+	if((exit_status = create_sized_outfile(dz->outfilename,dz))<0)
+		return(exit_status);
+	return(FINISHED);
+}
+
+/***************************** INSERT_NEWNUMBER_AT_FILENAME_END **************************/
+
+void insert_newnumber_at_filename_end(char *filename,int num,int overwrite_last_char)
+/* FUNCTIONS ASSUMES ENOUGH SPACE IS ALLOCATED !! */
+{
+	char *p;
+	char ext[64];
+	p = filename + strlen(filename) - 1;
+	while(p > filename) {
+		if(*p == '/' || *p == '\\' || *p == ':') {
+			p = filename;
+			break;
+		}
+		if(*p == '.') {
+			strcpy(ext,p);
+			if(overwrite_last_char)
+				p--;
+			sprintf(p,"%d",num);
+			strcat(filename,ext);
+			return;
+		}
+		p--;
+	}
+	if(p == filename) {
+		p += strlen(filename);
+		if(overwrite_last_char)
+			p--;
+		sprintf(p,"%d",num);
+	}
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/************************* SETUP_THE_APPLICATION *******************/
+
+int setup_the_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	// SEE parstruct FOR EXPLANATION of next 2 functions
+	if((exit_status = set_param_data(ap,0   ,2,2,"dd"      ))<0)
+		return(FAILED);
+	if((exit_status = set_vflgs(ap,"",0,"","r",1,0,"0"))<0)
+		return(FAILED);
+	dz->has_otherfile = FALSE;
+	dz->input_data_type = ANALFILE_ONLY;
+	dz->process_type	= EQUAL_ANALFILE;	
+	dz->outfiletype  	= ANALFILE_OUT;
+	return application_init(dz);	//GLOBAL
+}
+
+/************************* PARSE_INFILE_AND_CHECK_TYPE *******************/
+
+int parse_infile_and_check_type(char **cmdline,dataptr dz)
+{
+	int exit_status;
+	infileptr infile_info;
+	if(!sloom) {
+		if((infile_info = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for infile structure to test file data.");
+			return(MEMORY_ERROR);
+		} else if((exit_status = cdparse(cmdline[0],infile_info))<0) {
+			sprintf(errstr,"Failed tp parse input file %s\n",cmdline[0]);
+			return(PROGRAM_ERROR);
+		} else if(infile_info->filetype != ANALFILE)  {
+			sprintf(errstr,"File %s is not of correct type\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if((exit_status = copy_parse_info_to_main_structure(infile_info,dz))<0) {
+			sprintf(errstr,"Failed to copy file parsing information\n");
+			return(PROGRAM_ERROR);
+		}
+		free(infile_info);
+	}
+	dz->clength		= dz->wanted / 2;
+	dz->chwidth 	= dz->nyquist/(double)(dz->clength-1);
+	dz->halfchwidth = dz->chwidth/2.0;
+	return(FINISHED);
+}
+
+/************************* SETUP_THE_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_the_param_ranges_and_defaults(dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	// NB total_input_param_cnt is > 0 !!!s
+	if((exit_status = setup_input_param_range_stores(ap->total_input_param_cnt,ap))<0)
+		return(FAILED);
+	// get_param_ranges()
+	ap->lo[0]			= 0;
+	ap->hi[0]			= dz->nyquist;
+	ap->default_val[0]	= 0;
+	ap->lo[1]			= 0;
+	ap->hi[1]			= dz->nyquist;
+	ap->default_val[1]	= dz->nyquist;
+	dz->maxmode = 0;
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_the_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+/*********************** CHECK_THE_PARAM_VALIDITY_AND_CONSISTENCY *********************/
+
+int check_the_param_validity_and_consistency(dataptr dz)
+{
+	int diff;
+	if(dz->param[1] <= dz->param[0]) {
+		sprintf(errstr,"Min frq (%lf) must be less than the max frq (%lf)\n",dz->param[0],dz->param[1]);
+		return(MEMORY_ERROR);
+	}
+	dz->iparam[0] = (int)round(dz->param[0]/dz->chwidth); 
+	dz->iparam[1] = (int)round(dz->param[1]/dz->chwidth); 
+	if((diff = dz->iparam[1] - dz->iparam[0]) < 3) {
+		sprintf(errstr,"Min and max frqs must be separated by at least %lf Hz\n",dz->chwidth * 3);
+		return(MEMORY_ERROR);
+	}
+	if(EVEN(diff)) {			//	(diff is ODD if chan-cnt is EVEN) Force an even number of channels 
+		if(dz->iparam[1] < dz->clength - 1)
+			dz->iparam[1]++;
+		else if(dz->iparam[0] > 0)
+			dz->iparam[0]--;
+		else
+			dz->iparam[1]--;
+	}
+	return FINISHED;
+}
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int read_special_data(char *str,dataptr dz)	
+{
+	return(FINISHED);
+}
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return FINISHED;
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if      (!strcmp(prog_identifier_from_cmdline,"speculate"))		dz->process = SPECULATE;
+	else {
+		sprintf(errstr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+	fprintf(stderr,
+	"\nPERMUTATIONS ON ANALYSIS FILE SPECTRA\n\n"
+	"USAGE: speculate NAME (mode) infile(s) outfile parameters: \n"
+	"\n"
+	"where NAME can be any one of\n"
+	"\n"
+	"speculation\n\n"
+	"Type 'speculate speculate' for more info on speculate speculate..ETC.\n");
+	return(USAGE_ONLY);
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+	if(!strcmp(str,"speculate")) {
+		fprintf(stdout,
+	    "USAGE:\n"
+		"speculate speculate inanalfile generic-outname minfrq maxfrq [-r]\n"
+		"\n"
+		"OUTNAME    generic name for the (numbered) output files to generate.\n"
+		"MINFRQ     minimum frequency to partake in channel-permutations.\n"
+		"MAXFRQ     maximum frequency to partake in channel-permutations.\n"
+		"-r         remove any other components.\n"
+		"\n"
+		"Generates versions of source with channel data progressively permuted.\n"
+		"Using bell-ringing \"Plain Bob\" type channel-swapping sequence.\n"
+		"\n");
+	} else
+		fprintf(stdout,"Unknown option '%s'\n",str);
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	fprintf(stderr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/*********************** SPECULATE ***************************/
+
+int speculate(dataptr dz)
+{
+	int exit_status;
+	float *buf = dz->bigfbuf;
+	unsigned int cnt, outcnt;
+	int chans_to_swap, windows_in_buf = dz->insams[0]/dz->wanted;
+	chans_to_swap = dz->iparam[1] - dz->iparam[0] + 1;
+	outcnt = chans_to_swap * 2;
+	cnt = 0;
+/* TEST */
+fprintf(stderr,"AAA dz->itemcnt = %d\n",dz->itemcnt);
+/* TEST */
+	fprintf(stdout,"INFO: Number of output files to create = %d\n",outcnt);
+	fflush(stdout);
+	while(cnt < outcnt) {
+		if(cnt == 0) {
+			if((exit_status = read_samps(buf,dz))<0)
+				return(exit_status);
+		} else {
+			if((exit_status = headwrite(dz->ofd,dz))<0)
+				return(exit_status);
+			if((exit_status = reset_peak_finder(dz))<0)
+				return(exit_status);
+			if(sndcloseEx(dz->ofd) < 0) {
+				fprintf(stdout,"WARNING: Can't close output soundfile %s\n",dz->outfilename);
+				fflush(stdout);
+			}
+			dz->ofd = -1;
+			if((exit_status = create_next_outfile(dz)) < 0)
+				return(exit_status);
+		}
+		if(EVEN(cnt)) {
+			if((exit_status = swap_chans(dz->iparam[0],dz->iparam[1],windows_in_buf,dz)) < 0)		//	Swaps all channels (even number chans)
+				return(exit_status);
+		} else {
+			if((exit_status = swap_chans(dz->iparam[0]+1,dz->iparam[1],windows_in_buf,dz)) < 0)		//	Swaps all but outer channels (even number chans)
+				return(exit_status);
+		}																							//	Process accumulates i.e. acts on previously-altered buffer
+		dz->total_samps_written = 0;
+		if((exit_status = write_samps(buf,dz->buflen,dz))<0)
+			return(exit_status);
+		cnt++;
+		fprintf(stdout,"INFO: Written output file %d\n",cnt);
+		fflush(stdout);
+	}
+	return(FINISHED);
+}
+
+/**************************** SWAP_CHANS ****************************/
+
+int swap_chans(int startchan,int endchan,int windows_in_buf,dataptr dz)
+{
+	int wc, cc, vc;
+	float temp;
+	dz->flbufptr[0] = dz->bigfbuf;
+	for(wc=0; wc<windows_in_buf; wc++) {
+		for(cc = startchan; cc < endchan; cc+=2) {
+			vc = cc * 2;
+			temp = dz->flbufptr[0][vc+2];				//	Swap amplitudes of adjacent channels
+			dz->flbufptr[0][vc+2] = dz->flbufptr[0][vc];
+			dz->flbufptr[0][vc] = temp;
+		}	
+		dz->flbufptr[0] += dz->wanted;
+	}
+	return FINISHED;
+}
+
+/**************************** SETUP_SPECSLICE_PARAMETER_STORAGE ****************************/
+
+int setup_specslice_parameter_storage(dataptr dz) {
+
+	if((dz->brk      = (double **)realloc(dz->brk,2 * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_specslice_parameter_storage(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)realloc(dz->brkptr,2 * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_specslice_parameter_storage(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)realloc(dz->brksize,2 * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_specslice_parameter_storage(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)realloc(dz->firstval,2 * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_specslice_parameter_storage(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)realloc(dz->lastind,2 * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_specslice_parameter_storage(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)realloc(dz->lastval,2 * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_specslice_parameter_storage(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)realloc(dz->brkinit,2 * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_specslice_parameter_storage(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	dz->brk[1]     = NULL;
+	dz->brkptr[1]  = NULL;
+	dz->brkinit[1] = 0;
+	dz->brksize[1] = 0;
+	if((dz->param       = (double *)realloc(dz->param,2 * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_specslice_parameter_storage(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)realloc(dz->iparam, 2 * sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_specslice_parameter_storage(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)realloc(dz->is_int,2 * sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_specslice_parameter_storage(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)realloc(dz->no_brk,2 * sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_specslice_parameter_storage(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_active   = (char   *)realloc(dz->is_active,2 * sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	dz->is_int[1] = 0;
+	dz->is_active[1] = 1;
+	dz->no_brk[1] = (char)0;
+	return FINISHED;
+}
+
+/**************************** ALLOCATE_SPECULATION_BUFFER ******************************
+ * Make buffer to contain entire input sound.
+ */
+
+int allocate_speculation_buffer(dataptr dz)
+{
+	unsigned int buffersize;
+	buffersize = dz->insams[0];
+	dz->buflen = buffersize;
+	buffersize += 1;
+	if((dz->bigfbuf	= (float*) malloc(buffersize * sizeof(float)))==NULL) {  
+		sprintf(errstr,"INSUFFICIENT MEMORY for sound buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	dz->big_fsize = dz->buflen;
+	dz->bigfbuf[dz->big_fsize] = 0.0f;	/* safety value */
+	return(FINISHED);
+}
+

+ 1352 - 0
dev/standnew/spike.c

@@ -0,0 +1,1352 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <tkglobals.h>
+#include <pnames.h>
+#include <filetype.h>
+#include <processno.h>
+#include <modeno.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <math.h>
+#include <mixxcon.h>
+#include <osbind.h>
+#include <standalone.h>
+#include <ctype.h>
+#include <sfsys.h>
+#include <string.h>
+#include <srates.h>
+
+
+#ifdef unix
+#define round(x) lround((x))
+#endif
+
+char errstr[2400];
+
+int anal_infiles = 1;
+int	sloom = 0;
+int sloombatch = 0;
+
+const char* cdp_version = "6.1.0";
+
+//CDP LIB REPLACEMENTS
+static int check_gate_param_validity_and_consistency(dataptr dz);
+static int setup_spike_application(dataptr dz);
+static int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+static int parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int setup_spike_param_ranges_and_defaults(dataptr dz);
+static int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int establish_application(dataptr dz);
+static int initialise_vflags(dataptr dz);
+static int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int mark_parameter_types(dataptr dz,aplptr ap);
+static int assign_file_data_storage(int infilecnt,dataptr dz);
+static int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+static int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt);
+static int handle_the_special_data(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int spike(dataptr dz);
+static void TrimPeakData(dataptr dz);
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status;
+	dataptr dz = NULL;
+	char **cmdline;
+	int  cmdlinecnt;
+	int n;
+	aplptr ap;
+	int is_launched = FALSE;
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+						/* CHECK FOR SOUNDLOOM */
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {					// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc == 2) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+	}
+	if(!sloom) {
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		dz->maxmode = 0;
+		// setup_particular_application =
+		if((exit_status = setup_spike_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+
+	// parse_infile_and_hone_type() = 
+	if((exit_status = parse_infile_and_check_type(cmdline,dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// setup_param_ranges_and_defaults() =
+	if((exit_status = setup_spike_param_ranges_and_defaults(dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// open_first_infile		CDP LIB
+	if((exit_status = open_first_infile(cmdline[0],dz))<0) {	
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);	
+		return(FAILED);
+	}
+	cmdlinecnt--;
+	cmdline++;
+
+//	handle_extra_infiles() : redundant
+	// handle_outfile() = 
+	if((exit_status = handle_the_outfile(&cmdlinecnt,&cmdline,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+//	handle_formants()			redundant
+//	handle_formant_quiksearch()	redundant
+//	handle_special_data ...
+	if((exit_status = handle_the_special_data(&cmdlinecnt,&cmdline,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	is_launched = TRUE;
+	dz->bufcnt = 2;
+	if((dz->sampbuf = (float **)malloc(sizeof(float *) * (dz->bufcnt+1)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->sbufptr = (float **)malloc(sizeof(float *) * dz->bufcnt))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffer pointers.\n");
+		return(MEMORY_ERROR);
+	}
+	for(n = 0;n <dz->bufcnt; n++)
+		dz->sampbuf[n] = dz->sbufptr[n] = (float *)0;
+	dz->sampbuf[n] = (float *)0;
+
+	if(dz->param[2] > 0.0 || dz->param[3] > 0.0)
+		TrimPeakData(dz);
+
+	if((exit_status = create_sndbufs(dz))<0) {							// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//param_preprocess()						redundant
+	//spec_process_file =
+	if((exit_status = spike(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = complete_output(dz))<0) {										// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);		// CDP LIB
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc, brkcnt;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	brkcnt = tipc;
+	//THERE ARE NO INPUTFILE brktables USED IN THIS PROCESS
+	if(brkcnt>0) {
+		if((exit_status = setup_and_init_input_brktable_constants(dz,brkcnt))<0)			  
+			return(exit_status);
+	}
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+		return(exit_status);
+	
+	// establish_infile_constants() replaced by
+	dz->infilecnt = 1;
+	//establish_bufptrs_and_extra_buffers():
+	return(FINISHED);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}						 		/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_OUTFILE *********************/
+
+int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status;
+	char *filename = (*cmdline)[0];
+	if(filename[0]=='-' && filename[1]=='f') {
+		dz->floatsam_output = 1;
+		dz->true_outfile_stype = SAMP_FLOAT;
+		filename+= 2;
+	}
+	if(!sloom) {
+		if(file_has_invalid_startchar(filename) || value_is_numeric(filename)) {
+			sprintf(errstr,"Outfile name %s has invalid start character(s) or looks too much like a number.\n",filename);
+			return(DATA_ERROR);
+		}
+	}
+	strcpy(dz->outfilename,filename);	   
+	if((exit_status = create_sized_outfile(filename,dz))<0)
+		return(exit_status);
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/************************* SETUP_SPIKE_APPLICATION *******************/
+
+int setup_spike_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	// SEE parstruct FOR EXPLANATION of next 2 functions
+	if((exit_status = set_param_data(ap,SPIKEDATA   ,2,2,"DD"))<0)
+		return(FAILED);
+	if((exit_status = set_vflgs(ap,"ud",2,"dd","n",1,0,"0"))<0)
+		return(FAILED);
+	// set_legal_infile_structure -->
+	dz->has_otherfile = FALSE;
+	// assign_process_logic -->
+	dz->input_data_type = SNDFILES_ONLY;
+	dz->process_type	= EQUAL_SNDFILE;	
+	dz->outfiletype  	= SNDFILE_OUT;
+	return application_init(dz);	//GLOBAL
+}
+
+/************************* PARSE_INFILE_AND_CHECK_TYPE *******************/
+
+int parse_infile_and_check_type(char **cmdline,dataptr dz)
+{
+	int exit_status;
+	infileptr infile_info;
+	if(!sloom) {
+		if((infile_info = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for infile structure to test file data.");
+			return(MEMORY_ERROR);
+		} else if((exit_status = cdparse(cmdline[0],infile_info))<0) {
+			sprintf(errstr,"Failed to parse input file %s\n",cmdline[0]);
+			return(PROGRAM_ERROR);
+		} else if(infile_info->filetype != SNDFILE)  {
+			sprintf(errstr,"File %s is not of correct type\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if((exit_status = copy_parse_info_to_main_structure(infile_info,dz))<0) {
+			sprintf(errstr,"Failed to copy file parsing information\n");
+			return(PROGRAM_ERROR);
+		}
+		free(infile_info);
+	}
+	return(FINISHED);
+}
+
+/************************* SETUP_SPIKE_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_spike_param_ranges_and_defaults(dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	// NB total_input_param_cnt is > 0 !!!
+	if((exit_status = setup_input_param_range_stores(ap->total_input_param_cnt,ap))<0)
+		return(FAILED);
+	// get_param_ranges()
+	ap->lo[0]	= 1.0;
+	ap->hi[0]	= 100.0;
+	ap->default_val[0]	= 20;
+	ap->lo[1]	= 1.0;
+	ap->hi[1]	= 100.0;
+	ap->default_val[1]	= 20;
+	ap->lo[2]	= 0.0;
+	ap->hi[2]	= 1;
+	ap->default_val[2]	= 0;
+	ap->lo[3]	= 0.0;
+	ap->hi[3]	= 1;
+	ap->default_val[3]	= 0;
+	dz->maxmode = 0;
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_spike_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+	usage2("spike");
+	return(USAGE_ONLY);
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if(!strcmp(prog_identifier_from_cmdline,"spike"))				dz->process = SPIKE;
+	else {
+		sprintf(errstr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/******************************** SETUP_AND_INIT_INPUT_BRKTABLE_CONSTANTS ********************************/
+
+int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt)
+{	
+	int n;
+	if((dz->brk      = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<brkcnt;n++) {
+		dz->brk[n]     = NULL;
+		dz->brkptr[n]  = NULL;
+		dz->brkinit[n] = 0;
+		dz->brksize[n] = 0;
+	}
+	return(FINISHED);
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+	if(!strcmp(str,"spike")) {
+		fprintf(stderr,
+	    "USAGE:\n"
+	    "spike spike infile outfile peak(s) upslope downslope [-mmaxup] [-dmaxdown] [-n]\n"
+		"\n"
+		"Envelope the input sound to spike at the peak.\n"
+		"\n"
+		"PEAKS(S)  Is either a single time (single peak) or a list of trof-peak-trof triplets,\n"
+		"          Adjacent trofs may be at the same time, but other times must advance.\n"
+		"\n"
+		"UPSLOPE   Power-value for slope of envelope before peak(s) Range (1 to 100).\n"
+		"DOWNSLOPE Power-value for slope of envelope after peak(s) Range (1 to 100).\n"
+		"\n"
+		"MAXUP     Maximum duration of upward approach: Range (0 to 1 secs).\n"
+		"MAXDOWN   Maximum duration of downward approach: Range (0 to 1 secs).\n"
+		"          (In both cases ZERO implies NO maximum)\n"
+		"\n"
+		"-n        Raise all peaks to that of maximum.\n"
+		"\n");
+	} else
+		fprintf(stdout,"Unknown option '%s'\n",str);
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	fprintf(stderr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/******************************** SPIKE ********************************/
+
+int spike(dataptr dz)
+{
+	int exit_status, chans = dz->infile->channels, c;
+	int n, m, i, k, j, samppos, abssamppos, pretrof, pksamp, postrof, prestep, poststep, peakcnt;
+	float *ibuf = dz->sampbuf[0], *obuf = dz->sampbuf[1];
+	double *pktrofs = dz->parray[0],*maxvals = dz->parray[1];
+	double srate = (double)dz->infile->srate;
+	double maxsamp, maxmax = 0.0, normaliser = 1.0, incr, uppow = dz->param[0], dnpow = dz->param[1];
+	if(dz->vflag[0]) {
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+		memset((char *)obuf,0,dz->buflen * sizeof(float));
+		pretrof = 0;
+		samppos = 0;
+		abssamppos = 0;
+		peakcnt = 0;
+		for(n = 0,m = 1,i = 2; n < dz->itemcnt; n+=3,m+=3,i+=3) {
+			pretrof = (int)round(pktrofs[n] * srate);
+			pksamp  = (int)round(pktrofs[m] * srate);
+			postrof = (int)round(pktrofs[i] * srate);
+			prestep  = pksamp - pretrof;
+			poststep = postrof - pksamp;
+			maxsamp = 0.0;
+			while(abssamppos < pretrof * chans) {
+				for(c= 0;c < chans; c++) {
+					maxmax = max(maxmax,fabs(ibuf[samppos]));
+					samppos++;
+					abssamppos++;
+				}
+				if(samppos >= dz->ssampsread) {
+					if((exit_status = read_samps(ibuf,dz))<0)
+						return(exit_status);
+					memset((char *)obuf,0,dz->buflen * sizeof(float));
+					samppos = 0;
+				}
+			}
+			for(k = pretrof,j = 0; k < pksamp; k++,j++) {
+				incr = (double)j/(double)prestep;
+				incr = pow(incr,uppow);
+				for(c= 0;c < chans; c++) {
+					maxmax = max(maxmax,fabs(ibuf[samppos]));
+					obuf[samppos] = (float)(ibuf[samppos] * incr);
+					maxsamp = max(maxsamp,fabs(obuf[samppos]));
+					samppos++;
+					abssamppos++;
+				}
+				if(samppos >= dz->ssampsread) {
+					if((exit_status = read_samps(ibuf,dz))<0)
+						return(exit_status);
+					samppos = 0;
+				}
+			}
+			for(k = pksamp,j = 0; k < postrof; k++,j++) {
+				incr = 1.0 - ((double)j/(double)poststep);
+				incr = pow(incr,dnpow);
+				for(c= 0;c < chans; c++) {
+					maxmax = max(maxmax,fabs(ibuf[samppos]));
+					obuf[samppos] = (float)(ibuf[samppos] * incr);
+					maxsamp = max(maxsamp,fabs(obuf[samppos]));
+					samppos++;
+					abssamppos++;
+				}
+				if(samppos >= dz->ssampsread) {
+					if((exit_status = read_samps(ibuf,dz))<0)
+						return(exit_status);
+					if(dz->ssampsread == 0)
+						break;
+					samppos = 0;
+				}
+			}
+			maxvals[peakcnt++] = maxsamp;
+		}
+		while (dz->ssampsread > 0) {
+			while(samppos < dz->ssampsread) {
+				for(c= 0;c < chans; c++) {
+					maxmax = max(maxmax,fabs(ibuf[samppos]));
+					samppos++;
+					abssamppos++;
+				}
+			}
+			if((exit_status = read_samps(ibuf,dz))<0)
+				return(exit_status);
+		}
+		maxmax = min(maxmax,0.95);
+		sndseekEx(dz->ifd[0],0,0);
+		for(n=0;n < peakcnt;n++)
+			maxvals[n] = maxmax/maxvals[n];			//	convert to a normaliser
+
+		reset_filedata_counters(dz);
+	}
+	if((exit_status = read_samps(ibuf,dz))<0)
+		return(exit_status);
+	memset((char *)obuf,0,dz->buflen * sizeof(float));
+	pretrof = 0;
+	samppos = 0;
+	abssamppos = 0;
+	peakcnt = 0;
+	for(n = 0,m = 1,i = 2; n < dz->itemcnt; n+=3,m+=3,i+=3) {
+		pretrof = (int)round(pktrofs[n] * srate);
+		pksamp  = (int)round(pktrofs[m] * srate);
+		postrof = (int)round(pktrofs[i] * srate);
+		if(dz->vflag[0])
+			normaliser = maxvals[peakcnt++];
+		prestep  = pksamp - pretrof;
+		poststep = postrof - pksamp;
+		while(abssamppos < pretrof * chans) {
+			samppos += chans;
+			abssamppos += chans;
+			if(samppos >= dz->ssampsread) {
+				if((exit_status = write_samps(obuf,dz->ssampsread,dz))<0)
+					return(exit_status);
+				if((exit_status = read_samps(ibuf,dz))<0)
+					return(exit_status);
+				memset((char *)obuf,0,dz->buflen * sizeof(float));
+				samppos = 0;
+			}
+		}
+		for(k = pretrof,j = 0; k < pksamp; k++,j++) {
+			incr = (double)j/(double)prestep;
+			incr = pow(incr,uppow);
+			for(c= 0;c < chans; c++) {
+				obuf[samppos] = (float)(ibuf[samppos] * incr);
+				if(dz->vflag[0])
+					obuf[samppos] = (float)(obuf[samppos] * normaliser);
+				samppos++;
+				abssamppos++;
+			}
+			if(samppos >= dz->ssampsread) {
+				if((exit_status = write_samps(obuf,dz->ssampsread,dz))<0)
+					return(exit_status);
+				if((exit_status = read_samps(ibuf,dz))<0)
+					return(exit_status);
+				memset((char *)obuf,0,dz->buflen * sizeof(float));
+				samppos = 0;
+			}
+		}
+		for(k = pksamp,j = 0; k < postrof; k++,j++) {
+			incr = 1.0 - ((double)j/(double)poststep);
+			incr = pow(incr,dnpow);
+			for(c= 0;c < chans; c++) {
+				obuf[samppos] = (float)(ibuf[samppos] * incr);
+				if(dz->vflag[0])
+					obuf[samppos] = (float)(obuf[samppos] * normaliser);
+				samppos++;
+				abssamppos++;
+			}
+			if(samppos >= dz->ssampsread) {
+				if((exit_status = write_samps(obuf,dz->ssampsread,dz))<0)
+					return(exit_status);
+				if((exit_status = read_samps(ibuf,dz))<0)
+					return(exit_status);
+				memset((char *)obuf,0,dz->buflen * sizeof(float));
+				if(dz->ssampsread == 0)
+					break;
+				samppos = 0;
+			}
+		}
+	}
+	while(dz->ssampsread > 0) {
+		if((exit_status = write_samps(obuf,dz->ssampsread,dz))<0)
+			return(exit_status);
+		memset((char *)obuf,0,dz->buflen * sizeof(float));
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+	}
+	return FINISHED;
+}
+
+/************************ HANDLE_THE_SPECIAL_DATA *********************/
+
+int handle_the_special_data(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+
+	if(ap->special_data) {
+		if(!sloom) {
+			if(*cmdlinecnt <= 0) {
+				sprintf(errstr,"Insufficient parameters on command line.\n");
+				return(USAGE_ONLY);
+			}
+		}
+		if((exit_status = read_special_data((*cmdline)[0],dz))<0)
+			return(exit_status);
+		(*cmdline)++;		
+		(*cmdlinecnt)--;
+	}
+	return(FINISHED);
+}
+
+/*************************** GET_FOFBANK_INFO ***********************/
+
+int read_special_data(char *filename,dataptr dz)
+{
+	FILE *fp;
+	double dummy, lasttime = 0.0;
+	int cnt, peakcnt;
+	double *vals;
+	char temp[200], *q;
+	q = filename;
+	if((dz->parray = (double **)malloc(2 * sizeof(double *)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for data in file %s (1).\n",filename);
+		return(MEMORY_ERROR);
+	}
+
+	if((sloom && *q == '@') || (!sloom && value_is_numeric(filename))) {
+		if((dz->parray[0] = (double *)malloc(3 * sizeof(double)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for data in file %s (2).\n",filename);
+			return(MEMORY_ERROR);
+		}
+		if(sloom)
+			q++;
+		dummy = (double)atof(q);
+		if(dummy <= 0.0) {
+			sprintf(errstr,"Invalid peak time (%lf) at or before sound start, %s\n",dummy,filename);
+			return(MEMORY_ERROR);
+		}
+		if(dummy >= dz->duration) {
+			sprintf(errstr,"Invalid peak time (%lf) at or beyond sound end (%lf), %s\n",dummy,dz->duration,filename);
+			return(MEMORY_ERROR);
+		}
+		dz->parray[0][0] = 0.0;
+		dz->parray[0][1] = dummy;
+		dz->parray[0][2] = dz->duration;
+		dz->itemcnt = 3;
+		return(FINISHED);
+	}
+	if((fp = fopen(filename,"r"))==NULL) {
+		sprintf(errstr,	"Can't open file %s to read data.\n",filename);
+		return(DATA_ERROR);
+	}
+	cnt = 0;
+	while(fgets(temp,200,fp)==temp) {
+		q = temp;
+		if(*q == ';')	//	Allow comments in file
+			continue;
+		while(get_float_from_within_string(&q,&dummy)) {
+			if(cnt % 3 == 0) {
+				if (dummy < lasttime) {
+					sprintf(errstr,"Times between peaks (%lf and %lf) regress in file %s\n",lasttime,dummy,filename);  //RWD first was $lf
+					return DATA_ERROR;
+				}
+			} else {
+				if (dummy <= lasttime) {
+					sprintf(errstr,"Times within peaks (%lf and %lf) do not progress in file %s\n",lasttime,dummy,filename); //RWD ditto
+					return DATA_ERROR;
+				}
+			}
+			if(dummy > dz->duration) {
+				sprintf(errstr,"Invalid peak time (%lf) at or beyond sound end (%lf), in file %s.\n",dummy,dz->duration,filename);
+				return(MEMORY_ERROR);
+			}
+			lasttime = dummy;
+			cnt++;
+		}
+	}
+	if(cnt == 0) {
+		sprintf(errstr,"No data in file %s\n",filename);
+		return(DATA_ERROR);
+	}
+	if(cnt % 3 != 0) {
+		sprintf(errstr,"Data in file %s not grouped in triplets : should be sets of TROF PK TROF.\n",filename);
+		return(DATA_ERROR);
+	}
+	if((dz->parray[0] = (double *)malloc(cnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for data in file %s.\n",filename);
+		return(MEMORY_ERROR);
+	}
+	vals = dz->parray[0];
+	rewind(fp);
+	cnt = 0;
+	while(fgets(temp,200,fp)==temp) {
+		q = temp;
+		if(*q == ';')	//	Allow comments in file
+			continue;
+		while(get_float_from_within_string(&q,&dummy)) {
+			vals[cnt] = dummy;
+		}
+		cnt++;
+	}	    
+	if(fclose(fp)<0) {
+		fprintf(stdout,"WARNING: Failed to close file %s.\n",filename);
+		fflush(stdout);
+	}
+	dz->itemcnt = cnt;
+	peakcnt = dz->itemcnt/3;
+	if(peakcnt) {
+		if((dz->parray[1] = (double *)malloc(peakcnt * sizeof(double)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for data in file %s (2).\n",filename);
+			return(MEMORY_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+
+void TrimPeakData(dataptr dz)
+{
+	double upmax = dz->param[2], dnmax = dz->param[3], upstep, dnstep;
+	double *pktrofs = dz->parray[0];
+	int n, m, i;
+	for(n = 0,m = 1,i = 2; n < dz->itemcnt; n+=3,m+=3,i+=3) {
+/* TEST */
+fprintf(stderr,"BEFORE: upstep %lf dnstep %lf\n",pktrofs[m] - pktrofs[n],pktrofs[i] - pktrofs[m]);
+/* TEST */
+		if(dz->param[2] > 0.0) {
+			upstep = pktrofs[m] - pktrofs[n];
+			if(upstep > upmax)
+				pktrofs[n] = pktrofs[m] - upmax;
+		}
+		if(dz->param[3] > 0.0) {
+			dnstep = pktrofs[i] - pktrofs[m];
+			if(dnstep > dnmax)
+				pktrofs[i] = pktrofs[m] + dnmax;
+		}
+/* TEST */
+fprintf(stderr,"AFTER: upstep %lf dnstep %lf\n",pktrofs[m] - pktrofs[n],pktrofs[i] - pktrofs[m]);
+/* TEST */
+	}
+}

+ 1231 - 0
dev/standnew/suppress.c

@@ -0,0 +1,1231 @@
+/*	cdparams_other() AND tkusage_other() NEED TO BE UPDATED
+ *	standalone.h NEEDS TO BE UPDATED
+ *	gobo AND gobosee NEED TO BE UPDATED
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <standalone.h>
+#include <tkglobals.h>
+#include <blur.h>
+#include <filetype.h>
+#include <modeno.h>
+#include <formants.h>
+#include <cdpmain.h>
+#include <special.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <sfsys.h>
+#include <ctype.h>
+#include <string.h>
+
+#ifdef unix
+#define round lround
+#endif
+
+char errstr[2400];
+const char* cdp_version = "5.0.2";
+
+/* extern */ int sloom = 0;
+/* extern */ int	sloombatch = 0;
+/* extern */ int anal_infiles = 1;
+/* extern */ int is_converted_to_stereo = -1;
+
+/* CDP LIBRARY FUNCTIONS TRANSFERRED HERE */
+
+static int 	set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist);
+static int  set_vflgs(aplptr ap,char *optflags,int optcnt,char *optlist,
+				char *varflags,int vflagcnt, int vparamcnt,char *varlist);
+static int 	setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int	initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int	mark_parameter_types(dataptr dz,aplptr ap);
+static int  establish_application(dataptr dz);
+static int  application_init(dataptr dz);
+static int  initialise_vflags(dataptr dz);
+static int  setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int  setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int  get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int  assign_file_data_storage(int infilecnt,dataptr dz);
+static int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+
+/* CDP LIB FUNCTION MODIFIED TO AVOID CALLING setup_particular_application() */
+
+static int  parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+
+/* SIMPLIFICATION OF LIB FUNC TO APPLY TO JUST THIS FUNCTION */
+
+static int  parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int  handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int  setup_suppress_application(dataptr dz);
+static int  setup_suppress_param_ranges_and_defaults(dataptr dz);
+static int  open_the_first_infile(char *filename,dataptr dz);
+
+/* BYPASS LIBRARY GLOBAL FUNCTION TO GO DIRECTLY TO SPECIFIC APPLIC FUNCTIONS */
+
+static int read_the_special_data(char *filename,dataptr dz);
+static int handle_the_special_data(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int check_suppress_param_validity_and_consistency(dataptr dz);
+static int suppress(dataptr dz);
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status;
+/*	FILE *fp   = NULL; */
+	dataptr dz = NULL;
+//	char *special_data_string = NULL;
+	char **cmdline = NULL;
+	int  cmdlinecnt;
+	aplptr ap;
+	int is_launched = FALSE;
+
+						/* CHECK FOR SOUNDLOOM */
+//TW UPDATE
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc == 2) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+	}
+	if(!sloom) {
+						  /* INITIAL CHECK OF CMDLINE DATA */
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;	/* GET PRE_DATA, ALLOCATE THE APPLICATION, CHECK FOR EXTRA INFILES */
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		dz->maxmode = 0;
+		// setup_particular_application =
+		if((exit_status = setup_suppress_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {  	/* includes setup_particular_application()      */
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);/* and cmdlinelength check = sees extra-infiles */
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+
+	// parse_infile_and_hone_type() = 
+	if((exit_status = parse_infile_and_check_type(cmdline,dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+	if((exit_status = setup_suppress_param_ranges_and_defaults(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+					/* OPEN FIRST INFILE AND STORE DATA, AND INFORMATION, APPROPRIATELY */
+
+	if((exit_status = open_the_first_infile(cmdline[0],dz))<0) {	
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);	
+		return(FAILED);
+	}
+	cmdlinecnt--;
+	cmdline++;
+	
+	//	handle_extra_infiles() : redundant
+	// handle_outfile
+	if((exit_status = handle_the_outfile(&cmdlinecnt,&cmdline,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+	// handle_formants
+	// handle_formant_quiksearch
+	if((exit_status = handle_the_special_data(&cmdlinecnt,&cmdline,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+//	check_param_validity_and_consistency....
+	if((exit_status = check_suppress_param_validity_and_consistency(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+ 	is_launched = TRUE;
+
+	if((exit_status = allocate_single_buffer(dz))<0){
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// param_preprocess
+	// spec_process_file
+	if((exit_status = suppress(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+	if((exit_status = complete_output(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	//THERE ARE NO brktables USED IN THIS PROCESS
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+			return(exit_status);
+	
+		dz->infilecnt = 1;
+	// establish_bufptrs_and_extra_buffers
+	dz->extra_bufcnt =  0; 
+	dz->bptrcnt = 1; 	
+	// setup_internal_arrays_and_array_pointers(): not required
+	return establish_spec_bufptrs_and_extra_buffers(dz);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}						 		/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/************************* SETUP_SUPPRESS_APPLICATION *******************/
+
+int setup_suppress_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	// SEE parstruct FOR EXPLANATION of next 2 functions
+	if((exit_status = set_param_data(ap,MANYCUTS   ,3,3,"ddi"      ))<0)
+		return(FAILED);
+	if((exit_status = set_vflgs(ap,  "",0,""  ,""     ,0,0,""     ))<0)
+		return(FAILED);
+	// THERE IS NO NEED TO set_formant_flags in this case....
+	// Following only needed if internal params are linked to dz structure
+	//set_internalparam_data
+	// set_legal_infile_structure -->
+	dz->has_otherfile = FALSE;
+	// assign_process_logic -->
+	dz->input_data_type = ANALFILE_ONLY;
+	dz->process_type	= EQUAL_ANALFILE;	
+	dz->outfiletype  	= ANALFILE_OUT;
+	return application_init(dz);	//GLOBAL
+}
+
+/************************* PARSE_INFILE_AND_CHECK_TYPE *******************/
+
+int parse_infile_and_check_type(char **cmdline,dataptr dz)
+{
+	int exit_status;
+	infileptr infile_info;
+	if(!sloom) {
+		if((infile_info = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for infile structure to test file data.");
+			return(MEMORY_ERROR);
+		} else if((exit_status = cdparse(cmdline[0],infile_info))<0) {
+			sprintf(errstr,"Failed tp parse input file %s\n",cmdline[0]);
+			return(PROGRAM_ERROR);
+		} else if(infile_info->filetype != ANALFILE)  {
+			sprintf(errstr,"File %s is not of correct type\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if((exit_status = copy_parse_info_to_main_structure(infile_info,dz))<0) {
+			sprintf(errstr,"Failed to copy file parsing information\n");
+			return(PROGRAM_ERROR);
+		}
+		free(infile_info);
+	}
+	return(FINISHED);
+}
+
+/************************* SETUP_SUPPRESS_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_suppress_param_ranges_and_defaults(dataptr dz)
+{
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	// NB total_input_param_cnt is == 0 !!!s
+	ap->lo[0]	= 0.0;
+	ap->hi[0]	= dz->nyquist;
+	ap->default_val[0]	= 0.0;
+	ap->lo[1]	= 0.0;
+	ap->hi[1]	= dz->nyquist;
+	ap->default_val[1]	= dz->nyquist;
+	ap->lo[2]	= 1;
+	ap->hi[2]	= (dz->infile->channels)/2;
+	ap->default_val[2] = 1;
+	dz->maxmode = 0;
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_suppress_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+/************************** OPEN_THE_FIRST_INFILE *****************************/
+
+int open_the_first_infile(char *filename,dataptr dz)
+{
+	if((dz->ifd[0] = sndopenEx(filename,0,CDP_OPEN_RDONLY)) < 0) {
+		sprintf(errstr,"Failure to open file %s for input.\n",filename);
+		return(SYSTEM_ERROR);
+	}
+	if(dz->infilecnt<=0 || dz->infile->filetype!=ANALFILE) {
+		sprintf(errstr,"%s is wrong type of file for this process.\n",filename);
+		return(DATA_ERROR);
+	}
+	dz->samps_left = dz->insams[0];
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_OUTFILE *********************/
+
+int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status;
+	char *filename = (*cmdline)[0];
+	if(filename[0]=='-' && filename[1]=='f') {
+		dz->floatsam_output = 1;
+		dz->true_outfile_stype = SAMP_FLOAT;
+		filename+= 2;
+	}
+	if(!sloom) {
+		if(file_has_invalid_startchar(filename) || value_is_numeric(filename)) {
+			sprintf(errstr,"Outfile name %s has invalid start character(s) or looks too much like a number.\n",filename);
+			return(DATA_ERROR);
+		}
+	}
+	strcpy(dz->outfilename,filename);	   
+	if((exit_status = create_sized_outfile(filename,dz))<0)
+		return(exit_status);
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+	usage2("partials");
+	return(USAGE_ONLY);
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if(!strcmp(prog_identifier_from_cmdline,"partials"))	dz->process = SUPPRESS;
+	else {
+		sprintf(errstr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+	if(!strcmp(str,"partials")) {
+		fprintf(stdout,
+		"USAGE: suppress partials inanal outanal timeslots lofrq hifrq chancnt\n"
+		"\n"
+		"SUPPRESS THE MOST PROMINENT PARTIALS IN THE FRQ BAND INDICATED\n"
+		"\n"
+		"TIMESLOTS File with time-pairs between which bands are suppressed.\n"
+		"LOFRQ     Low frequency limit of band where partials to be suppressed.\n"
+		"HIFRQ     High frequency limit of band where partials to be suppressed.\n"
+		"CHANCNT   Number of most prominent channels in band, to be suppressed.\n");
+	} else
+		fprintf(stdout,"Unknown option '%s'\n",str);
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	sprintf(errstr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/************************* SUPPRESS *******************/
+
+int suppress(dataptr dz)
+{
+	int exit_status, havamp;
+	float *ibuf = dz->bigfbuf;
+	int total_window_cnt = 0;
+	double *timeslot = dz->parray[0], *ampstore = dz->parray[1];
+	double time = 0.0, maxamp;
+	double lofrq = dz->param[0], hifrq = dz->param[1];
+	int partialcnt = dz->iparam[2], samps_read, wlen, wcnt;
+	int cc, vc, k, slots, process_it, maxloc;
+	float frqatmax;
+	dz->clength	= dz->wanted / 2;
+	while(dz->samps_left > 0) {
+		if((samps_read = fgetfbufEx(ibuf,dz->buflen,dz->ifd[0],0)) < 0) {	//	Read next bufferfull of windows
+			sprintf(errstr,"Problem reading data from analfile.\n");
+			return(PROGRAM_ERROR);
+		}
+		wlen = samps_read/dz->wanted;
+		dz->samps_left -= samps_read; 
+		wcnt = 0;
+		while(wcnt < wlen) {
+			if(total_window_cnt == 0) {										//	Skip initial (zeroed) window
+				wcnt++;
+				total_window_cnt++;
+				time += dz->frametime;
+				ibuf += dz->wanted;
+				continue;	
+			}
+			process_it = 0;													//	Skip input which is NOT in a time-slot-to-process
+			for(slots = 0,k=0; slots < dz->itemcnt;slots++,k+=2) {
+				if(time >= timeslot[k] && time <= timeslot[k+1]) {
+					process_it = 1;
+					break;
+				}
+			}
+			if(!process_it) {
+				wcnt++;
+				total_window_cnt++;
+				time += dz->frametime;
+				ibuf += dz->wanted;
+				continue;
+			}
+			havamp = 0;
+			for(cc = 0, vc = 0; cc < dz->clength; cc++, vc +=2) {
+				if(ibuf[FREQ] >= lofrq && ibuf[FREQ] <= hifrq) {				//	Store amplitude of any frqs lying within desired frq band
+					if(ibuf[AMPP] > 0.0) {
+						ampstore[cc] = ibuf[AMPP];
+						havamp = 1;
+					}
+				} else
+					ampstore[cc] = 0.0;
+			}
+			if (!havamp) {
+				wcnt++;
+				total_window_cnt++;
+				time += dz->frametime;
+				ibuf += dz->wanted;
+				continue;
+			}
+			for(k = 1; k <= partialcnt; k++) {								//	For each required partial
+				maxamp = 0.0;
+				maxloc = -1;
+				for(cc = 0; cc < dz->clength; cc++) {						//	Find the maximum of the stored amplitudes
+					if(ampstore[cc] > maxamp) {
+						maxamp = ampstore[cc];
+						maxloc = cc;
+					}
+				}
+				if(maxloc < 0) {
+					sprintf(errstr,"Error locating maximum channel amplitude %d at time %lf.\n",k,time);
+					return(PROGRAM_ERROR);
+				}
+				maxloc *= 2;												//	Maxloc in analchans, grouped in pairs
+				ibuf[maxloc] = 0.0;											//	Zero the associated sound data
+				frqatmax = ibuf[maxloc + 1];
+				for(cc = 0, vc = 0; cc < dz->clength; cc++, vc +=2) {		//	Zero any channels that have the same frequency
+					if(flteq(ibuf[FREQ],frqatmax)) {
+						ibuf[AMPP] = 0.0;
+						ampstore[cc] = 0.0;									//	Set that ampstore to zero, so not "seen" in search for next loudest partial
+					}
+				}
+				ampstore[cc] = 0.0;											//	Set that ampstore to zero, so not "seen" in search for next loudest partial
+			}
+			wcnt++;
+			total_window_cnt++;
+			time += dz->frametime;
+			ibuf += dz->wanted;
+		}
+		ibuf = dz->bigfbuf;
+		if((exit_status = write_samps(ibuf,samps_read,dz))<0)
+			return(exit_status);
+	}			
+	return FINISHED;
+}
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int read_special_data(char *str,dataptr dz)	
+{
+	return(FINISHED);
+}
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return(FINISHED);
+}
+
+/**************************** CHECK_SUPPRESS_PARAM_VALIDITY_AND_CONSISTENCY *****************************/
+
+int check_suppress_param_validity_and_consistency(dataptr dz)
+{
+	double temp;
+	if (dz->param[0] > dz->param[1]) {
+		fprintf(stdout,"WARNING: High and Low frequency parameters inverted: correcting.\n");
+		fflush(stdout);
+		temp = dz->param[0];
+		dz->param[0] = dz->param[1];
+		dz->param[1] = temp;
+	}
+	return FINISHED;
+}
+
+/************************ HANDLE_THE_SPECIAL_DATA *********************/
+
+int handle_the_special_data(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+
+	if(ap->special_data) {
+		if(!sloom) {
+			if(*cmdlinecnt <= 0) {
+				sprintf(errstr,"Insufficient parameters on command line.\n");
+				return(USAGE_ONLY);
+			}
+		}
+		ap->min_special 	= 0;
+		ap->max_special 	= dz->duration;
+		if((exit_status = read_the_special_data((*cmdline)[0],dz))<0)
+			return(exit_status);
+		(*cmdline)++;		
+		(*cmdlinecnt)--;
+	}
+	return(FINISHED);
+}
+
+/************************* READ_THE_SPECIAL_DATA *******************/
+
+int read_the_special_data(char *filename,dataptr dz)
+{
+	FILE *fp;
+	double dummy, *time, lasttime = 0;
+	int done;
+	int cnt;
+	char temp[2000], *q;
+	if((fp = fopen(filename,"r"))==NULL) {
+		sprintf(errstr,	"Can't open file %s to read data.\n",filename);
+		return(DATA_ERROR);
+	}
+	cnt = 0;
+	while(fgets(temp,200,fp)==temp) {
+		q = temp;
+		if(*q == ';')	//	Allow comments in file
+			continue;
+		while(get_float_from_within_string(&q,&dummy)) {
+			if(dummy < 0.0) {
+				sprintf(errstr,"Invalid time value (%lf) in file %s.\n",dummy,filename);
+				return(DATA_ERROR);
+			}
+			cnt++;
+		}
+	}	    
+	if(cnt == 0) {
+		sprintf(errstr,"No data in file %s\n",filename);
+		return(DATA_ERROR);
+	}
+	if(((dz->itemcnt = cnt/2) * 2) != cnt) {
+		sprintf(errstr,"Data not paired correctly in file %s\n",filename);
+		return(DATA_ERROR);
+	}
+	if((dz->parray = (double **)malloc(2 * sizeof(double *)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY (1) for data in file %s.\n",filename);
+		return(MEMORY_ERROR);
+	}
+	if((dz->parray[0] = (double *)malloc(cnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY (3) for data in file %s.\n",filename);
+		return(MEMORY_ERROR);
+	}
+	dz->clength = dz->wanted/2;
+	if((dz->parray[1] = (double *)malloc(dz->clength * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY (4) for data in file %s.\n",filename);
+		return(MEMORY_ERROR);
+	}
+	time = dz->parray[0];
+	rewind(fp);
+	lasttime = -1;
+	cnt = 0;
+	done = 0;
+	while(fgets(temp,200,fp)==temp) {
+		q = temp;
+		if(*q == ';')	//	Allow comments in file
+			continue;
+		while(get_float_from_within_string(&q,&dummy)) {
+			if(cnt > 0) {
+				if(EVEN(cnt)) {
+					if(dummy < lasttime) {
+						sprintf(errstr,"Times (%lf & %lf) in file %s are not in increasing order.\n",
+						lasttime,dummy,filename);
+						return(DATA_ERROR);
+					}
+					if (dummy >= dz->duration) {
+						done = 1;
+						break;
+					}
+				} else {
+					if((dummy - lasttime) < dz->frametime) {
+						sprintf(errstr,"Times (%lf & %lf) in file %s less than 1 sampleframe (%lf secs) apart.\n",
+						lasttime,dummy,filename,dz->frametime);
+						return(DATA_ERROR);
+					}
+				}
+			}
+			*time = dummy;
+			time++;
+			lasttime = dummy;
+			cnt++;
+		}
+		if(done)
+			break;
+	}	    
+	if(fclose(fp)<0) {
+		fprintf(stdout,"WARNING: Failed to close file %s.\n",filename);
+		fflush(stdout);
+	}
+	dz->itemcnt = cnt/2;
+	return(FINISHED);
+}
+

+ 1322 - 0
dev/standnew/tostereo.c

@@ -0,0 +1,1322 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <tkglobals.h>
+#include <pnames.h>
+#include <filetype.h>
+#include <processno.h>
+#include <modeno.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <math.h>
+#include <mixxcon.h>
+#include <osbind.h>
+#include <standalone.h>
+#include <ctype.h>
+#include <sfsys.h>
+#include <string.h>
+#include <srates.h>
+
+
+#ifdef unix
+#define round(x) lround((x))
+#endif
+
+#define converges is_flat	
+#define fork is_mapping
+
+#define TS_CHANS 2
+#define TS_LCHAN 3
+#define TS_RCHAN 4
+#define TS_MLEV  5
+
+#define STEREO_DEFAULT_MIXLEVEL 0.5
+#define FORK_DEFAULT_MIXLEVEL 0.707
+
+char errstr[2400];
+
+int anal_infiles = 1;
+int	sloom = 0;
+int sloombatch = 0;
+
+const char* cdp_version = "6.1.0";
+
+//CDP LIB REPLACEMENTS
+static int check_tostereo_param_validity_and_consistency(dataptr dz);
+static int setup_tostereo_application(dataptr dz);
+static int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+static int parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int setup_tostereo_param_ranges_and_defaults(dataptr dz);
+static int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int establish_application(dataptr dz);
+static int initialise_vflags(dataptr dz);
+static int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int mark_parameter_types(dataptr dz,aplptr ap);
+static int assign_file_data_storage(int infilecnt,dataptr dz);
+static int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+static int get_the_mode_from_cmdline(char *str,dataptr dz);
+static int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt);
+static int tostereo(dataptr dz);
+static int create_tostereo_sndbufs(dataptr dz);
+static int open_the_outfile(dataptr dz);
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status;
+	dataptr dz = NULL;
+	char **cmdline;
+	int  cmdlinecnt;
+	int n;
+	aplptr ap;
+	int is_launched = FALSE;
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+						/* CHECK FOR SOUNDLOOM */
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {					// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc == 2) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+	}
+	if(!sloom) {
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		dz->maxmode = 0;
+		// setup_particular_application =
+		if((exit_status = setup_tostereo_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+
+	// parse_infile_and_hone_type() = 
+	if((exit_status = parse_infile_and_check_type(cmdline,dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// open_first_infile		CDP LIB
+	if((exit_status = open_first_infile(cmdline[0],dz))<0) {	
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);	
+		return(FAILED);
+	}
+	cmdlinecnt--;
+	cmdline++;
+	// setup_param_ranges_and_defaults() =
+	if((exit_status = setup_tostereo_param_ranges_and_defaults(dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+//	handle_extra_infiles() : redundant
+	// handle_outfile() = 
+	if((exit_status = handle_the_outfile(&cmdlinecnt,&cmdline,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+//	handle_formants()			redundant
+//	handle_formant_quiksearch()	redundant
+//	handle_special_data()		redundant
+ 
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+//	check_param_validity_and_consistency....
+	if((exit_status = check_tostereo_param_validity_and_consistency(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = open_the_outfile(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	is_launched = TRUE;
+	dz->bufcnt = 2;
+	if((dz->sampbuf = (float **)malloc(sizeof(float *) * (dz->bufcnt+1)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->sbufptr = (float **)malloc(sizeof(float *) * dz->bufcnt))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffer pointers.\n");
+		return(MEMORY_ERROR);
+	}
+	for(n = 0;n <dz->bufcnt; n++)
+		dz->sampbuf[n] = dz->sbufptr[n] = (float *)0;
+	dz->sampbuf[n] = (float *)0;
+
+	if((exit_status = create_tostereo_sndbufs(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//param_preprocess()						redundant
+	//spec_process_file =
+	if((exit_status = tostereo(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = complete_output(dz))<0) {										// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);		// CDP LIB
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc, brkcnt;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	brkcnt = 2;	// Only in this program!!!
+	if((exit_status = setup_and_init_input_brktable_constants(dz,brkcnt))<0)			  
+		return(exit_status);
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+		return(exit_status);
+	
+	// establish_infile_constants() replaced by
+	dz->infilecnt = 1;
+	//establish_bufptrs_and_extra_buffers():
+	return(FINISHED);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}						 		/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_OUTFILE *********************/
+
+int handle_the_outfile(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	char *filename = (*cmdline)[0];
+	if(filename[0]=='-' && filename[1]=='f') {
+		dz->floatsam_output = 1;
+		dz->true_outfile_stype = SAMP_FLOAT;
+		filename+= 2;
+	}
+	if(!sloom) {
+		if(file_has_invalid_startchar(filename) || value_is_numeric(filename)) {
+			sprintf(errstr,"Outfile name %s has invalid start character(s) or looks too much like a number.\n",filename);
+			return(DATA_ERROR);
+		}
+	}
+	strcpy(dz->outfilename,filename);
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/************************ HANDLE_THE_OUTFILE *********************/
+
+int open_the_outfile(dataptr dz)
+{
+	int exit_status;
+	dz->infile->channels = dz->iparam[TS_CHANS];
+	if((exit_status = create_sized_outfile(dz->outfilename,dz))<0)
+		return(exit_status);
+	dz->infile->channels = STEREO;
+	return(FINISHED);
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/************************* SETUP_TOSTEREO_APPLICATION *******************/
+
+int setup_tostereo_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	// SEE parstruct FOR EXPLANATION of next 2 functions
+	if((exit_status = set_param_data(ap,0   ,2,2,"dd"))<0)
+		return(FAILED);
+	if((exit_status = set_vflgs(ap,"olrm",4,"iiid","",0,0,""))<0)
+		return(FAILED);
+	// set_legal_infile_structure -->
+	dz->has_otherfile = FALSE;
+	// assign_process_logic -->
+	dz->input_data_type = SNDFILES_ONLY;
+	dz->process_type	= UNEQUAL_SNDFILE;	
+	dz->outfiletype  	= SNDFILE_OUT;
+	return application_init(dz);	//GLOBAL
+}
+
+/************************* PARSE_INFILE_AND_CHECK_TYPE *******************/
+
+int parse_infile_and_check_type(char **cmdline,dataptr dz)
+{
+	int exit_status;
+	infileptr infile_info;
+	if(!sloom) {
+		if((infile_info = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for infile structure to test file data.");
+			return(MEMORY_ERROR);
+		} else if((exit_status = cdparse(cmdline[0],infile_info))<0) {
+			sprintf(errstr,"Failed to parse input file %s\n",cmdline[0]);
+			return(PROGRAM_ERROR);
+		} else if(infile_info->filetype != SNDFILE)  {
+			sprintf(errstr,"File %s is not of correct type\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if(infile_info->channels != 2)  {
+			sprintf(errstr,"File %s is not of correct type (must be stereo)\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if((exit_status = copy_parse_info_to_main_structure(infile_info,dz))<0) {
+			sprintf(errstr,"Failed to copy file parsing information\n");
+			return(PROGRAM_ERROR);
+		}
+		free(infile_info);
+	}
+	return(FINISHED);
+}
+
+/************************* SETUP_TOSTEREO_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_tostereo_param_ranges_and_defaults(dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	// NB total_input_param_cnt is > 0 !!!
+	if((exit_status = setup_input_param_range_stores(ap->total_input_param_cnt,ap))<0)
+		return(FAILED);
+	// get_param_ranges()
+	ap->lo[0]	= 0.0;
+	ap->hi[0]	= dz->duration;
+	ap->default_val[0]	= 0.0;
+	ap->lo[1]	= 0.0;
+	ap->hi[1]	= dz->duration;
+	ap->default_val[1] = dz->duration;
+	ap->lo[TS_CHANS]	= 2;
+	ap->hi[TS_CHANS]	= 16;
+	ap->default_val[TS_CHANS]	= 2;
+	ap->lo[TS_LCHAN]	= 1;
+	ap->hi[TS_LCHAN]	= 16;
+	ap->default_val[TS_LCHAN]	= 0;
+	ap->lo[TS_RCHAN]	= 1;
+	ap->hi[TS_RCHAN]	= 16;
+	ap->default_val[TS_RCHAN]	= 0;
+	ap->lo[TS_MLEV]	= 0.0;
+	ap->hi[TS_MLEV]	= 1;
+	ap->default_val[TS_MLEV] = 0.0;
+	dz->maxmode = 0;
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_tostereo_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int read_special_data(char *str,dataptr dz)	
+{
+	return(FINISHED);
+}
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+	usage2("tostereo");
+	return(USAGE_ONLY);
+}
+
+/**************************** CHECK_TOSTEREO_PARAM_VALIDITY_AND_CONSISTENCY *****************************/
+
+int check_tostereo_param_validity_and_consistency(dataptr dz)
+{
+	int isset;
+	double temp;
+	if(flteq(dz->param[0],dz->param[1])) {	
+		sprintf(errstr,"Start and end of divergence to stereo are the same time. Cannot proceed.\n");
+		return(DATA_ERROR);
+	}
+	dz->converges = 0;
+	if(dz->param[0] > dz->param[1]) {
+		dz->converges = 1;
+		temp = dz->param[1];
+		dz->param[1] = dz->param[0];
+		dz->param[0] = temp;
+		fprintf(stdout,"Start and end of divergence to stereo are inverted. Moving from stereo to mono.\n");
+		fflush(stdout);
+	}
+	isset = 0;
+	dz->fork = -1;
+	if(dz->iparam[TS_RCHAN] == 0 && dz->iparam[TS_LCHAN] == 0) {
+		if(dz->iparam[TS_CHANS] == 2) {
+			dz->iparam[TS_LCHAN] = 1;
+			dz->iparam[TS_RCHAN] = 2;
+			isset = 1;
+		}
+	}
+	if(!isset) {
+		if(dz->iparam[TS_LCHAN] > dz->iparam[TS_CHANS]) {
+			sprintf(errstr,"Left output channel exceeds total number of channels.\n");
+			return(DATA_ERROR);
+		}
+		if(dz->iparam[TS_RCHAN] > dz->iparam[TS_CHANS]) {
+			sprintf(errstr,"Right output channel exceeds total number of channels.\n");
+			return(DATA_ERROR);
+		}
+		if(dz->iparam[TS_LCHAN] == 0) {
+			if(dz->iparam[TS_CHANS] == 2) {
+				sprintf(errstr,"No Lefthand channel set.\n");
+				return(DATA_ERROR);
+			} else {
+				sprintf(errstr,"No Lefthand or Central channel set.\n");
+				return(DATA_ERROR);
+			}
+		}
+		if(dz->iparam[TS_RCHAN] == 0) {
+			if(dz->iparam[TS_CHANS] == 2) {
+				sprintf(errstr,"No Righthand channel set.\n");
+				return(DATA_ERROR);
+			} else {
+				dz->fork = dz->iparam[TS_LCHAN];
+				dz->iparam[TS_RCHAN] = dz->fork + 1;
+				if(dz->iparam[TS_RCHAN] > dz->iparam[TS_CHANS])
+					dz->iparam[TS_RCHAN] -= dz->iparam[TS_CHANS];
+				dz->iparam[TS_LCHAN] = dz->fork - 1;
+				if(dz->iparam[TS_LCHAN] <= 0)
+					dz->iparam[TS_LCHAN] += dz->iparam[TS_CHANS];
+			}
+		}
+		if(dz->iparam[TS_RCHAN] == dz->iparam[TS_LCHAN]) {
+			sprintf(errstr,"Output channels are the same.\n");
+			return(DATA_ERROR);
+		}
+	}
+	if(dz->param[TS_MLEV] > 0.0 && dz->param[TS_MLEV] < 0.5) {
+		sprintf(errstr,"Mix Level range is 0.5 to 1.0, Except for ZERO (sets a default for channel output cnt used)\n");
+		return(DATA_ERROR);
+	}
+	if(dz->param[TS_MLEV] == 0) {
+		if(dz->fork > 0)
+			dz->param[TS_MLEV] = FORK_DEFAULT_MIXLEVEL;			//	This is better default for forking case
+		else
+			dz->param[TS_MLEV] = STEREO_DEFAULT_MIXLEVEL;		//	This is better default for stereo case
+	}
+	if(dz->fork > 0)
+		dz->fork--;
+	dz->iparam[TS_RCHAN]--;
+	dz->iparam[TS_LCHAN]--;
+	return FINISHED;
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if(!strcmp(prog_identifier_from_cmdline,"tostereo"))				dz->process = TOSTEREO;
+	else {
+		sprintf(errstr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/******************************** SETUP_AND_INIT_INPUT_BRKTABLE_CONSTANTS ********************************/
+
+int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt)
+{	
+	int n;
+	if((dz->brk      = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<brkcnt;n++) {
+		dz->brk[n]     = NULL;
+		dz->brkptr[n]  = NULL;
+		dz->brkinit[n] = 0;
+		dz->brksize[n] = 0;
+	}
+	return(FINISHED);
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+	if(!strcmp(str,"tostereo")) {
+		fprintf(stderr,
+	    "USAGE:\n"
+	    "tostereo tostereo infil outfil start end [-oochans -lleftchan -rrightchan -mmixlev]\n"
+		"\n"
+		"Cause stereo file to start mixed-to-mono and then diverge to real stereo.\n"
+		"\n"
+		"START  Start time of divergence to stereo.\n"
+		"END    Time of complete stereo.\n"
+		"\n"
+		"If \"END\" time is before \"START\", file goes FROM stereo TO mono.\n"
+		"\n"
+		"OCHANS Output channel count (default stereo).\n"
+		"LEFT   Output left channel (default 1).\n"
+		"RIGHT  Output right channel (default 2).\n"
+		"MIXLEV Level of each chan when mixed to mono (Set to ZERO for good default level).\n"
+		"       (Range 0.5 to 1.0 OR  zero: values above 0.707 are not recommended)\n"
+		"\n"
+		"In multichannel, if Leftchan is selected but RIGHT is set to zero,\n"
+		"signal will FORK from the indicated channel to the channels on either side.\n");
+	} else
+		fprintf(stdout,"Unknown option '%s'\n",str);
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	fprintf(stderr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/******************************** TOSTEREO ********************************/
+
+int tostereo(dataptr dz)
+{
+	int exit_status, t, v, l, r, L, R, F;
+	int loutchan = dz->iparam[TS_LCHAN],routchan = dz->iparam[TS_RCHAN], ochans = dz->iparam[TS_CHANS];
+	float *ibuf = dz->sampbuf[0], *obuf = dz->sampbuf[1];
+	double *ll, *lr, llval, lrval, rrval, rlval, srate = dz->infile->srate, time, stttime, endtime, timestep, tratio, tpos, levboost;
+	int total_samps_here, samps_to_write;
+	
+	if((dz->brk[0] = (double *)malloc(8 * sizeof(double)))==NULL) {
+		sprintf(errstr,"No memory for internal breaktable 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brk[1] = (double *)malloc(8 * sizeof(double)))==NULL) {
+		sprintf(errstr,"No memory for internal breaktable 2\n");
+		return(MEMORY_ERROR);
+	}
+	dz->brksize[0] = 4;
+	dz->brksize[1] = 4;
+	ll = dz->brk[0];
+	lr = dz->brk[1];
+	stttime = dz->param[0];
+	endtime = dz->param[1];
+	timestep = endtime - stttime;
+	if(dz->fork >= 0) {
+		if(dz->converges) {
+			ll[0] = 0.0;				//	OUTER CHANNELS
+			ll[1] = 1.0;				//	Start with full (half of) stereo
+			ll[2] = dz->param[0];
+			ll[3] = 1.0;
+			ll[4] = dz->param[1];
+			ll[5] = 0.0;				//	End with nothing
+			ll[6] = 10000.0;
+			ll[7] = 0.0;
+
+			lr[0] = 0.0;
+			lr[1] = 0.0;				//	FORK starts with nothing
+			lr[2] = dz->param[0];
+			lr[3] = 0.0;
+			lr[4] = dz->param[1];
+			lr[5] = dz->param[TS_MLEV];	//	Ends mono (mix of stereo sigs)
+			lr[6] = 10000.0;
+			lr[7] = dz->param[TS_MLEV];
+		} else {
+			ll[0] = 0.0;				//	OUTER CHANNELS
+			ll[1] = 0.0;				//	Starts with nothing
+			ll[2] = dz->param[0];
+			ll[3] = 0.0;
+			ll[4] = dz->param[1];
+			ll[5] = 1.0;				//	Ends with full (half of) stereo
+			ll[6] = 10000.0;
+			ll[7] = 1.0;
+
+			lr[0] = 0.0;
+			lr[1] = dz->param[TS_MLEV];	//	FORK channel Starts mono (mix of stereo sigs)
+			lr[2] = dz->param[0];
+			lr[3] = dz->param[TS_MLEV];
+			lr[4] = dz->param[1];
+			lr[5] = 0.0;				//	Ends with nothing
+			lr[6] = 10000.0;
+			lr[7] = 0.0;
+		}
+
+	} else {
+		if(dz->converges) {
+			ll[0] = 0.0;
+			ll[1] = 1.0;				//	Starts stereo
+			ll[2] = dz->param[0];
+			ll[3] = 1.0;
+			ll[4] = dz->param[1];
+			ll[5] = 0.5;				//	Ends mono
+			ll[6] = 10000.0;
+			ll[7] = 0.5;			
+		} else {
+			ll[0] = 0.0;
+			ll[1] = 0.5;				//	Starts mono
+			ll[2] = dz->param[0];
+			ll[3] = 0.5;			
+			ll[4] = dz->param[1];
+			ll[5] = 1.0;				//	Ends stereo
+			ll[6] = 10000.0;
+			ll[7] = 1.0;
+		}
+		for(t=0,v=1;t<8;t+=2,v+=2) {
+			lr[t] = ll[t];
+			lr[v] = 1.0 - ll[v];	//	Left channel level on right channel = 1 minus level on left
+		}
+	}
+	if((exit_status = read_samps(ibuf,dz))<0)
+		return(exit_status);
+	total_samps_here = 0;
+	time = 0.0;
+	dz->is_int[0] = 0;		//	Reset params to read from float brktables created
+	dz->is_int[1] = 0;
+	while(dz->ssampsread > 0) {
+		for(l=0,r=1,L = loutchan,R = routchan,F = dz->fork;l<dz->ssampsread;l+=2,r+=2,L+=ochans,R+=ochans,F+=ochans) {
+			time = (double)total_samps_here/srate;
+			if((exit_status = read_value_from_brktable(time,0,dz))<0) {
+				sprintf(errstr,"Cannot read left-to-left pan data.\n");
+				return(PROGRAM_ERROR);
+			}
+			if((exit_status = read_value_from_brktable(time,1,dz))<0) {
+				sprintf(errstr,"Cannot read left-to-right pan data.\n");
+				return(PROGRAM_ERROR);
+			}
+			if(dz->fork >= 0) {
+				obuf[L] = (float)(ibuf[l] * dz->param[0]);
+				obuf[R] = (float)(ibuf[r] * dz->param[0]);
+				obuf[F] = (float)((ibuf[l] + ibuf[r]) * dz->param[1]);
+			} else {
+				llval = ibuf[l] * dz->param[0];
+				lrval = ibuf[l] * dz->param[1];
+				rrval = ibuf[r] * dz->param[0];
+				rlval = ibuf[r] * dz->param[1];
+				tpos = time - stttime;
+				tratio = tpos/timestep;
+				tratio = max(tratio,0.0);
+				tratio = min(tratio,1.0);
+				if(dz->converges)		
+					levboost = ((dz->param[TS_MLEV] * 2.0) - 1) * tratio;		//	i.e. if TS_MLEV = 0.707 this is Max at  ROOT2 - 1
+				else															//	but if TS_MLEV = 0.5 this is EVERYWHERE 0
+					levboost = ((dz->param[TS_MLEV] * 2.0) - 1) * (1.0 - tratio);
+				levboost += 1.0;												//	and this is max respectively at ROOT2 and 1
+				obuf[L] = (float)((llval + rlval) * levboost);
+				obuf[R] = (float)((rrval + lrval) * levboost);
+			}
+			total_samps_here++;
+		}
+		samps_to_write = (dz->ssampsread/STEREO) * dz->iparam[TS_CHANS];
+		if((exit_status = write_samps(obuf,samps_to_write,dz))<0)
+			return(exit_status);
+		if((exit_status = read_samps(ibuf,dz))<0)
+			return(exit_status);
+	}
+	return FINISHED;
+}
+
+int create_tostereo_sndbufs(dataptr dz)
+{
+	int n;
+	int bigbufsize, secsize;
+	int framesize, floatlen;
+	int factor = 2 + dz->iparam[TS_CHANS];
+	framesize = F_SECSIZE * factor * sizeof(float);
+	if(dz->sbufptr == 0 || dz->sampbuf==0) {
+		sprintf(errstr,"buffer pointers not allocated: create_sndbufs()\n");
+		return(PROGRAM_ERROR);
+	}
+	if((bigbufsize = ((dz->insams[0]/STEREO) * factor) * sizeof(float)) < 0) {
+		bigbufsize = (int)Malloc(-1);
+		secsize = bigbufsize/framesize;
+		if(secsize * framesize != bigbufsize) {
+			secsize++;
+			bigbufsize = secsize * framesize;
+		}
+		if(bigbufsize <= 0)
+			bigbufsize = framesize * factor;
+		if(bigbufsize <= 0)  {
+			sprintf(errstr,"INSUFFICIENT MEMORY to create sound buffers.\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	if((dz->bigbuf = (float *)malloc(bigbufsize)) == NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to create sound buffers.\n");
+		return(PROGRAM_ERROR);
+	}
+	floatlen = bigbufsize/sizeof(float);
+	dz->buflen = (floatlen/factor) * STEREO;
+	for(n=0;n<dz->bufcnt;n++)
+		dz->sbufptr[n] = dz->sampbuf[n] = dz->bigbuf + (dz->buflen * n);
+	dz->sampbuf[n] = dz->bigbuf + floatlen;
+	return(FINISHED);
+}

+ 2959 - 0
dev/standnew/unitary_matrix.c

@@ -0,0 +1,2959 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <structures.h>
+#include <tkglobals.h>
+#include <pnames.h>
+#include <filetype.h>
+#include <processno.h>
+#include <modeno.h>
+#include <pvoc.h>
+#include <logic.h>
+#include <globcon.h>
+#include <cdpmain.h>
+#include <math.h>
+#include <mixxcon.h>
+#include <osbind.h>
+#include <standalone.h>
+#include <speccon.h>
+#include <ctype.h>
+#include <sfsys.h>
+#include <string.h>
+#include <srates.h>
+
+/* MATRIX FILES : FORMAT
+ *
+ * 1st value is analysis-overlap value
+ * after this there are N*N * 2 values
+ * where N = analysis chancnt as COMPLEX values (dz->chancnt)
+ * and there are N*N entries in the matrix, each being a complex number.
+ * So there N*N*2 entries, with all real & imaginary components included.
+ */
+
+#ifdef unix
+#define round lround
+#endif
+
+#define overlap	ringsize
+#define ENVWIN 8
+#define wincnt rampbrksize
+
+char errstr[2400];
+
+int anal_infiles = 1;
+int	sloom = 0;
+int sloombatch = 0;
+
+const char* cdp_version = "8.0.0";
+
+/* CDP LIBRARY FUNCTIONS TRANSFERRED HERE */
+
+static int 	set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist);
+static int  set_vflgs(aplptr ap,char *optflags,int optcnt,char *optlist,
+				char *varflags,int vflagcnt, int vparamcnt,char *varlist);
+static int 	setup_parameter_storage_and_constants(int storage_cnt,dataptr dz);
+static int	initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz);
+static int	mark_parameter_types(dataptr dz,aplptr ap);
+static int  establish_application(dataptr dz);
+static int  application_init(dataptr dz);
+static int  initialise_vflags(dataptr dz);
+static int  setup_input_param_defaultval_stores(int tipc,aplptr ap);
+static int  setup_and_init_input_param_activity(dataptr dz,int tipc);
+static int  get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q);
+static int  assign_file_data_storage(int infilecnt,dataptr dz);
+
+/* CDP LIB FUNCTION MODIFIED TO AVOID CALLING setup_particular_application() */
+
+static int  parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz);
+
+/* SIMPLIFICATION OF LIB FUNC TO APPLY TO JUST THIS FUNCTION */
+
+static int  parse_infile_and_check_type(char **cmdline,dataptr dz);
+static int	handle_the_extra_infile(char ***cmdline,int *cmdlinecnt,dataptr dz);
+static int  handle_the_outfile(int *cmdlinecnt,char ***cmdline,int is_launched,dataptr dz);
+static int  setup_the_application(dataptr dz);
+static int  setup_the_param_ranges_and_defaults(dataptr dz);
+static int	check_the_param_validity_and_consistency(dataptr dz);
+static int  get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz);
+static int  setup_and_init_input_brktable_constants(dataptr dz,int brkcnt);
+static int  get_the_mode_no(char *str, dataptr dz);
+
+/* BYPASS LIBRARY GLOBAL FUNCTION TO GO DIRECTLY TO SPECIFIC APPLIC FUNCTIONS */
+
+static int  outfloats(float *nextOut, float *maxsampl,float *minsample,float *local_maxsample,int *num_overflows,int todo, int finished, dataptr dz);
+static int  pvoc_float_array(int nnn,float **ptr);
+static int  sndwrite_header(dataptr dz);
+static void hamming(float *win,int winLen,int even);
+static int  matrix_time_display(int nI,int srate,int *samptime,dataptr dz);
+static int write_samps_matrix(float *bbuf,int samps_to_write,dataptr dz);
+static int handle_matrixdata(int *cmdlinecnt,char ***cmdline,dataptr dz);
+static int do_specmatrix(dataptr dz);
+static int matrix_process(dataptr dz);
+static int create_random_unitary_matrix(dataptr dz);
+static int multiply_by_matrix(float *reals,float *imags,double *matrix, int N);
+static void change_extension(char *filename);
+static int is_pow_of_two(int val);
+static int matrix_cycle(double *matrix,double *matrix2,dataptr dz);
+static float complex_product(float r1,float i1,float r2,float i2,float *iout);
+static double normalise_complex(float *anal,float *anal2,dataptr dz);
+int reals_(float *a, float *b, int n, int isn);
+int fftmx(float *a,float *b,int ntot,int n,int nspan,int isn,int m,int *kt,
+			float *at,float *ck,float *bt,float *sk,int *np,int nfac[]);
+int fft_(float *a, float *b, int nseg, int n, int nspn, int isn);
+
+/**************************************** MAIN *********************************************/
+
+int main(int argc,char *argv[])
+{
+	int exit_status, n;
+	dataptr dz = NULL;
+	char **cmdline;
+	int  cmdlinecnt;
+	aplptr ap;
+	int is_launched = FALSE;
+	if(argc==2 && (strcmp(argv[1],"--version") == 0)) {
+		fprintf(stdout,"%s\n",cdp_version);
+		fflush(stdout);
+		return 0;
+	}
+						/* CHECK FOR SOUNDLOOM */
+	if((sloom = sound_loom_in_use(&argc,&argv)) > 1) {
+		sloom = 0;
+		sloombatch = 1;
+	}
+	if(sflinit("cdp")){
+		sfperror("cdp: initialisation\n");
+		return(FAILED);
+	}
+						  /* SET UP THE PRINCIPLE DATASTRUCTURE */
+	if((exit_status = establish_datastructure(&dz))<0) {					// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+					  
+	if(!sloom) {
+		if(argc == 1) {
+			usage1();	
+			return(FAILED);
+		} else if(argc == 2) {
+			usage2(argv[1]);	
+			return(FAILED);
+		}
+		if((exit_status = make_initial_cmdline_check(&argc,&argv))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		cmdline    = argv;
+		cmdlinecnt = argc;
+		if((get_the_process_no(argv[0],dz))<0)
+			return(FAILED);
+		cmdline++;
+		cmdlinecnt--;
+		dz->maxmode = 4;
+		if(cmdlinecnt <= 0) {
+			sprintf(errstr,"Too few commandline parameters.\n");
+			return(FAILED);
+		}
+		if((get_the_mode_no(cmdline[0],dz))<0) {
+			if(!sloom)
+				fprintf(stderr,"%s",errstr);
+			return(FAILED);
+		}
+		cmdline++;
+		cmdlinecnt--;
+		if((exit_status = setup_the_application(dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+		if((exit_status = count_and_allocate_for_infiles(cmdlinecnt,cmdline,dz))<0) {		// CDP LIB
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	} else {
+		//parse_TK_data() =
+		if((exit_status = parse_sloom_data(argc,argv,&cmdline,&cmdlinecnt,dz))<0) {
+			exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(exit_status);		 
+		}
+	}
+	ap = dz->application;
+	// parse_infile_and_hone_type() = 
+	if((exit_status = parse_infile_and_check_type(cmdline,dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// setup_param_ranges_and_defaults() =
+	if((exit_status = setup_the_param_ranges_and_defaults(dz))<0) {
+		exit_status = print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	// open_first_infile		CDP LIB
+	if((exit_status = open_first_infile(cmdline[0],dz))<0) {	
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);	
+		return(FAILED);
+	}
+	cmdlinecnt--;
+	cmdline++;
+
+//	handle_extra_infiles() redundant
+	// handle_outfile() = 
+	if((exit_status = handle_the_outfile(&cmdlinecnt,&cmdline,is_launched,dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+//	handle_formants()			redundant
+//	handle_formant_quiksearch()	redundant
+	if(dz->mode == MATRIX_USE) {
+		if((exit_status = handle_matrixdata(&cmdlinecnt,&cmdline,dz))<0) {
+			print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+			return(FAILED);
+		}
+	}
+	if((exit_status = read_parameters_and_flags(&cmdline,&cmdlinecnt,dz))<0) {		// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	//check_param_validity_and_consistency .....
+	if((exit_status = check_the_param_validity_and_consistency(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	is_launched = TRUE;
+
+	dz->bufcnt = 2;
+	if((dz->sampbuf = (float **)malloc(sizeof(float *) * (dz->bufcnt+1)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffers.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->sbufptr = (float **)malloc(sizeof(float *) * dz->bufcnt))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY establishing sample buffer pointers.\n");
+		return(MEMORY_ERROR);
+	}
+	for(n = 0;n <dz->bufcnt; n++)
+		dz->sampbuf[n] = dz->sbufptr[n] = (float *)0;
+	dz->sampbuf[n] = (float *)0;
+
+	if((exit_status = create_sndbufs(dz))<0) {										// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	if((exit_status = do_specmatrix(dz))<0) {
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+
+	if((exit_status = complete_output(dz))<0) {										// CDP LIB
+		print_messages_and_close_sndfiles(exit_status,is_launched,dz);
+		return(FAILED);
+	}
+	exit_status = print_messages_and_close_sndfiles(FINISHED,is_launched,dz);		// CDP LIB
+	free(dz);
+	return(SUCCEEDED);
+}
+
+/**********************************************
+		REPLACED CDP LIB FUNCTIONS
+**********************************************/
+
+/****************************** SET_PARAM_DATA *********************************/
+
+int set_param_data(aplptr ap, int special_data,int maxparamcnt,int paramcnt,char *paramlist)
+{
+	ap->special_data   = (char)special_data;	   
+	ap->param_cnt      = (char)paramcnt;
+	ap->max_param_cnt  = (char)maxparamcnt;
+	if(ap->max_param_cnt>0) {
+		if((ap->param_list = (char *)malloc((size_t)(ap->max_param_cnt+1)))==NULL) {	
+			sprintf(errstr,"INSUFFICIENT MEMORY: for param_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->param_list,paramlist); 
+	}
+	return(FINISHED);
+}
+
+/****************************** SET_VFLGS *********************************/
+
+int set_vflgs
+(aplptr ap,char *optflags,int optcnt,char *optlist,char *varflags,int vflagcnt, int vparamcnt,char *varlist)
+{
+	ap->option_cnt 	 = (char) optcnt;			/*RWD added cast */
+	if(optcnt) {
+		if((ap->option_list = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_list,optlist);
+		if((ap->option_flags = (char *)malloc((size_t)(optcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for option_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->option_flags,optflags); 
+	}
+	ap->vflag_cnt = (char) vflagcnt;		   
+	ap->variant_param_cnt = (char) vparamcnt;
+	if(vflagcnt) {
+		if((ap->variant_list  = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_list\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_list,varlist);		
+		if((ap->variant_flags = (char *)malloc((size_t)(vflagcnt+1)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY: for variant_flags\n");
+			return(MEMORY_ERROR);
+		}
+		strcpy(ap->variant_flags,varflags);
+
+	}
+	return(FINISHED);
+}
+
+/***************************** APPLICATION_INIT **************************/
+
+int application_init(dataptr dz)
+{
+	int exit_status;
+	int storage_cnt;
+	int tipc, brkcnt;
+	aplptr ap = dz->application;
+	if(ap->vflag_cnt>0)
+		initialise_vflags(dz);	  
+	tipc  = ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt;
+	ap->total_input_param_cnt = (char)tipc;
+	if(tipc>0) {
+		if((exit_status = setup_input_param_range_stores(tipc,ap))<0)			  
+			return(exit_status);
+		if((exit_status = setup_input_param_defaultval_stores(tipc,ap))<0)		  
+			return(exit_status);
+		if((exit_status = setup_and_init_input_param_activity(dz,tipc))<0)	  
+			return(exit_status);
+	}
+	brkcnt = tipc;
+	if(brkcnt>0) {
+		if((exit_status = setup_and_init_input_brktable_constants(dz,brkcnt))<0)			  
+			return(exit_status);
+	}
+	if((storage_cnt = tipc + ap->internal_param_cnt)>0) {		  
+		if((exit_status = setup_parameter_storage_and_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+		if((exit_status = initialise_is_int_and_no_brk_constants(storage_cnt,dz))<0)	  
+			return(exit_status);
+	}													   
+ 	if((exit_status = mark_parameter_types(dz,ap))<0)	  
+			return(exit_status);
+	
+	// establish_infile_constants() replaced by
+	dz->infilecnt = ONE_NONSND_FILE;
+	//establish_bufptrs_and_extra_buffers():
+	dz->array_cnt=2;
+	if((dz->parray  = (double **)malloc(dz->array_cnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for internal double arrays.\n");
+		return(MEMORY_ERROR);
+	}
+	dz->parray[0] = NULL;
+	dz->parray[1] = NULL;
+	return(FINISHED);
+}
+
+/******************************** SETUP_AND_INIT_INPUT_BRKTABLE_CONSTANTS ********************************/
+
+int setup_and_init_input_brktable_constants(dataptr dz,int brkcnt)
+{	
+	int n;
+	if((dz->brk      = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkptr   = (double **)malloc(brkcnt * sizeof(double *)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 6\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brksize  = (int    *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->firstval = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 3\n");
+		return(MEMORY_ERROR);												  
+	}
+	if((dz->lastind  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 4\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->lastval  = (double  *)malloc(brkcnt * sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->brkinit  = (int     *)malloc(brkcnt * sizeof(int)))==NULL) {
+		sprintf(errstr,"setup_and_init_input_brktable_constants(): 7\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<brkcnt;n++) {
+		dz->brk[n]     = NULL;
+		dz->brkptr[n]  = NULL;
+		dz->brkinit[n] = 0;
+		dz->brksize[n] = 0;
+	}
+	return(FINISHED);
+}
+
+/********************** SETUP_PARAMETER_STORAGE_AND_CONSTANTS ********************/
+/* RWD mallo changed to calloc; helps debug verison run as release! */
+
+int setup_parameter_storage_and_constants(int storage_cnt,dataptr dz)
+{
+	if((dz->param       = (double *)calloc(storage_cnt, sizeof(double)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 1\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->iparam      = (int    *)calloc(storage_cnt, sizeof(int)   ))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 2\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->is_int      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 3\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->no_brk      = (char   *)calloc(storage_cnt, sizeof(char)))==NULL) {
+		sprintf(errstr,"setup_parameter_storage_and_constants(): 5\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************** INITIALISE_IS_INT_AND_NO_BRK_CONSTANTS *****************/
+
+int initialise_is_int_and_no_brk_constants(int storage_cnt,dataptr dz)
+{
+	int n;
+	for(n=0;n<storage_cnt;n++) {
+		dz->is_int[n] = (char)0;
+		dz->no_brk[n] = (char)0;
+	}
+	return(FINISHED);
+}
+
+/***************************** MARK_PARAMETER_TYPES **************************/
+
+int mark_parameter_types(dataptr dz,aplptr ap)
+{
+	int n, m;							/* PARAMS */
+	for(n=0;n<ap->max_param_cnt;n++) {
+		switch(ap->param_list[n]) {
+		case('0'):	break; /* dz->is_active[n] = 0 is default */
+		case('i'):	dz->is_active[n] = (char)1; dz->is_int[n] = (char)1;dz->no_brk[n] = (char)1; break;
+		case('I'):	dz->is_active[n] = (char)1;	dz->is_int[n] = (char)1; 						 break;
+		case('d'):	dz->is_active[n] = (char)1;							dz->no_brk[n] = (char)1; break;
+		case('D'):	dz->is_active[n] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid parameter type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}						 		/* OPTIONS */
+	for(n=0,m=ap->max_param_cnt;n<ap->option_cnt;n++,m++) {
+		switch(ap->option_list[n]) {
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1; 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1;	/* normal case: double val or brkpnt file */	 break;
+		default:
+			sprintf(errstr,"Programming error: invalid option type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* VARIANTS */
+	for(n=0,m=ap->max_param_cnt + ap->option_cnt;n < ap->variant_param_cnt; n++, m++) {
+		switch(ap->variant_list[n]) {
+		case('0'): break;
+		case('i'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1; break;
+		case('I'): dz->is_active[m] = (char)1; dz->is_int[m] = (char)1;	 						 break;
+		case('d'): dz->is_active[m] = (char)1; 							dz->no_brk[m] = (char)1; break;
+		case('D'): dz->is_active[m] = (char)1; /* normal case: double val or brkpnt file */		 break;
+		default:
+			sprintf(errstr,"Programming error: invalid variant type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}								/* INTERNAL */
+	for(n=0,
+	m=ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt; n<ap->internal_param_cnt; n++,m++) {
+		switch(ap->internal_param_list[n]) {
+		case('0'):  break;	 /* dummy variables: variables not used: but important for internal paream numbering!! */
+		case('i'):	dz->is_int[m] = (char)1;	dz->no_brk[m] = (char)1;	break;
+		case('d'):								dz->no_brk[m] = (char)1;	break;
+		default:
+			sprintf(errstr,"Programming error: invalid internal param type in mark_parameter_types()\n");
+			return(PROGRAM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/***************************** HANDLE_THE_OUTFILE **************************/
+
+int handle_the_outfile(int *cmdlinecnt,char ***cmdline,int is_launched,dataptr dz)
+{
+	int exit_status, len;
+	char *filename = NULL;
+	len = strlen((*cmdline)[0]);
+	if((filename = (char *)malloc(len + 8))==NULL) {
+		sprintf(errstr,"handle_the_outfile()\n");
+		return(MEMORY_ERROR);
+	}
+	strcpy(filename,(*cmdline)[0]);
+	strcpy(dz->outfilename,filename);	   
+	if((exit_status = create_sized_outfile(filename,dz))<0)
+		return(exit_status);
+	(*cmdline)++;
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/***************************** ESTABLISH_APPLICATION **************************/
+
+int establish_application(dataptr dz)
+{
+	aplptr ap;
+	if((dz->application = (aplptr)malloc(sizeof (struct applic)))==NULL) {
+		sprintf(errstr,"establish_application()\n");
+		return(MEMORY_ERROR);
+	}
+	ap = dz->application;
+	memset((char *)ap,0,sizeof(struct applic));
+	return(FINISHED);
+}
+
+/************************* INITIALISE_VFLAGS *************************/
+
+int initialise_vflags(dataptr dz)
+{
+	int n;
+	if((dz->vflag  = (char *)malloc(dz->application->vflag_cnt * sizeof(char)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY: vflag store,\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<dz->application->vflag_cnt;n++)
+		dz->vflag[n]  = FALSE;
+	return FINISHED;
+}
+
+/************************* SETUP_INPUT_PARAM_DEFAULTVALS *************************/
+
+int setup_input_param_defaultval_stores(int tipc,aplptr ap)
+{
+	int n;
+	if((ap->default_val = (double *)malloc(tipc * sizeof(double)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY for application default values store\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		ap->default_val[n] = 0.0;
+	return(FINISHED);
+}
+
+/***************************** SETUP_AND_INIT_INPUT_PARAM_ACTIVITY **************************/
+
+int setup_and_init_input_param_activity(dataptr dz,int tipc)
+{
+	int n;
+	if((dz->is_active = (char   *)malloc((size_t)tipc))==NULL) {
+		sprintf(errstr,"setup_and_init_input_param_activity()\n");
+		return(MEMORY_ERROR);
+	}
+	for(n=0;n<tipc;n++)
+		dz->is_active[n] = (char)0;
+	return(FINISHED);
+}
+
+/************************* SETUP_THE_APPLICATION *******************/
+
+int setup_the_application(dataptr dz)
+{
+	int exit_status;
+	aplptr ap;
+	if((exit_status = establish_application(dz))<0)		// GLOBAL
+		return(FAILED);
+	ap = dz->application;
+	// SEE parstruct FOR EXPLANATION of next 2 functions
+	switch(dz->mode) {
+	case (MATRIX_USE):  
+		exit_status = set_param_data(ap,MATRIX_DATA,0,0,""  );
+		break;
+	default: 
+		exit_status = set_param_data(ap,0		   ,2,2,"ii");	
+		break;
+	}
+	if(exit_status<0)
+		return(FAILED);
+	switch(dz->mode) {
+	case(MATRIX_MAKE):
+	case(MATRIX_USE):
+		exit_status = set_vflgs(ap,"",0,"","c",1,0,"0");
+		break;
+	default: 
+		exit_status = set_vflgs(ap,"",0,"","" ,0,0,"" );
+		break;
+	}
+	if(exit_status <0)
+		return(FAILED);
+
+
+	dz->has_otherfile = FALSE;
+	// assign_process_logic -->
+	dz->input_data_type = SNDFILES_ONLY;
+	dz->process_type	= UNEQUAL_SNDFILE;	
+	dz->outfiletype  	= SNDFILE_OUT;
+	dz->maxmode = 4;
+	return application_init(dz);	//GLOBAL
+}
+
+/************************* PARSE_INFILE_AND_CHECK_TYPE *******************/
+
+int parse_infile_and_check_type(char **cmdline,dataptr dz)
+{
+	int exit_status;
+	infileptr infile_info;
+	if(!sloom) {
+		if((infile_info = (infileptr)malloc(sizeof(struct filedata)))==NULL) {
+			sprintf(errstr,"INSUFFICIENT MEMORY for infile structure to test file data.");
+			return(MEMORY_ERROR);
+		} else if((exit_status = cdparse(cmdline[0],infile_info))<0) {
+			sprintf(errstr,"Failed tp parse input file %s\n",cmdline[0]);
+			return(PROGRAM_ERROR);
+		} else if(infile_info->filetype != SNDFILE)  {
+			sprintf(errstr,"File %s is not of correct type\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if(infile_info->channels != MONO)  {
+			sprintf(errstr,"File %s is not MONO\n",cmdline[0]);
+			return(DATA_ERROR);
+		} else if((exit_status = copy_parse_info_to_main_structure(infile_info,dz))<0) {
+			sprintf(errstr,"Failed to copy file parsing information\n");
+			return(PROGRAM_ERROR);
+		}
+		free(infile_info);
+	}
+	return(FINISHED);
+}
+
+/************************* SETUP_THE_PARAM_RANGES_AND_DEFAULTS *******************/
+
+int setup_the_param_ranges_and_defaults(dataptr dz)
+{
+	int exit_status;
+	aplptr ap = dz->application;
+	// set_param_ranges()
+	ap->total_input_param_cnt = (char)(ap->max_param_cnt + ap->option_cnt + ap->variant_param_cnt);
+	// NB total_input_param_cnt is > 0 !!!s
+	if((exit_status = setup_input_param_range_stores(ap->total_input_param_cnt,ap))<0)
+		return(FAILED);
+	// get_param_ranges()
+	switch(dz->mode) {
+	case(MATRIX_USE):
+		break;
+	default:
+		ap->lo[0]			= (double)2;
+		ap->hi[0]			= (double)MAX_PVOC_CHANS;
+		ap->default_val[0]	= (double)DEFAULT_PVOC_CHANS;
+		ap->lo[1]			= (double)1;
+		ap->hi[1]			= (double)4;
+		ap->default_val[1]	= (double)DEFAULT_WIN_OVERLAP;
+		break;
+	}
+	if(!sloom)
+		put_default_vals_in_all_params(dz);
+	return(FINISHED);
+}
+
+/********************************* PARSE_SLOOM_DATA *********************************/
+
+int parse_sloom_data(int argc,char *argv[],char ***cmdline,int *cmdlinecnt,dataptr dz)
+{
+	int exit_status;
+	int cnt = 1, infilecnt;
+	int filesize, insams, inbrksize;
+	double dummy;
+	int true_cnt = 0;
+	aplptr ap;
+
+	while(cnt<=PRE_CMDLINE_DATACNT) {
+		if(cnt > argc) {
+			sprintf(errstr,"Insufficient data sent from TK\n");
+			return(DATA_ERROR);
+		}
+		switch(cnt) {
+		case(1):	
+			if(sscanf(argv[cnt],"%d",&dz->process)!=1) {
+				sprintf(errstr,"Cannot read process no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+
+		case(2):	
+			if(sscanf(argv[cnt],"%d",&dz->mode)!=1) {
+				sprintf(errstr,"Cannot read mode no. sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(dz->mode > 0)
+				dz->mode--;
+			//setup_particular_application() =
+			if((exit_status = setup_the_application(dz))<0)
+				return(exit_status);
+			ap = dz->application;
+			break;
+
+		case(3):	
+			if(sscanf(argv[cnt],"%d",&infilecnt)!=1) {
+				sprintf(errstr,"Cannot read infilecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(infilecnt < 1) {
+				true_cnt = cnt + 1;
+				cnt = PRE_CMDLINE_DATACNT;	/* force exit from loop after assign_file_data_storage */
+			}
+			if((exit_status = assign_file_data_storage(infilecnt,dz))<0)
+				return(exit_status);
+			break;
+		case(INPUT_FILETYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->filetype)!=1) {
+				sprintf(errstr,"Cannot read filetype sent from TK (%s)\n",argv[cnt]);
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FILESIZE+4):	
+			if(sscanf(argv[cnt],"%d",&filesize)!=1) {
+				sprintf(errstr,"Cannot read infilesize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = filesize;	
+			break;
+		case(INPUT_INSAMS+4):	
+			if(sscanf(argv[cnt],"%d",&insams)!=1) {
+				sprintf(errstr,"Cannot read insams sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->insams[0] = insams;	
+			break;
+		case(INPUT_SRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->srate)!=1) {
+				sprintf(errstr,"Cannot read srate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_CHANNELS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->channels)!=1) {
+				sprintf(errstr,"Cannot read channels sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_STYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->stype)!=1) {
+				sprintf(errstr,"Cannot read stype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGSTYPE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origstype)!=1) {
+				sprintf(errstr,"Cannot read origstype sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGRATE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origrate)!=1) {
+				sprintf(errstr,"Cannot read origrate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MLEN+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Mlen)!=1) {
+				sprintf(errstr,"Cannot read Mlen sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DFAC+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->Dfac)!=1) {
+				sprintf(errstr,"Cannot read Dfac sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ORIGCHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->origchans)!=1) {
+				sprintf(errstr,"Cannot read origchans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_SPECENVCNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->infile->specenvcnt)!=1) {
+				sprintf(errstr,"Cannot read specenvcnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->specenvcnt = dz->infile->specenvcnt;
+			break;
+		case(INPUT_WANTED+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wanted)!=1) {
+				sprintf(errstr,"Cannot read wanted sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_WLENGTH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->wlength)!=1) {
+				sprintf(errstr,"Cannot read wlength sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_OUT_CHANS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->out_chans)!=1) {
+				sprintf(errstr,"Cannot read out_chans sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+			/* RWD these chanegs to samps - tk will have to deal with that! */
+		case(INPUT_DESCRIPTOR_BYTES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->descriptor_samps)!=1) {
+				sprintf(errstr,"Cannot read descriptor_samps sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_IS_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->is_transpos)!=1) {
+				sprintf(errstr,"Cannot read is_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_TRANSPOS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_transpos)!=1) {
+				sprintf(errstr,"Cannot read could_be_transpos sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_COULD_BE_PITCH+4):	
+			if(sscanf(argv[cnt],"%d",&dz->could_be_pitch)!=1) {
+				sprintf(errstr,"Cannot read could_be_pitch sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DIFFERENT_SRATES+4):	
+			if(sscanf(argv[cnt],"%d",&dz->different_srates)!=1) {
+				sprintf(errstr,"Cannot read different_srates sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DUPLICATE_SNDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->duplicate_snds)!=1) {
+				sprintf(errstr,"Cannot read duplicate_snds sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_BRKSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&inbrksize)!=1) {
+				sprintf(errstr,"Cannot read brksize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			if(inbrksize > 0) {
+				switch(dz->input_data_type) {
+				case(WORDLIST_ONLY):
+					break;
+				case(PITCH_AND_PITCH):
+				case(PITCH_AND_TRANSPOS):
+				case(TRANSPOS_AND_TRANSPOS):
+					dz->tempsize = inbrksize;
+					break;
+				case(BRKFILES_ONLY):
+				case(UNRANGED_BRKFILE_ONLY):
+				case(DB_BRKFILES_ONLY):
+				case(ALL_FILES):
+				case(ANY_NUMBER_OF_ANY_FILES):
+					if(dz->extrabrkno < 0) {
+						sprintf(errstr,"Storage location number for brktable not established by CDP.\n");
+						return(DATA_ERROR);
+					}
+					if(dz->brksize == NULL) {
+						sprintf(errstr,"CDP has not established storage space for input brktable.\n");
+						return(PROGRAM_ERROR);
+					}
+					dz->brksize[dz->extrabrkno]	= inbrksize;
+					break;
+				default:
+					sprintf(errstr,"TK sent brktablesize > 0 for input_data_type [%d] not using brktables.\n",
+					dz->input_data_type);
+					return(PROGRAM_ERROR);
+				}
+				break;
+			}
+			break;
+		case(INPUT_NUMSIZE+4):	
+			if(sscanf(argv[cnt],"%d",&dz->numsize)!=1) {
+				sprintf(errstr,"Cannot read numsize sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_LINECNT+4):	
+			if(sscanf(argv[cnt],"%d",&dz->linecnt)!=1) {
+				sprintf(errstr,"Cannot read linecnt sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ALL_WORDS+4):	
+			if(sscanf(argv[cnt],"%d",&dz->all_words)!=1) {
+				sprintf(errstr,"Cannot read all_words sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_ARATE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->arate)!=1) {
+				sprintf(errstr,"Cannot read arate sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_FRAMETIME+4):	
+			if(sscanf(argv[cnt],"%lf",&dummy)!=1) {
+				sprintf(errstr,"Cannot read frametime sent from TK\n");
+				return(DATA_ERROR);
+			}
+			dz->frametime = (float)dummy;
+			break;
+		case(INPUT_WINDOW_SIZE+4):	
+			if(sscanf(argv[cnt],"%f",&dz->infile->window_size)!=1) {
+				sprintf(errstr,"Cannot read window_size sent from TK\n");
+					return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_NYQUIST+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->nyquist)!=1) {
+				sprintf(errstr,"Cannot read nyquist sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_DURATION+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->duration)!=1) {
+				sprintf(errstr,"Cannot read duration sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minbrk)!=1) {
+				sprintf(errstr,"Cannot read minbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXBRK+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxbrk)!=1) {
+				sprintf(errstr,"Cannot read maxbrk sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MINNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->minnum)!=1) {
+				sprintf(errstr,"Cannot read minnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		case(INPUT_MAXNUM+4):	
+			if(sscanf(argv[cnt],"%lf",&dz->maxnum)!=1) {
+				sprintf(errstr,"Cannot read maxnum sent from TK\n");
+				return(DATA_ERROR);
+			}
+			break;
+		default:
+			sprintf(errstr,"case switch item missing: parse_sloom_data()\n");
+			return(PROGRAM_ERROR);
+		}
+		cnt++;
+	}
+	if(cnt!=PRE_CMDLINE_DATACNT+1) {
+		sprintf(errstr,"Insufficient pre-cmdline params sent from TK\n");
+		return(DATA_ERROR);
+	}
+
+	if(true_cnt)
+		cnt = true_cnt;
+	*cmdlinecnt = 0;		
+
+	while(cnt < argc) {
+		if((exit_status = get_tk_cmdline_word(cmdlinecnt,cmdline,argv[cnt]))<0)
+			return(exit_status);
+		cnt++;
+	}
+	return(FINISHED);
+}
+
+/********************************* GET_TK_CMDLINE_WORD *********************************/
+
+int get_tk_cmdline_word(int *cmdlinecnt,char ***cmdline,char *q)
+{
+	if(*cmdlinecnt==0) {
+		if((*cmdline = (char **)malloc(sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	} else {
+		if((*cmdline = (char **)realloc(*cmdline,((*cmdlinecnt)+1) * sizeof(char *)))==NULL)	{
+			sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline array.\n");
+			return(MEMORY_ERROR);
+		}
+	}
+	if(((*cmdline)[*cmdlinecnt] = (char *)malloc((strlen(q) + 1) * sizeof(char)))==NULL)	{
+		sprintf(errstr,"INSUFFICIENT MEMORY for TK cmdline item %d.\n",(*cmdlinecnt)+1);
+		return(MEMORY_ERROR);
+	}
+	strcpy((*cmdline)[*cmdlinecnt],q);
+	(*cmdlinecnt)++;
+	return(FINISHED);
+}
+
+/****************************** ASSIGN_FILE_DATA_STORAGE *********************************/
+
+int assign_file_data_storage(int infilecnt,dataptr dz)
+{
+	int exit_status;
+	int no_sndfile_system_files = FALSE;
+	dz->infilecnt = infilecnt;
+	if((exit_status = allocate_filespace(dz))<0)
+		return(exit_status);
+	if(no_sndfile_system_files)
+		dz->infilecnt = 0;
+	return(FINISHED);
+}
+
+/*********************** CHECK_THE_PARAM_VALIDITY_AND_CONSISTENCY *********************/
+
+int check_the_param_validity_and_consistency(dataptr dz)
+{
+	if(dz->mode != MATRIX_USE) {
+		if(!is_pow_of_two(dz->iparam[MATRIX_CHANS])) {
+			sprintf(errstr,"Number of analysis channels must be a power of 2\n");
+			return(DATA_ERROR);
+		}
+		dz->wanted  = dz->iparam[MATRIX_CHANS];
+		dz->clength = dz->wanted/2;
+		dz->overlap = dz->iparam[MATRIX_OVLAP];
+	}
+	return FINISHED;
+}
+
+/************************* redundant functions: to ensure libs compile OK *******************/
+
+int assign_process_logic(dataptr dz)
+{
+	return(FINISHED);
+}
+
+void set_legal_infile_structure(dataptr dz)
+{}
+
+int set_legal_internalparam_structure(int process,int mode,aplptr ap)
+{
+	return(FINISHED);
+}
+
+int setup_internal_arrays_and_array_pointers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int establish_bufptrs_and_extra_buffers(dataptr dz)
+{
+	return(FINISHED);
+}
+
+int get_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	return(FINISHED);
+}
+
+int read_special_data(char *str,dataptr dz)	
+{
+	return(FINISHED);
+}
+
+int inner_loop
+(int *peakscore,int *descnt,int *in_start_portion,int *least,int *pitchcnt,int windows_in_buf,dataptr dz)
+{
+	return FINISHED;
+}
+
+/********************************************************************************************/
+
+int get_the_process_no(char *prog_identifier_from_cmdline,dataptr dz)
+{
+	if      (!strcmp(prog_identifier_from_cmdline,"matrix"))		dz->process = MATRIX;
+	else {
+		sprintf(errstr,"Unknown program identification string '%s'\n",prog_identifier_from_cmdline);
+		return(USAGE_ONLY);
+	}
+	return(FINISHED);
+}
+
+/******************************** USAGE1 ********************************/
+
+int usage1(void)
+{
+	fprintf(stderr,
+	"\nMATRIX MANIPULATION OF SPECTRUM OF SOUND\n\n"
+	"USAGE: matrix matrix (matrix-data) infile outfile(s).\n"
+	"\n"
+	"Type 'matrix matrix' for more info\n");
+	return(USAGE_ONLY);
+}
+
+/******************************** USAGE2 ********************************/
+
+int usage2(char *str)
+{
+	if(!strcmp(str,"matrix")) {
+		fprintf(stdout,
+	    "USAGE:\n"
+		"matrix matrix 1 infile outfiles analchans winoverlap [-c]\n"
+		"matrix matrix 2 infile outfile inmatrixfile [-c]\n"
+		"matrix matrix 3-4 infile outfiles analchans winoverlap\n"
+		"\n"
+		"MODE 1: Generates matrix, and transformed sound.\n"
+		"MODE 2: Uses input matrix data to transform sound.\n"		
+		"MODE 3: Exchanges reals and imags in fft output.\n"
+		"MODE 4: Invert phase in each channel +ve to -ve\n"
+		"\n"
+		"ANALCHANS   No of Analysis Channels (Pow-of-2: 4-16384)\n"
+		"WINOVERLAP  Overlap of Analysis windows (Range 1-4)\n"
+		"-c          Apply matrix-transform Cyclically.\n"
+		"            window1 = spec * matrix\n"
+		"            window2 = spec * matrix * matrix\n"
+		"            window3 = spec * matrix * matrix * matrix\n"
+		"            and so on\n"
+		"\n");
+	} else
+		fprintf(stdout,"Unknown option '%s'\n",str);
+	return(USAGE_ONLY);
+}
+
+int usage3(char *str1,char *str2)
+{
+	fprintf(stderr,"Insufficient parameters on command line.\n");
+	return(USAGE_ONLY);
+}
+
+/************************ GET_THE_MODE_NO *********************/
+
+int get_the_mode_no(char *str, dataptr dz)
+{
+	if(sscanf(str,"%d",&dz->mode)!=1) {
+		sprintf(errstr,"Cannot read mode of program.\n");
+		return(USAGE_ONLY);
+	}
+	if(dz->mode <= 0 || dz->mode > dz->maxmode) {
+		sprintf(errstr,"Program mode value [%d] is out of range [1 - %d].\n",dz->mode,dz->maxmode);
+		return(USAGE_ONLY);
+	}
+	dz->mode--;		/* CHANGE TO INTERNAL REPRESENTATION OF MODE NO */
+	return(FINISHED);
+}
+
+/************************ HANDLE_MATRIXDATA *********************/
+
+int handle_matrixdata(int *cmdlinecnt,char ***cmdline,dataptr dz)
+{
+	aplptr ap = dz->application;
+	int n, rowcnt, colcnt;
+	int cnt_of_vals, cnt_of_matrix_vals, cnt_of_complex_vals;
+	char temp[200], *q, *filename = (*cmdline)[0];
+	double *p, *matrix;
+	double dummy, maxmatrix;
+	if(!sloom) {
+		if(*cmdlinecnt <= 0) {
+			sprintf(errstr,"Insufficient parameters on command line.\n");
+			return(USAGE_ONLY);
+		}
+	}
+	ap->data_in_file_only 	= TRUE;
+	ap->special_range 		= TRUE;
+	ap->min_special 		= -1.0;
+	ap->max_special 		= 4.0;
+	maxmatrix				= 1.0;
+	if((dz->fp = fopen(filename,"r"))==NULL) {
+		sprintf(errstr,"Cannot open datafile %s\n",filename);
+		return(DATA_ERROR);
+	}
+	n = 0;
+	p = &dummy;
+	while(fgets(temp,200,dz->fp)!=NULL) {
+		q = temp;
+		if(is_an_empty_line_or_a_comment(q))
+			continue;
+		while(get_float_from_within_string(&q,p)) {
+			if(n==0) {
+				if(*p < 1.0 || *p > 4.0) {
+					sprintf(errstr,"Invalid analysis overlap val %d (range 1 - 4) : file %s\n",(int)round(*p),filename);
+					return(DATA_ERROR);
+				}
+				dz->overlap = (int)round(dummy);
+			} else {
+				if(*p < ap->min_special || *p > maxmatrix) {
+					sprintf(errstr,"Matrix value out of range (%lf - %lf) : line %d: file %s\n",ap->min_special,ap->max_special,n+1,filename);
+					return(DATA_ERROR);
+				}
+			}
+			n++;
+		}
+	}
+	if(n==0) {
+		sprintf(errstr,"No data in matrix file %s\n",filename);
+		return(DATA_ERROR);
+	}
+	if(dz->overlap < 1 || dz->overlap > 4) {
+		sprintf(errstr,"Analysis Overlap value (%d) out of range (1-4) if file %s\n",dz->overlap,filename);
+		return(DATA_ERROR);
+	}
+	cnt_of_vals = n;
+	cnt_of_matrix_vals = n - 1;
+	cnt_of_complex_vals = cnt_of_matrix_vals/2;	//	for 512 complex vals : matrix is 512 * 512 complex values
+				//	= 512 rows of 1024 (real+imag) values, so matrix is 1024 X 512 : and k = n/2 = 512 X 512
+				//	1024 is dz->wanted	512 is dz->clength	so sqrt(k) = dz->clength
+	dz->clength = (int)round(sqrt(cnt_of_complex_vals));
+	if(!is_pow_of_two(dz->clength)) {
+		sprintf(errstr,"Matrix has invalid no of values (%d : corresponds to chancnt %d)\n",cnt_of_matrix_vals,dz->clength*2);
+		return(DATA_ERROR);
+	}
+	dz->wanted = dz->clength * 2;
+	if ((dz->parray[0] = (double *)malloc(cnt_of_matrix_vals * sizeof(double)))==NULL) {
+		sprintf(errstr,"Insufficient memory to store matrix data\n");
+		return(MEMORY_ERROR);
+	}
+	if ((dz->parray[1] = (double *)malloc(cnt_of_matrix_vals * sizeof(double)))==NULL) {
+		sprintf(errstr,"Insufficient memory to store 2nd matrix data\n");
+		return(MEMORY_ERROR);
+	}
+	if(fseek(dz->fp,0,0)<0) {
+		sprintf(errstr,"fseek() failed in handle_matrixdata()\n");
+		return(SYSTEM_ERROR);
+	}
+	p = dz->parray[0];
+	n = 0;
+	while(fgets(temp,200,dz->fp)!=NULL) {
+		q = temp;
+		if(is_an_empty_line_or_a_comment(temp))
+			continue;
+		while(get_float_from_within_string(&q,p)) {
+			if(n == 0)
+				p--;					//	overwrite first (ovlap) value by first true value in matrix
+			if(++n >= cnt_of_vals)
+				break;
+			p++;
+		}
+		if(n >= cnt_of_vals)
+			break;
+	}
+	matrix = dz->parray[0];
+	dz->itemcnt = cnt_of_matrix_vals;
+	if(fclose(dz->fp)<0) {
+		fprintf(stdout,"WARNING: Failed to close input textfile %s.\n",filename);
+		fflush(stdout);
+	}
+	rowcnt = -1;
+	for(n = 0; n < cnt_of_matrix_vals; n+=2) {	//	advancing in real-imag pairs
+		colcnt = (n % dz->wanted)/2;			//	new col reacned when we have a multiple of 1024 entries
+		if(colcnt == 0)							//	but this is column modcnt/2 as there are 2 entries per column
+			rowcnt++;
+		if(rowcnt == colcnt) {					//	Diagonal entry : bot hreal and imag vals should be zero
+			if((matrix[n] != 0.0) || (matrix[n+1] != 0.0)) {
+				sprintf(errstr,"WARNING: Matrix data does not have zeros on the diagonal. Not a unitary matrix.\n");
+				return(DATA_ERROR);
+			}
+		}
+	}
+	(*cmdline)++;		
+	(*cmdlinecnt)--;
+	return(FINISHED);
+}
+
+/* How to form an N X N unitary matrix.
+ *
+ * (1) Set up an empty N X N matrix = A
+ * (2) Put any complex numbers at all, above the main diagonal
+ * (3) Make the hermitian transpose A* i.e. rotate A about the diagonal
+ * 	and then replace the values by their complex conjugates.
+ * (4) Form matrix B  =  A  -  A*
+ * (5) Form matrix U  =  exp(B)
+ * 
+ * My interpretation for 4X4
+ *    (1)			 (2)				 (3)
+ * |0 0 0 0|		|0 a+ib c+id e+if|	| 0    0    0   0|
+ * |0 0 0 0|		|0  0   g+ih j+ik|	|a-ib  0    0   0|
+ * |0 0 0 0|		|0  0    0   m+in|	|c-id g-ih  0   0|
+ * |0 0 0 0|		|0  0    0    0  |	|e-if j-ik m-in 0|
+ * 
+ * 		(4)						(5)
+ * |  0    a+ib  c+id  e+if|	|   1       exp(a+ib)   exp(c+id) exp(e+if)|
+ * |-a+ib   0    g+ih  j+ik|	|exp(-a+ib)     1       exp(g+ih) exp(j+ik)|
+ * |-c+id -g+ih     0  m+in|	|exp(-c+id) exp(-g+ih)      1     exp(e+if)|
+ * |-e+if -j+ik  -m+in   0 |	|exp(-e+if) exp(-j +ik) exp(-e+if)    1    |
+ * 
+ * where "1" could be stored as exp(0,0)
+ *
+ * Store as a single array, row by row.	
+ * Store real+imag data as *fptr  malloc(*fptr, N * N * 2, sizeof(float))
+ * 
+ * for row,column (Y,X)
+ * rowindex = Y * N		with val-pairs = Y * N * 2
+ * column index = X		with val-pairs = X * 2
+ * row-column-index_real (Y,X) = (Y*N*2) + (X*2) = ((Y*N) + X)*2
+ * row-column-index_imag (Y,X) = ditto+1
+ */
+
+/****************************** MULTIPLY_BY_MATRIX ************************
+ *
+ * Presumably FFT data is exp(x(n)+iy(n))  stored as reals[n] and imags[n]
+ * 
+ * Let N be the size of the (spectrum as amp and phase) vector
+ *
+ * MULTIPLY EXPONENTS incorrect but may be interesting!!
+ *	  NB:	(a+ib)*(c+id) = (ac-bd) + i(ad+bc)
+ * ADD EXPONENTS to multply exponentials
+ *	  NB:	(a+ib)+(c+id) = (ac) + i(bd)
+ */
+
+int multiply_by_matrix(float *reals,float *imags,double *matrix, int N)
+{
+	double * transformed_realval, *transformed_imagval;
+	double realval, imagval, rmval, imval, nurealval, nuimagval;
+	int x, y, m_index;
+	if((transformed_realval = (double *)malloc(sizeof(double) * (N*2)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to establish output vector reals.\n");
+		return(MEMORY_ERROR);
+	}
+	if((transformed_imagval = (double *)malloc(sizeof(double) * (N*2)))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to establish output vector imags.\n");
+		return(MEMORY_ERROR);
+	}
+
+	for (x = 0; x < N; x++) {
+	  	transformed_realval[x] = 0.0;
+	  	transformed_imagval[x] = 0.0;
+  		for (y = 0; y < N; y++) {
+  			realval = reals[y];			//	get each (yth) value of the original vector
+  			imagval = imags[y];
+//		rmval = "row-column-index_real[row y,col x]";
+  			m_index = ((y*N) + x)*2;	//	mutiplied by the (yth) row entry in the xth column
+  			rmval = matrix[m_index++];
+  			imval = matrix[m_index];
+// MULTIPLY EXPONENTS
+			nurealval = (realval * rmval) - (imagval * imval);	// (ac-bd)
+			nuimagval = (realval * imval) + (imagval * rmval);	// (ad+bc)
+// ADD EXPONENTS
+//			nurealval = (realval + rmval);	// (a+c)
+// 			nuimagval = (imagval + imval);	// (b+d)
+
+			transformed_realval[x] += nurealval;
+   			transformed_imagval[x] += nuimagval;
+		}
+	}
+	for (x = 0; x < N; x++) {
+		reals[x] = (float)transformed_realval[x];
+		imags[x] = (float)transformed_imagval[x];
+	}
+	return FINISHED;
+}
+
+/****************************** CREATE_RANDOM_UNITARY_MATRIX ************************
+ *
+ * An arbitrary N X N unitary matrix
+ * Length of diagonal = no of rows = no of cols = N
+ * e.g. for N = 5
+ * Number of vals required(K) =         1  +  2	...	  + (N-1)
+ * 								|  0	x	  x	    x	  x	|
+ *								|	 \						|
+ *								|  0	0	  x	    x	  x	|
+ *								|		   \				|
+ * 								|  0	0	  0	    x	  x	|
+ *								|			     \			|
+ *								|  0	0	  0	    0	  x	|
+ *								|				       \	|
+ *								|  0	0	  0	    0	  0	|
+ * K = (1 + 2 + 3 .... +(N-1))
+ *
+ * For unitary matrix, diagonal is all zero, and matrix is symmetrical about diagonal
+ * except that REAL values to lower left are negation of their mirror values to upper right.
+ *
+ *	The matrix rows and columns are indexed by row,column (n,m)
+ *	and the matrix is stored as row 1, row 2, row 3 ....
+ *		for row,column (Y,X)
+ *		index of row-start	= Y * N
+ *		index of column entry in row = X
+ *		row-column-index_(complex) (Y,X) = ((Y*N) + X)
+ *		row-column-index_real/imag	(a pair of vals : real & imag : for each complex number)
+ *		row-column-index_real		[(Y*N) + X] * 2
+ *		row-column-index_imag		ditto + 1
+ */
+
+int create_random_unitary_matrix(dataptr dz)
+{
+	int N, K = 0, M, cnt, m_index, mc_index;
+	double *r, *i, *matrix;
+	int n, m;
+	N = dz->clength;					//  N is number of COMPLEX-number entries in FFT
+	for(n=1; n<N; n++)					//	Sum of 1,2, .... (N-1)
+		K += n;
+	M = N * N;							//	matrix size (in complex-numbers);
+	if((r = (double *)malloc(sizeof(double) * K))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to establish real matrix components.\n");
+		return(MEMORY_ERROR);
+	}
+	if((i = (double *)malloc(sizeof(double) * K))==NULL) {
+		sprintf(errstr,"INSUFFICIENT MEMORY to establish imag matrix components.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->parray[0] = (double *)malloc(sizeof(double) * (M*2)))==NULL) {	//	double size, to store reals & imags
+		sprintf(errstr,"INSUFFICIENT MEMORY to establish matrix array.\n");
+		return(MEMORY_ERROR);
+	}
+	if((dz->parray[1] = (double *)malloc(sizeof(double) * (M*2)))==NULL) {	//	double size, to store reals & imags
+		sprintf(errstr,"INSUFFICIENT MEMORY to establish 2nd matrix array.\n");
+		return(MEMORY_ERROR);
+	}
+	matrix = dz->parray[0];
+	memset((char *)matrix,0,M * 2 * sizeof(double));		//	Presetting matrix vals to zero
+															//	ensures diagonal will hold zeros.
+	initrand48();	
+
+	for(n=0;n<K; n++) {										//	Generate all required (K) real numbers
+		r[n] = drand48();			//	reals
+  		if(flteq(r[n],0.0)) {		//	Ensure no zeros in reals
+  			n--;
+  			continue;
+  		}
+	}
+	for(n=0;n<K; n++) {
+		i[n] = drand48();			//	imags
+	}
+																//	| 00  01  02  03  ... to upper right of diagonal	
+	cnt = 0;		//	set counter	for reals & imags			//	|    x				  m > n
+																//	| 10  11  12  13  ...	
+	for(n = 0; n < N; n++) {		//	rows						|		 x
+  		for(m = 0; m < N; m++) {	//	cols						| 20  21  22  23  ... to lower left of diagonal
+  			if(m > n) {		//	to upper right of diagonal			|			 x		  m < n
+				m_index = ((n*N)+m) * 2;						//	| 30  31  32  33  ...
+				matrix[m_index++] = r[cnt];						//	|				 x
+  				matrix[m_index]   = i[cnt++];					//	| ... ... ... ..  ...	
+			} else if(m < n) {
+				m_index  = ((n*N)+m) * 2;					//	matrix index here
+				mc_index = ((m*N)+n) * 2;					//	matrix index diagonally opposite
+				matrix[m_index++] = -matrix[mc_index++];	//	COMPLEMENTARY real values
+				matrix[m_index]   =  matrix[mc_index];		//	imag value is the same
+			}	
+  		}
+	}
+
+	dz->itemcnt = M*2;
+//												// TEST ONLY : check diagonal values are all zero
+//	for(m = 0; m < N; m++) {		//	cols
+//		for(n = 0; n < N; n++) {	//	rows
+//			if(m == n) {
+//				m_index = ((n*N)+m) * 2;
+//				if(matrix[m_index] != 0.0 || matrix[m_index+1] != 0.0) {
+//					sprintf(errstr,"Error in array creation\n");
+//					return(PROGRAM_ERROR);
+//				}
+//			}
+//		}
+//	}
+	for(n = 0; n < N; n++)
+		dz->parray[1][n] = dz->parray[0][n];		// File 2nd array for cycling of matrix
+	return FINISHED;
+}
+
+/*	NB:														00 01 02 ....
+ *		Matrix filled across one row then across next, so	10 11 12 ...
+ *															20 21 22 ...
+ *		So any location nm where m > n (e.g. 12), 
+ *		is always assigned before we reach mn (e.g. 21)
+ *		So when we reach mn we can always use
+ *		the previously assigned values in nm
+ */
+
+/********************************** DO_SPECMATRIX **************************/
+
+int do_specmatrix(dataptr dz)
+{
+	int exit_status;
+	int n;
+	char filename[2000];
+	if(dz->mode == MATRIX_MAKE) {
+		if((exit_status = create_random_unitary_matrix(dz)) < 0) {	
+			return(exit_status);
+		}
+		strcpy(filename,dz->outfilename);
+		change_extension(filename);
+		if((dz->fp = fopen(filename,"w")) == NULL) {
+			fprintf(stdout,"WARNING: Failed to write matrix data to output file.\n");
+			fflush(stdout);
+		} else {
+//			WRITE AS BINARY
+			fprintf(dz->fp,"%d\n",dz->overlap);
+			for(n=0;n<dz->itemcnt;n++) {
+				fprintf(dz->fp,"%f\n",dz->parray[0][n]);
+			}
+			fclose(dz->fp);
+		}
+	}							
+	if((exit_status = matrix_process(dz))<0)
+		return exit_status;
+	return FINISHED;
+}
+
+/********************************** CHANGE_EXTENSION **************************/
+
+void change_extension(char *filename)
+{
+	int len;
+	char *p;
+	len = strlen(filename);
+	p = filename + len - 1;
+	while(p > filename) {
+		if(*p == '.')
+			break;
+		p--;
+	}
+	if(p > filename) {
+		if(sloom)
+			p--;
+		*p = ENDOFSTR;
+	}
+	if(sloom) {
+		strcat(filename,"1");
+	} else {
+		strcat(filename,".txt");
+	}
+	return;
+}
+
+/****************************** MATRIX_PROCESS ******************************/
+
+int matrix_process(dataptr dz)
+{
+	int exit_status;
+	int finished = 0;
+	int rr, ii;
+	float temp;
+	int num_overflows = 0;
+	int samptime = SAMP_TIME_STEP;
+
+	double	*matrix,		/* pointer to start of matrix buffer */
+			*matrix2;		/* pointer to start of 2nd matrix buffer */
+	float	*input,			/* pointer to start of input buffer */
+			*output,		/* pointer to start of output buffer */
+			*anal,			/* pointer to start of analysis buffer */
+			*banal,			/* pointer to anal[1] (for FFT calls) */
+			*nextIn,		/* pointer to next empty word in input */
+			*nextOut,		/* pointer to next empty word in output */
+			*analWindow,	/* pointer to center of analysis window */
+			*synWindow,		/* pointer to center of synthesis window */
+			maxsample = 0.0, minsample = 0.0, biggest;
+
+	int		M = 0,			/* length of analWindow impulse response */
+			D = 0,			/* decimatin factor */
+			I = 0,			/* interpolation factor (default will be I=D)*/
+			analWinLen,		/* half-length of analysis window */
+			synWinLen;		/* half-length of synthesis window */
+
+	int	outCount,		/* number of samples written to output */
+			ibuflen,		/* length of input buffer */
+			obuflen,		/* length of output buffer */
+			nI = 0,			/* current input (analysis) sample */
+			nO,				/* current output (synthesis) sample */
+			nMaxOut;		/* last output (synthesis) sample */
+	int	isr,			/* sampling rate */
+			endsamp = VERY_BIG_INT;
+
+	float	sum,			/* scale factor for renormalizing windows */
+			R,				/* input sampling rate */
+
+			local_maxsample = 0.0;
+
+	int		i,j,k,		/* index variables */
+			Dd,			/* number of new inputs to read (Dd <= D) */
+			Ii,			/* number of new outputs to write (Ii <= I) */
+			N2,			/* dz->wanted/2 = dz->clength */
+			NO,			/* synthesis NO = dz->wanted / P */
+			NO2,		/* NO/2 */
+			IO,			/* synthesis IO = I / P */
+			IOi,		/* synthesis IOi = Ii / P */
+			Mf = 0,		/* flag for even M */
+			flag = 0,	/* end-of-input flag */
+			matrix_ovlap;
+	/*RWD */
+	float F = 0.0f;
+
+	matrix  = dz->parray[0];
+	matrix2 = dz->parray[1];
+
+	isr 	 = dz->infile->srate;
+	R        = (float)isr;
+
+	if(flteq(R,0.0)) {
+		sprintf(errstr,"Problem: zero sampling rate\n");
+		return(DATA_ERROR);
+	}
+	N2 = dz->wanted / 2;		//	N2 = clength
+
+	F = /*(int)*/(float)(R /(float)dz->wanted);	  /*RWD*/
+
+	matrix_ovlap = dz->overlap - 1;		//	See pvoc_preprocess
+	switch(matrix_ovlap){
+		case 0:	M = 4*dz->wanted;	break;
+		case 1:	M = 2*dz->wanted;	break;
+		case 2: M = dz->wanted;		break;
+		case 3: M = N2;				break;
+		default:
+			sprintf(errstr,"ERROR: Invalid window Overlap factor.\n");
+			return(PROGRAM_ERROR);
+	}
+
+	Mf = 1 - M%2;
+
+	if (M < 7) {
+		fprintf(stdout,"WARNING: analWindow impulse response is too small\n");
+ 		fflush(stdout);
+	}
+	ibuflen = 4 * M;
+	obuflen = 4 * M;
+
+	if((D = (int)(M/PVOC_CONSTANT_A)) == 0){
+		fprintf(stdout,"WARNING: Decimation too low: adjusted.\n");
+		fflush(stdout);
+		D = 1;
+	}
+
+	if(sloom)
+		dz->tempsize = dz->insams[0];
+
+	I   = D;
+	NO  = dz->wanted;	/* synthesis transform will be NO points */
+	NO2 = NO/2;
+	IO  = I;
+
+	//	TW : possibly redundant
+	if((exit_status = sndwrite_header(dz))<0)
+		return(exit_status);
+
+	//	DO ANALYSIS
+
+	if(!sloom && !sloombatch) {
+		fprintf(stdout,"analysis beginning\n");	
+		fflush(stdout);
+	}
+	/* set up analysis window: The window is assumed to be symmetric
+		with M total points.  After the initial memory allocation,
+		analWindow always points to the midpoint of the window
+		(or one half sample to the right, if M is even); analWinLen
+		is half the true window length (rounded down). Any low pass
+		window will work; a Hamming window is generally fine,
+		but a Kaiser is also available.  If the window duration is
+		longer than the transform (M > N), then the window is
+		multiplied by a sin(x)/x function to meet the condition:
+		analWindow[Ni] = 0 for i != 0.  In either case, the
+		window is renormalized so that the phase vocoder amplitude
+		estimates are properly scaled.  The maximum allowable
+		window duration is ibuflen/2. */
+
+	if((exit_status = pvoc_float_array(M+Mf,&analWindow))<0)
+		return(exit_status);
+	analWinLen = M/2;
+	analWindow += analWinLen;
+
+	hamming(analWindow,analWinLen,Mf);
+
+	for (i = 1; i <= analWinLen; i++)
+		*(analWindow - i) = *(analWindow + i - Mf);
+
+	if (M > dz->wanted) {
+		if (Mf)
+		*analWindow *=(float)
+		((double)dz->wanted*sin((double)PI*.5/dz->wanted)/(double)(PI*.5));
+		for (i = 1; i <= analWinLen; i++) 
+			*(analWindow + i) *=(float)
+			((double)dz->wanted * sin((double) (PI*(i+.5*Mf)/dz->wanted)) / (PI*(i+.5*Mf))); /* D.Timis */
+		for (i = 1; i <= analWinLen; i++)
+			*(analWindow - i) = *(analWindow + i - Mf);
+	}
+
+	sum = 0.0f;
+	for (i = -analWinLen; i <= analWinLen; i++)
+		sum += *(analWindow + i);
+
+	sum = (float)(2.0/sum);		/*factor of 2 comes in later in trig identity*/
+
+	for (i = -analWinLen; i <= analWinLen; i++)
+		*(analWindow + i) *= sum;
+
+	/* set up synthesis window:  For the minimal mean-square-error
+		formulation (valid for N >= M), the synthesis window
+		is identical to the analysis window (except for a
+		scale factor), and both are even in length.  If N < M,
+		then an interpolating synthesis window is used. */
+
+	if((exit_status = pvoc_float_array(M+Mf,&synWindow))<0)
+		return(exit_status);
+	synWinLen = M/2;
+	synWindow += synWinLen;
+
+	if (M <= dz->wanted){
+		hamming(synWindow,synWinLen,Mf);
+		for (i = 1; i <= synWinLen; i++)
+			*(synWindow - i) = *(synWindow + i - Mf);
+
+		for (i = -synWinLen; i <= synWinLen; i++)
+			*(synWindow + i) *= sum;
+
+		sum = 0.0f;
+		for (i = -synWinLen; i <= synWinLen; i+=I)
+			sum += *(synWindow + i) * *(synWindow + i);
+
+		sum = (float)(1.0/ sum);
+
+		for (i = -synWinLen; i <= synWinLen; i++)
+			*(synWindow + i) *= sum;
+	} else {	
+		hamming(synWindow,synWinLen,Mf);
+		for (i = 1; i <= synWinLen; i++)
+			*(synWindow - i) = *(synWindow + i - Mf);
+
+		if (Mf)
+			*synWindow *= (float)((double)IO * sin((double) (PI*.5/IO)) / (double)(PI*.5));
+		for (i = 1; i <= synWinLen; i++) 
+			*(synWindow + i) *=(float)
+			((double)IO * sin((double) (PI*(i+.5*Mf)/IO)) /(double) (PI*(i+.5*Mf)));
+		for (i = 1; i <= synWinLen; i++)
+			*(synWindow - i) = *(synWindow + i - Mf);
+
+		sum = (float)(1.0/sum);
+
+		for (i = -synWinLen; i <= synWinLen; i++)
+			*(synWindow + i) *= sum;
+	}
+      
+	/* set up input buffer:  nextIn always points to the next empty
+		word in the input buffer (i.e., the sample following
+		sample number (n + analWinLen)).  If the buffer is full,
+		then nextIn jumps back to the beginning, and the old
+		values are written over. */
+
+	if((exit_status = pvoc_float_array(ibuflen,&input))<0)
+		return(exit_status);
+
+	nextIn = input;
+
+	/* set up output buffer:  nextOut always points to the next word
+		to be shifted out.  The shift is simulated by writing the
+		value to the standard output and then setting that word
+		of the buffer to zero.  When nextOut reaches the end of
+		the buffer, it jumps back to the beginning.  */
+
+	if((exit_status = pvoc_float_array(obuflen,&output))<0)
+		return(exit_status);
+
+	nextOut = output;
+
+	/* set up analysis buffer for (N/2 + 1) channels: The input is real,
+		so the other channels are redundant. */
+
+	if((exit_status = pvoc_float_array(dz->wanted+2,&anal))<0)
+		return(exit_status);
+	banal = anal + 1;
+
+	/* initialization: input time starts negative so that the rightmost
+		edge of the analysis filter just catches the first non-zero
+		input samples; output time is always T times input time. */
+
+	outCount = 0;
+	nI = -(analWinLen / D) * D;	/* input time (in samples) */
+	nO = nI;					/* output time (in samples) */
+	Dd = analWinLen + nI + 1;	/* number of new inputs to read */
+	Ii = 0;				/* number of new outputs to write */
+	IOi = 0;
+	flag = 1;
+
+	/* main loop:  If endsamp is not specified it is assumed to be very large
+		and then readjusted when fgetfloat detects the end of input. */
+
+	display_virtual_time(0L,dz);	
+
+	dz->wincnt = 0;
+	while(nI < (endsamp + analWinLen)){
+		{
+			static float *sbuf = 0;
+			static int sblen = 0;
+			int got, tocp;
+			float *sp;
+
+			if(sblen < Dd) {
+				if(sbuf != 0)
+					free(sbuf);
+
+				if((sbuf = (float *)malloc(Dd*sizeof(float))) == 0) {
+					sprintf(errstr, "pvoc: can't allocate short buffer\n");
+					return(MEMORY_ERROR);
+				}
+				sblen = Dd;
+			}
+			if((got = fgetfbufEx(sbuf, Dd, dz->ifd[0],0)) < 0) {
+				sfperror("pvoc: read error");
+				return(SYSTEM_ERROR);
+			}
+			if(got < Dd)
+				Dd = got;
+			sp = sbuf;
+
+			tocp = min(got, input+ibuflen-nextIn);
+			got -= tocp;
+			while(tocp-- > 0)
+				*nextIn++ = *sp++;
+
+			if(got > 0) {
+				nextIn -= ibuflen;
+				while(got-- > 0)
+					*nextIn++ = *sp++;
+			}
+			if (nextIn >= (input + ibuflen))
+				nextIn -= ibuflen;
+		}
+		if (nI > 0)
+			for (i = Dd; i < D; i++){	/* zero fill at EOF */
+				*(nextIn++) = 0.0f;
+				if (nextIn >= (input + ibuflen))
+					nextIn -= ibuflen;
+			}
+	
+/* analysis: The analysis subroutine computes the complex output at
+	time n of (dz->wanted/2 + 1) of the phase vocoder channels.  It operates
+	on input samples (n - analWinLen) thru (n + analWinLen) and
+	expects to find these in input[(n +- analWinLen) mod ibuflen].
+	It expects analWindow to point to the center of a
+	symmetric window of length (2 * analWinLen +1).  It is the
+	responsibility of the main program to ensure that these values
+	are correct!  The results are returned in anal as succesive
+	pairs of real and imaginary values for the lowest (dz->wanted/2 + 1)
+	channels.   The subroutines fft and reals together implement
+	one efficient FFT call for a real input sequence.  */
+
+
+		for (i = 0; i < dz->wanted+2; i++) 
+			*(anal + i) = 0.0f;	/*initialize*/
+
+		j = (nI - analWinLen - 1 + ibuflen) % ibuflen;	/*input pntr*/
+
+		k = nI - analWinLen - 1;			/*time shift*/
+		while (k < 0)
+			k += dz->wanted;
+		k = k % dz->wanted;
+		for (i = -analWinLen; i <= analWinLen; i++) {
+			if (++j >= ibuflen)
+				j -= ibuflen;
+			if (++k >= dz->wanted)
+				k -= dz->wanted;
+			*(anal + k) += *(analWindow + i) * *(input + j);
+		}
+		if((exit_status = fft_(anal,banal,1,N2,1,-2))<0)
+			return(exit_status);
+		if((exit_status = reals_(anal,banal,N2,-2))<0)
+			return(exit_status);
+
+		switch(dz->mode) {
+		case(2):
+			for(rr=0,ii = 1;rr<dz->wanted+2;rr+=2,ii+=2) {				// Swap reals and imags
+				temp     = anal[rr];
+				anal[rr] = anal[ii];
+				anal[ii] = temp;
+			}
+			break;
+		case(3):
+			for(ii = 1;ii<dz->wanted+2;ii+=2)							// Invert phase in each channel
+				anal[ii] = (float)-anal[ii];
+			break;
+		default:
+			if((exit_status = multiply_by_matrix(anal,banal,matrix,N2))< 0)
+				return(exit_status);
+			if(dz->vflag[0]) {
+				if((exit_status = matrix_cycle(matrix,matrix2,dz))< 0)
+					return(exit_status);
+			}
+			break;
+		}
+
+//	DO RESYNTH
+
+	/* synthesis: The synthesis subroutine uses the Weighted Overlap-Add
+		technique to reconstruct the time-domain signal.  The (dz->wanted/2 + 1)
+		phase vocoder channel outputs at time n are inverse Fourier
+		transformed, windowed, and added into the output array.  The
+		subroutine thinks of output as a shift register in which 
+		locations are referenced modulo obuflen.  Therefore, the main
+		program must take care to zero each location which it "shifts"
+		out (to standard output). The subroutines reals and fft
+		together perform an efficient inverse FFT.  */
+
+		if((exit_status = reals_(anal,banal,NO2,2))<0)
+			return(exit_status);
+		if((exit_status = fft_(anal,banal,1,NO2,1,2))<0)
+			return(exit_status);
+
+		j = nO - synWinLen - 1;
+		while (j < 0)
+			j += obuflen;
+		j = j % obuflen;
+
+		k = nO - synWinLen - 1;
+		while (k < 0)
+			k += NO;
+		k = k % NO;
+
+		for (i = -synWinLen; i <= synWinLen; i++) {	/*overlap-add*/
+			if (++j >= obuflen)
+				j -= obuflen;
+			if (++k >= NO)
+				k -= NO;
+			*(output + j) += *(anal + k) * *(synWindow + i);
+		}
+
+		for (i = 0; i < IOi;){	/* shift out next IOi values */
+			int j;
+			int todo = min(IOi-i, output+obuflen-nextOut);
+
+// NEW 2014 -->
+			if((exit_status = outfloats(nextOut,&maxsample,&minsample,&local_maxsample,&num_overflows,todo,finished,dz))<0)
+				return(exit_status);
+// <-- NEW 2014
+			i += todo;
+			outCount += todo;
+			for(j = 0; j < todo; j++)
+				*nextOut++ = 0.0f;
+			if (nextOut >= (output + obuflen))
+				nextOut -= obuflen;
+
+		}
+					
+		if(flag 							/* flag means do this operation only once */
+		&& (nI > 0) && (Dd < D)){			/* EOF detected */
+			flag = 0;
+			endsamp = nI + analWinLen - (D - Dd);
+		}
+
+		nI += D;				/* increment time */
+		nO += IO;
+								/* Dd = D except when the end of the sample stream intervenes */
+		Dd = min(D, max(0, D+endsamp-nI-analWinLen));
+
+		if (nO > (synWinLen + I))
+			Ii = I;
+		else if (nO > synWinLen)
+			Ii = nO - synWinLen;
+		else {
+			Ii = 0;
+			for (i=nO+synWinLen; i<obuflen; i++) {
+				if (i > 0)
+					*(output+i) = 0.0f;
+			}
+		}
+		IOi = Ii;
+
+
+		if(nI > samptime && (exit_status = matrix_time_display(nI,isr,&samptime,dz))<0)
+			return(exit_status);
+		dz->wincnt++;
+	}	/* End of SYNTH subloop */
+	nMaxOut = endsamp;
+	while (outCount <= nMaxOut){
+		int todo = min(nMaxOut-outCount, output+obuflen-nextOut);
+		if(todo == 0)
+			break;
+		if((exit_status = outfloats(nextOut,&maxsample,&minsample,&local_maxsample,&num_overflows,todo,finished,dz))<0)
+			return(exit_status);
+		outCount += todo;
+		nextOut += todo;
+		if (nextOut >= (output + obuflen))
+			nextOut -= obuflen;
+
+	}
+	if((exit_status = matrix_time_display((int)endsamp,isr,&samptime,dz))<0)
+		return(exit_status);
+
+#ifndef NOOVERCHK
+	if(num_overflows > 0) {
+		biggest =  maxsample;
+		if(-minsample > maxsample)
+			biggest = -minsample;
+		fprintf(stdout, "WARNING: %d samples overflowed, and were clipped\n",num_overflows);
+		fprintf(stdout, "WARNING: maximum sample was %f  :  minimum sample was %f\n",maxsample,minsample);
+		fprintf(stdout, "WARNING: You should reduce source level to avoid clipping: use gain of <= %lf\n",1.0/biggest);
+		fflush(stdout);
+	}
+#endif
+	return(FINISHED);
+}
+
+/****************************** HAMMING ******************************/
+
+void hamming(float *win,int winLen,int even)
+{
+	float Pi,ftmp;
+	int i;
+
+/***********************************************************
+					Pi = (float)((double)4.*atan((double)1.));
+***********************************************************/
+	Pi = (float)PI;
+	ftmp = Pi/winLen;
+
+	if (even) {
+		for (i=0; i<winLen; i++)
+		*(win+i) = (float)((double).54 + (double).46*cos((double)(ftmp*((float)i+.5))));
+		*(win+winLen) = 0.0f;}
+	else{	*(win) = 1.0f;
+		for (i=1; i<=winLen; i++)
+		*(win+i) =(float)((double).54 + (double).46*cos((double)(ftmp*(float)i)));
+	}
+	return;
+}
+
+/****************************** FLOAT_ARRAY ******************************/
+
+int pvoc_float_array(int nnn,float **ptr)
+{	/* set up a floating point array length nnn. */
+	*ptr = (float *) calloc(nnn,sizeof(float));
+	if(*ptr==NULL){
+		sprintf(errstr,"pvoc: insufficient memory\n");
+		return(MEMORY_ERROR);
+	}
+	return(FINISHED);
+}
+
+/************************************ OUTFLOATS ************************************/
+
+int outfloats(float *nextOut,float *maxsample,float *minsample,float *local_maxsample,int *num_overflows,int todo,int finished,dataptr dz)
+{
+	static float *sbuf = 0;
+	static int sblen = 0;
+	float *sp;
+	int cnt;
+	float val;
+	float local_minsample = 0.0;
+	*local_maxsample = 0.0;
+	if(sblen < todo) {
+		if(sbuf != 0)
+			free(sbuf); 
+		if((sbuf = (float *)malloc(todo*sizeof(float))) == 0) {
+			sprintf(errstr, "pvoc: can't allocate output buffer\n");
+			return(MEMORY_ERROR);
+		}
+		sblen = todo;
+	}
+
+	sp = sbuf;
+#ifdef NOOVERCHK
+	for(cnt = 0; cnt < todo; cnt++)
+		*sp++ = *nextOut++;	
+#else
+	for(cnt = 0; cnt < todo; cnt++) {
+		val = *nextOut++;
+		if(val >= 1.0 || val <= -1.0) {
+			(*num_overflows)++;
+			if(val > 0.0f) {
+				if(val > *maxsample)
+					*maxsample = val;
+				val = 1.0f;
+			}
+			if(val < 0.0f) {
+				if(val < *minsample)
+					*minsample = val;
+				val = -1.0f;
+			}
+		}
+		*sp = val;
+		if(*sp > *local_maxsample)
+			*local_maxsample = val;
+		if(*sp < local_minsample)
+			local_minsample = val;
+		sp++;
+	}
+#endif
+	*local_maxsample = max(-local_minsample,*local_maxsample);
+	if(finished && (*local_maxsample == 0.0))	//	Input read finished && Output buffer empty
+		todo = 0;
+	if(todo > 0) {
+		if(write_samps_matrix(sbuf, todo, dz) < 0) {
+			sfperror("pvoc: write error");
+			return(SYSTEM_ERROR);
+		}
+	}
+	return(FINISHED);
+}
+
+/************************************ SNDWRITE_HEADER ************************************/
+
+int sndwrite_header(dataptr dz)
+{
+	dz->outfile->srate = dz->infile->srate;
+	dz->outfile->channels = dz->infile->channels;
+	fflush(stdout);
+	return(FINISHED);
+}
+
+/*********************************** MATRIX_TIME_DISPLAY ***********************************/
+
+int matrix_time_display(int nI,int srate,int *samptime, dataptr dz)
+{
+	display_virtual_time(nI,dz);	
+	*samptime += SAMP_TIME_STEP;
+	return(FINISHED);
+}
+
+/******************************* WRITE_SAMPS_MATRIX ********************************/
+
+int write_samps_matrix(float *bbuf,int samps_to_write,dataptr dz)
+{
+	
+	int samps_written;
+	int i,j;
+   	int granularity = 22100;
+   	int this_granularity = 0;
+	float val;
+
+	if(dz->needpeaks){
+		for(i=0;i < samps_to_write; i += dz->outchans){
+			for(j = 0;j < dz->outchans;j++){
+				val = (float)fabs(bbuf[i+j]);
+				/* this way, posiiton of first peak value is stored */
+				if(val > dz->outpeaks[j].value){
+					dz->outpeaks[j].value = val;
+					dz->outpeaks[j].position = dz->outpeakpos[j];
+				}
+			}
+			/* count framepos */
+			for(j=0;j < dz->outchans;j++)
+				dz->outpeakpos[j]++;
+		}
+	}
+	if((samps_written = fputfbufEx(bbuf,samps_to_write,dz->ofd))<=0) {
+		sprintf(errstr,"Can't write to output soundfile: %s\n",sferrstr());
+		return(SYSTEM_ERROR);
+	}
+	dz->total_samps_written += samps_written;	
+    this_granularity += samps_to_write;
+    if(this_granularity > granularity){
+        display_virtual_time(dz->total_samps_written,dz);
+        this_granularity -= granularity;
+    }
+	return(FINISHED);
+}
+
+/************************** MXFFT ********************/
+
+/*
+ *-----------------------------------------------------------------------
+ * subroutine:  fft
+ * multivariate complex fourier transform, computed in place
+ * using mixed-radix fast fourier transform algorithm.
+ *-----------------------------------------------------------------------
+ *
+ *	this is the call from C:
+ *		fft_(anal,banal,&one,&N2,&one,&mtwo);
+ *	CHANGED TO:-
+ *		fft_(anal,banal,one,N2,one,mtwo);
+ */
+
+int fft_(float *a, float *b, int nseg, int n, int nspn, int isn)
+		/*  a: pointer to array 'anal'  */
+		/*  b: pointer to array 'banal' */
+{
+	int exit_status;
+	int nfac[16];		/*  These are one bigger than needed   */
+						/*  because wish to use Fortran array  */
+						/* index which runs 1 to n, not 0 to n */
+
+	int 	m = 0, nf, k, kt, ntot, j, jj, maxf, maxp=0;
+
+/* work space pointers */
+	float	*at, *ck, *bt, *sk;
+	int		*np;
+
+
+/* reduce the pointers to input arrays - by doing this, FFT uses FORTRAN
+   indexing but retains compatibility with C arrays */
+	a--;	b--;
+
+/*	
+ * determine the factors of n
+ */
+	k=nf=abs(n);
+   	if(nf==1) 
+		return(FINISHED);
+
+	nspn=abs(nf*nspn);
+	ntot=abs(nspn*nseg);
+
+	if(isn*ntot == 0){
+		sprintf(errstr,"zero in FFT parameters %d %d %d %d",nseg, n, nspn, isn);
+		return(DATA_ERROR);
+	}
+	for (m=0; !(k%16); nfac[++m]=4,k/=16);
+	for (j=3,jj=9; jj<=k; j+=2,jj=j*j)
+		for (; !(k%jj); nfac[++m]=j,k/=jj);
+
+      	if (k<=4){
+	      	kt = m;
+	      	nfac[m+1] = k;
+	      	if(k != 1) 
+			m++;
+	}
+	else{
+		if(k%4==0){
+		nfac[++m]=2;
+		k/=4;
+		}
+
+	 	kt = m;
+	       	maxp = max((kt+kt+2),(k-1));
+		for(j=2; j<=k; j=1+((j+1)/2)*2)
+			if(k%j==0){
+				nfac[++m]=j;
+				k/=j;
+			}
+	}
+	if(m <= kt+1) 
+		maxp = m + kt + 1;
+      	if(m+kt > 15) {
+			sprintf(errstr,"FFT parameter n has more than 15 factors : %d", n);
+	    	return(DATA_ERROR);
+	}
+      	if(kt!=0){
+	      	j = kt;
+		while(j)
+			nfac[++m]=nfac[j--];
+	}
+	maxf = nfac[m-kt];
+      	if(kt > 0) 
+		maxf = max(nfac[kt],maxf);
+
+/*  allocate workspace - assume no errors! */
+	at = (float *) calloc(maxf,sizeof(float));
+	ck = (float *) calloc(maxf,sizeof(float));
+	bt = (float *) calloc(maxf,sizeof(float));
+	sk = (float *) calloc(maxf,sizeof(float));
+	np = (int *) calloc(maxp,sizeof(int));
+
+/* decrement pointers to allow FORTRAN type usage in fftmx */
+	at--;	bt--;	ck--;	sk--;	np--;
+
+/* call fft driver */
+
+	if((exit_status = fftmx(a,b,ntot,nf,nspn,isn,m,&kt,at,ck,bt,sk,np,nfac))<0)
+		return(exit_status);
+
+/* restore pointers before releasing */
+	at++;	bt++;	ck++;	sk++;	np++;
+
+/* release working storage before returning - assume no problems */
+	(void) free(at);
+	(void) free(sk);
+	(void) free(bt);
+	(void) free(ck);
+	(void) free(np);
+    return(FINISHED);
+}
+
+/*
+ *-----------------------------------------------------------------------
+ * subroutine:  fftmx
+ * called by subroutine 'fft' to compute mixed-radix fourier transform
+ *-----------------------------------------------------------------------
+ */
+int fftmx(float *a,float *b,int ntot,int n,int nspan,int isn,int m,int *kt,
+			float *at,float *ck,float *bt,float *sk,int *np,int nfac[])
+{	
+	int	i,inc,
+		j,jc,jf, jj,
+		k, k1, k2, k3=0, k4,
+		kk,klim,ks,kspan, kspnn,
+		lim,
+		maxf,mm,
+		nn,nt;
+	double  aa, aj, ajm, ajp, ak, akm, akp,
+		bb, bj, bjm, bjp, bk, bkm, bkp,
+		c1, c2=0.0, c3=0.0, c72, cd,
+		dr,
+		rad, 
+		sd, s1, s2=0.0, s3=0.0, s72, s120;
+
+	double	xx;	/****** ADDED APRIL 1991 *********/
+	inc=abs(isn);
+	nt = inc*ntot;
+      	ks = inc*nspan;
+/******************* REPLACED MARCH 29: ***********************
+					rad = atan((double)1.0);
+**************************************************************/
+	rad = 0.785398163397448278900;
+/******************* REPLACED MARCH 29: ***********************
+			      		s72 = rad/0.625;
+			      		c72 = cos(s72);
+				      	s72 = sin(s72);
+**************************************************************/
+	c72 = 0.309016994374947451270;
+	s72 = 0.951056516295153531190;
+/******************* REPLACED MARCH 29: ***********************
+			      		s120 = sqrt((double)0.75);
+**************************************************************/
+      	s120 = 0.866025403784438707600;
+
+/* scale by 1/n for isn > 0 ( reverse transform ) */
+
+      	if (isn < 0){
+	      	s72 = -s72;
+	      	s120 = -s120;
+	      	rad = -rad;}
+	else{	ak = 1.0/(double)n;
+		for(j=1; j<=nt;j += inc){
+	        	a[j] = (float)(a[j] * ak);
+	        	b[j] = (float)(b[j] * ak);
+		}
+	}
+	kspan = ks;
+      	nn = nt - inc;
+      	jc = ks/n;
+
+/* sin, cos values are re-initialized each lim steps  */
+
+      	lim = 32;
+      	klim = lim * jc;
+      	i = 0;
+      	jf = 0;
+      	maxf = m - (*kt);
+      	maxf = nfac[maxf];
+      	if((*kt) > 0) 
+		maxf = max(nfac[*kt],maxf);
+
+/*
+ * compute fourier transform
+ */
+
+lbl40:
+	dr = (8.0 * (double)jc)/((double)kspan);
+/*************************** APRIL 1991 POW & POW2 not WORKING.. REPLACE *******
+	  	    cd = 2.0 * (pow2 ( sin((double)0.5 * dr * rad)) );
+*******************************************************************************/
+	xx =  sin((double)0.5 * dr * rad);
+      	cd = 2.0 * xx * xx;
+      	sd = sin(dr * rad);
+      	kk = 1;
+      	if(nfac[++i]!=2) goto lbl110;
+/*
+ * transform for factor of 2 (including rotation factor)
+ */
+      	kspan /= 2;
+      	k1 = kspan + 2;
+		do{	do{	k2 = kk + kspan;
+		      	ak = a[k2];
+		      	bk = b[k2];
+		      	a[k2] = (float)((a[kk]) - ak);
+		      	b[k2] = (float)((b[kk]) - bk);
+		      	a[kk] = (float)((a[kk]) + ak);
+		      	b[kk] = (float)((b[kk]) + bk);
+		      	kk = k2 + kspan;
+		} while(kk <= nn);
+	      	kk -= nn;
+	}while(kk <= jc);
+      	if(kk > kspan) goto lbl350;
+lbl60:  c1 = 1.0 - cd;
+      	s1 = sd;
+      	mm = min((k1/2),klim);
+      	goto lbl80;
+lbl70:	ak = c1 - ((cd*c1)+(sd*s1));
+      	s1 = ((sd*c1)-(cd*s1)) + s1;
+      	c1 = ak;
+lbl80:	do{	do{	k2 = kk + kspan;
+		      	ak = a[kk] - a[k2];
+		      	bk = b[kk] - b[k2];
+		      	a[kk] = a[kk] + a[k2];
+		      	b[kk] = b[kk] + b[k2];
+		      	a[k2] = (float)((c1 * ak) - (s1 * bk));
+		      	b[k2] = (float)((s1 * ak) + (c1 * bk));
+		      	kk = k2 + kspan;
+		}while(kk < nt);
+	      	k2 = kk - nt;
+	      	c1 = -c1;
+	      	kk = k1 - k2;
+	}while(kk > k2);
+      	kk += jc;
+      	if(kk <= mm) goto lbl70;
+      	if(kk < k2)  goto lbl90;
+      	k1 += (inc + inc);
+      	kk = ((k1-kspan)/2) + jc;
+      	if(kk <= (jc+jc)) goto lbl60;
+      	goto lbl40;
+lbl90: 	s1 = ((double)((kk-1)/jc)) * dr * rad;
+      	c1 = cos(s1);
+      	s1 = sin(s1);
+      	mm = min( k1/2, mm+klim);
+      	goto lbl80;
+/*
+ * transform for factor of 3 (optional code)
+ */
+
+
+lbl100:	k1 = kk + kspan;
+	k2 = k1 + kspan;
+	ak = a[kk];
+	bk = b[kk];
+      	aj = a[k1] + a[k2];
+      	bj = b[k1] + b[k2];
+      	a[kk] = (float)(ak + aj);
+      	b[kk] = (float)(bk + bj);
+      	ak += (-0.5 * aj);
+      	bk += (-0.5 * bj);
+      	aj = (a[k1] - a[k2]) * s120;
+      	bj = (b[k1] - b[k2]) * s120;
+      	a[k1] = (float)(ak - bj);
+      	b[k1] = (float)(bk + aj);
+      	a[k2] = (float)(ak + bj);
+      	b[k2] = (float)(bk - aj);
+      	kk = k2 + kspan;
+      	if(kk < nn)     goto lbl100;
+      	kk -= nn;
+      	if(kk <= kspan) goto lbl100;
+      	goto lbl290;
+
+/*
+ * transform for factor of 4
+ */
+
+lbl110:	if(nfac[i] != 4) goto lbl230;
+      	kspnn = kspan;
+      	kspan = kspan/4;
+lbl120:	c1 = 1.0;
+      	s1 = 0;
+      	mm = min( kspan, klim);
+      	goto lbl150;
+lbl130:	c2 = c1 - ((cd*c1)+(sd*s1));
+      	s1 = ((sd*c1)-(cd*s1)) + s1;
+/*
+ * the following three statements compensate for truncation
+ * error.  if rounded arithmetic is used, substitute
+ * c1=c2
+ *
+ * c1 = (0.5/(pow2(c2)+pow2(s1))) + 0.5;
+ * s1 = c1*s1;
+ * c1 = c1*c2;
+ */
+      	c1 = c2;
+lbl140:	c2 = (c1 * c1) - (s1 * s1);
+      	s2 = c1 * s1 * 2.0;
+      	c3 = (c2 * c1) - (s2 * s1);
+      	s3 = (c2 * s1) + (s2 * c1);
+lbl150:	k1 = kk + kspan;
+      	k2 = k1 + kspan;
+      	k3 = k2 + kspan;
+      	akp = a[kk] + a[k2];
+      	akm = a[kk] - a[k2];
+      	ajp = a[k1] + a[k3];
+      	ajm = a[k1] - a[k3];
+      	a[kk] = (float)(akp + ajp);
+       	ajp = akp - ajp;
+      	bkp = b[kk] + b[k2];
+      	bkm = b[kk] - b[k2];
+      	bjp = b[k1] + b[k3];
+      	bjm = b[k1] - b[k3];
+      	b[kk] = (float)(bkp + bjp);
+      	bjp = (float)(bkp - bjp);
+      	if(isn < 0) goto lbl180;
+      	akp = akm - bjm;
+      	akm = akm + bjm;
+      	bkp = bkm + ajm;
+      	bkm = bkm - ajm;
+      	if(s1 == 0.0) goto lbl190;
+lbl160:	a[k1] = (float)((akp*c1) - (bkp*s1));
+      	b[k1] = (float)((akp*s1) + (bkp*c1));
+      	a[k2] = (float)((ajp*c2) - (bjp*s2));
+      	b[k2] = (float)((ajp*s2) + (bjp*c2));
+      	a[k3] = (float)((akm*c3) - (bkm*s3));
+      	b[k3] = (float)((akm*s3) + (bkm*c3));
+      	kk = k3 + kspan;
+      	if(kk <= nt)   goto lbl150;
+lbl170: kk -= (nt - jc);
+      	if(kk <= mm)   goto lbl130;
+      	if(kk < kspan) goto lbl200;
+      	kk -= (kspan - inc);
+      	if(kk <= jc)   goto lbl120;
+      	if(kspan==jc)  goto lbl350;
+      	goto lbl40;
+lbl180:	akp = akm + bjm;
+      	akm = akm - bjm;
+      	bkp = bkm - ajm;
+      	bkm = bkm + ajm;
+      	if(s1 != 0.0)  goto lbl160;
+lbl190:	a[k1] = (float)akp;
+      	b[k1] = (float)bkp;
+      	a[k2] = (float)ajp;
+      	b[k2] = (float)bjp;
+      	a[k3] = (float)akm;
+      	b[k3] = (float)bkm;
+      	kk = k3 + kspan;
+      	if(kk <= nt) goto lbl150;
+      	goto lbl170;
+lbl200: s1 = ((double)((kk-1)/jc)) * dr * rad;
+      	c1 = cos(s1);
+      	s1 = sin(s1);
+      	mm = min( kspan, mm+klim);
+      	goto lbl140;
+
+/*
+ * transform for factor of 5 (optional code)
+ */
+
+lbl210:	c2 = (c72*c72) - (s72*s72);
+      	s2 = 2.0 * c72 * s72;
+lbl220:	k1 = kk + kspan;
+      	k2 = k1 + kspan;
+      	k3 = k2 + kspan;
+      	k4 = k3 + kspan;
+      	akp = a[k1] + a[k4];
+      	akm = a[k1] - a[k4];
+      	bkp = b[k1] + b[k4];
+      	bkm = b[k1] - b[k4];
+      	ajp = a[k2] + a[k3];
+      	ajm = a[k2] - a[k3];
+      	bjp = b[k2] + b[k3];
+      	bjm = b[k2] - b[k3];
+      	aa = a[kk];
+      	bb = b[kk];
+      	a[kk] = (float)(aa + akp + ajp);
+      	b[kk] = (float)(bb + bkp + bjp);
+      	ak = (akp*c72) + (ajp*c2) + aa;
+      	bk = (bkp*c72) + (bjp*c2) + bb;
+      	aj = (akm*s72) + (ajm*s2);
+      	bj = (bkm*s72) + (bjm*s2);
+      	a[k1] = (float)(ak - bj);
+      	a[k4] = (float)(ak + bj);
+      	b[k1] = (float)(bk + aj);
+      	b[k4] = (float)(bk - aj);
+      	ak = (akp*c2) + (ajp*c72) + aa;
+      	bk = (bkp*c2) + (bjp*c72) + bb;
+      	aj = (akm*s2) - (ajm*s72);
+	bj = (bkm*s2) - (bjm*s72);
+	a[k2] = (float)(ak - bj);
+      	a[k3] = (float)(ak + bj);
+      	b[k2] = (float)(bk + aj);
+      	b[k3] = (float)(bk - aj);
+      	kk = k4 + kspan;
+      	if(kk < nn)     goto lbl220;
+      	kk -= nn;
+      	if(kk <= kspan) goto lbl220;
+      	goto lbl290;
+
+/*
+ * transform for odd factors
+ */
+
+lbl230:	k = nfac[i];
+	kspnn = kspan;
+	kspan /= k;
+	if(k==3)   goto lbl100;
+	if(k==5)   goto lbl210;
+	if(k==jf)  goto lbl250;
+      	jf = k;
+      	s1 = rad/(((double)(k))/8.0);
+      	c1 = cos(s1);
+      	s1 = sin(s1);
+      	ck[jf] = 1.0f;
+	sk[jf] = 0.0f;
+	for(j=1; j<k ; j++){
+		ck[j] = (float)((ck[k])*c1 + (sk[k])*s1);
+	      	sk[j] = (float)((ck[k])*s1 - (sk[k])*c1);
+	      	k--;
+	      	ck[k] = ck[j];
+	      	sk[k] = -(sk[j]);
+	}
+lbl250:	k1 = kk;
+      	k2 = kk + kspnn;
+	aa = a[kk];
+	bb = b[kk];
+      	ak = aa;
+      	bk = bb;
+      	j = 1;
+      	k1 += kspan;
+		do{	k2 -= kspan;
+	      	j++;
+	      	at[j] = a[k1] + a[k2];
+	      	ak = at[j] + ak;	
+	      	bt[j] = b[k1] + b[k2];
+	      	bk = bt[j] + bk;	
+	      	j++;
+	      	at[j] = a[k1] - a[k2];
+	      	bt[j] = b[k1] - b[k2];
+	      	k1 += kspan;
+	}while(k1 < k2);
+      	a[kk] = (float)ak;
+      	b[kk] = (float)bk;
+      	k1 = kk;
+      	k2 = kk + kspnn;
+      	j = 1;
+lbl270:	k1 += kspan;
+      	k2 -= kspan;
+      	jj = j;
+      	ak = aa;
+      	bk = bb;
+      	aj = 0.0;
+      	bj = 0.0;
+      	k = 1;
+		do{	k++;
+	      	ak = (at[k] * ck[jj]) + ak;
+	      	bk = (bt[k] * ck[jj]) + bk;	
+	      	k++;
+	      	aj = (at[k] * sk[jj]) + aj;
+	      	bj = (bt[k] * sk[jj]) + bj;
+	      	jj += j;
+	      	if (jj > jf) 
+			jj -= jf;
+	}while(k < jf);
+      	k = jf - j;
+      	a[k1] = (float)(ak - bj);
+      	b[k1] = (float)(bk + aj);
+      	a[k2] = (float)(ak + bj);
+      	b[k2] = (float)(bk - aj);
+      	j++;
+      	if(j < k)     goto lbl270;
+      	kk += kspnn;
+      	if(kk <= nn)  goto lbl250;
+      	kk -= nn;
+      	if(kk<=kspan) goto lbl250;
+
+/*
+ * multiply by rotation factor (except for factors of 2 and 4)
+ */
+
+lbl290:	if(i==m) goto lbl350;
+      	kk = jc + 1;
+lbl300:	c2 = 1.0 - cd;
+      	s1 = sd;
+      	mm = min( kspan, klim);
+      	goto lbl320;
+lbl310:	c2 = c1 - ((cd*c1) + (sd*s1));
+      	s1 = s1 + ((sd*c1) - (cd*s1));
+lbl320:	c1 = c2;
+      	s2 = s1;
+      	kk += kspan;
+lbl330:	ak = a[kk];
+      	a[kk] = (float)((c2*ak) - (s2 * b[kk]));
+      	b[kk] = (float)((s2*ak) + (c2 * b[kk]));
+      	kk += kspnn;
+      	if(kk <= nt) goto lbl330;
+      	ak = s1*s2;
+      	s2 = (s1*c2) + (c1*s2);
+      	c2 = (c1*c2) - ak;
+      	kk -= (nt - kspan);
+     	if(kk <= kspnn) goto lbl330;
+      	kk -= (kspnn - jc);
+      	if(kk <= mm)   goto lbl310;
+      	if(kk < kspan) goto lbl340;
+      	kk -= (kspan - jc - inc);
+      	if(kk <= (jc+jc)) goto lbl300;
+      	goto lbl40;
+lbl340:	s1 = ((double)((kk-1)/jc)) * dr * rad;
+      	c2 = cos(s1);
+      	s1 = sin(s1);
+     	mm = min( kspan, mm+klim);
+      	goto lbl320;
+
+/*
+ * permute the results to normal order---done in two stages
+ * permutation for square factors of n
+ */
+
+lbl350:	np[1] = ks;
+      	if (!(*kt)) goto lbl440;
+      	k = *kt + *kt + 1;
+      	if(m < k) 
+		k--;
+	np[k+1] = jc;
+		for(j=1; j < k; j++,k--){
+		np[j+1] = np[j] / nfac[j];
+	      	np[k] = np[k+1] * nfac[j];
+	}
+      	k3 = np[k+1];
+      	kspan = np[2];
+      	kk = jc + 1;
+      	k2 = kspan + 1;
+      	j = 1;
+      	if(n != ntot) goto lbl400;
+/*
+ * permutation for single-variate transform (optional code)
+ */
+lbl370:	do{	ak = a[kk];
+	      	a[kk] = a[k2];
+	      	a[k2] = (float)ak;
+	      	bk = b[kk];
+	      	b[kk] = b[k2];
+	      	b[k2] = (float)bk;
+	      	kk += inc;
+	      	k2 += kspan;
+	}while(k2 < ks);
+lbl380:	do{	k2 -= np[j++];
+	      	k2 += np[j+1];
+	}while(k2 > np[j]);
+      	j = 1;
+lbl390:	if(kk < k2){
+		goto lbl370;
+	}
+      	kk += inc;
+      	k2 += kspan;
+      	if(k2 < ks) goto lbl390;
+      	if(kk < ks) goto lbl380;
+      	jc = k3;
+      	goto lbl440;
+/*
+ * permutation for multivariate transform
+ */
+lbl400:	do{	do{	k = kk + jc;
+				do{	ak = a[kk];
+			      	a[kk] = a[k2];
+			      	a[k2] = (float)ak;
+			      	bk = b[kk];
+			      	b[kk] = b[k2];
+			      	b[k2] = (float)bk;
+			      	kk += inc;
+			      	k2 += inc;
+			}while(kk < k);
+		      	kk += (ks - jc);
+		      	k2 += (ks - jc);
+		}while(kk < nt);
+	      	k2 -= (nt - kspan);
+	      	kk -= (nt - jc);
+	}while(k2 < ks);
+lbl420:	do{	k2 -= np[j++];
+	      	k2 += np[j+1];
+	}while(k2 > np[j]);
+      	j = 1;
+lbl430:	if(kk < k2) 	 goto lbl400;
+      	kk += jc;
+      	k2 += kspan;
+      	if(k2 < ks)      goto lbl430;
+      	if(kk < ks)      goto lbl420;
+      	jc = k3;
+lbl440:	if((2*(*kt))+1 >= m)
+		return(FINISHED);
+
+      	kspnn = *(np + *(kt) + 1);
+      	j = m - *kt;		
+      	nfac[j+1] = 1;
+lbl450:	nfac[j] = nfac[j] * nfac[j+1];
+      	j--;
+      	if(j != *kt) goto lbl450;
+      	*kt = *(kt) + 1;
+      	nn = nfac[*kt] - 1;
+      	jj = 0;
+      	j = 0;
+      	goto lbl480;
+lbl460:	jj -= k2;
+      	k2 = kk;
+      	kk = nfac[++k];
+lbl470:	jj += kk;
+      	if(jj >= k2) goto lbl460;
+      	np[j] = jj;
+lbl480:	k2 = nfac[*kt];
+      	k = *kt + 1;	
+      	kk = nfac[k];
+      	j++;
+      	if(j <= nn) goto lbl470;
+/* Determine permutation cycles of length greater than 1 */
+      	j = 0;
+      	goto lbl500;
+lbl490:	k = kk;
+     	kk = np[k];	
+      	np[k] = -kk;	
+      	if(kk != j) goto lbl490;
+      	k3 = kk;
+lbl500:	kk = np[++j];	
+      	if(kk < 0)  goto lbl500;
+      	if(kk != j) goto lbl490;
+      	np[j] = -j;
+      	if(j != nn) goto lbl500;
+      	maxf *= inc;
+/* Perform reordering following permutation cycles */
+      	goto lbl570;
+lbl510:	j--;
+      	if (np[j] < 0) goto lbl510;
+      	jj = jc;
+lbl520:	kspan = jj;
+      	if(jj > maxf) 
+		kspan = maxf;
+      	jj -= kspan;
+      	k = np[j];	
+      	kk = (jc*k) + i + jj;
+      	k1 = kk + kspan;
+      	k2 = 0;
+lbl530:	k2++;
+      	at[k2] = a[k1];
+      	bt[k2] = b[k1];
+      	k1 -= inc;
+      	if(k1 != kk) goto lbl530;
+lbl540:	k1 = kk + kspan;
+      	k2 = k1 - (jc * (k + np[k]));
+      	k = -(np[k]);
+lbl550:	a[k1] = a[k2];
+      	b[k1] = b[k2];
+      	k1 -= inc;
+      	k2 -= inc;
+      	if(k1 != kk) goto lbl550;
+      	kk = k2;
+      	if(k != j)   goto lbl540;
+      	k1 = kk + kspan;
+      	k2 = 0;
+lbl560:	k2++;
+      	a[k1] = at[k2];
+      	b[k1] = bt[k2];
+      	k1 -= inc;
+      	if(k1 != kk) goto lbl560;
+      	if(jj)       goto lbl520;
+      	if(j  != 1)  goto lbl510;
+lbl570:	j = k3 + 1;
+      	nt -= kspnn;
+      	i = nt - inc + 1;
+      	if(nt >= 0)  goto lbl510;
+      	return(FINISHED);; 
+}
+
+
+/*
+ *-----------------------------------------------------------------------
+ * subroutine:  reals
+ * used with 'fft' to compute fourier transform or inverse for real data
+ *-----------------------------------------------------------------------
+ *	this is the call from C:
+ *		reals_(anal,banal,N2,mtwo);
+ *	which has been changed from CARL call
+ *		reals_(anal,banal,&N2,&mtwo);
+ */
+
+int reals_(float *a, float *b, int n, int isn)
+
+			/* a refers to an array of floats 'anal'   */
+			/* b refers to an array of floats 'banal'  */
+/* See IEEE book for a long comment here on usage */
+
+{	int	inc,
+		j,
+		k,
+		lim,
+		mm,ml,
+		nf,nk,nh;
+ 
+	double	aa,ab,
+		ba,bb,
+		cd,cn,
+		dr,
+		em,
+		rad,re,
+		sd,sn;
+	double	xx;	/******* ADDED APRIL 1991 ******/
+/* adjust  input array pointers (called from C) */
+	a--;	b--;
+	inc=abs(isn);
+	nf=abs(n);
+      	if(nf*isn==0){
+			sprintf(errstr,"zero in reals parameters in FFT : %d : %d ",n,isn);
+	       	return(DATA_ERROR);;
+		}
+	 	nk = (nf*inc) + 2;
+      	nh = nk/2;
+/*****************************
+    	rad  = atan((double)1.0);
+******************************/
+	rad = 0.785398163397448278900;
+      	dr = -4.0/(double)(nf);
+/********************************** POW2 REMOVED APRIL 1991 *****************
+			      	cd = 2.0 * (pow2(sin((double)0.5 * dr * rad)));
+*****************************************************************************/
+	xx = sin((double)0.5 * dr * rad);
+      	cd = 2.0 * xx * xx;
+      	sd = sin(dr * rad);
+/*
+ * sin,cos values are re-initialized each lim steps
+ */
+      	lim = 32;
+      	mm = lim;
+      	ml = 0;
+      	sn = 0.0;
+	if(isn<0){
+		cn = 1.0;
+		a[nk-1] = a[1];
+		b[nk-1] = b[1]; }
+	else {
+		cn = -1.0;
+		sd = -sd;
+	}
+	 	for(j=1;j<=nh;j+=inc)	{
+        	k = nk - j;
+        	aa = a[j] + a[k];
+        	ab = a[j] - a[k];
+        	ba = b[j] + b[k];
+        	bb = b[j] - b[k];
+        	re = (cn*ba) + (sn*ab);
+        	em = (sn*ba) - (cn*ab);
+        	b[k] = (float)((em-bb)*0.5);
+        	b[j] = (float)((em+bb)*0.5);
+        	a[k] = (float)((aa-re)*0.5);
+		a[j] = (float)((aa+re)*0.5);
+        	ml++;
+		if(ml!=mm){
+			aa = cn - ((cd*cn)+(sd*sn));
+			sn = ((sd*cn) - (cd*sn)) + sn;
+			cn = aa;}
+		else {
+			mm +=lim;
+			sn = ((float)ml) * dr * rad;
+			cn = cos(sn);
+			if(isn>0)
+				cn = -cn;
+			sn = sin(sn);
+		}
+	}
+	return(FINISHED);
+}
+
+/************************** IS_POW_OF_TWO ****************************/
+
+int is_pow_of_two(int val)
+{
+	int intbitlen, j, k;
+	int sum = 0;
+	intbitlen = sizeof(int) * CHARBITSIZE;
+	j = 1;
+	for(k=1;k<intbitlen;k++) {		//	Max positive number = 0100 0000 0000 0000
+		if(j & val)					//	so check all bits from 1 to 15
+			sum++;					//	"sum" counts number of bits set
+		j = j << 1; 
+	}
+	if(sum == 1)
+		return 1;
+	return 0;
+}
+
+/************************** MATRIX_CYCLE ****************************/
+
+int matrix_cycle(double *matrix,double *matrix2,dataptr dz)
+{
+	int n;
+	for(n=0;n<dz->itemcnt;n++)
+		dz->parray[0][n] += dz->parray[1][n];
+	return FINISHED;
+}
+
+/************************** COMPLEX_PRODUCT ****************************
+ *
+ *	(a + bi) *  (c - di)  =		(ac + bd) + i(bc - ad)
+ *   r1  i1      r2  i2      (r1r2 + i1i2)   (i1r2 - r1i2)
+ *
+ *
+ */
+
+float complex_product(float r1,float i1,float r2,float i2,float *iout)
+{
+	double rreal;
+	double iimag;
+	rreal = (r1 * r2) + (i1 * i2);
+	iimag = (i1 * r2) - (r1 * i2);
+	*iout = (float)iimag;
+	return (float)rreal;
+}