Esempio n. 1
0
void CPSong::cleanup_unused_samples(){
	
	if (!has_instruments())
		return;
	
	bool sample_found[MAX_SAMPLES];
	for (int i=0;i<MAX_INSTRUMENTS;i++)
		sample_found[i]=false;
	
	for (int i=0;i<MAX_PATTERNS;i++) {
		
		if (get_pattern(i)->is_empty())
			continue;
		
		
		for (int row=0;row<get_pattern(i)->get_length();row++) {
			
			
			for (int col=0;col<CPPattern::WIDTH;col++) {
			
				CPNote n;
				n=get_pattern(i)->get_note( col,row );
				
				if (n.instrument>=MAX_SAMPLES)
					continue;
				
				if (has_instruments()) {
							
					for (int nt=0;nt<CPNote::NOTES;nt++) {
						
						int smp=get_instrument(n.instrument)->get_sample_number(nt);
						if (smp<MAX_SAMPLES)
							sample_found[smp]=true;
					}
					
				} else {
					if (n.instrument<MAX_SAMPLES)
						sample_found[n.instrument]=true;
				}
			
			}
			
		}
		
	}
	
	for (int i=0;i<MAX_SAMPLES;i++)
		if (!sample_found[i])
			get_sample(i)->reset();
	
}
Esempio n. 2
0
bool
ok_left(int idx, TTile* tiles, TPlacement* p)
{
    int h, v;
    int n;

    h = idx2h(idx);
    if (h == 0)
        return true;
    v = idx2v(idx);
    n = hv2idx(h - 1, v);

    return ((get_pattern(n, tiles, p, 3) ^ get_pattern(idx, tiles, p, 1) ^ MATCHMASK) & MATCHMASK);
}
Esempio n. 3
0
bool
ok_up(int idx, TTile* tiles, TPlacement* p)
{
    int h, v;
    int n;

    if(idx < HSIZE)
        return true;
    h = idx2h(idx);
    v = idx2v(idx);
    n = hv2idx(h - 1, v);

    return ((get_pattern(n, tiles, p, 2) ^ get_pattern(idx, tiles, p, 0) ^ MATCHMASK) & MATCHMASK);
}
Esempio n. 4
0
int CPSong::get_channels_in_use() {

	int max=0;
	
	for (int p=0;p<CPSong::MAX_PATTERNS;p++) {
	
		CPPattern *pat = get_pattern(p);
		if (pat->is_empty())
			continue;
		
		
		for (int c=(CPPattern::WIDTH-1);c>=0;c--) {
		
			if (c<max)
				break;
		
			bool has_note=false;
			for (int r=0;r<pat->get_length();r++) {
			
				CPNote n = pat->get_note( c, r );
				if (!n.is_empty()) {
					has_note=true;
					break;
				}
			}
			
			if (has_note) {
			
				max=c+1;	
			}
		}
	}

	return max;
}
Esempio n. 5
0
void CPSong::reset(bool p_clear_patterns,bool p_clear_samples,bool p_clear_instruments,bool p_clear_variables) {
	
	if (p_clear_variables) {
		variables.name[0]=0;
		variables.message[0]=0;
		variables.row_highlight_major=16;
		variables.row_highlight_minor=4;
		variables.mixing_volume=48;
		variables.old_effects=false;
		if (p_clear_instruments) //should not be cleared, if not clearing instruments!!
			variables.use_instruments=false;
		variables.stereo_separation=128;
		variables.use_linear_slides=true;
		variables.use_stereo=true;
		
		initial_variables.global_volume=128;
		initial_variables.speed=6;
		initial_variables.tempo=125;
		
		for (int i=0;i<CPPattern::WIDTH;i++) {
			
			initial_variables.channel[i].pan=32;
			initial_variables.channel[i].volume=CHANNEL_MAX_VOLUME;
			initial_variables.channel[i].mute=false;
			initial_variables.channel[i].surround=false;
			initial_variables.channel[i].chorus=0;
			initial_variables.channel[i].reverb=0;
			
		}
		
		effects.chorus.delay_ms=6;
		effects.chorus.separation_ms=3;
		effects.chorus.depth_ms10=6,
		effects.chorus.speed_hz10=5;
		effects.reverb_mode=REVERB_MODE_ROOM;
	}
	
	if (p_clear_samples) {
		for (int i=0;i<MAX_SAMPLES;i++)
			get_sample(i)->reset();
	}
		
	if (p_clear_instruments) {
		for (int i=0;i<MAX_INSTRUMENTS;i++)
			get_instrument(i)->reset();
	}
	
	if (p_clear_patterns) {
		for (int i=0;i<MAX_PATTERNS;i++)
			get_pattern(i)->clear();
	
		for (int i=0;i<MAX_ORDERS;i++)
			set_order( i, CP_ORDER_NONE );
	}
	
			
}
Esempio n. 6
0
void bb_alog_sms(SMSCConn *conn, Msg *msg, const char *message)
{
    Octstr *text = NULL;
    
    gw_assert(msg_type(msg) == sms);

    /* if we don't have any custom log, then use our "default" one */
    
    if (custom_log_format == NULL) {
        Octstr *udh;
        const Octstr *cid;

        text = msg->sms.msgdata ? octstr_duplicate(msg->sms.msgdata) : octstr_create("");
        udh = msg->sms.udhdata ? octstr_duplicate(msg->sms.udhdata) : octstr_create("");

        if (conn && smscconn_id(conn))
            cid = smscconn_id(conn);
        else if (conn && smscconn_name(conn))
            cid = smscconn_name(conn);
        else if (msg->sms.smsc_id)
            cid = msg->sms.smsc_id;
        else
            cid = octstr_imm("");

        if ((msg->sms.coding == DC_8BIT || msg->sms.coding == DC_UCS2))
            octstr_binary_to_hex(text, 1);
        else
            octstr_convert_printable(text);
        octstr_binary_to_hex(udh, 1);

        alog("%s [SMSC:%s] [SVC:%s] [ACT:%s] [BINF:%s] [FID:%s] [META:%s] [from:%s] [to:%s] [flags:%ld:%ld:%ld:%ld:%ld] "
             "[msg:%ld:%s] [udh:%ld:%s]",
             message,
             octstr_get_cstr(cid),
             msg->sms.service ? octstr_get_cstr(msg->sms.service) : "",
             msg->sms.account ? octstr_get_cstr(msg->sms.account) : "",
             msg->sms.binfo ? octstr_get_cstr(msg->sms.binfo) : "",
             msg->sms.foreign_id ? octstr_get_cstr(msg->sms.foreign_id) : "",
             msg->sms.meta_data ? octstr_get_cstr(msg->sms.meta_data) : "",
             msg->sms.sender ? octstr_get_cstr(msg->sms.sender) : "",
             msg->sms.receiver ? octstr_get_cstr(msg->sms.receiver) : "",
             msg->sms.mclass, msg->sms.coding, msg->sms.mwi, msg->sms.compress,
             msg->sms.dlr_mask, 
             octstr_len(msg->sms.msgdata), octstr_get_cstr(text),
             octstr_len(msg->sms.udhdata), octstr_get_cstr(udh)
        );

        octstr_destroy(udh);
    } else {
        text = get_pattern(conn, msg, message);
        alog("%s", octstr_get_cstr(text));
    }

    octstr_destroy(text);
}
Esempio n. 7
0
void pdptool_save_copying_response(int d, int l, int s, int p)
{
    double response;
    int i;
    for (i = 0; i < PDPTOOL_N_VISUAL; i++) {
        response = (pdptool_get_state(PDPTOOL_N_NAME+i) >= 0.25);
        if (get_pattern(p, PDPTOOL_N_NAME+i)) { //if there is a feature that needs to be added
            if (get_pattern(p, PDPTOOL_N_NAME+i) == response) { //if it is included
// 		copying_correct[d][l][s][p]++;
            }
            else {
                copying_omission[d][l][s][p]++;
            }
        } else { // nothing should be drawn
            if (response) { // but if it is
                copying_intrusion[d][l][s][p]++;
            }
        }
    }
}
Esempio n. 8
0
void CPSong::cleanup_unused_patterns() {
	
	for (int i=0;i<MAX_PATTERNS;i++) {
		
		bool used=false;
		if (get_pattern(i)->is_empty())
			continue;
		
		for (int j=0;j<MAX_ORDERS;j++) {
			
			if (get_order(j)==i) {
				used=true;
				
			}
		}
		
		if (!used)
			get_pattern(i)->clear();
	}
	
}
Esempio n. 9
0
void CPSong::cleanup_unused_instruments(){
	
	if (!has_instruments())
		return;
	
	bool instr_found[MAX_INSTRUMENTS];
	for (int i=0;i<MAX_INSTRUMENTS;i++)
		instr_found[i]=false;
	
	for (int i=0;i<MAX_PATTERNS;i++) {
		
		if (get_pattern(i)->is_empty())
			continue;
		
		for (int row=0;row<get_pattern(i)->get_length();row++) {
			
			
			for (int col=0;col<CPPattern::WIDTH;col++) {
			
				CPNote n;
				n=get_pattern(i)->get_note( col,row );
				
				if (n.instrument<MAX_INSTRUMENTS)
					instr_found[n.instrument]=true;
			
			}
			
		}
		
	}
	
	for (int i=0;i<MAX_INSTRUMENTS;i++)
		if (!instr_found[i])
			get_instrument(i)->reset();
	
	
}
Esempio n. 10
0
int CPSong::get_pattern_in_use_count() {

	
	int pattern_count=0;
	
	for (int i=(CPSong::MAX_PATTERNS-1);i>=0;i--) {

		
		if (!get_pattern(i)->is_empty()) {
			pattern_count=i+1;
			break;
		}
	}

	return pattern_count;
}
Esempio n. 11
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    unsigned short*inArray;
    inArray=mxGetData(prhs[0]);
    const int* wid_len=mxGetDimensions(prhs[0]);
    int wid=wid_len[0], len=wid_len[1];
    //printf("%d %d\n", wid, len);
    int x_max=wid-1, y_max=len-1;
    int dims[3]={wid, len, 3};// 480,640
    plhs[0]=mxCreateNumericArray(3,dims,mxINT16_CLASS,mxREAL);
    short* outArray;
    outArray=mxGetData(plhs[0]);
    char* patt=mxArrayToString(prhs[1]);
    Pattern pattern=get_pattern(patt);
    int im1=0,ip1=0,jm1=0,jp1=0;
    int lenxwid=len*wid;
    switch(pattern)
    {
    case GRBG:
        for(int j=0;j<len;j++)
        {
            jm1=j==0?j+1:j-1;//j-1
            jp1=j==y_max?j-1:j+1;//j+1
            for(int i=0;i<wid;i++)
            {
                im1=i==0?i+1:i-1;//i-1
                ip1=i==x_max?i-1:i+1;//i+1
                if((i&1)==0)
                {
                    if((j&1)==0)//R(G)R
                    {
                        outArray[i+j*wid]=(I[i+jm1*wid]+I[i+jp1*wid])>>1;//B
                    }
                    else//G(B)G
                    {
                        outArray[i+j*wid]=I[i+wid*j];//B
                    }
                }
                else
                {
                    if((j&1)==0)//G(R)G
                    {
                        outArray[i+j*wid]=(I[im1+wid*jm1]+I[ip1+wid*jp1]+I[im1+wid*jp1]+I[ip1+wid*jm1])>>2;//B
                    }
                    else//B(G)B
                    {
Esempio n. 12
0
long numoccs(unsigned char byte) {
  int i;
  long noccurrences = 0;
  unsigned mask;
  unsigned char pat;
  
  for (i = 0; i < CHAR_BIT; i++) {
    mask = bit_mask(bit_pattern_str);
    pat = get_pattern(bit_pattern_str);

    if ((byte & mask) == pat) {  /* byte contains pat as a sub-pattern */
      noccurrences += 1;
    }
    byte >>= 1;  /* shift over 1 bit */
  }
  
  return noccurrences;
}
Esempio n. 13
0
int main (int argc, char *argv [])
{
	progname = argv[0];

	if (argc < 3)
		usage ();

	get_pattern (argc - 2, argv + 2);

	inputname = argv[1];

	inputfd = open (inputname, O_RDONLY);
	if (inputfd == -1) {
		fprintf (stderr, "%s: cannot open '%s'\n",
				progname, inputname);
		exit (3);
	}

	filesize = get_filesize (inputfd);

	madr = mmap (0, filesize, PROT_READ, MAP_PRIVATE, inputfd, 0);
	if (madr == MAP_FAILED) {
		fprintf (stderr, "mmap error = %d\n", errno);
		close (inputfd);
		exit (4);
	}

	search_pattern ();

	if (munmap (madr, filesize))
		fprintf (stderr, "munmap error = %d\n", errno);

	if (close (inputfd))
		fprintf (stderr, "%s: error %d closing '%s'\n",
				progname, errno, inputname);

	fprintf (stderr, "number of pattern matches = %d\n", num_matches);
	if (num_matches == 0)
		firstloc = ~0;
	printf ("%ld\n", firstloc);
	fprintf (stderr, "%ld\n", firstloc);

	exit (num_matches ? 0 : 2);
}
Esempio n. 14
0
/**
 * \brief Changes the id of a pattern in the tileset.
 * \param old_pattern_id Old id of the pattern.
 * \param new_pattern_id New id to set.
 * \return \c true in case of success.
 * In case of failure, the old pattern is unchanged.
 */
bool TilesetData::set_pattern_id(
    const std::string& old_pattern_id, const std::string& new_pattern_id) {

  if (!exists(old_pattern_id)) {
    // No pattern was found with the old id.
    return false;
  }

  if (exists(new_pattern_id)) {
    // The new id is already used.
    return false;
  }

  TilePatternData pattern = get_pattern(old_pattern_id);
  remove_pattern(old_pattern_id);
  add_pattern(new_pattern_id, pattern);

  return true;
}
Esempio n. 15
0
bool SearchInfo::dialog (bool default_backward)
{
	std::wstring new_pattern;
	bool new_backward;
	bool new_regex;

	ui::dialog_search (new_pattern, new_backward, new_regex,
			get_pattern (), default_backward, get_use_regex ());
	if (new_pattern.empty ()) {
		return false;
	}
	if (StringMatch::assign (new_pattern, new_regex)) {
		backward = new_backward;
		return true;
	}
	else {
		dialog_message (L"Invalid regular expression", L"Error");
		return false;
	}
}
Esempio n. 16
0
void
show_patterns(void)
{
	int			i, x;
	struct iog_pattern	p;

	printf("id\tpattern\n");
	for (i = 0; i < IOGEN_PAT_TEXT; i++) {
		memset(&p, 0, sizeof(p));
		if (get_pattern(i, &p))
			return;

		printf("%d:\t", i);
		for (x = 0; x < p.size; x++) {
			if ((x != 0) && (x % (sizeof(u_int64_t) * 4)) == 0)
				printf("\n\t");
			printf("%02x", p.buf[x]);
		}
		printf("\n");
	}
}
Esempio n. 17
0
void f_rain(frame_t *buffer, uint16_t frame) {

	uint8_t i = 0;
	uint8_t z = 0;
	uint8_t drops = rand() % 4;
	frame_t layers[CUBE_HEIGHT];

	(void) frame;
	memset(layers, 0, sizeof(frame_t) * CUBE_HEIGHT);

	for (z = 0; z < CUBE_HEIGHT - 1; z++)
		layers[z + 1].layer = get_pattern(buffer[z],0);

	for (i = 0; i < drops; i++) {
		uint8_t x = rand() % CUBE_SIZE;
		uint8_t y = rand() % CUBE_SIZE;
		set_led(layers, x, y, 0);
	}

	memset(buffer, 0, sizeof(frame_t) * CUBE_HEIGHT);
	memcpy(buffer, layers, sizeof(frame_t) * CUBE_HEIGHT);
}
Esempio n. 18
0
static void add_line(struct file *info, const char *str)
{
	struct line *line;
	struct pattern *p;
	struct values *vals;

	p = get_pattern(str, &vals);

	line = linehash_get(&info->patterns, p);
	if (line) {
		add_stats(line, p, vals);
	} else {
		/* We need to keep a copy of this! */
		p->text = strdup(p->text); 
		line = malloc(sizeof(*line));
		line->pattern = p;
		list_head_init(&line->vals);
		list_add(&line->vals, &vals->list);
		linehash_add(&info->patterns, line);
		list_add_tail(&info->lines, &line->list);
	}
}
Esempio n. 19
0
void
fill_buffer(char *buffer, size_t size, int pat)
{
	long long		i = 0, more = 1;
	char			*p = buffer;
	size_t			copy_len;
	struct iog_pattern	ip;

	memset(&ip, 0, sizeof(ip));
	if (get_pattern(pat, &ip))
		err_log(LOGFATAL, "can't find pattern %d", pat);

	/* this really should become a regular pattern */
	if (ip.pattern == IOGEN_PAT_TEXT) {
		while (more) {
			if (io_pattern[i] == NULL)
				i = 0;

			copy_len = strlen(io_pattern[i]);
			if ((p + copy_len) > (buffer + size))
				copy_len = (buffer + size) - p;
			memcpy(p, io_pattern[i], copy_len);
			p += copy_len;
			i++;
			if (p == buffer + size)
				more = 0;
			else if (p > buffer + size)
				err_log(LOGFATAL,
				    "buffer overflow in fill pattern");
		}
		return;
	}

	/* fill buffer for non text pattern */
	for (i = 0; i < size; i++)
		buffer[i] = ip.buf[i % ip.size];
}
Esempio n. 20
0
void create_sandbox(struct index_args *iargs, int n_proc, char *prefix,
                    int config_basename, FILE *fh,
                    Stream *stream, const char *tempdir)
{
	int i;
	int allDone;
	struct sigaction sa;
	int r;
	pthread_t reader_thread;
	struct sandbox *sb;
	size_t ll;
	struct stat s;

	sb = calloc(1, sizeof(struct sandbox));
	if ( sb == NULL ) {
		ERROR("Couldn't allocate memory for sandbox.\n");
		return;
	}

	sb->reader = calloc(1, sizeof(struct sb_reader));
	if ( sb->reader == NULL ) {
		ERROR("Couldn't allocate memory for SB reader.\n");
		free(sb);
		return;
	}

	pthread_mutex_init(&sb->lock, NULL);
	pthread_mutex_init(&sb->reader->lock, NULL);

	sb->n_processed = 0;
	sb->n_hadcrystals = 0;
	sb->n_crystals = 0;
	sb->n_processed_last_stats = 0;
	sb->n_hadcrystals_last_stats = 0;
	sb->n_crystals_last_stats = 0;
	sb->t_last_stats = get_monotonic_seconds();
	sb->n_proc = n_proc;
	sb->iargs = iargs;

	sb->reader->fds = NULL;
	sb->reader->fhs = NULL;
	sb->reader->stream = stream;

	sb->stream_pipe_write = calloc(n_proc, sizeof(int));
	if ( sb->stream_pipe_write == NULL ) {
		ERROR("Couldn't allocate memory for pipes.\n");
		return;
	}

	lock_sandbox(sb);
	sb->filename_pipes = calloc(n_proc, sizeof(int));
	sb->result_fhs = calloc(n_proc, sizeof(FILE *));
	sb->pids = calloc(n_proc, sizeof(pid_t));
	sb->running = calloc(n_proc, sizeof(int));
	if ( sb->filename_pipes == NULL ) {
		ERROR("Couldn't allocate memory for pipes.\n");
		return;
	}
	if ( sb->result_fhs == NULL ) {
		ERROR("Couldn't allocate memory for pipe file handles.\n");
		return;
	}
	if ( sb->pids == NULL ) {
		ERROR("Couldn't allocate memory for PIDs.\n");
		return;
	}
	if ( sb->running == NULL ) {
		ERROR("Couldn't allocate memory for process flags.\n");
		return;
	}

	sb->last_filename = calloc(n_proc, sizeof(char *));
	if ( sb->last_filename == NULL ) {
		ERROR("Couldn't allocate memory for last filename list.\n");
		return;
	}
	unlock_sandbox(sb);

	if ( pipe(signal_pipe) == -1 ) {
		ERROR("Failed to create signal pipe.\n");
		return;
	}

	/* Set up signal handler to take action if any children die */
	sa.sa_flags = SA_SIGINFO | SA_NOCLDSTOP;
	sigemptyset(&sa.sa_mask);
	sa.sa_sigaction = signal_handler;
	r = sigaction(SIGCHLD, &sa, NULL);
	if ( r == -1 ) {
		ERROR("Failed to set signal handler!\n");
		return;
	}

	if ( tempdir == NULL ) {
		tempdir = strdup("");
	}

	ll = 64+strlen(tempdir);
	sb->tmpdir = malloc(ll);
	if ( sb->tmpdir == NULL ) {
		ERROR("Failed to allocate temporary directory name\n");
		return;
	}
	snprintf(sb->tmpdir, ll, "%s/indexamajig.%i", tempdir, getpid());

	if ( stat(sb->tmpdir, &s) == -1 ) {

		int r;

		if ( errno != ENOENT ) {
			ERROR("Failed to stat temporary folder.\n");
			return;
		}

		r = mkdir(sb->tmpdir, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
		if ( r ) {
			ERROR("Failed to create temporary folder: %s\n",
			      strerror(errno));
			return;
		}

	}

	/* Fork the right number of times */
	lock_sandbox(sb);
	for ( i=0; i<n_proc; i++ ) {
		start_worker_process(sb, i);
	}
	unlock_sandbox(sb);

	/* Start reader thread after forking, so that things are definitely
	 * "running" */
	if ( pthread_create(&reader_thread, NULL, run_reader,
	                    (void *)sb->reader) ) {
		ERROR("Failed to create reader thread.\n");
		return;
	}

	allDone = 0;
	while ( !allDone ) {

		int r, i;
		struct timeval tv;
		fd_set fds;
		double tNow;
		int fdmax;

		tv.tv_sec = 1;
		tv.tv_usec = 0;

		FD_ZERO(&fds);
		fdmax = 0;
		lock_sandbox(sb);
		for ( i=0; i<n_proc; i++ ) {

			int fd;

			if ( sb->result_fhs[i] == NULL) continue;

			fd = fileno(sb->result_fhs[i]);
			FD_SET(fd, &fds);
			if ( fd > fdmax ) fdmax = fd;

		}
		unlock_sandbox(sb);

		FD_SET(signal_pipe[0], &fds);
		if ( signal_pipe[0] > fdmax ) fdmax = signal_pipe[0];

		r = select(fdmax+1, &fds, NULL, NULL, &tv);
		if ( r == -1 ) {
			if ( errno == EINTR ) continue;
			ERROR("select() failed: %s\n", strerror(errno));
			break;
		}

		if ( FD_ISSET(signal_pipe[0], &fds) ) {

			char d;
			read(signal_pipe[0], &d, 1);
			handle_zombie(sb);

		}

		lock_sandbox(sb);
		for ( i=0; i<n_proc; i++ ) {

			char *nextImage;
			char results[1024];
			char *rval;
			int fd;
			char *eptr;

			if ( sb->result_fhs[i] == NULL ) continue;

			fd = fileno(sb->result_fhs[i]);
			if ( !FD_ISSET(fd, &fds) ) continue;

			rval = fgets(results, 1024, sb->result_fhs[i]);
			if ( rval == NULL ) {
				if ( !feof(sb->result_fhs[i]) ) {
					ERROR("fgets() failed: %s\n",
					      strerror(errno));
				}
				sb->result_fhs[i] = NULL;
				continue;
			}

			chomp(results);

			strtol(results, &eptr, 10);
			if ( eptr == results ) {
				if ( strlen(results) > 0 ) {
					ERROR("Invalid result '%s'\n", results);
				}
			} else {

				int nc = atoi(results);
				sb->n_crystals += nc;
				if ( nc > 0 ) {
					sb->n_hadcrystals++;
				}
				sb->n_processed++;

			}

			/* Send next filename */
			nextImage = get_pattern(fh, config_basename, prefix);

			free(sb->last_filename[i]);
			sb->last_filename[i] = nextImage;

			if ( nextImage == NULL ) {
				/* No more images */
				r = write(sb->filename_pipes[i], "\n", 1);
				if ( r < 0 ) {
					ERROR("Write pipe\n");
				}
			} else {
				r = write(sb->filename_pipes[i], nextImage,
				          strlen(nextImage));
				r -= write(sb->filename_pipes[i], "\n", 1);
				if ( r < 0 ) {
					ERROR("write pipe\n");
				}
			}

		}
		unlock_sandbox(sb);

		/* Update progress */
		lock_sandbox(sb);
		tNow = get_monotonic_seconds();
		if ( tNow >= sb->t_last_stats+STATS_EVERY_N_SECONDS ) {

			STATUS("%4i indexable out of %4i processed (%4.1f%%), "
			       "%4i crystals so far. "
			       "%4i images processed since the last message.\n",
			       sb->n_hadcrystals, sb->n_processed,
			       100.0 * sb->n_hadcrystals / sb->n_processed,
			       sb->n_crystals,
			       sb->n_processed - sb->n_processed_last_stats);

			sb->n_processed_last_stats = sb->n_processed;
			sb->n_hadcrystals_last_stats = sb->n_hadcrystals;
			sb->n_crystals_last_stats = sb->n_crystals;
			sb->t_last_stats = tNow;

		}
		unlock_sandbox(sb);

		allDone = 1;
		lock_sandbox(sb);
		for ( i=0; i<n_proc; i++ ) {
			if ( sb->running[i] ) allDone = 0;
		}
		unlock_sandbox(sb);

	}

	fclose(fh);

	/* Indicate to the reader thread that we are done */
	pthread_mutex_lock(&sb->reader->lock);
	sb->reader->done = 1;
	pthread_mutex_unlock(&sb->reader->lock);

	pthread_join(reader_thread, NULL);

	for ( i=0; i<n_proc; i++ ) {
		int status;
		waitpid(sb->pids[i], &status, 0);
	}

	for ( i=0; i<n_proc; i++ ) {
		close(sb->filename_pipes[i]);
		if ( sb->result_fhs[i] != NULL ) fclose(sb->result_fhs[i]);
	}

	free(sb->running);
	free(sb->filename_pipes);
	free(sb->result_fhs);
	free(sb->pids);
	free(sb->tmpdir);

	pthread_mutex_destroy(&sb->lock);

	STATUS("Final:"
	       " %i images processed, %i had crystals, %i crystals overall.\n",
	       sb->n_processed, sb->n_hadcrystals, sb->n_crystals);

	free(sb);
}
Esempio n. 21
0
void setparams()
{
    potproc_double pot;
    double pos[3],acc[3],epot,vel2,per;
    int ndim=3;
    int signcount;
    int lzsign;

    p.name = getparam("potname");
    p.pars = getparam("potpars");
    p.file = getparam("potfile");

    signcount = 0;
    Dpos = -1;
    if (streq(getparam("x"),"+") || streq(getparam("x"),"-")) {
      Dpos = 0;
      signcount++;
    }
    if (streq(getparam("y"),"+") || streq(getparam("y"),"-")) {
      Dpos = 1;
      signcount++;
    }
    if (streq(getparam("z"),"+") || streq(getparam("z"),"-")) {
      Dpos = 2;
      signcount++;
    }
    if (signcount > 1) error("Can only set one of x,y,z to + or -");

    signcount = 0;
    Dvel = -1;
    if (streq(getparam("vx"),"+") || streq(getparam("vx"),"-")) {
      Dvel = 0;
      signcount++;
    }
    if (streq(getparam("vy"),"+") || streq(getparam("vy"),"-")) {
      Dvel = 1;
      signcount++;
    }
    if (streq(getparam("vz"),"+") || streq(getparam("vz"),"-")) {
      Dvel = 2;
      signcount++;
    }
    if (signcount > 1) error("Can only set one of vx,vy,vz to + or -");
    tnow = getdparam("time");
    

    outfile = getparam("out");
    if(hasvalue("etot")) {	  /* energy given; calculate missing vx or vy */
 	   etot = getdparam("etot");
           if(!hasvalue("potname"))
              error("No potential given (potname=)");
	   pot = get_potential_double(p.name, p.pars, p.file);
	   if (pot==NULL) 
		error("potential %s cannot be loaded",p.name);
	   omega = get_pattern();
	   dprintf(0,"Using pattern speed = %g\n",omega);
	   if (hasvalue("lz")) {
	     lz = getdparam("lz");
	     lzsign = SGN(lz);
	   } else
	     lz = 0;

	   /* allow only u or v missing for now */
	   /* if x or y not given, 0.0 will be taken */

	   pos[0] = x = getdparam("x");
	   pos[1] = y = getdparam("y");
	   pos[2] = z = 0.0;			/* force z=0 if E_tot given */
	   (*pot)(&ndim,pos,acc,&epot,&tnow);
	   epot -= 0.5*omega*omega*(x*x+y*y);

           if(!hasvalue("vx")) {                /* vx missing */
		v = getdparam("vy");
		u = 2*(etot-epot) - v*v;
		if (u<0.0)
			error("vy too large for this energy: epot=%g vy(max)=%g\n",
					epot,2*sqrt(etot-epot));
		else
			u = sqrt(u);
		lz = x*v-y*u;	
		if(lzsign<0 && lz>0) u = -u;     /* switch rotation */
	   } else {
                if(hasvalue("vy"))
			error("cannot give e=,  vx= and vy= at the same time");
		u = getdparam("vx");
		v = 2*(etot-epot) - u*u;
		if (v<0.0)
			error("vx too large for this energy: epot=%g vx(max)=%g\n",
					epot,2*sqrt(etot-epot));
		else
			v = sqrt(v);
		lz = x*v-y*u;	
		if(lzsign<0 && lz>0) v = -v;     /* switch rotation */
	   }
	   w = 0.0;
           lz = x*v-y*u;
    } else {
	   if(hasvalue("etot")) warning("Initial value for etot= not used");
	   if(hasvalue("lz")) warning("Initial value for lz= not used");
	   x = getdparam("x");			
	   y = getdparam("y");
	   z = getdparam("z");
	   dprintf(0,"Dvel=%d\n",Dvel);
	   u = Dvel==0 ? 0 : getdparam("vx");
	   v = Dvel==1 ? 0 : getdparam("vy");
	   w = Dvel==2 ? 0 : getdparam("vz");
	   
           if(hasvalue("potname")) {
    	       pot = get_potential_double(p.name, p.pars, p.file);
	       if (pot==NULL) {
		  warning("potential %s cannot be loaded",p.name);
                  etot = 0.0;
               } else {
	          omega = get_pattern();
                  dprintf(0,"Using pattern speed = %g\n",omega);
	          pos[0] = x;
	          pos[1] = y;
	          pos[2] = z;
	          (*pot)(&ndim,pos,acc,&epot,&tnow);
		  if (Dvel==0) {
		    error("Dvel=0 not implemented");
		  } else if (Dvel==1) {
		    vel2 = -acc[0]*x;
		    v = sqrt(vel2);
		    per = TWO_PI*x/v;
		    dprintf(0,"vel2=%g  p=%g\n",vel2,per);
		  } else if (Dvel==2) {
		    error("Dvel=2 not implemented");
		  } 
		  etot = epot + 0.5*(u*u+v*v+w*w) - 0.5*omega*omega*(x*x+y*y);
               }
           } else {
               warning("Potential potname=%s not used; set etot=0.0",p.name);
               etot = 0.0;
           }
           lz = x*v-y*u;
    } 
    if (hasvalue("headline")) set_headline(getparam("headline"));
}
Esempio n. 22
0
File: kill.c Progetto: jheiss/nn
static int
compile_kill_file(void)
{
    FILE           *killf, *compf, *patternf, *dropf;
    comp_kill_header header;
    comp_kill_entry entry;
    time_t          now, age;
    long            cur_line_start;
    char            line[512];
    register char  *cp, *np;
    register int    c;
    group_header   *gh;
    flag_type       flag, fields[10];
    int             any_errors, nfield, nf, len;

    any_errors = 0;
    header.ckh_entries = header.ckh_regexp_size = 0;

    killf = open_file(relative(nn_directory, KILL_FILE),
                      OPEN_READ | DONT_CREATE);
    if (killf == NULL)
        return 0;

    dropf = NULL;

    compf = open_file(relative(nn_directory, COMPILED_KILL), OPEN_CREATE);
    if (compf == NULL)
        goto err1;

    new_temp_file();
    if ((patternf = open_file(temp_file, OPEN_CREATE)) == NULL)
        goto err2;

    msg("Compiling kill file");

    fseek(compf, sizeof(header), 0);

    now = cur_time();

next_entry:

    for (;;) {
        cur_line_start = ftell(killf);

        if (fgets(line, 512, killf) == NULL)
            break;

        cp = line;
        while (*cp && isascii(*cp) && isspace(*cp))
            cp++;
        if (*cp == NUL || *cp == '#' || !isascii(*cp))
            continue;

        if ((np = strchr(cp, ':')) == NULL)
            goto bad_entry;

        /* optional "age:" */

        if (np != cp && isdigit(*cp)) {
            *np++ = NUL;
            age = (time_t) atol(cp);
            if (age < now)
                goto drop_entry;
            cp = np;
            if ((np = strchr(cp, ':')) == NULL)
                goto bad_entry;
        }
        /* "group-name:"  or "/regexp:" or ":" for all groups */

        flag = COMP_KILL_ENTRY;

        if (np == cp) {
            entry.ck_group = -1;
            np++;
        } else {
            *np++ = NUL;
            if (*cp == '/') {
                entry.ck_group = (long) ftell(patternf);
                cp++;
                len = strlen(cp) + 1;
                if (fwrite(cp, sizeof(char), len, patternf) != len)
                    goto err3;
                flag |= GROUP_REGEXP | GROUP_REGEXP_HDR;
            } else {
                if ((gh = lookup(cp)) == NULL || (gh->master_flag & M_IGNORE_GROUP)) {
                    tprintf("Unknown/ignored group in kill file: %s\n", cp);
                    any_errors++;
                    goto drop_entry;
                }
                entry.ck_group = gh->group_num;
            }
        }

        /* flags */

        cp = np;
        nfield = 0;

        for (;;) {
            switch (*cp++) {
            case EXT_AND_MATCH:
            case EXT_OR_MATCH:
                fields[nfield++] = flag;
                flag &= ~(AND_MATCH | ON_SUBJECT | ON_SENDER |
                          KILL_CASE_MATCH | KILL_ON_REGEXP |
                          GROUP_REGEXP_HDR);
                flag |= (cp[-1] == EXT_AND_MATCH) ? AND_MATCH : OR_MATCH;
                continue;
            case EXT_AUTO_KILL:
                flag |= AUTO_KILL;
                continue;
            case EXT_AUTO_SELECT:
                flag |= AUTO_SELECT;
                continue;
            case EXT_ON_FOLLOW_UP:
                flag |= ON_FOLLOW_UP;
                continue;
            case EXT_ON_NOT_FOLLOW_UP:
                flag |= ON_NOT_FOLLOW_UP;
                continue;
            case EXT_ON_ANY_REFERENCES:
                flag |= ON_ANY_REFERENCES;
                continue;
            case EXT_ON_SUBJECT:
                flag |= ON_SUBJECT;
                continue;
            case EXT_ON_SENDER:
                flag |= ON_SENDER;
                continue;
            case EXT_KILL_CASE_MATCH:
                flag |= KILL_CASE_MATCH;
                continue;
            case EXT_KILL_UNLESS_MATCH:
                flag |= KILL_UNLESS_MATCH;
                continue;
            case EXT_KILL_ON_REGEXP:
                flag |= KILL_ON_REGEXP;
                continue;
            case ':':
                break;
            case NL:
                goto bad_entry;
            default:
                tprintf("Ignored flag '%c' in kill file\n", cp[-1]);
                any_errors++;
                continue;
            }
            break;
        }

        fields[nfield++] = flag;

        for (nf = 0; --nfield >= 0; nf++) {
            entry.ck_flag = flag = fields[nf];
            np = cp;
            if ((cp = get_pattern(np, &len, nfield)) == NULL)
                goto bad_entry;

            if ((flag & KILL_CASE_MATCH) == 0)
                fold_string(np);

            entry.ck_pattern_index = ftell(patternf);

            if (fwrite((char *) &entry, sizeof(entry), 1, compf) != 1)
                goto err3;

            if (fwrite(np, sizeof(char), len, patternf) != len)
                goto err3;

            header.ckh_entries++;
            if (flag & GROUP_REGEXP)
                header.ckh_regexp_size++;
        }
    }

    header.ckh_pattern_size = ftell(patternf);

    fclose(patternf);
    patternf = open_file(temp_file, OPEN_READ | OPEN_UNLINK);
    if (patternf == NULL)
        goto err2;

    header.ckh_pattern_offset = ftell(compf);

    while ((c = getc(patternf)) != EOF)
        putc(c, compf);

    fclose(patternf);

    rewind(compf);

    header.ckh_magic = COMP_KILL_MAGIC;
    header.ckh_db_check = master.db_created;

    if (fwrite((char *) &header, sizeof(header), 1, compf) != 1)
        goto err2;

    fclose(compf);
    fclose(killf);
    if (dropf != NULL)
        fclose(dropf);

    if (any_errors) {
        tputc(NL);
        any_key(0);
    }
    return 1;

bad_entry:
    tprintf("Incomplete kill file entry:\n%s", line);
    fl;
    any_errors++;

drop_entry:
    if (dropf == NULL) {
        dropf = open_file(relative(nn_directory, KILL_FILE),
                          OPEN_UPDATE | DONT_CREATE);
        if (dropf == NULL)
            goto next_entry;
    }
    fseek(dropf, cur_line_start, 0);
    fwrite("# ", sizeof(char), 2, dropf);
    goto next_entry;

err3:
    fclose(patternf);
    unlink(temp_file);
err2:
    fclose(compf);
    rm_kill_file();
err1:
    fclose(killf);
    if (dropf != NULL)
        fclose(dropf);

    msg("cannot compile kill file");
    return 0;
}
main(int argc ,char *argv[])
{
	int i;

	/*checking for creation and printing the tree ---Working*/
	node *tree ;
	tree=create_tree();
	read_ssf_from_file(tree, argv[1]);
	print_tree(tree);
	printf("Checked read and print\n\n");



	/*checking for get_nth_child ----Working*/
	node *child = get_nth_child(tree, 2);
	print_node_without_index(child);
	printf("Checked get_nth_child\n\n");

	/*checking for getchildren-----Working*/
	list_of_nodes *l1;
	l1=getchildren(tree);
	printf("\n\nsize=%d\n", l1->size);
	for (i=0; i< l1->size; i++)
	{
		print_attr_of_node(l1->l[i] );
		printf("\n");
	}
	printf("Checked getchildren\n\n");


	/*checking for getleaves----Working*/
	list_of_nodes *l2;
	l2=getleaves(tree);
	printf("\n\nsize=%d\n", l2->size);
	for (i=0; i< l2->size; i++)
	{
		print_attr_of_node(l2->l[i] );
		printf("\n");
	}
	printf("Checked getleaves\n\n");
	
	/*checking for getleaves_child---Working*/
	list_of_nodes *l3;
	l3=getleaves_child(l1->l[1]);
	printf("\n\nsize=%d\n", l3->size);
	for (i=0; i< l3->size; i++)
	{
		print_attr_of_node(l3->l[i] );
		printf("\n");
	}
	printf("Checked getleaves_child\n\n");

	/*checking for get_nodes---Working*/
	list_of_nodes *l4;
	l4=get_nodes(2,"NNS",tree);
	printf("\n\nsize=%d\n",l4->size);
	for (i=0; i< l4->size; i++)
	{
		print_attr_of_node(l4->l[i]);
		printf("\n");
	}
	printf("Checked get_nodes\n\n");


	/*checking for get_pattern---Working*/
	list_of_nodes *l5;
	l5=get_pattern(2,".*N.*",tree);
	printf("\n\nsize=%d\n",l5->size);
	for (i=0; i< l5->size; i++)
	{
		print_attr_of_node(l5->l[i]);
		printf("\n");
	}
	printf("Checked get_pattern\n\n");

	//checking for delete_node------Working
	//printf("%d\n",delete_node(l5->l[1]));
	//print_tree(tree);

	//checking for count_leaf_nodes ----Working
	printf("count of leaf nodes----%d\n\n", count_leaf_nodes(tree));

	//checking for get_field(s)  ----Working 
	char *str;
       	str=get_field(l5->l[1],1);
	printf("%s\n",str);
	str=get_fields(l5->l[1]);
	printf("%s\n", str);
	printf("Checked get_field and get_fields\n\n");


	//checking for get_next_node  and get_previos_node----Working
	node *N;
	N=get_next_node(l1->l[1]);
	str=get_fields(N);
	printf("%s\n", str);
	N=get_previous_node(l1->l[1]);
	str=get_fields(N);
	printf("%s\n", str);
	printf("Checked get_next_node & get_previous_node\n\n");


	//checking for insert_node_position------Working
	node *M;
	M=create_node_with_attr("iiit","NNP","<loc=hyd>",NULL);
	insert_node_into_position(tree,M,1);
	print_tree(tree);
	printf("Checked insert_node_position\n\n");
	
	/*Checkin print_attr_of_or_node--------Working*/	
	print_attr_of_or_node(M->OR);
	printf("\nChecked print_attr_of_or_node\n\n");
		
}
Esempio n. 24
0
static int OSC_handler(const char *path, const char *types,
                       lo_arg **argv, int argc, void *data, void *p)
{
    OSC_PORT  *pp = (OSC_PORT*) p;
    OSCLISTEN *o;
    CSOUND *csound = (CSOUND *) pp->csound;
    int       retval = 1;

    pp->csound->LockMutex(pp->mutex_);
    o = (OSCLISTEN*) pp->oplst;
    while (o != NULL) {
      if (strcmp(o->saved_path, path) == 0 &&
          strcmp(o->saved_types, types) == 0) {
        /* Message is for this guy */
        int     i;
        OSC_PAT *m;
        m = get_pattern(o);
        if (m != NULL) {
          /* queue message for being read by OSClisten opcode */
          m->next = NULL;
          if (o->patterns == NULL)
            o->patterns = m;
          else {
            OSC_PAT *mm;
            for (mm = o->patterns; mm->next != NULL; mm = mm->next)
              ;
            mm->next = m;
          }
          /* copy argument list */
          for (i = 0; o->saved_types[i] != '\0'; i++) {
            switch (types[i]) {
            default:              /* Should not happen */
            case 'i':
              m->args[i].number = (MYFLT) argv[i]->i; break;
            case 'h':
              m->args[i].number = (MYFLT) argv[i]->i64; break;
            case 'c':
               m->args[i].number= (MYFLT) argv[i]->c; break;
            case 'f':
               m->args[i].number = (MYFLT) argv[i]->f; break;
            case 'd':
               m->args[i].number= (MYFLT) argv[i]->d; break;
            case 's':
              {
                char  *src = (char*) &(argv[i]->s), *dst = m->args[i].string.data;
                if(m->args[i].string.size <= (int) strlen(src)){
                  if(dst != NULL) csound->Free(csound, dst);
                    dst = csound->Strdup(csound, src);
                    m->args[i].string.size = strlen(dst) + 1;
                    m->args[i].string.data = dst;
                }
                else strcpy(dst, src);

              }
              break;
            }
          }

          retval = 0;
        }

        break;

      }


      o = (OSCLISTEN*) o->nxt;
    }

    pp->csound->UnlockMutex(pp->mutex_);
    return retval;
}
Esempio n. 25
0
void CPSong::separate_in_one_sample_instruments(int p_instrument) {

	CP_ERR_COND( !variables.use_instruments );
	CP_FAIL_INDEX( p_instrument, MAX_INSTRUMENTS );

	int remapped_count=0;
	
	signed char remap[MAX_SAMPLES];
	
	for (int i=0;i<MAX_SAMPLES;i++) {
	
		remap[i]=-1;
	}
	
	/* Find remaps */
	CPInstrument *ins=get_instrument(p_instrument);
	for (int i=0;i<CPNote::NOTES;i++) {
	
		int sn = ins->get_sample_number(i);
		
		// check for unusable sample
		if (sn<0 || sn>=MAX_SAMPLES || get_sample(sn)->get_sample_data().is_null())
			continue;
		printf("sample %i\n",sn);	
		if ( remap[sn] !=-1 ) {
			printf("already mapped to %i\n",remap[sn]);	
			continue;
		}
			
		printf("isn't remapped\n");	
			
		// find remap
		
		for (int j=0;j<MAX_INSTRUMENTS;j++) {
	
			if (!get_instrument(j)->is_empty()) 
				continue;
			
			printf("map to %i\n",j);	
			
			//copy
			*get_instrument(j)=*ins;
			
			// assign samples
			for (int k=0;k<CPNote::NOTES;k++) {
			
				get_instrument(j)->set_note_number(k,k);
				get_instrument(j)->set_sample_number(k,sn);
			}					
			remap[sn]=j;
			remapped_count++;
			break;
		}
		
		CP_ERR_COND(remap[sn]==-1); // no more free instruments
	}
	
	printf("remapped %i\n",remapped_count);	
	
	if (remapped_count<2) {
		//undo if only one is remapped
		for (int i=0;i<MAX_SAMPLES;i++) {
		
			if (remap[i]!=-1) {
			
				get_instrument(remap[i])->reset();
			}
		}
		return;
	}
	
	/* remap all song */
	
	for (int p=0;p<CPSong::MAX_PATTERNS;p++) {
	
		CPPattern *pat = get_pattern(p);
		if (pat->is_empty())
			continue;
		
		
		for (int c=0;c<CPPattern::WIDTH;c++) {
		
			for (int r=0;r<pat->get_length();r++) {
			
				CPNote n = pat->get_note(c,r);
				if (n.note<CPNote::NOTES && n.instrument==p_instrument) {
				
					int sn = ins->get_sample_number(n.note);
					if (remap[sn]==-1)
						pat->set_note(c,r,CPNote());
					else {
					
						n.instrument=remap[sn];
						pat->set_note(c,r,n);
					}
				}
			}
		}
	}
	
	ins->reset();
	
}
Esempio n. 26
0
static int OSC_handler(const char *path, const char *types,
                       lo_arg **argv, int argc, void *data, void *p)
{
    OSC_PORT  *pp = (OSC_PORT*) p;
    OSCLISTEN *o;
    CSOUND *csound = (CSOUND *) pp->csound;
    int       retval = 1;

    pp->csound->LockMutex(pp->mutex_);
    o = (OSCLISTEN*) pp->oplst;
    //printf("opst=%p\n", o);
    while (o != NULL) {
      //printf("Looking at %s/%s against %s/%s\n",
      //       o->saved_path, path,o->saved_types, types);
      if (strcmp(o->saved_path, path) == 0 &&
          strcmp(o->saved_types, types) == 0) {
        /* Message is for this guy */
        int     i;
        OSC_PAT *m;
        //printf("handler found message\n");
        m = get_pattern(o);
        if (m != NULL) {
          /* queue message for being read by OSClisten opcode */
          m->next = NULL;
          if (o->patterns == NULL)
            o->patterns = m;
          else {
            OSC_PAT *mm;
            for (mm = o->patterns; mm->next != NULL; mm = mm->next)
              ;
            mm->next = m;
          }
          /* copy argument list */
          for (i = 0; o->saved_types[i] != '\0'; i++) {
            switch (types[i]) {
            default:              /* Should not happen */
            case 'i':
              m->args[i].number = (MYFLT) argv[i]->i; break;
            case 'h':
              m->args[i].number = (MYFLT) argv[i]->i64; break;
            case 'c':
               m->args[i].number= (MYFLT) argv[i]->c; break;
            case 'f':
               m->args[i].number = (MYFLT) argv[i]->f; break;
            case 'd':
               m->args[i].number= (MYFLT) argv[i]->d; break;
            case 's':
              { // ***NO CHECK THAT m->args[i] IS A STRING
                char  *src = (char*) &(argv[i]->s), *dst = m->args[i].string.data;
                if (m->args[i].string.size <= (int) strlen(src)) {
                  if (dst != NULL) csound->Free(csound, dst);
                  dst = csound->Strdup(csound, src);
                  // who sets m->args[i].string.size ??
                  m->args[i].string.data = dst;
                  m->args[i].string.size = strlen(dst)+1;
                }
                else strcpy(dst, src);
                break;
              }
            case 'b':
              {
                int len =
                  lo_blobsize((lo_blob*)argv[i]);
                m->args[i].blob =
                  csound->Malloc(csound,len);
                memcpy(m->args[i].blob, argv[i], len);
#ifdef JPFF
                {
                  lo_blob *bb = (lo_blob*)m->args[i].blob;
                  int size = lo_blob_datasize(bb);
                  MYFLT *data = lo_blob_dataptr(bb);
                  int   *idata = (int*)data;
                  printf("size=%d data=%.8x %.8x ...\n",size, idata[0], idata[1]);
                }
#endif
              }
            }
          }
          retval = 0;
        }
        break;
      }
      o = (OSCLISTEN*) o->nxt;
    }

    pp->csound->UnlockMutex(pp->mutex_);
    return retval;
}
Esempio n. 27
0
void nemo_main()
{
    int    i, dir, nrad, npots=0, ltype, ndim = NDIM, nx, ny, ns, ndat, nret;
    int    cols[4], n, idx, idx_max;
    real   pmax, symsize, rr, omk_max = 0.0, omk_rmax;
    real   rad[MAXPT], *vel, *vel1, *vel2, *vel3, *vel4, *curve;
    real   *ome, *kap, *opk, *omk, r0l[MAXPT+2], omega, *f;
    real   inrad[MAXPT], invel[MAXPT], inrade[MAXPT], invele[MAXPT];
    double pos[3], acc[3], pot, time = 0.0;
/*    char   *fmt, s[20], pfmt[256];    */
    char   headline[256], fmt1[80];
    string axis, mode, infile, plotlabel;
    stream instr;
    bool   Qtab, Qplot, Qome, Qvel, Qlv, Qin, QoILR;

    mode = getparam("mode");
    n = getiparam("n");
    plotlabel = getparam("headline");
    sprintf(fmt1,"%s ",getparam("format"));
    Qome = (*mode == 'o');      /*  options are: velocity|omega|lv */
    Qlv = (*mode == 'l');
    Qvel = (*mode == 'v');
    Qtab = getbparam("tab");
    Qplot = getbparam("plot");
    infile = getparam("in");
    Qin =  (*infile != 0);
    if (Qin) {
        nret = nemoinpi(getparam("cols"),cols,4);
        if (nret<0 || nret > 4) error("cols= requires 4 numbers");
        for (i=nret; i<4; i++)
            cols[i] = 0;
        instr = stropen(infile,"r");
        ndat = read_table(instr,MAXPT,inrad,invel,inrade,invele,cols);
        strclose(instr);
    }
    
    mypot1 = get_potential(getparam("name1"),getparam("pars1"),getparam("file1"));
    omega = get_pattern();
    dprintf(0,"Pattern speed: %f\n",omega);
    mypot2 = get_potential(getparam("name2"),getparam("pars2"),getparam("file2"));
    mypot3 = get_potential(getparam("name3"),getparam("pars3"),getparam("file3"));
    mypot4 = get_potential(getparam("name4"),getparam("pars4"),getparam("file4"));
    headline[0] = '\0';         /* accumulate headline */
    if (mypot1) {
        strcat(headline,getparam("name1"));
        strcat(headline,"(");
        strcat(headline,getparam("pars1"));
        strcat(headline,")");
        npots++;
    } 
    if (mypot2) {
        strcat(headline,getparam("name2"));
        strcat(headline,"(");
        strcat(headline,getparam("pars2"));
        strcat(headline,") ");
        npots++;
    }
    if (mypot3) {
        strcat(headline,getparam("name3"));
        strcat(headline,"(");
        strcat(headline,getparam("pars3"));
        strcat(headline,") ");
        npots++;
    }
    if (mypot4) {
        strcat(headline,getparam("name4"));
        strcat(headline,"(");
        strcat(headline,getparam("pars4"));
        strcat(headline,")");
        npots++;
    }

    nrad = nemoinpr(getparam("radii"),rad,MAXPT);   /* get radii */
    if (nrad <= 0)
        warning("Using %d radii is not very productive",nrad);
    vel  = (real *) allocate(sizeof(real) * nrad);  /* allocate stuff */
    vel1 = (real *) allocate(sizeof(real) * nrad);
    vel2 = (real *) allocate(sizeof(real) * nrad);
    vel3 = (real *) allocate(sizeof(real) * nrad);
    vel4 = (real *) allocate(sizeof(real) * nrad);
    if (Qome) {
        ome = (real *) allocate(4 * sizeof(real) * nrad);  /* plus spline */
        kap = (real *) allocate(sizeof(real) * nrad);
        opk = (real *) allocate(sizeof(real) * nrad);
        omk = (real *) allocate(sizeof(real) * nrad);
    } 

    axis = getparam("axis");
    dir = 0;
    if (*axis == 'x') dir=0;
    if (*axis == 'y') dir=1;
    if (*axis == 'z') dir=2;
    if (dir>NDIM) error("Axis %s not supported in NDIM=%d",axis,NDIM);

    pmax = 0.0;

    for (i=0; i<nrad; i++) {            /* loop to compute */
        CLRV(pos);                      /* clear positions */
        pos[dir] = rad[i];              /* set the right axis */
        vel[i] = 0.0;
        if (mypot1) {
            CLRV(acc);
            (*mypot1) (&ndim,pos,acc,&pot,&time);
            vel1[i] = -rad[i] * acc[dir];
            vel[i] += vel1[i];
            vel1[i] = sqrt(vel1[i]);        
        }
        if (mypot2) {
            CLRV(acc);
            (*mypot2) (&ndim,pos,acc,&pot,&time);
            vel2[i] = -rad[i] * acc[dir];
            vel[i] += vel2[i];
	    vel2[i] = sqrt(vel2[i]);        
        }
        if (mypot3) {
            CLRV(acc);
            (*mypot3) (&ndim,pos,acc,&pot,&time);
            vel3[i] = -rad[i] * acc[dir];
            vel[i] += vel3[i];
	    vel3[i] = sqrt(vel3[i]);        
        }
        if (mypot4) {
            CLRV(acc);
            (*mypot4) (&ndim,pos,acc,&pot,&time);
            vel4[i] = -rad[i] * acc[dir];
            vel[i] += vel4[i];
            vel4[i] = sqrt(vel4[i]);        
        }
        vel[i]  = sqrt(vel[i]);        
    }
    if (Qome) {
	lindblad(nrad,rad,vel,ome,kap,opk,omk,n);
        if (omega> 0.0) {                               /* compute resonances */
            f = opk;
            idx = nrad-1;
            if (omega < f[idx]) {
                warning("Radii not far enough out for OLR: %g",f[idx]);
                f = ome;
                if (omega < f[idx]) {
                    warning("Radii not far enough out for CR: %g",f[idx]);
                    f = omk;
                }
            }
            QoILR = FALSE;
            for(; idx>0; idx--) {
                if (omk[idx] > omk_max) {
                    idx_max = idx;
                    omk_max = omk[idx];
                }
                if (f==omk) {
                    if (QoILR) {
                        if (omega < f[idx]) continue;
                    } else {
                        if (omega > f[idx]) continue;
                    }
                } else {
                    if (omega > f[idx]) continue;
                }
                
                /* found a resonance: */

                rr = rad[idx] + (rad[idx+1]-rad[idx])*
                                (omega-f[idx])/(f[idx+1]-f[idx]);
                if (f == omk) {
#if 0                    
                    if (QoILR) {
                        dprintf(0,"iILR: %g\n",rr);
                        break;
                    } else {
                        dprintf(0,"oILR: %g\n",rr);
                        QoILR = TRUE;
                    }
#endif                    
                } else if (f == ome) {
                    dprintf(0,"CR: %g\n",rr);
                    f = omk;
                } else if (f == opk) {
                    dprintf(0,"OLR: %g\n",rr);
                    f = ome;
                } else
                    error("impossble resonance");
            }
            peak(nrad,rad,omk,idx_max,1, &omk_rmax, &omk_max);
            dprintf(0,"OMK_max: %g\n",omk_max);
            dprintf(0,"OMK_rmax: %g\n",omk_rmax);

            if (omega < omk_max) {			/* search for ILR */
            	for (idx=idx_max; idx<nrad; idx++) {
                    if (omega > omk[idx]) {
                        rr = rad[idx-1] + (rad[idx]-rad[idx-1])*
                                (omega-f[idx-1])/(f[idx]-f[idx-1]);
                        dprintf(0,"oILR: %g\n",rr);
                        break;
                    }
            	}
                for (idx=idx_max; idx>0; idx--) {
                    if (omega > omk[idx]) {
                        rr = rad[idx] + (rad[idx+1]-rad[idx])*
                               (omega-f[idx])/(f[idx+1]-f[idx]);
                        dprintf(0,"iILR: %g\n",rr);
                        break;
                    }
            	}
            }
        }
    }
    for (i=0; i<nrad; i++) {                            /* loop to print */
        if (Qtab) {
	  printf(fmt1,rad[i]);
	  printf(fmt1,vel[i]);
	}
	if (Qtab && npots>1 && !Qome) {
	    if (mypot1) printf(fmt1,vel1[i]);
	    if (mypot2) printf(fmt1,vel2[i]);
	    if (mypot3) printf(fmt1,vel3[i]);
	    if (mypot4) printf(fmt1,vel4[i]);
        }
        if (Qtab && Qome) {
	  printf(fmt1,ome[i]);
	  printf(fmt1,kap[i]);
	  printf(fmt1,opk[i]);
	  printf(fmt1,omk[i]);
	}
	if (Qtab) printf("\n");
        if (Qome)
            pmax = MAX(pmax,opk[i]);
        else
            pmax = MAX(pmax,vel[i]);
    }
    if (Qin && Qvel) 
        goodness(nrad,rad,vel,ndat,inrad,invel,(cols[3]>0?invele:NULL));
    if (Qplot) {
        plinit("***",0.0,20.0,0.0,20.0);                /* open device */
        nx = nemoinpr(getparam("xrange"),xplot,2);      /* get xrange in plot */
        switch(nx) {
         case 0:
            xplot[0] = rad[0];
         case 1:
            xplot[1] = rad[nrad-1];
            break;
         case 2:
            break;
         default:
            warning("xrange= only accepts two values");
            break;
        }
        ny = nemoinpr(getparam("yrange"),yplot,2);      /* get yrange in plot */
        switch(ny) {
         case 0:
            yplot[0] = 0.0;
            yplot[1] = 1.1 * pmax;      /* extra 10% for egde */
            break;
         case 1:
            yplot[1] = 1.1 * pmax;      /* extra 10% for egde */
            break;
         case 2:
            break;
         default:
            warning("yrange= only accepts two values");
            break;
        }
        xaxis ( 2.0, 2.0, 16.0, xplot, -7, xtrans, "R");    /* plot axes */
        xaxis ( 2.0,18.0, 16.0, xplot, -7, xtrans, NULL);
        if (Qome)
            yaxis ( 2.0, 2.0, 16.0, yplot, -7, ytrans, "[V/R]");
        else
            yaxis ( 2.0, 2.0, 16.0, yplot, -7, ytrans, "V");
        yaxis (18.0, 2.0, 16.0, yplot, -7, ytrans, NULL);
        if (*plotlabel)
            pltext(plotlabel,2.0,18.5,0.5,0.0);
        else
            pltext(headline,2.0,18.5,0.35,0.0);
        if (*plotmsg)
            pltext(plotmsg,8.0,2.5,0.25,0.0);

        curve = (Qome ? ome : vel);            /* assign first curve */
        plltype(3,1);                                 /* thick solid line */
        plmove(xtrans(rad[0]),ytrans(curve[0]));
        for (i=1; i<nrad; i++)
            plline(xtrans(rad[i]),ytrans(curve[i]));
        if (Qome) {                   /* if Lindblad - plot omk, opk */
            plltype(1,1);                      /* all regular solid lines */
            plmove(xtrans(rad[0]), ytrans(omk[0]));
            for (i=1; i<nrad; i++)
                plline(xtrans(rad[i]),ytrans(omk[i]));
            plmove(xtrans(rad[0]), ytrans(opk[0]));
            for (i=1; i<nrad; i++)
                plline(xtrans(rad[i]),ytrans(opk[i]));
        } else if (npots>1) {            /* if velocity and > 1 component */
            ltype = 1;
            if (mypot1) {
                plltype(1,++ltype);
                plmove(xtrans(rad[0]),ytrans(vel1[0]));
                for (i=1; i<nrad; i++)
                    plline(xtrans(rad[i]),ytrans(vel1[i]));
            }
            if (mypot2) {
                plltype(1,++ltype);
                plmove(xtrans(rad[0]),ytrans(vel2[0]));
                for (i=1; i<nrad; i++)
                    plline(xtrans(rad[i]),ytrans(vel2[i]));
            }
            if (mypot3) {
                plltype(1,++ltype);
                plmove(xtrans(rad[0]),ytrans(vel2[0]));
                for (i=1; i<nrad; i++)
                    plline(xtrans(rad[i]),ytrans(vel3[i]));
            }
            if (mypot4) {
                plltype(1,++ltype);
                plmove(xtrans(rad[0]),ytrans(vel2[0]));
                for (i=1; i<nrad; i++)
                    plline(xtrans(rad[i]),ytrans(vel4[i]));
            }
        }
	plltype(1,1); 
        symsize = 0.1;
        if (Qin && Qvel) {           /* if input file with velocities */
            for (i=0; i<ndat; i++)
                plbox(xtrans(inrad[i]),ytrans(invel[i]),symsize);
            if (cols[3]>0) {        /* if error bars in radius */
                for (i=0; i<ndat; i++) {
                    plmove(xtrans(inrad[i]-inrade[i]),ytrans(invel[i]));
                    plline(xtrans(inrad[i]+inrade[i]),ytrans(invel[i]));
                }
            }
            if (cols[4]>0) {        /* if error bars in velocity */
                for (i=0; i<ndat; i++) {
                    plmove(xtrans(inrad[i]),ytrans(invel[i]-invele[i]));
                    plline(xtrans(inrad[i]),ytrans(invel[i]+invele[i]));
                }
            }
        } else if (Qin && Qome) {       /* if input file with omega */
            for (i=0; i<ndat; i++)
                plbox(xtrans(inrad[i]),ytrans(invel[i]/inrad[i]),symsize);
        }
        plstop();
    }  /* if plot vel/ome */
    if (Qlv) {
        ns = nemoinpr(getparam("r0l"),r0l,MAXPT+2) - 2;
        if (ns < 0)
            error("r0l= needs at least two values: r0 and l");
        else if (ns==0)
            warning("r0l= no lv-radii array supplied");
        lv(nrad,rad,vel,r0l[0],r0l[1],ns,&r0l[2]);
    }
}