Ejemplo n.º 1
0
Archivo: nal.c Proyecto: walafc0/soclib
/****************************************************************************
  Non static functions
****************************************************************************/
int32_t get_next_nal_unit(nal_unit * nalu)
{
  int32_t i, segment_start;
  int32_t nalu_size = 0;

  // search for the next NALU start
  for (;;) {
    if (input_remain <= 4)
      return 0;		//scan the ring BUF
    
    if ((!ring_buf[ring_pos]) &&
	(!ring_buf[(ring_pos + 1) & RING_MOD]) &&
	(!ring_buf[(ring_pos + 2) & RING_MOD]) &&
	(ring_buf[(ring_pos + 3) & RING_MOD] == 1))
      break;
    gnn_advance();
  }

  for (i = 0; i < 4; ++i)
    gnn_advance();
  
  // add bytes to the NALU until the end is found
  segment_start = ring_pos;

  while (input_remain) {
    if ((!ring_buf[ring_pos]) &&
	(!ring_buf[(ring_pos + 1) & RING_MOD]) &&
	(!ring_buf[(ring_pos + 2) & RING_MOD]))
      break;
    
    ring_pos = (ring_pos + 1) & RING_MOD;
    --input_remain;
    if (ring_pos == 0) {
      gnn_add_segment(RING_BUF_SIZE);
      input_read(&ring_buf[HALF_RING], HALF_RING);
    }
    if (ring_pos == HALF_RING) {
      gnn_add_segment(HALF_RING);
      input_read(&ring_buf[0], HALF_RING);
    }
  }
  gnn_add_segment(ring_pos);

  if (!nalu_size)
    return 0;

  // read the NAL unit
  nal_pos[0] = 0;
  nal_bit[0] = 0;
  nalu->forbidden_zero_bit = input_get_bits(1);
  nalu->nal_ref_idc = input_get_bits(2);
  nalu->nal_unit_type = input_get_bits(5);
  nalu->last_rbsp_byte = &nal_buf[0][nalu_size - 1];
  nalu->NumBytesInNALunit = nalu_size;
    
  EBSPtoRBSP(nal_buf[0],nalu_size,0);

  return 1;
}
Ejemplo n.º 2
0
/* 
 * A simple test for the l2 norm
 */
int test_norm_l2()
{
    int i, j, n, err = 0;
    string_t strs[10];

    input_config("lines");
    char *test_file = getenv("TEST_FILE");
    n = input_open(test_file);
    input_read(strs, n);

    test_printf("Testing L2 normalization");
    config_set_string(&cfg, "features.vect_norm", "l2");
    for (i = 0, err = 0; i < n; i++) {
        fvec_t *fv = fvec_extract(strs[i].str, strs[i].len);
        double n = 0;
        for (j = 0; j < fv->len; j++)
            n += fv->val[j] * fv->val[j];
        err += fabs(sqrt(n) - 1.0) > 1e-6;
        fvec_destroy(fv);
    }
    test_return(err, n);

    input_free(strs, n);
    input_close();
    return err;
}
Ejemplo n.º 3
0
/* 
 * A simple test for the binary embedding
 */
int test_embed_tfidf()
{
    int i, j, n, err = 0;
    string_t strs[10];

    config_set_string(&cfg, "features.vect_norm", "none");
    config_set_string(&cfg, "features.tfidf_file", TEST_TFIDF);

    unlink(TEST_TFIDF);
    char *test_file = getenv("TEST_FILE");
    idf_create(test_file);
    test_printf("Testing TFIDF embedding");

    input_config("lines");
    n = input_open(test_file);
    input_read(strs, n);

    /* Compute IDF manually */
    config_set_string(&cfg, "features.vect_embed", "bin");
    fvec_t *w = fvec_zero();
    for (i = 0, err = 0; i < n; i++) {
        fvec_t *fv = fvec_extract(strs[i].str, strs[i].len);
        fvec_add(w, fv);
        fvec_destroy(fv);
    }
    fvec_invert(w);
    fvec_mul(w, n);
    fvec_log2(w);

    if (!idf_check(w)) {
        err++;
        test_error("(%d) internal idf values seem to be wrong", i);
    }

    /* Invert w for multiplying out IDFs */
    fvec_invert(w);

    config_set_string(&cfg, "features.vect_embed", "tfidf");
    for (i = 0, err = 0; i < n; i++) {
        fvec_t *fv = fvec_extract(strs[i].str, strs[i].len);
        fvec_times(fv, w);

        /* Check if rest tf */
        double d = 0;
        for (j = 0; j < fv->len; j++)
            d += fv->val[j];
        err += fabs(d - 1.0) > 1e-6;
        fvec_destroy(fv);
    }
    test_return(err, n);

    fvec_destroy(w);
    input_free(strs, n);
    input_close();

    idf_destroy();
    unlink(TEST_TFIDF);

    return err;
}
Ejemplo n.º 4
0
/* 
 * A simple test for the binary embedding
 */
int test_embed_bin()
{
    int i, j, n, err = 0;
    string_t strs[10];

    input_config("lines");
    char *test_file = getenv("TEST_FILE");
    n = input_open(test_file);
    input_read(strs, n);

    test_printf("Testing binary embedding");
    config_set_string(&cfg, "features.vect_embed", "bin");
    config_set_string(&cfg, "features.vect_norm", "none");

    for (i = 0, err = 0; i < n; i++) {
        fvec_t *fv = fvec_extract(strs[i].str, strs[i].len);
        double n = 0;
        for (j = 0; j < fv->len; j++)
            n += fv->val[j];
        err += fabs(n - fv->len) > 1e-6;
        fvec_destroy(fv);
    }
    test_return(err, n);

    input_free(strs, n);
    input_close();
    return err;
}
Ejemplo n.º 5
0
// 0 for false, 1 for true
int confirm(const char *label) {
	int ret = -1;
	char str[64];

	DECL_LINE(yesbtn);
	DECL_LINE(nobtn);

	strcpy(sbstr, "confirm action");

	if (label == NULL)
		strcpy(str, "are you sure?");
	else
		sprintf(str, "are you sure you want to %s?", label);

	clear_screen();

	START_LIST(16, 96, 416, 0xFF00FF00, 0xFF0000FF, 0xFFC0C0C0);

	text(str, 16,16, 2,2, 0xFFC0C0C0, 0x00000000);

	DRAW_LINE(yesbtn, "yes", "perform the action");
	DRAW_LINE(nobtn, "no", "cancel the action and return to the previous screen");

	while (ret == -1) {
		update_screen();
		input_read();

		if (BTN_CLICKED(yesbtn)) ret = 1;
		else if (BTN_CLICKED(nobtn)) ret = 0;
	}
	return ret;
}
Ejemplo n.º 6
0
char * select_lv_set(void) {
	int *by, pagenum = 1, npages;
	int n, ret = 0;
	char *selected_set = NULL;

	DECL_LINE(backbtn);
	DECL_LINE(prevpage);
	DECL_LINE(nextpage);

	strcpy(sbstr, "select volume set");

	update_lv_lists();
	n = lv_set_count();
	by = malloc(n * sizeof(int));
	npages = 1 + n / PERPAGE;
	
	do {
		clear_screen();
		START_LIST(8, 32, 352, 0xFF404040, 0xFF808080, 0xFFC0C0C0)

		DRAW_LINE(backbtn, "back", "return to previous menu without making a selection"); 
		if (pagenum > 1) {
			DRAW_LINE(prevpage, "previous page", "not all volume sets are shown"); 
		}
		for (int i = PERPAGE * (pagenum - 1); i < n; ++i) {
			if (i > pagenum * PERPAGE) break;
		
			USECOLR = !USECOLR; 
			CURCOLR = USECOLR ? BG1COLR : BG2COLR; 
			current_y += 48; 
			by[i] =  current_y; 
			fill_rect(0, by[i], 1024, 44, CURCOLR);
			text(lv_set_name(i), col1_x, by[i] + 8, 2, 2, 0xFFFFFFFF, CURCOLR);
		}
		if (pagenum < npages) {
			DRAW_LINE(nextpage, "next page", "not all volume sets are shown");
		}

		update_screen();
		input_read();
		if (BTN_CLICKED(backbtn)) ret = 2;

		for (int i = PERPAGE * (pagenum - 1); i < n; ++i)
			if (was_clicked(0, by[i], 1024, 44)) {
				if (i > pagenum * PERPAGE) break;
				selected_set = strdup(lv_set_name(i));
				ret = 1;				
			}
		if (BTN_CLICKED(prevpage)) --pagenum;
		else if (BTN_CLICKED(nextpage)) ++pagenum;
	} while (!ret);

	free(by);

	return selected_set;
}
Ejemplo n.º 7
0
Archivo: sally.c Proyecto: yangke/sally
/**
 * Main processing routine of Sally. This function processes chunks of
 * strings. It might be suitable for OpenMP support in a later version.
 */
static void sally_process()
{
    long read, i, j;
    int chunk;
    const char *hash_file;

    /* Check if a hash file is set */
    config_lookup_string(&cfg, "features.hash_file", &hash_file);

    /* Get chunk size */
    config_lookup_int(&cfg, "input.chunk_size", &chunk);

    /* Allocate space */
    fvec_t **fvec = malloc(sizeof(fvec_t *) * chunk);
    string_t *strs = malloc(sizeof(string_t) * chunk);

    if (!fvec || !strs)
        fatal("Could not allocate memory for embedding");

    info_msg(1, "Processing %d strings in chunks of %d.", entries, chunk);

    for (i = 0, read = 0; i < entries; i += read) {
        read = input_read(strs, chunk);
        if (read <= 0)
            fatal("Failed to read strings from input '%s'", input);

        /* Generic preprocessing of input */
        input_preproc(strs, read);

#ifdef ENABLE_OPENMP
#pragma omp parallel for
#endif
        for (j = 0; j < read; j++) {
            fvec[j] = fvec_extract(strs[j].str, strs[j].len);
            fvec_set_label(fvec[j], strs[j].label);
            fvec_set_source(fvec[j], strs[j].src);
        }

        if (!output_write(fvec, read))
            fatal("Failed to write vectors to output '%s'", output);

        /* Free memory */
        input_free(strs, read);
        output_free(fvec, read);

        /* Reset hash if enabled but no hash file is set */
        if (fhash_enabled() && !strlen(hash_file) > 0)
            fhash_reset();

        prog_bar(0, entries, i + read);
    }
    
    free(fvec);
    free(strs);
}
Ejemplo n.º 8
0
u16 input_wait(void)
{
	u16 res;

	do {
		udelay(20000);
		res = input_read();
	} while (!(res & PAD_ANY));
	
	return res;
}
Ejemplo n.º 9
0
int main(int argc, char *argv[])
{
	if (argc != 2) {
		fprintf(stderr, "Usage: %s <soundfilename>\n", argv[0]);
		return -1;
	}
	FILE *soundfile;
	if ((soundfile = fopen(argv[1], "w")) == NULL) {
		printf("Could not open sound file\n");
		return -1;
	}
	int err;
	done = 0;
	snd_pcm_t *handle;
	short *buffer;
	int buffer_l = 1024;
	
	signal(SIGINT, closedown);
	printf("Recording sound to: %s\n", argv[1]);
	if ((err = snd_pcm_open(&handle, "hw:2,0", SND_PCM_STREAM_CAPTURE, 0)) < 0) {
		fprintf(stderr, "Error opening sound device\n");
		return -1;
	}
	if (input_initialize(handle, &buffer, &buffer_l) < 0) {
		return -1;
	}

	while (!done) {
		input_read(handle, buffer, buffer_l);
		fwrite(buffer, 2, buffer_l, soundfile);
	}

	printf("Closing down...\n");
	fclose(soundfile);
	input_cleanup(handle);
	
	return 0;
}
Ejemplo n.º 10
0
Archivo: bmon.c Proyecto: noushi/bmon
int main(int argc, char *argv[])
{
	unsigned long sleep_time;
	double read_interval;
	

	start_time = time(0);

	parse_args_pre(argc, argv);
	configfile_read();
	parse_args_post(argc, argv);

	conf_init();
	module_init();

	read_interval = cfg_read_interval;
	sleep_time = cfg_getint(cfg, "sleep_time");

	if (((double) sleep_time / 1000000.0f) > read_interval)
		sleep_time = (unsigned long) (read_interval * 1000000.0f);

	// pipe_start();

	if (cfg_getbool(cfg, "daemon")) {
		init_syslog();
		daemonize();
		write_pidfile();
	}

	drop_privs();

	do {
		/*
		 * E  := Elapsed time
		 * NR := Next Read
		 * LR := Last Read
		 * RI := Read Interval
		 * ST := Sleep Time
		 * C  := Correction
		 */
		timestamp_t e, ri, tmp;
		unsigned long st;

		float_to_timestamp(&ri, read_interval);

		/*
		 * NR := NOW
		 */
		update_timestamp(&rtiming.rt_next_read);
		
		for (;;) {
			output_pre();

			/*
			 * read the chucka chucka pipe
			 */
			// pipe_handle();

			/*
			 * E := NOW
			 */
			update_timestamp(&e);

			/*
			 * IF NR <= E THEN
			 */
			if (timestamp_le(&rtiming.rt_next_read, &e)) {
				timestamp_t c;

				/*
				 * C :=  (NR - E)
				 */
				timestamp_sub(&c, &rtiming.rt_next_read, &e);

				//calc_variance(&c, &ri);

				/*
				 * LR := E
				 */
				copy_timestamp(&rtiming.rt_last_read, &e);

				/*
				 * NR := E + RI + C
				 */
				timestamp_add(&rtiming.rt_next_read, &e, &ri);
				timestamp_add(&rtiming.rt_next_read,
				       &rtiming.rt_next_read, &c);


				reset_update_flags();
				input_read();
				free_unused_elements();
				output_draw();
				output_post();
			}

			if (do_quit)
				exit(0);

			/*
			 * ST := Configured ST
			 */
			st = sleep_time;

			/*
			 * IF (NR - E) < ST THEN
			 */
			timestamp_sub(&tmp, &rtiming.rt_next_read, &e);

			if (tmp.tv_sec < 0)
				continue;

			if (tmp.tv_sec == 0 && tmp.tv_usec < st) {
				if (tmp.tv_usec < 0)
					continue;
				/*
				 * ST := (NR - E)
				 */
				st = tmp.tv_usec;
			}
			
			/*
			 * SLEEP(ST)
			 */
			usleep(st);
		}
	} while (0);

	return 0; /* buddha says i'll never be reached */
}
Ejemplo n.º 11
0
int 
main(int argc, char** argv) {


  int c, i, rd, j;
  long bytes_read = 0;
  int samples_per_tick;
  div_t rest;
  rdfun input_read;
  char* input = "alsa:default";

  while ( ( c = getopt(argc, argv, "vphN:o:g:k:r:c:lS:i:t:s") ) != -1) 
	switch (c) {
	case 'v': debug++; break;
	case 'p': print_freqs = 1; break;
	case 'h': use_harm_comp = 1; break;
	case 'N': N = atoi(optarg); break;
	case 'g': gain = atof(optarg); break;
	case 'o': 
	  if (strcmp(optarg, "seq") == 0 ) use_sequencer = 1;
	  else midi_filename =strdup(optarg); 
	  break;
	case 'k': hysteresis = atof(optarg); break;
	case 'r': ringsize = atoi(optarg); break;
	case 'c': midi_channel = atoi(optarg); break;
	case 'i': input = strdup(optarg); break;
	case 'S': SR = atoi(optarg); break;
	case 's': print_statistics = 1; break;
	case 't': threshold = atof(optarg); break;
	default: usage();
	}

  if ( debug > 0 )
	fprintf(stderr, 
			"ringbuffersize: %d ringbuffermask:0x%08x\n"
			"gain: %f\n",
			RINGBUFFERSIZE, RINGBUFFERMASK, gain);



  print_prologoue(N, SR);

  input_read = input_open(input);

  // allocate buffers

  buffer_f = (real_t**)malloc ( RINGBUFFERSIZE * sizeof(real_t*) );
  for ( j = 0; j < RINGBUFFERSIZE; j++ ) {
	buffer_f[j] = malloc ( N * sizeof(real_t) );
	for ( i = 0; i < N ; i ++ )
	  buffer_f[j][i] = 0.0;
  }


  // prepare midi file
  if (midi_filename != NULL ) {
	midi_file = midi_write_open(midi_filename);
	midi_write_header(midi_timeDivision, 1, midi_file);
	midi_write_track_header(midi_file);
  }

  if ( use_sequencer )
	midi_connect_sequencer();


  // prebuffer everthing
  precalculate();

  samples_per_tick = samples_per_midi_tick(SR, midi_bpm, midi_timeDivision);
  rest.rem = 0;

  // process data
  while ( (rd = input_read(buffer_f[current_buffer], N)) ) { 

	bytes_read += rd;

	rest = div(rest.rem + N, samples_per_tick);

	if (midi_file != NULL )
	  midi_write_increase_difftime(rest.quot, midi_file);

	absolute_time += N;

 	scan_freqs(); 

	// advance buffer:
	current_buffer = (current_buffer+1) & RINGBUFFERMASK;
  }



  for ( j = lo_note; j < hi_note; j++ ) {
	if ( act_freq[j] )
	  note_off(j, 0);
  }

  // free stuff
  for ( j = 0; j < RINGBUFFERSIZE; j++ ) free(buffer_f[j]);
  free(buffer_f);
  for (i = 0; i< NTONES; i++ ) free(cos_precalc[i]);

  // fixup midi
  if (midi_file != NULL ) {
	midi_write_track_end(midi_file);
	midi_write_close(midi_file);
  }


  if ( print_statistics ) {

	// octave style output of powers over frequency
	// first row: frequencies
	// second row: power for that freq
	fprintf(stderr, "freqs = [");
	for (j=lo_note;j<hi_note-1;j++) fprintf(stderr, "%.2f,", midi_note_to_hertz(j));
	fprintf(stderr, "%.2f", midi_note_to_hertz(j));
	fprintf(stderr, ";");
	for (j=lo_note;j<hi_note-1;j++) fprintf(stderr, "%.2f,", max_powers[j]);
	fprintf(stderr, "%.2f", max_powers[j]);
	fprintf(stderr, "];\n");
	
	fprintf(stderr, 
			"\n\n note_ons:%ld bytes_read:%ld playtime:%ld:%ld\n", 
			stats_note_ons, bytes_read, bytes_read/(SR*60), (bytes_read / SR)%60 );
  }


  input_close();

  print_epilogue();

  return 0;
}
Ejemplo n.º 12
0
void boot_menu(void) {
	int npages, pagenum = 1;
	int *by, ret = -1;
	char helpstr[256];

	DECL_LINE(backbtn);
	DECL_LINE(prevpage);
	DECL_LINE(nextpage);

	if (!menu_size) scan_boot_lvs();
	by = malloc(menu_size * sizeof(int));
	npages = 1 + menu_size / PERPAGE;

	strcpy(sbstr, "boot menu");

	clear_screen();

	do {
		clear_screen();
		START_LIST(0, 32, 384, 0xFF404040, 0xFF808080, 0xFFC0C0C0)
		col1_x = 8;

		DRAW_LINE(backbtn, "back", "return to previous menu without making a selection"); 
		if (pagenum > 1) {
			DRAW_LINE(prevpage, "previous page", "not all available kernels are shown"); 
		}

		for (int i = PERPAGE * (pagenum - 1); i < menu_size; ++i) {
			boot_item *cur_item = menu + i; 

			if (i > pagenum * PERPAGE) break;

			snprintf(helpstr, sizeof(helpstr), "volume is %s,\nkernel is %s", 
					cur_item->cfgdev, cur_item->kernel);

			USECOLR = !USECOLR; 
			CURCOLR = USECOLR ? BG1COLR : BG2COLR; 
			current_y += 48; 
			by[i] =  current_y; 
			fill_rect(0, by[i], 1024, 44, CURCOLR);
			text(cur_item->label, col1_x, by[i] + 8, 1, 1, 0xFFFFFFFF, CURCOLR);
			text(helpstr, col2_x, by[i] + 8, 1, 1, 0xFFFFFFFF, CURCOLR);
		}

		while (ret == -1) {
			update_screen();
			input_read();

			if (BTN_CLICKED(backbtn)) ret = 1;

			for (int i = 0; i < menu_size; ++i) {
				if (i > pagenum * PERPAGE) break;
				if (was_clicked(0, by[i], 1024, 44))
					boot_kexec(i);
			}
			if (BTN_CLICKED(nextpage)) ++pagenum;
			else if (BTN_CLICKED(prevpage)) --pagenum;
		}
	} while (!ret);

	free(by);
}
Ejemplo n.º 13
0
// filtloc and filter operate on the filenames and determine whether they
// may be selected:
// ALL: don't filter, in this case, filter can be NULL
// BASE: filter with cmp_base(filename, filter) - only show when part up to
//       last extension matches
// EXT: filter with cmp_ext(filename, filter) - only show when (last) extension
//      matches
// NAME: filter with strcasecmp(filename, filter) - only show when whole name
//       matches
char * select_file(enum filter_spec filtloc, char *filter) {
	char *selected_file, str[256];
	int npages, pagenum = 1;
	const int perpage = PERPAGE - 1;

	DECL_LINE(backbtn);
	DECL_LINE(prevpage);
	DECL_LINE(nextpage);

	strcpy(sbstr, "file browser");

	selected_file = malloc(PATH_MAX * sizeof(char));

	selected_file[0] = '\0';

	while (selected_file[0] == '\0') {
		char *pwd = NULL;
		int n;
		int *by, *kept;
		int j, nkept;
		int match, keep;
		uint16_t mode;

		sel = -1;

		clear_screen();
		START_LIST(8, 48, 448, 0xFF404040, 0xFF808080, 0xFFC0C0C0)

		update_dir_list();
		n = file_count();
		by = malloc(n * sizeof(int));
		kept = malloc(n * sizeof(int));
		npages = 1 + n / perpage;

		pwd = getcwd(pwd, PATH_MAX);
		text(pwd, 16, 24, 1, 1, 0xFF606060, 0xFF000000);

		DRAW_LINE(backbtn, "back", "return to previous menu without making a selection"); 
		if (pagenum > 1) {
			DRAW_LINE(prevpage, "previous page", "not all files are shown"); 
		}

		j = 0;
		for (int i = 0; i < n; ++i) {
			switch (filtloc) {
			case ANY:
				match = 1;
				break;
			case BASE:
				match = !cmp_base(file_name(i), filter);
				break;
			case EXT:
				match = !cmp_ext(file_name(i), filter);
				break;
			case NAME:
				match = !strcasecmp(file_name(i), filter);
				break;
			default:
				match = 0;
			}

			if (file_is_dir(i) || match) {
				kept[j] = i; 
				++j;
			}
		}
		nkept = j;

		for (int i = perpage * (pagenum - 1); i < nkept; ++i) {
			if (i > pagenum * perpage) break;

			snprintf(str, sizeof(str), "permissions = %o", file_mode(kept[i]) & 07777);

			USECOLR = !USECOLR; 
			CURCOLR = USECOLR ? BG1COLR : BG2COLR; 
			current_y += 48; 
			by[i] =  current_y; 
			fill_rect(0, by[i], 1024, 44, CURCOLR);
			text(file_name(kept[i]), col1_x, by[i] + 8, 1, 1, 0xFFFFFFFF, CURCOLR);
			text(str, col2_x, by[i] + 8, 1, 1, 0xFFFFFFFF, CURCOLR);
		}
		if (pagenum < npages) {
			DRAW_LINE(nextpage, "next page", "not all files are shown");
		}

		while (sel == -1) {
			update_screen();
			input_read();

			if (BTN_CLICKED(backbtn)) {
				free(by);
				free(kept);
				return NULL;
			}
			for (int i = perpage * (pagenum - 1); i <= nkept; ++i)
				if (was_clicked(0, by[i], 1024, 44))
					sel = kept[i];
			if (BTN_CLICKED(prevpage)) {
				--pagenum;
				break;
			} else if (BTN_CLICKED(nextpage)) {
				++pagenum;
				break;
			}
		}

		if (sel != -1) {
			free(by);
			free(kept);
			pagenum = 1;
	
			if (file_is_dir(sel)) {
				if (chdir(file_name(sel)) == -1)
					perror("chdir");
			} else {
				strcpy(selected_file, pwd);
				strcat(selected_file, "/");
				strcat(selected_file, file_name(sel));
			}
		}
	}

	return selected_file;
}
Ejemplo n.º 14
0
int main(int argc, char *argv[])
{
	int err;
	done = 0;
	snd_pcm_t *handle;
	FILE *sound_in_fd = NULL;
	FILE *sound_out_fd = NULL;
	int channels;
	short *buffer = NULL;
	int buffer_l;
	int buffer_read;
	struct serial_state_t *serial = NULL;
	struct ipc_state_t *ipc = NULL;
	struct receiver *rx_a = NULL;
	struct receiver *rx_b = NULL;
#ifdef HAVE_PULSEAUDIO
	pa_simple *pa_dev = NULL;
#endif
	
	/* command line */
	parse_cmdline(argc, argv);
	
	/* open syslog, write an initial log message and read configuration */
	open_log(logname, 0);
	hlog(LOG_NOTICE, "Starting up...");
	if (read_config()) {
		hlog(LOG_CRIT, "Initial configuration failed.");
		exit(1);
	}
	
	/* fork a daemon */
	if (fork_a_daemon) {
		int i = fork();
		if (i < 0) {
			hlog(LOG_CRIT, "Fork to background failed: %s", strerror(errno));
			fprintf(stderr, "Fork to background failed: %s\n", strerror(errno));
			exit(1);
		} else if (i == 0) {
			/* child */
			/* write pid file, now that we have our final pid... might fail, which is critical */
			hlog(LOG_DEBUG, "Writing pid...");
			if (!writepid(pidfile))
				exit(1);
		} else {
			/* parent, quitting */
			hlog(LOG_DEBUG, "Forked daemon process %d, parent quitting", i);
			exit(0);
		}
	}
	
	
	signal(SIGINT, closedown);
	signal(SIGPIPE, brokenconnection);
	
	/* initialize position cache for timed JSON AIS transmission */
	if (uplink_config) {
		hlog(LOG_DEBUG, "Initializing cache...");
		if (cache_init())
			exit(1);
		hlog(LOG_DEBUG, "Initializing jsonout...");
		if (jsonout_init())
			exit(1);
	}
	
	/* initialize serial port for NMEA output */
	if (serial_port)
		serial = serial_init();

	/* initialize Unix domain socket for communication with gnuaisgui */
	ipc = gnuais_ipc_init();
	if(ipc == 0){
		hlog(LOG_ERR, "Could not open Unix Domain Socket");
	}
	
	/* initialize the AIS decoders */
	if (sound_channels != SOUND_CHANNELS_MONO) {
		hlog(LOG_DEBUG, "Initializing demodulator A");
		rx_a = init_receiver('A', 2, 0,serial,ipc);
		hlog(LOG_DEBUG, "Initializing demodulator B");
		rx_b = init_receiver('B', 2, 1,serial,ipc);
		channels = 2;
	} else {
		hlog(LOG_DEBUG, "Initializing demodulator A");
		rx_a = init_receiver('A', 1, 0,serial,ipc);
		channels = 1;
	}
#ifdef HAVE_PULSEAUDIO
	if(sound_device != NULL && ((strcmp("pulse",sound_device) == 0) || (strcmp("pulseaudio",sound_device) == 0))){
		if((pa_dev = pulseaudio_initialize()) == NULL){
			hlog(LOG_CRIT, "Error opening pulseaudio device");
			return -1;
		}
		buffer_l = 1024;
		int extra = buffer_l % 5;
		buffer_l -= extra;
		buffer = (short *) hmalloc(buffer_l * sizeof(short) * channels);
	}
	else if (sound_device){
#else
	if (sound_device){
#endif

		if ((err = snd_pcm_open(&handle, sound_device, SND_PCM_STREAM_CAPTURE, 0)) < 0) {
			hlog(LOG_CRIT, "Error opening sound device (%s)", sound_device);
			return -1;
		}
		
		if (input_initialize(handle, &buffer, &buffer_l) < 0)
			return -1;
	} else if (sound_in_file) {
		if ((sound_in_fd = fopen(sound_in_file, "r")) == NULL) {
			hlog(LOG_CRIT, "Could not open sound file %s: %s", sound_in_file, strerror(errno));
			return -1;
		}
		hlog(LOG_NOTICE, "Reading audio from file: %s", sound_in_file);
		buffer_l = 1024;
		int extra = buffer_l % 5;
		buffer_l -= extra;
		buffer = (short *) hmalloc(buffer_l * sizeof(short) * channels);
	} else {
		hlog(LOG_CRIT, "Neither sound device or sound file configured.");
		return -1;
	}
	
	if (sound_out_file) {
		if ((sound_out_fd = fopen(sound_out_file, "w")) == NULL) {
			hlog(LOG_CRIT, "Could not open sound output file %s: %s", sound_out_file, strerror(errno));
			return -1;
		}
		hlog(LOG_NOTICE, "Recording audio to file: %s", sound_out_file);
	}
	
#ifdef HAVE_MYSQL
	if (mysql_db) {
		hlog(LOG_DEBUG, "Saving to MySQL database \"%s\"", mysql_db);
		if (!(my = myout_init()))
			return -1;
			
		if (mysql_keepsmall)
			hlog(LOG_DEBUG, "Updating database rows only.");
		else
			hlog(LOG_DEBUG, "Inserting data to database.");
			
		if (mysql_oldlimit)
			hlog(LOG_DEBUG, "Deleting data older than %d seconds", mysql_oldlimit);
	}
#endif
	
	hlog(LOG_NOTICE, "Started");
	
	while (!done) {
		if (sound_in_fd) {
			buffer_read = fread(buffer, channels * sizeof(short), buffer_l, sound_in_fd);
			if (buffer_read <= 0)
				done = 1;
		} 
#ifdef HAVE_PULSEAUDIO
		else if (pa_dev){
			buffer_read = pulseaudio_read(pa_dev, buffer, buffer_l);
		}
#endif
		else {
			buffer_read = input_read(handle, buffer, buffer_l);
			//printf("read %d\n", buffer_read);
		}
		if (buffer_read <= 0)
			continue;
		
		if (sound_out_fd) {
			fwrite(buffer, channels * sizeof(short), buffer_read, sound_out_fd);
		}
		
		if (sound_channels == SOUND_CHANNELS_MONO) {
			receiver_run(rx_a, buffer, buffer_read);
		}
		if (sound_channels == SOUND_CHANNELS_BOTH
		    || sound_channels == SOUND_CHANNELS_RIGHT) {
			/* ch a/0/right */
			receiver_run(rx_a, buffer, buffer_read);
		}
		if (sound_channels == SOUND_CHANNELS_BOTH
		    || sound_channels == SOUND_CHANNELS_LEFT) {	
			/* ch b/1/left */
			receiver_run(rx_b, buffer, buffer_read);
		}
	}
	
	hlog(LOG_NOTICE, "Closing down...");
	if (sound_in_fd) {
		fclose(sound_in_fd);
	}
#ifdef HAVE_PULSEAUDIO
	else if (pa_dev) {
		pulseaudio_cleanup(pa_dev);
	}
#endif
	else {
		input_cleanup(handle);
		handle = NULL;
	}

	
	if (sound_out_fd)
		fclose(sound_out_fd);
	
	hfree(buffer);

	gnuais_ipc_deinit(ipc);
	
	if (serial)
		serial_close(serial);
	
	if (uplink_config)
		jsonout_deinit();
	
	if (cache_positions)
		cache_deinit();
	
	if (rx_a) {
		struct demod_state_t *d = rx_a->decoder;
		hlog(LOG_INFO,
			"A: Received correctly: %d packets, wrong CRC: %d packets, wrong size: %d packets",
			d->receivedframes, d->lostframes,
			d->lostframes2);
	}
	
	if (rx_b) {
		struct demod_state_t *d = rx_b->decoder;
		hlog(LOG_INFO,
			"B: Received correctly: %d packets, wrong CRC: %d packets, wrong size: %d packets",
			d->receivedframes, d->lostframes,
			d->lostframes2);
	}
	
	free_receiver(rx_a);
	free_receiver(rx_b);
	
	free_config();
	close_log(0);
	
	return 0;
}
Ejemplo n.º 15
0
Archivo: bmon.c Proyecto: KISSMonX/bmon
int main(int argc, char *argv[])
{
	unsigned long sleep_time;
	double read_interval;
	
	start_time = time(0);
	memset(&rtiming, 0, sizeof(rtiming));
	rtiming.rt_variance.v_min = FLT_MAX;

	/*
	 * Early initialization before reading config
	 */
	conf_init_pre();
	parse_args_pre(argc, argv);

	/*
	 * Reading the configuration file */
	configfile_read();

	/*
	 * Late initialization after reading config
	 */
	if (parse_args_post(argc, argv))
		return 1;
	conf_init_post();

	module_init();

	read_interval = cfg_read_interval;
	sleep_time = cfg_getint(cfg, "sleep_time");

	if (((double) sleep_time / 1000000.0f) > read_interval)
		sleep_time = (unsigned long) (read_interval * 1000000.0f);

	DBG("Entering mainloop...");

	do {
		/*
		 * E  := Elapsed time
		 * NR := Next Read
		 * LR := Last Read
		 * RI := Read Interval
		 * ST := Sleep Time
		 * C  := Correction
		 */
		timestamp_t e, ri, tmp;
		unsigned long st;

		float_to_timestamp(&ri, read_interval);

		/*
		 * NR := NOW
		 */
		update_timestamp(&rtiming.rt_next_read);
		
		for (;;) {
			output_pre();

			/*
			 * E := NOW
			 */
			update_timestamp(&e);

			/*
			 * IF NR <= E THEN
			 */
			if (timestamp_le(&rtiming.rt_next_read, &e)) {
				timestamp_t c;

				/*
				 * C :=  (NR - E)
				 */
				timestamp_sub(&c, &rtiming.rt_next_read, &e);

				//calc_variance(&c, &ri);

				/*
				 * LR := E
				 */
				copy_timestamp(&rtiming.rt_last_read, &e);

				/*
				 * NR := E + RI + C
				 */
				timestamp_add(&rtiming.rt_next_read, &e, &ri);
				timestamp_add(&rtiming.rt_next_read,
				       &rtiming.rt_next_read, &c);


				reset_update_flags();
				input_read();
				free_unused_elements();
				output_draw();
				output_post();
			}

			if (do_quit)
				exit(0);

			/*
			 * ST := Configured ST
			 */
			st = sleep_time;

			/*
			 * IF (NR - E) < ST THEN
			 */
			timestamp_sub(&tmp, &rtiming.rt_next_read, &e);

			if (tmp.tv_sec < 0)
				continue;

			if (tmp.tv_sec == 0 && tmp.tv_usec < st) {
				if (tmp.tv_usec < 0)
					continue;
				/*
				 * ST := (NR - E)
				 */
				st = tmp.tv_usec;
			}
			
			/*
			 * SLEEP(ST)
			 */
			usleep(st);
		}
	} while (0);

	return 0; /* buddha says i'll never be reached */
}
Ejemplo n.º 16
0
int main()

{
    energymethod = 1;   /*melt calculated by energy balance approach*/
    /*needed in certain functions, which are    */
    /*also used by the degree day model         */

    ratio = startratio;

    /*----------------------------------------------------------------*/
    /*** READ DATA FROM CONTROLING INPUT FILE / INITIALISATION     ****/
    /*----------------------------------------------------------------*/

    input_read();           /*** READ INPUT DATA ***/
    startinputdata();       /***OPEN AND READ GRID FILES AND CLIMATE DATA***/
    checkgridinputdata_ok(); /*check if grid input data ok*/
    startoutascii();        /***OPEN ASCII-OUTPUT FILES AND WRITE HEAS***/
    startspecificmassbalance(); /*OPEN FILE FOR SPECIFIC MASS BAL, MULTI-YEAR RUNS*/
    startarrayreserve();    /***STORAGE RESERVATION OF ARRAYS FOR EACH TIME STEP***/
    glacierrowcol();  /*FIND FIRST, LAST ROW AND COLUMN OF AREA CALCULATED IN DTM*/
    readclim();       /*** READ CLIMATE INPUT FIRST ROW = ONE TIME STEP ****/

    /* puts("ok1");  */

    if((winterbalyes == 1) || (summerbalyes == 1))
        areaelevationbelts();    /*number of grid cells per elevation band, for bn profiles*/

    if(maxmeltstakes > 0)
        startmeltstakes();    /*OUTPUT OF MELT OF SEVERAL LOCATIONS - COMPARISON WITH STAKES*/

    if(methodsnowalbedo >= 2)  /*albedo variable in time, generated by model*/
        inialbedoalt();    /*allocate start albedo to each grid cell*/

    if(snowfreeyes == 1)   /*OPEN FILE WITH TIME SERIES WITH NO. OF SNOWFREE PIXELS*/
        opensnowfree();

    if((datesfromfileyes == 1) &&  (winterbalyes == 1) && (summerbalyes == 1))
        readdatesmassbal();      /*READ DATES OF MASS BAL MEASUREMENTS FOR EACH YEAR*/

    if(readsnowalbedo==1)      /*read measured daily snow albedo*/
        readalbedo29();        /*specific to Storglaciaren application: 1994*/
    /*   readalbedo16(); */

    if(methodprecipinterpol == 2)    /*read precipitation index map once (constant in time)*/
        readprecipindexmap();        /*in turbul.c under precipitation*/

    if (disyes >= 1)        /*DISCHARGE SIMULATION REQUESTED, 1=discharge data, 2=no data*/
        startdischarg();     /*INITIALIZE DISCHARGE SIMULATION for both cases*/

    /*======= for SNOWMODEL by Carleen Tijm-Reijmer, 2/2005=======*/
    if (methodsurftempglac == 4) { /* surface temperature determined using snowmodel */
        initgrid();        /*initialise subsurface grid including temperature and density profiles */
        outputsubsurf();   /*write initial conditions for each layer to file*/
    }
    if (methodsurftempglac != 4) /*CHR added for stability of subsurface scheme*/
        factinter = 1;
    /*============================================================*/

    /*=============FOR EVERY TIME STEP ===============================================*/

    do {

        nsteps += 1;         /*number of time steps of period calculated*/
        if((zeit==24) && ((int)jd/daysscreenoutput == floor((int)jd/daysscreenoutput)))
            printf("\n  yr= %4.0f  jd = %4.2f   time =%3.0f",year,jd,zeit);   /*SCREEN OUTPUT*/

        if(do_out_area == 1)
            areameannull();  /* SPATIAL MEANS OF MODEL OUTPUT SET TO ZERO */

        /*======= for SNOWMODEL by Carleen Tijm-Reijmer, 2/2005=======*/
        if (factinter > 1)   /*in case of subintervals per time interval*/
            timesteporig = timestep;    /*variable timestep will be manipulated in interpolate()*/
        /*set to original value after computation for further use in discharg.c etc*/

        for (inter=1; inter <= factinter; inter++) { /*CHR added: for each subinterval */
            /* start interpolation between two time steps in case of use of subsurface model*/
            if (factinter > 1)
                interpolate();     /*linearly interpolate climate data for subintervals*/
            /*============================================================*/

            /******* INTERPOLATION OF AIR TEMPERATURE ******/
            tempinterpol(); /*** ELEVATION-DEPENDENT AIR TEMP INTERPOLATION ***/

            /****** RADIATION *****************************/
            if (directfromfile == 0)
                schatten();      /*** CALCULATE SHADE, CORRECTION FACTOR, DIRECT GRIDs ***/
            else
                readdirect();    /* READ DIRECT RADIATION (slope corrected) FROM FILE */

            if(methodglobal==1)     /*no separation into direct and diffus at climate station*/
                ratioglobal();        /*CORRECTION RATIO FOR GLOBAL RADIATION DUE TO CLOUDS */
            else {          /*separation into direct and diffus at climate station*/
                topofatmosphere();           /*needed for ratio global/topofatm*/
                splitdiffusedirectkiruna();  /*split meas global into direct and diffuse*/
                meanalbedo();    /*mean albedo of entire drainage basin for terrain diffuse rad*/
                diffusunobstructed();   /*correct station diffuse rad, so that unobstructed sky*/
                ratiodirectdirect();    /*ratio actual direct to potential direct at station*/
            }  /*endelse*/

            if(methodglobal == 1) {  /*if methodglobal=2, topofatm already calculated; cloud parameterization with G/Toa ratio*/
                if( ((methodsnowalbedo == 3) || (methodsnowalbedo == 5)) || (methodlonginstation == 6))
                    topofatmosphere();   /*needed to determine cloudiness*/
            }

            switch(methodlonginstation) {  /*HOW IS LONGWAVE INCOMING AT STATION DETERMINED*/
            case 1:
                longinstationnetradmeas();     /*FROM MEAS NET, GLOB, REF*/
                break;
            case 2:
                break;                   /*LONGIN READ FROM CLIMATE DATA INPUT FILE*/
                /*has been read into LWin in readclim*/
            case 3:
                longinstationkonzel();   /*PARAMETERIZATION Konzelmann et al. using cloud amount*/
                break;
            case 4:
                longinstationbrunts();
                break;
            case 5:
                longinstationbrutsaert();
                break;
            case 6:
                longinstationkonzel();   /*as 3, but clouds are parameterized, function called there*/
                break;
            default:
                puts("\n no choice of methodlonginstation made\n\n");
                exit(3);
                break;
            }  /*end switch*/


            /*REMOVE TOPOGRAPHIC INFLUENCE ON CLIMATE STATION LONGWAVE INCOMING
              ONLY IF CLIMATE STATION NOT OUSIDE AREA TO BE CALCULATED*/
            if((methodlongin == 2) && (climoutsideyes == 0))    /*LONGWAVE BASED ON PLUESS, 1997*/
                longinskyunobstructed();  /*LONGWAVE IN AT CLIMATE STATION IF IT WAS UNOBSTRUCTED*/

            if(methodinisnow == 1)   /*DISTRIBUTION SNOW/ICE PRESCRIBED, READ FROM FILES*/
                albedoread();   /*OPEN AND READ SURFACE TYPE FILE IF NEW ONE VALID FOR TIME STEP*/
            /* integer for each surface type in array surface */
            else
                whichsurface(); /*VALUE FOR ARRAY surface (SNOW,FIRN,ICE,ROCK) FOR ALBEDO, K-VALUES*/

            /*LONGWAVE OUT RADIATION AT CLIMATE STATION FROM MEAS*/
            if(methodsurftempglac == 3) { /*use longwave outgoing measurements at climate station*/
                i=rowclim;
                j=colclim;   /*needed because surtempfromlongout also used later for entire grid*/
                surftempfromlongout();       /*CALCULATE SURFACE TEMP AT CLIMATE STATION*/
            } else
                surftemp[rowclim][colclim] = 0.;

            if(methodprecipinterpol == 3)   /*read precipitation grids from file for each time step*/
                readprecipfromfile();

            /*======= for SNOWMODEL by Carleen Tijm-Reijmer, 2/2005=======*/
            if(methodsurftempglac == 4) { /*CHR added option*/
                i=rowclim;
                j=colclim;
                if (skin_or_inter == 1) surftempfrommodel();  /*CALCULATE SURFACE TEMP AT CLIMATE STATION FROM T OF 2 UPPER LAYERS*/
                if (skin_or_inter == 0) surftempskin(); /*CALCULATE SURFACE TEMP BASED ON SKIN LAYER FORMULATION*/
                surftempstationalt=surftemp[rowclim][colclim];
                if (((int)jd2 == (int)summerjdend+1) && ((int)zeit == 1) && (inter == 1)) {
                    resetgridwinter();
                }
                if (((int)jd2 == (int)winterjdend+1) && ((int)zeit == 1) && (inter == 1))
                    resetgridsummer();
            }

            /*============================================================*/

            /*CLIMATE STATION GRID MUST BE COMPUTED FIRST, IN ORDER TO CALCULATE THE LONGWAVE INCOMING
              RADIATION FOR CLIMATE STATION IN CASE OF SPATIALLY DISTRIBUTED, BEFORE INTERPOLATING*/
            /*ONLY POSSIBLE IF STATION IS LOCATED ON GLACIER, OTHERWISE NO ITERATION FOR STATION GRID
               - USE LONGIN AS DETERMINED FROM MEASUREMENTS FOR EXTRAPOLATION*/
            if((methodsurftempglac == 2) || (methodsurftempglac == 4) && (griddgmglac[rowclim][colclim] != nodata))
                iterationstation();    /*CALCULATE ENERGY BALANCE AT CLIMATE STATION*/

            /*IF NO SURFACE TEMP ITERATION THERE IS NO COMPUTATION OF STABILITY FUNCTIONS FOR
              LOCATION OF CLIMATE STATION, THEREFORE FIRST COMPUTATON OF SENSIBLE HEAT FLUX
              FOR CLIMATE STATION */
            if((methodsurftempglac != 2) && (methodsurftempglac != 4)) {
                i=rowclim;
                j=colclim;    /*ONLY AT CLIMATE STATION GRID CELL*/
                if (methodturbul == 3) { /*CHR*/
                    airpress();    /*** CALCULATION AIR PRESSURE AT GRID POINT FOR TURB FLUXES ***/
                    vappress();    /*** CALCULATION VAPOUR PRESSURE FROM REL. HUMIDITY  ***/
                    sensiblestabilityiteration();    /*DETERMINE STABILITY FUNCTIONS AND z0T, zoe*/
                }
                if (methodturbul == 4) /*by C. Tijm-Reijmner*/
                    turbfluxes();  /*almost same as 3, but differently programmed*/
            }  /*endif*/


            /*================================================================================*/
            /*------- FOR EACH GRID POINT - only for grid cells defined by dgmdrain ----------*/
            /*================================================================================*/

            if(calcgridyes == 2) {    /*computation only for climate station grid cell*/
                firstrow = rowclim;
                lastrow = rowclim;
                firstcol[firstrow] = colclim;
                lastcol[firstrow] = colclim;
            }      /*will only go through grid loop once for climate station grid cell*/

            for (i=firstrow; i<=lastrow; i++)         /*for all rows of drainage basin grid*/
                for (j=firstcol[i]; j<=lastcol[i]; j++) { /*for all columns*/
                    if (griddgmdrain[i][j] != nodata) { /*only for area to be calculated*/
                        if (griddgmdrain[i][j] != griddgm[i][j]) {
                            printf("\n\n ERROR elevation in DTM is not the same as in glacier grid\n");
                            printf(" row  %d  col  %d      (in main) \n\n",i,j);
                            exit(12);
                        }

                        if(((methodsurftempglac == 2) || (methodsurftempglac == 4)) && (i==rowclim) && (j==colclim))
                            notcalc = 1;    /*ENERGY BALANCE FOR STATION GRID CELL ALREADY CALCULATED*/
                        else               /*TO AVOID TO BE COMPUTED AGAIN*/
                            notcalc = 0;


                        if(notcalc==0) {    /*COMPUTE ENERGY BALANCE ONLY IF NOT YET CALCULATED*/
                            /********* GLOBAL RADIATION **********************/
                            if(methodglobal==1)     /*no separation into direct and diffus*/
                                globradratio();           /*calculation of global radiation*/
                            if(methodglobal==2) {   /*separate interpolation of direct and diffuse radiation*/
                                interpoldirect();
                                interpoldiffus();
                                adddirectdiffus();
                            }

                            /********** PRECIPITATION *****needed before albedo in method 2*********/
                            precipinterpol();
                            precipenergy();      /*rain outside glacier considered after grid computed*/

                            /********* ALBEDO **********************/
                            if(readsnowalbedo==0) { /*no use of albedo measurements*/
                                switch(methodsnowalbedo) {
                                case 1:
                                    albedocalcconst();    /*constant albedo for snow/slush/ice*/
                                    break;
                                case 2:
                                    albedocalc();  /*albedo generated as function of T, snow fall*/
                                    break;
                                case 3:
                                    albedocalc();  /*as 2 but incl. cloud dependence*/
                                    break;
                                case 4:
                                    albedocalcdepth();  /*as 2 but depending on snowdepth*/
                                    break;
                                case 5:
                                    albedocalcdepth();  /*as 4 but incl. cloud dependence*/
                                    break;
                                case 6:
                                    albedosnowpoly();  /*modified version of oerlemans and knap, sicart PhD. p.243*/
                                    break;
                                }  /*end case*/
                            }  /*endif*/
                            else     /*measured albedo data read from file*/
                                albedosnowmeas();   /*use measured daily means of snow albedo - Storglac*/

                            shortwavebalance();    /*SHORTWAVE RADIATION BALANCE*/

                            /********* ROCK SURFACE TEMPERATURE **********************/
                            /*  if(methodlongin == 2)    LONGWAVE ASSUMED VARIABLE, BASED ON PLUESS, 1997*/
                            /*    tempsurfacerock();     SURFACE TEMPERATURE OF ROCK OUTSIDE GLACIER*/

                            /*CASE 2: before iteration surftemp must be reset to 0, strictly speaking, only if lowered via iteration,
                              or if surftemp written to output (because array is overwritten for output means*/
                            /* at start in initial.c set to 0 for area calculated*/
                            switch(methodsurftempglac) {
                            case 1:  /*NO ITERATION, TEMP CONSTANT AS AT CLIMATE STATION*/
                                surftemp[i][j] = surftemp[rowclim][colclim];
                                break;
                            case 2:  /*ITERATION SO THAT ENBAL IS BALANCED, START WITH TEMP=0, THEN LOWER TEMP*/
                                surftemp[i][j] = 0;
                                break;
                            case 3:
                                if(surftemplapserate == 0)	  /* measured surf temp constant in space*/
                                    surftemp[i][j] = surftemp[rowclim][colclim];
                                else {	                  /* measured surf temp decreases with elevation, lapserate change per 100 m */
                                    surftemp[i][j] = surftemp[rowclim][colclim] + (griddgm[i][j]-griddgm[rowclim][colclim])/100 * surftemplapserate;
                                    if(surftemp[i][j] > 0)
                                        surftemp[i][j] = 0;
                                }
                                break;
                            case 4:  /*SNOW MODEL*/
                                surftempfrommodel();   /*surftemp from interpolation of T of upper 2 layers*/
                                break;
                            }


                            airpress();    /*** CALCULATION AIR PRESSURE AT GRID POINT FOR TURB FLUXES ***/
                            vappress();    /*** CALCULATION VAPOUR PRESSURE FROM REL. HUMIDITY  ***/

                            /**** ======== ITERATION LOOP FOR SURFACE TEMP ICE, SNOW ============================ */
                            /**** longwave outgoing, turbulent fluxes and longwave incoming (if according to Pluess) are
                                  affected by surface temperature and thus calculated inside iteration loop
                                  effect of changing surface temp on rain energy neglected ***/
                            do {        /*goes only once through the loop in case methodsurftempglac is not 2*/
                                /************* TURBULENT FLUXES *********************/
                                if(methodsurftempglac >= 2)   /*surface temp may change*/
                                    vappressicesnow();       /*saturation vapour pressure of ice, snow surface*/

                                switch(methodturbul) {
                                case 1:
                                    sensescher();    /*ACCORDING TO ESCHER-VETTER*/
                                    latescher();
                                    break;
                                case 2:
                                    sensible();   /*NO STABILITY, STAB FUNCTIONS = 0*/
                                    latent();
                                    break;
                                case 3:
                                    sensible();   /*INCLUDING STABILITY, SAME FUNCTIONS AS 2 BUT*/
                                    latent();     /*STAB FUNCTIONS HAVE BEEN DETERMINED BEFORE */
                                    break;        /*STAB FUNCTIONS SPATIALLY NOT VARIABLE*/
                                case 4:
                                    sensiblenew();   /*SAME AS 3, BUT DIFFERENT WAYS OF COMPUTATION*/
                                    latentnew();     /*by Carleen Tijm-Reijmer, 2/2005*/
                                    break;
                                }


                                /********* LONGWAVE RADIATION **********************/
                                if(methodlongin == 2)      /*LONGWAVE INCOMING RADIATION VARIABLE IN SPACE*/
                                    longinpluess();           /*NEEDS SURFACE TEMPERATURE*/

                                if(methodsurftempglac >= 2)     /*LONGWAVE OUTGOING RAD VARIABLE IN SPACE OR FROM LONGOUT MEAS*/
                                    longoutcalc();    /*if melting surface: LWout is initialized to melting conditions*/

                                /********* RADIATION BALANCE **********************/
                                radiationbalance();

                                /*  for Keikos article:  NETRAD[rowclim][colclim] = glob - ref + LWin - LWout; */


                                /********* ICE HEAT FLUX **************************/
                                if(methodiceheat == 2)      /*if 1 no heat flux*/
                                    iceheatStorglac();        /*predefined ice heat flux, specific Storglac*/

                                /********* ENERGY BALANCE *************************/
                                if (methodsurftempglac == 4)
                                    ICEHEAT[i][j] = 0.;

                                energybalance();

                                if((methodnegbal == 2) && (iternumber == 0))
                                    negenergybalance();      /*STORE NEGATIVE ENERGY BALANCE*/
                                /*iternumber must to 0 to ensure that in case of iteration, the first
                                  negative ENBAL is stored  before it is brought to zero by lowering the surface
                                  temperature in the iteration procedure (the function is called only once for every
                                  time step and each grid cell), iternumber is increased when surface temp lowered,
                                  after iteration loop energy balance can not be negative any more*/

                                if((methodsurftempglac == 2) && (ENBAL[i][j] < 0)) {  /*iteration wanted*/
                                    if(surface[i][j] != 4)  /*glacier or snow on rock*/
                                        surftemp[i][j] -= iterstep;      /*decrease temperature*/
                                    iternumber += 1;
                                    /*count number of iteration steps*/
                                }  /*endif*/

                                if(methodsurftempglac == 2)    /*iterationend initialized to 10 in variab.h*/
                                    iterationend = ENBAL[i][j];  /*trick to determine iterationend: if pos no further iteration*/

                                if(iternumber > 1000) {   /*to avoid endless loops*/
                                    printf("\n\nTOO MANY ITERATIONS (<1000)  jd=%4.1f %5.1f row %5d col %5d\n\n",jd,zeit,i,j);
                                    exit(20);
                                }

                                if(surface[i][j] == 4)    /*no iteration for rock surface*/
                                    iterationend = 10;      /*energy balance only on glacier and on snow of interest*/
                                if(surftemp[i][j] < surftempminimum)     /*stop iteration to avoid surface temp too low*/
                                    iterationend = 10;

                            } while(iterationend < 0);   /*is set > 0 if ENBAL is positive and thus loop exited*/
                            /**** ======== ITERATION LOOP FOR SURFACE TEMP ICE, SNOW end: next temp ===== */

                            if(iternumber > 0) {
                                ENBAL[i][j] = 0;   /*set to 0, so that it is not pos after iteration is over*/
                                iternumber = 0;     /*set to zero for next grid cell*/
                                iterationend = 10;  /*set positive, to avoid iteration if ENBAL pos*/
                            }

                            /****** WATER EQUIVALENT MELT/ABLATION ******/
                            /*======= for SNOWMODEL by Carleen Tijm-Reijmer, 2/2005=======*/
                            /*before only waterequi-functions called*/
                            if ((methodsurftempglac != 4) || ((methodsurftempglac == 4) && (percolationyes == 0))) { /*CHR added*/
                                waterequivalentmelt();     /*** WATER EQUIVALENT MELT ***/
                                waterequivalentabla();     /*** WATER EQUIVALENT ABLATION ***/
                                RUNOFF[i][j] = MELT[i][j] + rainprec;
                            } else
                                MELT[i][j] = 0.0;

                            if (methodsurftempglac == 4) {
                                if (/*(percolationyes == 1) &&*/ (inter == 1)) { /*only first subtime step*/
                                    MELTsum[i][j] = 0.;
                                    ABLAsum[i][j] = 0.;
                                    RUNOFFsum[i][j] = 0.;
                                    SNOWsum[i][j] = 0.;
                                }
                                subsurf(); /*chr calculate new surface temperature field*/
                                waterequivalentabla();     /*** WATER EQUIVALENT ABLATION ***/
                                /* if (percolationyes == 1)*/
                                {
                                    ABLAsum[i][j] += ABLA[i][j];
                                    MELTsum[i][j] += MELT[i][j];
                                    RUNOFFsum[i][j] += RUNOFF[i][j];
                                    SNOWsum[i][j] += snowprec;
                                    sumSNOWprec[i][j] += snowprec;
                                    sumRAINprec[i][j] += rainprec;
                                }
                            }  /*endif method*/
                            /*============================================================*/

                            if(methodinisnow == 2)
                                snowcover();    /*compute how much snow is left*/

                            /*======= for SNOWMODEL by Carleen Tijm-Reijmer, 2/2005=======*/
                            if (methodsurftempglac == 4) {
                                changegrid();
                                if ((inter == factinter) &&
                                        ((int)((offsetsubsurfout+zeit)/factsubsurfout) == (offsetsubsurfout+zeit)/factsubsurfout))
                                    outputsubsurf();
                                if ((inter == factinter) && ((int)jd2 == (int)jdsurface[newday]) &&
                                        ((int)zeit == offsetsubsurfout) && (calcgridyes == 1))
                                    outputsubsurflines();
                            }
                            /*============================================================*/

                            if( (winterbalyes == 1) || (summerbalyes == 1) || (maxmeltstakes > 0))
                                if (griddgmglac[i][j] != nodata)   /*only for glacier, no matter if dgmdrain is larger*/
                                    massbalance();

                            /*============================================================*/

                            /*      if ((methodsurftempglac == 4) && (percolationyes == 1) && (inter == factinter)) */
                            if ((methodsurftempglac == 4) && (inter == factinter)) {
                                MELT[i][j] = MELTsum[i][j];
                                ABLA[i][j] = ABLAsum[i][j];
                                RUNOFF[i][j] = RUNOFFsum[i][j];
                            }

                            /********* OUTPUT ****/
                            if((do_out_area == 1) && (inter == factinter))  /*CHR added */
                                areasum();     /*** SUMMING UP ALL VALUES OVER AREA - for spatial means ***/

                        } /*endif notcalc*/

                    } /*endif griddgmdrain not nodata*/
                }  /*endfor next grid*/
        }/*END SUBTIMESTEP loop  for SNOWMODEL by Carleen Tijm-Reijmer, 2/2005*/

        /***------------------ NEXT GRID --------------------------------------------- ***/


        /*======= for SNOWMODEL by Carleen Tijm-Reijmer, 2/2005=======*/
        /*set back timestep to original value to be used in temporal mean calculations
          and in discharge functions; it was manipulated in interpolate()*/
        if (factinter > 1)
            timestep = timesteporig;
        /*============================================================*/


        if(methodglobal == 2)     /* direct and diffuse radiation separate */
            meanalbedo();    /*needed for extrapolation of diffuse radiation */
        /*needed every timestep, the value calculated for this time step will be used
          for the next time step, because otherwise, albedo and diffuse radiation could
          not be computed within the same grid cell loop, because the mean is needed
          for each grid cell before albedo has been calculated for the entire grid*/


        /*surftemp and longout may change by iteration, functions longinstationmeas and
          longinskyunobstructed are outside iteration loop, therefore the values obtained
          after iteration are used for next time step in these functions*/
        /*  if(methodsurftempglac == 2)
            surftempstationalt = surftemp[rowclim][colclim];
          if((methodlonginstation == 1) && (methodsurftempglac == 2))
            LWout = LONGOUT [rowclim][colclim];   */


        /*WHOLE GRIDS ARE CALCULATED FOR ONE TIME STEP -
            NOW CALCULATE DISCHARGE AND WRITE TO OUTPUTFILE*/
        /********************* DISCHARGE ************************/
        if (disyes >= 1) {   /*DISCHARGE TO BE CALCULATED, measured file available (1) or not (2)*/
            if(onlyglacieryes == 1)     /*drainage basin larger than glacier*/
                rainoutsideglac();      /*rain from outside put proportionally onto the glacier*/

            if (disyesopt == 0)      /*simulation run, no optimization*/
                discharge();    /*for every grid calculated discharge, sum to melt and sum discharge*/
            else                     /*optimization run*/
                dischargeopt();       /*calculate discharge for each parameter set*/
        }

        /*** WRITE MODEL RESULTS TO FILE FOR INDIVIDUAL GRIDPOINTS FOR EVERY TIME STEP ***/
        if (outgridnumber > 0)     /*output file requested by user*/
            stationoutput();


        /*** WRITE MELT FOR SEVERAL LOCATIONS TO ONE FILE ***/
        if(maxmeltstakes > 0)
            writemeltstakes();


        /*** WRITE GRID FILES ***/
        switch(do_out)   /*** WRITE ENERGY BALANCE GRID-OUTPUT-FILES ***/

        {
        case 0:
            break;
        case 1:     /*OUTPUT EVERY TIME STEP*/
            startwritehour();    /*open output-files for every time step*/
            writegridoutput();
            break;

        case 2:     /*OUTPUT ONLY EVERY DAY*/
            sumday();             /*sum up values for subdiurnal timesteps*/
            if (zeit == 24.0) {   /*last hour of day*/
                startwriteday();   /*open files for daily means*/
                writegridoutput(); /*write grid to output file*/
                meandaynull();     /*after writing initialize to zero*/
                if (methodsurftempglac == 4) meandaysnownull();
            }  /*if*/
            break;

        case 3:     /*OUTPUT ONLY FOR WHOLE PERIOD*/
            sumall();             /*sum up values for subdiurnal timesteps*/
            break;                /*mean for whole period : write at end*/

        case 4:     /*OUTPUT EVERY DAY AND FOR WHOLE PERIOD*/
            sumday();             /*sum up for daily means*/
            sumall();
            /*must be done before writing daily means to files, because
             MELT-array will be overwritten by daily mean, discharge must
             also be calculated before*/

            if (zeit == 24) {     /*daily means, write period means at end*/
                startwriteday();   /*open files for daily means*/
                writegridoutput();
                meandaynull();     /*after writing initialize to zero*/
                if (methodsurftempglac == 4) meandaysnownull();
            }  /*if*/
            break;
        } /*switch*/

        /*CHECK IF SURFACE CONDITIONS OR SNOW COVER FILES SHOULD BE WRITTEN TO OUTPUT*/
        /*    NO TEMPORAL MEANS POSSIBLE - FOR VALIDATION OF SNOW LINE RETREAT */
        writesnoworsurfaceyes();

        /* WRITE GRID OF SURFACE CONDITIONS - ONLY FOR MIDNIGHT EVERY daysnow-th DAY */
        /*   OR FOR SELECTED DAYS SPECIFIED IN input.dat*/

        if((surfyes >= 1) && (write2fileyes == 1) && (calcgridyes == 1))
            writesurface();      /*open file and write to file*/
        if((snowyes >= 1) && (write2fileyes == 1) && (calcgridyes == 1))
            writesnowcover();      /*open file and write to file*/

        /*  WRITE TO TIME SERIES ASCII FILE EVERY MIDNIGHT HOW MANY PIXELS SNOWFREE*/
        if((snowfreeyes == 1) && (zeit == 24) && (calcgridyes == 1))
            percentsnowfree();

        /* WRITE TIME SERIES OF SPATIAL MEAN MODEL RESULTS TO OUTPUT FOR EVERY TIME STEP*/
        if (do_out_area == 1)
            areameanwrite();

        /*write winter/summer/mass balance grids at end of winter/summer*/
        if((winterbalyes == 1) || (summerbalyes == 1))
            if((zeit == 24) && (calcgridyes == 1))    /*check at end of end*/
                writemassbalgrid();

        /*set snow array to zero at end of melt season for next mass balance year*/
        /*to avoid that snow constantly accumulates in accumulation area and therefore*/
        /*firn is never exposed; done each year at start of winter*/
        /*  if( (methodinisnow == 2) && (snow2zeroeachyearyes == 1) && (jd == (winterjdbeg-15)) && (zeit == 24) )*/
        if( (methodsurftempglac != 4) && (methodinisnow == 2) && (snow2zeroeachyearyes == 1) && (jd == (winterjdbeg)) && (zeit == 24))
            initializeglacier2zero_nodatadouble(SNOW);

        readclim();       /*** READ CLIMATE INPUT NEXT TIME STEP ****/

        /*DEFINE WHEN TO EXIT THE LOOP*/
        if(timestep != 24) {  /*subdaily timesteps: midnight row is next julian day not to continue with*/
            if((jd > (jdend+1)) && (year == yearend))
                stoploop = 1;
        } else   /*DAILY TIME STEPS*/
            if((jd == jdend+1) && (year == yearend))   /*otherwise last julian day would not be run*/
                stoploop = 1;

    }  while (stoploop != 1);
    /*====================== NEXT TIME STEP =======================================*/


    /*OUTPUT OF MEAN COMPONENTS OF ENERGY BALANCE FOR WHOLE PERIOD OF CALCULATION*/

    if ((do_out == 3) || (do_out == 4)) {   /*mean of whole period*/
        if (calcgridyes == 1) {
            startwriteall();   /*open files for whole period*/
            writegridoutput();
        }
    }

    /********** WRITE MEAN MASS BALANCE PROFILE TO FILE********************************/
    if(((winterbalyes == 1) || (summerbalyes == 1)) && (yearend > yearbeg))
        meanmassbalprofile();

    /******************************************************************/

    if (disyes == 1) {    /*only if discharge data available*/
        r2calc();
        r2calcln();
        if (disyesopt == 1)   /*optimization run*/
            write2matriz();    /*write r2 matriz to file*/
    }

    closeall();     /* CLOSE FILES, FREE STORAGE */

    printf("\n\n number of glacier grids         %d\n\n",nglac);
    printf(" number of calculated time steps               %d\n",nsteps);
    printf(" number of timesteps of discharge data available  %d\n\n",nstepsdis);
    printf(" output written to   %s\n\n",outpath);
    if((methodsurftempglac == 3) || (methodsurftempglac == 4))
        printf("\n unrealistic values reached = %d times (resoutlines) \n\n",resoutlines);

    printf("********* PROGRAM RUN COMPLETED ************\n\n");

    return 0;
}
Ejemplo n.º 17
0
int main()

{
    degreedaymethod = 1;
    ratio = startratio;

    /*----------------------------------------------------------------*/
    /*** READ DATA FROM CONTROLING INPUT FILE / INITIALISATION     ****/
    /*----------------------------------------------------------------*/

    input_read();      /*** READ INPUT DATA ***/    
    degreestart();
    startinputdata();  /***OPEN AND READ GRID FILES AND CLIMATE DATA until start***/
    checkgridinputdata_ok(); /*check if grid input data ok*/
    startoutascii();   /***OPEN ASCII-OUTPUT FILES AND WRITE HEADS***/
    startspecificmassbalance(); /*OPEN FILE FOR GLACIER-WIDE SEASONAL MASS BAL, MULTI-YEAR RUNS*/
    startarrayreserve();   /*RESERVE STORAGE FOR GRID-ARRAYS*/
    glacierrowcol();  /*FIND FIRST, LAST ROW AND COLUMN WHICH IS GLACIERIZED IN DTM*/
    readclim();       /*** READ CLIMATE INPUT FIRST ROW = ONE TIME STEP ****/

    if((winterbalyes == 1) || (summerbalyes == 1))
        areaelevationbelts();    /*number of grid cells per elevation band, for bn profiles*/

    if(maxmeltstakes > 0)
        startmeltstakes();    /*OUTPUT OF MELT OF SEVERAL LOCATIONS - COMPARISON WITH STAKES*/

    if(snowfreeyes == 1)    /*OPEN FILE WITH TIME SERIES WITH NUMBER OF SNOWFREE PIXELS PER DAY*/
        opensnowfree();

    if((datesfromfileyes == 1) &&  (winterbalyes == 1) && (summerbalyes == 1))
        readdatesmassbal();      /*READ DATES OF MASS BAL MEASUREMENTS FOR EACH YEAR*/

    if(methodprecipinterpol == 2)    /*read precipitation index map once (constant in time)*/
        readprecipindexmap();        /*in turbul.c under precipitation*/

    if (disyes >= 1)        /*DISCHARGE SIMULATION REQUESTED, 1=discharge data, 2=no data*/
        startdischarg();     /*INITIALIZE DISCHARGE SIMULATION*/

/*printf("==============ddmethod in detim.c = %d ===================\n",ddmethod);*/

    /*=============FOR EVERY TIME STEP ===============================================*/

    do {

        nsteps += 1;         /*number of time steps of period calculated*/

        /******* ADJUST BY USER, HOW OFTEN OUTPUT JD-TIME TO SCREEN *******/
        if((zeit==24) && (jd/daysscreenoutput == floor((int)jd/daysscreenoutput)))
            printf("\n  yr= %4.0f  jd = %4.2f   time =%3.0f  number of time steps=%d",year,jd,zeit,nsteps);


        /******* TEMPERATURE INTERPOLATION ******/
        tempinterpol(); /*** ELEVATION-DEPENDENT AIR TEMP INTERPOLATION ***/

        if(do_out_area == 1)
            areameannull();  /* SPATIAL MEANS OF MODEL OUTPUT SET TO ZERO */

        if(ddmethod > 1) {    /*DIRECT RAD NOT NEEDED FOR SIMPLE DEGREE DAY*/
            if (directfromfile == 0)
                schatten();      /*** CALCULATE SHADE, CORRECTION FACTOR, DIRECT GRIDs ***/
            else
                readdirect();    /* READ DIRECT RADIATION (slope corrected) FROM FILE */
        }

        if(methodinisnow == 1)  /*NEEDED FOR DISCHARGE CALCULATIONS FOR ANY ddmethod*/
            albedoread();   /* OPEN AND READ SPECIFIC ALBEDO FILE IF NEW ONE VALID FOR TIME STEP */
        else
            whichsurface();   /*VALUE FOR ARRAY surface (SNOW,FIRN,ICE,ROCK) ICE/SNOW DDF AND K-VALUES*/

        /*EXTENDED TEMP INDEX METHOD WITH DIRECT RAD AND CLOUD REDUCTION*/
        if(ddmethod == 3)
            ratioglobal();   /*CALC RATIO OF MEASURED GLOBAL RAD AND CALCULATED DIRECT RAD*/

        if(methodprecipinterpol == 3)   /*read precipitation grids from file for each time step*/
            readprecipfromfile();


/*------- FOR EACH GRID POINT - only for drainage basin grid (DEM 2 defines the area to be computed)--*/

        for (i=firstrow; i<=lastrow; i++)           /*for all rows with area to be calculated*/
            for (j=firstcol[i]; j<=lastcol[i]; j++) {  /*for all columns*/

                if (griddgmdrain[i][j] != nodata) { /*only for area to be calculated defined by dgmdrain*/
                    if (griddgmdrain[i][j] != griddgm[i][j]) {
                        printf("\n\n ERROR elevation in DTM is not the same as in drainage grid\n");
                        printf("	 row  %d  col  %d      (function meltmod.c\n\n",i,j);
                        exit(12);
                    }

                    temppos();      /*** copying interpolated temp into positive temp-grid ***/
                    airpress();     /*** CALCULATION AIR PRESSURE AT GRID POINT         ***/
                    vappress();     /*** CALCULATION VAPOUR PRESSURE FROM REL. HUMIDITY ***/

                    /*==================================================================*/

                    switch(ddmethod)
                    {
                    case 1:
                        degreedaymelt();    /*CALCULATING MELT WITH DEGREE DAY*/
                        break;
                    case 2:
                        dd_directmelt();    /*INCLUDING DIRECT RADIATION (J.Glac. 1999)*/
                        break;
                    case 3:
                        dd_directglobal();  /*AS BUT INCLUDING GLOBAL RAD (J.GLAC 1999)*/
                        break;

                    default:
                        printf("\n ERROR: No temperature index method (ddmethod) defined\n");
                        printf("       ddmethod should be 1, 2 or 3 (printed from detim.c)\n");
                        exit(20);
                    }

                    /*==================================================================*/

                    ddfcalculation();    /*CALCULATE CORRESPONDING DEGREE DAY MELT/TEMPOS*/

                    /******* PRECIPITATION *********************/
                    precipinterpol();

                    if(methodinisnow == 2)      /*run with known initial snow cover*/
                        snowcoverdegree();       /*snow precip added to snow cover, to find k-values*/

                    if (griddgmglac[i][j] != nodata)   /*only for glacier, no matter if dgmdrain is larger*/
                            massbalance();    /*compute mass balance in any case, used for areamean output*/

                    /*** SUMMING UP ALL VALUES OVER AREA - for spatial means ***/
                    if(do_out_area == 1)
                        areasum();

                } /*endif*/
            }  /*endfor next grid*/


/***------------------ NEXT GRID CELL--------------------------------------------- ***/

        /*WHOLE GRIDS ARE CALCULATED FOR ONE TIME STEP -
           NOW CACULATE DISCHARGE AND WRITE TO OUTPUTFILE*/

        /********************* DISCHARGE ************************/

        if (disyes >= 1) {   /*DISCHARGE TO BE CALCULATED, measured file available (1) or not (2)*/
            if(onlyglacieryes == 1)  /*drainage basin larger than glacier*/
                rainoutsideglac();       /*rain from outside put onto the glacier, discharg.c*/

            if (disyesopt == 0)       /*simulation run*/
                discharge();    /*for every grid calculated discharge, sum to melt and sum discharge*/

            if (disyesopt == 1)     /*optimization run, disyes set to 1 in input.c*/
                dischargeopt();       /*calculated discharg, with optimal r2-criterium*/
        }
 
        /*** WRITE MODEL RESULTS TO FILE FOR INDIVIDUAL GRIDPOINTS FOR EVERY TIME STEP ***/
        if (outgridnumber > 0)     /*output file requested by user*/
            stationoutput();

        /*** WRITE MASS BALANCE FOR SEVERAL LOCATIONS TO ONE FILE ***/
        if(maxmeltstakes > 0)
            writemeltstakes();

        /*** WRITE GRID FILES ***/
        switch(do_out)   /*** WRITE ENERGY BALANCE GRID-OUTPUT-FILES ***/

        {
        case 0:
            break;
        case 1:     /*OUTPUT EVERY TIME STEP*/
            startwritehour();    /*open output-files for every time step*/
            writegridoutput();
            break;

        case 2:     /*OUTPUT ONLY EVERY DAY*/
            sumday();             /*sum up values for subdiurnal timesteps*/
            if (zeit == 24.0) {   /*last hour of day*/
                startwriteday();   /*open files for daily means*/
                writegridoutput(); /*write grid to output file*/
                meandaynull();     /*after writing initialize to zero*/
            }  /*if*/
            break;

        case 3:     /*OUTPUT ONLY FOR WHOLE PERIOD*/
            sumall();             /*sum up values for subdiurnal timesteps*/
            break;                /*mean for whole period : write at end*/

        case 4:     /*OUTPUT EVERY DAY AND FOR WHOLE PERIOD*/
            sumday();             /*sum up for daily means*/
            sumall();             /*sum up for period means*/
            /*must be done before writing daily means to files, because
              MELT-array will be overwritten by daily mean, discharge must
              also be calculated before*/
            if (zeit == 24) {     /*daily means, write period means at end*/
                startwriteday();   /*open files for daily means*/
                writegridoutput();
                meandaynull();     /*after writing initialize to zero*/
            }  /*if*/
        } /*switch*/


        /*CHECK IF SURFACE CONDITIONS OR SNOW COVER FILES SHOULD BE WRITTEN TO OUTPUT*/
        /*    NO TEMPORAL MEANS POSSIBLE - FOR VALIDATION OF SNOW LINE RETREAT */
        writesnoworsurfaceyes();

        /* WRITE GRID OF SURFACE CONDITIONS - ONLY FOR MIDNIGHT EVERY daysnow-th DAY */
        /*   OR FOR SELECTED DAYS SPECIFIED IN input.dat*/

        if((surfyes >= 1) && (write2fileyes == 1))
            writesurface();      /*open file and write to file*/
        if((snowyes >= 1) && (write2fileyes == 1))
            writesnowcover();      /*open file and write to file*/

        /*  WRITE TO TIME SERIES ASCII FILE EVERY MIDNIGHT HOW MANY PIXELS SNOWFREE*/
        if((snowfreeyes == 1) && (zeit == 24))
            percentsnowfree();

        /* WRITE TIME SERIES OF SPATIAL MEAN MODEL RESULTS TO OUTPUT FOR EVERY TIME STEP*/
        if (do_out_area == 1)
            areameanwrite();

        /*write winter/summer/mass balance grids at end of winter/summer*/
        if((winterbalyes == 1) || (summerbalyes == 1))
            if(zeit == 24)
                writemassbalgrid();    /*balance grids are in arrays WINTERBAL, SUMMERBAL*/

        /********** Glacier geometry changes updated only once a year at end of summer **********************************/
    if((jd == summerjdend) && (retreatyes >= 1) && (zeit == 24) )
	 { if( (datesfromfileyes == 0) || ( (datesfromfileyes == 1) && (year == nextyear))) 
	    { switch(retreatyes)	      
	      { case 1:     /*V-A scaling*/
		      scaling();
		      break;
	        case 2:     /*Huss et al. 2010, NEW Aug 2015*/
		      retreat_Huss();
		      break;
	        case 3:     /*Truessel et al. 2015, JGlac, not implemented yet*/
		      break;
	        default:
		  printf("\n no retreat method defined (retreatyes=%d)\n  (Message send from detim.c\n",retreatyes);
                    exit(20);
	      }  /*end switch*/
	     } /*if*/
	    n_retreatyears += 1;  /*count number of years retreat is computed*/
	 } /*if retreat calculation*/


        /**********/
        /*set snow array to zero at end of melt season for next mass balance year*/
        /*to avoid that snow constantly accumulates in accumulation area and therefore*/
        /*firn is never exposed; done each year at start of winter*/
        if( (methodinisnow == 2) && (snow2zeroeachyearyes == 1) && (jd == (winterjdbeg)) && (zeit == 24) )
            initializeglacier2zero_nodatadouble(nrows, ncols, SNOW);

        readclim();       /*** READ CLIMATE INPUT NEXT TIME STEP ****/

        if(timestep != 24) {  /*subdaily timesteps: midnight row is next julian day not to continue with*/
            if((jd > (jdend+1)) && (year == yearend))
                stoploop = 1;
        } else if((jd == jdend+1) && (year == yearend)) /*otherwise last julian day would not be run*/
            stoploop = 1;

    }  while (stoploop != 1);

    /*====================== NEXT TIME STEP =======================================*/

    /*OUTPUT OF MEAN COMPONENTS OF ENERGY BALANCE FOR WHOLE PERIOD OF CALCULATION*/

    if ((do_out == 3) || (do_out == 4)) {   /*mean of whole period*/
        startwriteall();   /*open files for whole period*/
        writegridoutput();
    }

    /********** WRITE MEAN MASS BALANCE PROFILE TO FILE********************************/
        /* only if glacier area is constant*/
    if(((winterbalyes == 1) || (summerbalyes == 1)) && (retreatyes = 0))
        meanmassbalprofile();     /*mean over all years*/

    /******************************************************************/

    if (disyes == 1) {    /*only if discharge data available*/
        r2calc();
        r2calcln();
        if (disyesopt == 1)   /*optimization run*/
            write2matriz();    /*write r2 matriz to file*/
    }

	writeperformance();   /*write model performance (r2 etc) to text-file, added 10/2013*/
    closeall();     /* CLOSE FILES, SPEICHERFREIGABE */
    writemodelmeaspointbalances();    /*must be after closeall because it opens cummassbal.txt, added 10/2013*/
    fclose(outcontrol);    /*can not be in closeall.c because used in writemodelmeaspointbalances()*/
    outcontrol = NULL;

    printf("\n number of calculated grid cells (DEM2)  = %d\n",ndrain);
	printf(" number of glacier grid cells (DEM3)     =  %d\n",nglac);
	printf("   number of calculated time steps       = %d\n",nsteps);
    printf("   number of timesteps of discharge data = %d\n",nstepsdis);
    if(disyes ==1) {
        printf(" Simulated discharge volume (100 000 m3) = %8.2f\n",volumesim);
        printf(" Measured discharge volume               = %8.2f\n",volumemeas);
    }
    printf(" Mass balance over entire simulation period (m) = %.3f\n",areamassbalcum/100);

    printf("\n output written to   %s\n\n",outpath);
    printf("********* PROGRAM RUN COMPLETED ************\n\n");

    return 0;
}