Exemplo n.º 1
0
static void output_add_key( const ecl_sum_type * refcase , output_type * output , const char * qkey) {
  int tokens;
  double  quantile;
  char ** tmp;
  char  * sum_key;

  util_split_string( qkey , SUMMARY_JOIN , &tokens , &tmp);
  if (tokens == 1)
    util_exit("Hmmm - the key:%s is malformed - must be of the form SUMMARY_KEY:QUANTILE.\n",qkey);

  if (!util_sscanf_double( tmp[tokens - 1] , &quantile))
    util_exit("Hmmmm - failed to interpret:%s as a quantile - must be a number (0,1).\n",tmp[tokens-1]);

  if (quantile <= 0 || quantile >= 1.0)
    util_exit("Invalid quantile value:%g - must be in interval (0,1)\n", quantile);

  sum_key = util_alloc_joined_string( (const char **) tmp , tokens - 1 , SUMMARY_JOIN);
  {
    stringlist_type * matching_keys = stringlist_alloc_new();
    int i;
    ecl_sum_select_matching_general_var_list( refcase , sum_key , matching_keys );
    for (i=0; i < stringlist_get_size( matching_keys ); i++)
      vector_append_owned_ref( output->keys , quant_key_alloc( stringlist_iget( matching_keys , i ) , quantile) , quant_key_free__ );

    if (stringlist_get_size( matching_keys ) == 0)
      fprintf(stderr,"** Warning: No summary vectors matching:\'%s\' found?? \n", sum_key);
    stringlist_free( matching_keys );
  }

  util_free_stringlist( tmp, tokens );
}
Exemplo n.º 2
0
bool analysis_module_get_bool( const analysis_module_type * module , const char * var) {
  if (analysis_module_has_var( module , var )) {
    if (module->get_bool != NULL)
      return module->get_bool( module->module_data , var );
    else
      util_exit("%s: Tried to get bool variable:%s from module:%s - get_int() method not implemented for this module\n" , __func__ , var , module->user_name);
  } else 
    util_exit("%s: Tried to get bool variable:%s from module:%s - module does not support this variable \n" , __func__ , var , module->user_name);

  return false;
}
Exemplo n.º 3
0
void * analysis_module_get_ptr( const analysis_module_type * module , const char * var) {
  if (analysis_module_has_var( module , var )) {
    if (module->get_double != NULL)
      return module->get_ptr( module->module_data , var );
    else
      util_exit("%s: Tried to get pointer variable:%s from module:%s - get_ptr() method not implemented for this module\n" , __func__ , var , module->user_name);
  } else 
    util_exit("%s: Tried to get pointer variable:%s from module:%s - module does not support this variable \n" , __func__ , var , module->user_name);
  
  return NULL;
}
Exemplo n.º 4
0
void ensemble_init( ensemble_type * ensemble , config_type * config) {

  /*1 : Loading ensembles and settings from the config instance */
  /*1a: Loading the eclipse summary cases. */
  {
    thread_pool_type * tp = thread_pool_alloc( LOAD_THREADS , true );
    {
      int i,j;
      for (i=0; i < config_get_occurences( config , "CASE_LIST"); i++) {
        const stringlist_type * case_list = config_iget_stringlist_ref( config , "CASE_LIST" , i );
        for (j=0; j < stringlist_get_size( case_list ); j++) 
          ensemble_load_from_glob( ensemble , stringlist_iget( case_list , j ) , tp);
      }
    }
    thread_pool_join( tp );
    thread_pool_free( tp );
  }
  
  {
    const sum_case_type * tmp = vector_iget_const( ensemble->data , 0 );
    ensemble->refcase = tmp->ecl_sum;
  }
  
  /*1b: Other config settings */
  if (config_item_set( config , "NUM_INTERP" ))
    ensemble->num_interp  = config_iget_as_int( config , "NUM_INTERP" , 0 , 0 );
  
  
  /*2: Remaining initialization */
  ensemble_init_time_interp( ensemble );
  if (vector_get_size( ensemble->data ) < MIN_SIZE )
    util_exit("Sorry - quantiles make no sense with with < %d realizations; should have ~> 100.\n" , MIN_SIZE);
}
Exemplo n.º 5
0
void ensemble_config_init_SUMMARY( ensemble_config_type * ensemble_config , const config_type * config , const ecl_sum_type * refcase) {
  const config_content_item_type * item = config_get_content_item( config , SUMMARY_KEY );

  if (item != NULL) {
    int i;
    for (i=0; i < config_content_item_get_size( item ); i++) {
      const config_content_node_type * node = config_content_item_iget_node( item , i );
      int j;
      for (j= 0; j < config_content_node_get_size( node ); j++) {
        const char * key = config_content_node_iget( node , j );
        
        if (util_string_has_wildcard( key )) {
          if (ensemble_config->refcase != NULL) {
            int k;
            stringlist_type * keys = stringlist_alloc_new ( );

            ecl_sum_select_matching_general_var_list( ensemble_config->refcase , key , keys );   /* expanding the wildcard notatition with help of the refcase. */
            for (k=0; k < stringlist_get_size( keys ); k++) 
              ensemble_config_add_summary(ensemble_config , stringlist_iget(keys , k) , LOAD_FAIL_SILENT );

            stringlist_free( keys );
          } else
            util_exit("error: when using summary wildcards like: \"%s\" you must supply a valid refcase.\n",key);
        } else 
          ensemble_config_add_summary(ensemble_config , key , LOAD_FAIL_SILENT);
      }
    }
  }
}
Exemplo n.º 6
0
void ecl_config_assert_restart( const ecl_config_type * ecl_config ) {
  if (!ecl_config_can_restart(ecl_config)) {
    fprintf(stderr,"** Warning - tried to restart case which is not properly set up for restart.\n");
    fprintf(stderr,"** Need <INIT> in datafile and INIT_SECTION keyword in config file.\n");
    util_exit("%s: exiting \n",__func__);
  }
}
Exemplo n.º 7
0
void enkf_tui_util_scanf_report_steps(int last_report , int prompt_len , int * __step1 , int * __step2) {
  char * prompt = util_alloc_sprintf("Report steps (0 - %d)" , last_report);
  bool OK = false;

  util_printf_prompt(prompt , prompt_len , '=' , "=> ");
  
  while (!OK) {
    char * input = util_alloc_stdin_line();
    const char * current_ptr = input;
    int step1 , step2;
    OK = true;
    if(input == NULL){
      step1=0;
      step2=last_report;
    }
    else{
      current_ptr = util_parse_int(current_ptr , &step1 , &OK);
      current_ptr = util_skip_sep(current_ptr , " ,-:" , &OK);
      current_ptr = util_parse_int(current_ptr , &step2 , &OK);
    }
    if (!OK) 
      printf("Failed to parse two integers from: \"%s\". Example: \"0 - 19\" to get the 20 first report steps.\n",input);
    free(input);

    step1 = util_int_min(step1 , last_report);
    step2 = util_int_min(step2 , last_report);
    if (step1 > step2) 
      util_exit("%s: ohh come on - must have a finite interval forward in time - no plots for you.\n",__func__);
    *__step1 = step1;
    *__step2 = step2;
    
  }
  free(prompt);
}
Exemplo n.º 8
0
int main(int argc , char ** argv) {
  const int queue_timeout =  180;
  const int submit_timeout = 180;
  const int status_timeout = 180;
  const int number_of_jobs = 250;
  const int submit_threads = number_of_jobs / 10 ;
  const int status_threads = number_of_jobs + 1;
  const char * job = util_alloc_abs_path(argv[1]);
  rng_type * rng = rng_alloc( MZRAN , INIT_CLOCK );
  test_work_area_type * work_area = test_work_area_alloc("job_queue");
  job_type **jobs = alloc_jobs( rng , number_of_jobs , job);

  job_queue_type * queue = job_queue_alloc(number_of_jobs, "OK", "ERROR");
  queue_driver_type * driver = queue_driver_alloc_local();
  job_queue_manager_type * queue_manager = job_queue_manager_alloc( queue );

  job_queue_set_driver(queue, driver);
  job_queue_manager_start_queue(queue_manager, 0, false , true);

  {
    thread_pool_type * status_pool = thread_pool_alloc( status_threads , true );
    thread_pool_type * submit_pool = thread_pool_alloc( submit_threads , true );

    submit_jobs( queue , number_of_jobs , jobs , submit_pool );
    status_jobs( queue , number_of_jobs , jobs , status_pool );

    if (!thread_pool_try_join( submit_pool , submit_timeout ))
      util_exit("Joining submit pool failed \n");
    thread_pool_free( submit_pool );

    job_queue_submit_complete(queue);

    if (!thread_pool_try_join( status_pool , status_timeout))
      util_exit("Joining status pool failed \n");
    thread_pool_free( status_pool );
  }

  if (!job_queue_manager_try_wait(queue_manager , queue_timeout))
    util_exit("job_queue never completed \n");

  job_queue_manager_free(queue_manager);
  job_queue_free(queue);
  queue_driver_free(driver);
  check_jobs( number_of_jobs , jobs );
  test_work_area_free(work_area);
  rng_free( rng );
}
Exemplo n.º 9
0
int main(int argc , char ** argv) {
  if (argc == 1)
    util_exit("ecl_unpack UNIFIED_FILE1   UNIFIED_FILE2   ...\n");
  {
    int iarg;
    for (iarg = 1; iarg < argc; iarg++)
      unpack_file( argv[iarg] );
  }
}
Exemplo n.º 10
0
int main(int argc, char *argv[])
{
	int i;
	
	util_init();

	cpld_version();
	
//	return *((char *)(map_base+CPLD_VER));	
//	*((char *)(map_base+CONTROL_OFFSET3)) |= ETH_CPU_DIS;	
	util_exit();
}
Exemplo n.º 11
0
static void site_config_install_job_queue(site_config_type  * site_config ) {
  if (site_config->job_script == NULL)
    util_exit("Must set the path to the job script with the %s key in the site_config / config file\n",JOB_SCRIPT_KEY);
  
  site_config->job_queue = job_queue_alloc(site_config->max_submit , "OK" , "ERROR" );

  /* 
     All the various driver options are set, unconditionally of which
     driver is actually selected in the end.
  */
  site_config_set_job_queue__( site_config , site_config->driver_type );
}
Exemplo n.º 12
0
Arquivo: main.c Projeto: pgdr/ert
/*
  GIT_COMMIT and COMPILE_TIME_STAMP are env variables set by the
  makefile. Will exit if the config file does not exist.
*/
void enkf_welcome(const char * config_file) {
  if (util_file_exists(config_file)) {
    char * abs_path              = util_alloc_realpath(config_file);
    char * config_file_msg       = util_alloc_sprintf("Configuration file...: %s \n",abs_path);

    /* This will be printed if/when util_abort() is called on a later stage. */
    /* The svn_version and compile_time are added with the functione enkf_main_init_debug(). */
    util_abort_append_version_info(config_file_msg);

    free(config_file_msg);
    free(abs_path);
  } else util_exit(" ** Sorry: can not locate configuration file: %s \n\n", config_file);
}
Exemplo n.º 13
0
void output_save( const output_type * output , ensemble_type * ensemble , const double ** data ) {
  switch( output->format ) {
  case(S3GRAPH):
    output_save_S3Graph( output , ensemble , data );
    break;
  case(PLAIN):
    output_save_plain__( output , ensemble , data , false);
    break;
  case(HEADER):
    output_save_plain__( output , ensemble , data , true);
    break;
  default:
    util_exit("Sorry: output_format:%d not supported \n", output->format );
  }
}
Exemplo n.º 14
0
static void field_config_set_output_transform( field_config_type * config , const char * __output_transform_name ) {
    const char * output_transform_name = NULL;
    if (field_trans_table_has_key( config->trans_table , __output_transform_name))
        output_transform_name = __output_transform_name;
    else if (__output_transform_name) {
        fprintf(stderr , "Sorry: the field transformation function:%s is not recognized \n\n",__output_transform_name);
        field_trans_table_fprintf(config->trans_table , stderr);
        util_exit("Exiting ... \n");
    }

    config->output_transform_name = util_realloc_string_copy( config->output_transform_name , output_transform_name );
    if (output_transform_name != NULL)
        config->output_transform = field_trans_table_lookup( config->trans_table , output_transform_name);
    else
        config->output_transform = NULL;
}
Exemplo n.º 15
0
void enkf_main_select_fs( enkf_main_type * enkf_main , const char * case_path ) {
    if (enkf_main_case_is_current( enkf_main , case_path ))
        return;  /* We have tried to select the currently selected case - just return. */
    else {
        enkf_fs_type * new_fs = enkf_main_mount_alt_fs( enkf_main , case_path , true );
        if (enkf_main->dbase == new_fs)
            util_abort("%s : return reference to current FS in situation where that should not happen.\n",__func__);

        if (new_fs != NULL)
            enkf_main_set_fs( enkf_main , new_fs , case_path);
        else {
            const char * ens_path = model_config_get_enspath( enkf_main->model_config );
            util_exit("%s: select filesystem %s:%s failed \n",__func__ , ens_path , case_path );
        }
        enkf_fs_decref( new_fs );
    }
}
Exemplo n.º 16
0
Arquivo: main.c Projeto: pgdr/ert
int main (int argc, char ** argv) {
  text_splash();
  init_debug(argv[0]);
  printf("\n");
  printf("Documentation : %s \n","http://ert.nr.no");
  printf("git commit    : %s \n",ert_version_get_git_commit( ));
  printf("compile time  : %s \n",ert_version_get_build_time( ));
  printf("site config   : %s \n", site_config_get_location());

  enkf_main_install_SIGNALS();                     /* Signals common to both tui and gui. */
  signal(SIGINT, util_abort_signal);              /* Control C - tui only.               */
  if (argc < 2) {
    enkf_usage();
    exit(1);
  } else {
    const char * model_config_file = argv[1];
    stringlist_type * workflow_list = stringlist_alloc_new();

    parse_workflows(argc, argv, workflow_list);
    if (!(util_entry_readable(model_config_file) && util_is_file(model_config_file)))
      util_exit("Can not read file %s - exiting \n", model_config_file);

    {
      char * abs_config = util_alloc_realpath(model_config_file);
      printf("model config  : %s \n\n", abs_config);
      free(abs_config);
    }
    enkf_welcome(model_config_file);
    {
      res_config_type * res_config = res_config_alloc_load(model_config_file);
      util_chdir( res_config_get_config_directory( res_config ));
      {
        enkf_main_type * enkf_main = enkf_main_alloc(res_config, true, true);
        enkf_main_run_workflows(enkf_main, workflow_list);
        enkf_tui_main_menu(enkf_main);
        enkf_main_free(enkf_main);
        res_config_free(res_config);
      }
    }

    stringlist_free(workflow_list);
    util_abort_free_version_info(); /* No f*****g leaks ... */
  }
  exit(0);
}
Exemplo n.º 17
0
const char * member_config_update_eclbase(member_config_type * member_config , const ecl_config_type * ecl_config , const subst_list_type * subst_list) {
  util_safe_free( member_config->eclbase );
  {
    const path_fmt_type * eclbase_fmt = ecl_config_get_eclbase_fmt(ecl_config);
    if (eclbase_fmt != NULL) {
      {
        char * tmp = path_fmt_alloc_path(eclbase_fmt , false , member_config->iens);
        member_config->eclbase = subst_list_alloc_filtered_string( subst_list , tmp );
        free( tmp );
      }

      if (!ecl_util_valid_basename( member_config->eclbase )) 
        util_exit("Sorry - the basename:%s is invalid. ECLIPSE does not handle mIxeD cAsE :-( \n" , member_config->eclbase);
    }
  }
  
  return member_config->eclbase;
}
Exemplo n.º 18
0
int main(int argc, char ** argv) {
  if (argc < 4) {
    fprintf(stderr,"%s  src_file target_file kw1 kw2 kw3 \n",argv[0]);
    exit(0);
  }
  {
    const char *  src_file   = argv[1];
    const char * target_file = argv[2];
    const char ** kw_list    = (const char **) &argv[3];
    int num_kw               = argc - 3;
    fortio_type * fortio_src;
    fortio_type * fortio_target;
    bool fmt_src , fmt_target;
    set_type    * kw_set = set_alloc( num_kw , kw_list );
    
    if (!ecl_util_fmt_file(src_file, &fmt_src))
      util_exit("Hmm - could not determine formatted/unformatted status for:%s \n",src_file);
    
    fmt_target        = fmt_src;                         /* Can in principle be different */
    fortio_src        = fortio_open_reader(src_file     , fmt_src , ECL_ENDIAN_FLIP);
    fortio_target     = fortio_open_writer(target_file , fmt_target , ECL_ENDIAN_FLIP);

    {
      ecl_kw_type * ecl_kw = ecl_kw_alloc_empty();
      while (true) {
        if (ecl_kw_fread_header( ecl_kw , fortio_src )) {
          const char * header = ecl_kw_get_header( ecl_kw ); 
          if (set_has_key( kw_set , header )) {
            ecl_kw_fread_realloc_data(ecl_kw , fortio_src );
            ecl_kw_fwrite( ecl_kw , fortio_target );
          } else
            ecl_kw_fskip_data( ecl_kw , fortio_src );
        } else 
          break; /* We have reached EOF */
      }
      ecl_kw_free( ecl_kw );
    }
    
    fortio_fclose(fortio_src);
    fortio_fclose(fortio_target);
    set_free( kw_set );
  }
}
Exemplo n.º 19
0
gen_data_file_format_type gen_data_config_check_format( const void * format_string ) {
  gen_data_file_format_type type = GEN_DATA_UNDEFINED;
  
  if (format_string != NULL) {
    
    if (strcmp(format_string , "ASCII") == 0)
      type = ASCII;
    else if (strcmp(format_string , "ASCII_TEMPLATE") == 0)
      type = ASCII_TEMPLATE;
    else if (strcmp(format_string , "BINARY_DOUBLE") == 0)
      type = BINARY_DOUBLE;
    else if (strcmp(format_string , "BINARY_FLOAT") == 0)
      type = BINARY_FLOAT;
    
    if (type == GEN_DATA_UNDEFINED)
      util_exit("Sorry: format:\"%s\" not recognized - valid values: ASCII / ASCII_TEMPLATE / BINARY_DOUBLE / BINARY_FLOAT \n", format_string);
  }
  
  return type;
}
Exemplo n.º 20
0
trans_func_type * trans_func_alloc( const char * func_name ) {
  trans_func_type * trans_func = trans_func_alloc_empty( func_name );
  {
    if (util_string_equal(func_name , "NORMAL")) {
      stringlist_append_ref( trans_func->param_names , "MEAN");
      stringlist_append_ref( trans_func->param_names , "STD" );
      arg_pack_append_double( trans_func->params , 0 );
      arg_pack_append_double( trans_func->params , 0 );
      trans_func->func = trans_normal;
    }  
    
    if (util_string_equal( func_name , "LOGNORMAL")) {
      stringlist_append_ref( trans_func->param_names , "MEAN");
      stringlist_append_ref( trans_func->param_names , "STD" );
      arg_pack_append_double( trans_func->params , 0 );
      arg_pack_append_double( trans_func->params , 0 );
      trans_func->func = trans_lognormal;
    }
    
    if (util_string_equal( func_name , "UNIFORM")) {
      stringlist_append_ref( trans_func->param_names , "MIN");
      stringlist_append_ref( trans_func->param_names , "MAX" );
      arg_pack_append_double( trans_func->params , 0 );
      arg_pack_append_double( trans_func->params , 0 );
      trans_func->func = trans_unif;
    }


    if (util_string_equal( func_name , "DUNIF")) {
      stringlist_append_ref( trans_func->param_names , "STEPS");
      stringlist_append_ref( trans_func->param_names , "MIN");
      stringlist_append_ref( trans_func->param_names , "MAX" );
      arg_pack_append_int( trans_func->params , 0 );
      arg_pack_append_double( trans_func->params , 0 );
      arg_pack_append_double( trans_func->params , 0 );
      
      trans_func->func = trans_dunif;
    }


    if (util_string_equal( func_name , "ERRF")) {
      stringlist_append_ref( trans_func->param_names , "MIN");
      stringlist_append_ref( trans_func->param_names , "MAX" );
      stringlist_append_ref( trans_func->param_names , "SKEWNESS");
      stringlist_append_ref( trans_func->param_names , "WIDTH" );
      arg_pack_append_double( trans_func->params , 0 );
      arg_pack_append_double( trans_func->params , 0 );
      arg_pack_append_double( trans_func->params , 0 );
      arg_pack_append_double( trans_func->params , 0 );

      trans_func->func = trans_errf;
    }
    

    if (util_string_equal( func_name , "DERRF")) {
      stringlist_append_ref( trans_func->param_names , "STEPS");
      stringlist_append_ref( trans_func->param_names , "MIN");
      stringlist_append_ref( trans_func->param_names , "MAX" );
      stringlist_append_ref( trans_func->param_names , "SKEWNESS");
      stringlist_append_ref( trans_func->param_names , "WIDTH" );
      arg_pack_append_int( trans_func->params , 0 );
      arg_pack_append_double( trans_func->params , 0 );
      arg_pack_append_double( trans_func->params , 0 );
      arg_pack_append_double( trans_func->params , 0 );
      arg_pack_append_double( trans_func->params , 0 );

      trans_func->func = trans_derrf;
    }


    if (util_string_equal( func_name , "LOGUNIF")) {
      stringlist_append_ref( trans_func->param_names , "MIN");
      stringlist_append_ref( trans_func->param_names , "MAX" );
      
      arg_pack_append_double( trans_func->params , 0 );
      arg_pack_append_double( trans_func->params , 0 );
      trans_func->func = trans_logunif;
    }


    if (util_string_equal( func_name , "CONST")) {
      stringlist_append_ref( trans_func->param_names , "VALUE");
      arg_pack_append_double( trans_func->params , 0 );
      trans_func->func = trans_const;
    }
    
    if (util_string_equal( func_name , "NONE")) 
      trans_func->func = trans_const;


    if (trans_func->func == NULL) 
      util_exit("%s: Sorry: function name:%s not recognized \n",__func__ , func_name);
  }
  return trans_func;
}
Exemplo n.º 21
0
void ecl_config_init( ecl_config_type * ecl_config , const config_type * config ) {
  if (config_item_set( config , ECLBASE_KEY ))
    ecl_config_set_eclbase( ecl_config , config_iget(config , ECLBASE_KEY ,0,0) );
  
  if (config_item_set( config , DATA_FILE_KEY ))
    ecl_config_set_data_file( ecl_config , config_iget( config , DATA_FILE_KEY ,0,0));
  
  if (config_item_set( config , SCHEDULE_FILE_KEY ))
    ecl_config_set_schedule_file( ecl_config , config_iget( config , SCHEDULE_FILE_KEY ,0,0));

  
  if (config_item_set(config , GRID_KEY))
    ecl_config_set_grid( ecl_config , config_iget(config , GRID_KEY , 0,0) );
  
  if (config_item_set( config , ADD_FIXED_LENGTH_SCHEDULE_KW_KEY)) {
    int iocc;
    for (iocc = 0; iocc < config_get_occurences(config , ADD_FIXED_LENGTH_SCHEDULE_KW_KEY); iocc++) 
      ecl_config_add_fixed_length_schedule_kw( ecl_config , 
                                               config_iget(config , ADD_FIXED_LENGTH_SCHEDULE_KW_KEY , iocc , 0) , 
                                               config_iget_as_int(config , ADD_FIXED_LENGTH_SCHEDULE_KW_KEY , iocc , 1));
  }
  
  
  if (config_item_set( config , REFCASE_KEY)) {
    const char * refcase_path = config_get_value_as_path( config , REFCASE_KEY );
    if (!ecl_config_load_refcase( ecl_config , refcase_path))
      fprintf(stderr,"** Warning: loading refcase:%s failed \n", refcase_path);
  }
  

  if (config_item_set( config , REFCASE_LIST_KEY)) {
    config_content_item_type * item = config_get_content_item( config , REFCASE_LIST_KEY);
    int i;
    for (i=0; i < config_content_item_get_size( item ); i++) {
      config_content_node_type * node = config_content_item_iget_node( item , i );
      int j;
      for (j=0; j < config_content_node_get_size( node ); j++) {
        const char * case_glob = config_content_node_iget_as_path( node , j );
        ecl_refcase_list_add_matching( ecl_config->refcase_list , case_glob );
      }
    }
  }
  
  /* Deprecated */
  if (config_item_set( config , PLOT_REFCASE_LIST_KEY)) {
    const char * case_list_file = config_get_value( config , PLOT_REFCASE_LIST_KEY);
    FILE * stream = util_fopen(case_list_file , "r");
    bool at_eof;
    do {
      char * case_name = util_fscanf_alloc_line(stream , &at_eof);
      if (case_name) {
        ecl_refcase_list_add_case( ecl_config->refcase_list , case_name);
        free( case_name );
      }
    } while (!at_eof);
    
    fclose( stream );
  }
  
  if (config_item_set(config , INIT_SECTION_KEY)) 
    ecl_config_set_init_section( ecl_config , config_get_value( config , INIT_SECTION_KEY ));
  else 
    if (ecl_config->can_restart) 
      /** 
          This is a hard error - the datafile contains <INIT>, however
          the config file does NOT contain INIT_SECTION, i.e. we have
          no information to fill in for the <INIT> section. This case
          will not be able to initialize an ECLIPSE model, and that is
          broken behaviour. 
      */
      util_exit("Sorry: when the datafile contains <INIT> the config file MUST have the INIT_SECTION keyword. \n");
  
  /*
      The user has not supplied a INIT_SECTION keyword whatsoever, 
      this essentially means that we can not restart - because:

      1. The EQUIL section must be inlined in the DATAFILE without any
         special markup.
      
      2. ECLIPSE will fail hard if the datafile contains both an EQUIL
         section and a restart statement, and when we have not marked
         the EQUIL section specially with the INIT_SECTION keyword it
         is impossible for ERT to dynamically change between a
         datafile with initialisation and a datafile for restart.
         
      IFF the user has no intentitions of any form of restart, this is
      perfectly legitemate.
  */
  if (config_item_set( config , END_DATE_KEY )) {
    const char * date_string = config_get_value( config , END_DATE_KEY );
    time_t end_date;
    if (util_sscanf_date( date_string , &end_date))
      ecl_config_set_end_date( ecl_config , end_date );
    else
      fprintf(stderr,"** WARNING **: Failed to parse %s as a date - should be in format dd/mm/yyyy \n",date_string);
  }
}
Exemplo n.º 22
0
Arquivo: util.c Projeto: Govelius/dmd
void err_break()
{
    util_exit(255);
}
Exemplo n.º 23
0
void ecl_util_alloc_restart_files(const char * path , const char * _base , char *** _restart_files , int * num_restart_files , bool * _fmt_file , bool * _unified) {
  
  util_exit("Function:%s currently not implemented - sorry \n",__func__);

  //char * base = NULL;
  //if (_base == NULL)
  //  base = ecl_util_alloc_base_guess(path);
  //else
  //  base = (char *) _base;
  //{
  //  int num_F_files;
  //  int num_X_files;
  //
  //  char *  unrst_file  = ecl_util_alloc_filename(path , base , ECL_UNIFIED_RESTART_FILE , false , -1);  
  //  char *  funrst_file = ecl_util_alloc_filename(path , base , ECL_UNIFIED_RESTART_FILE , true  , -1);
  //  char *  unif_file   = NULL; 
  //
  //  char ** F_files     = ecl_util_alloc_scandir_filelist(path , base , ECL_RESTART_FILE , true  , &num_F_files); 
  //  char ** X_files     = ecl_util_alloc_scandir_filelist(path , base , ECL_RESTART_FILE , false , &num_X_files); 
  //  char *  FX_file      = NULL;
  //  char *  final_file; 
  //
  //  /*
  //    Ok now we have formatted/unformatted unified and not
  //    unified: Time to check what exists in the filesystem, and which
  //    is the newest.
  //  */
  //  unif_file = util_newest_file(unrst_file , funrst_file);
  //  
  //  if (num_F_files > 0 || num_X_files > 0) {    
  //    if (num_F_files > 0 && num_X_files > 0) {
  //      /* 
  //         We have both a list of .Fnnnn and a list of .Xnnnn files; if
  //         the length of lists is not equal we take the longest,
  //         otherwise we compare the dates of the last files in the
  //         list. 
  //      */
  //      if (num_F_files == num_X_files) {
  //        FX_file = util_newest_file( F_files[num_F_files - 1] , X_files[num_X_files - 1]);
  //      } else if (num_F_files > num_X_files)
  //        FX_file = F_files[num_F_files - 1];
  //      else
  //        FX_file = X_files[num_X_files - 1];
  //    } else if (num_F_files > 0)
  //      FX_file = F_files[num_F_files - 1];
  //    else
  //      FX_file = X_files[num_X_files - 1];
  //
  //    if (unif_file != NULL)
  //      final_file = util_newest_file(unif_file , FX_file);
  //    else
  //      final_file = FX_file;
  //  } else
  //    final_file = unif_file;
  //    
  //  
  //  if (final_file == NULL) 
  //    util_abort("%s: could not find any restart data in %s/%s \n",__func__ , path , base);
  //  
  //
  //  /* 
  //     Determine type of final_file. Thois block is where the return
  //     values are actually set.
  //  */
  //  {
  //    char ** restart_files;
  //    bool fmt_file , unified;
  //    ecl_file_enum file_type;
  //    
  //    ecl_util_get_file_type( final_file , &file_type , &fmt_file , NULL);
  //    if (file_type == ECL_UNIFIED_RESTART_FILE) {
  //      *num_restart_files = 1;
  //      restart_files = util_malloc(sizeof * restart_files, __func__);
  //      restart_files[0] = util_alloc_string_copy( final_file );
  //      unified = true;
  //    } else {
  //      restart_files = ecl_util_alloc_scandir_filelist( path , base , ECL_RESTART_FILE , fmt_file , num_restart_files);
  //      unified = false;
  //    }
  //    *_restart_files = restart_files;
  //
  //    if (_fmt_file != NULL) *_fmt_file = fmt_file;
  //    if (_unified  != NULL) *_unified  = unified; 
  //  }
  //
  //  util_free_stringlist(F_files , num_F_files);
  //  util_free_stringlist(X_files , num_X_files);
  //  free(unrst_file);
  //  free(funrst_file);
  //}
  //
  //if (_base == NULL)
  //  free(base);
}
Exemplo n.º 24
0
int main( int argc, char ** argv) {
  if (argc == 1)
    util_exit("block_node  node1  node2  node3:2  \n");
  
  /* Initialize lsf environment */
  util_setenv( "LSF_BINDIR"    , "/prog/LSF/9.1/linux2.6-glibc2.3-x86_64/bin" );
  util_setenv( "LSF_LINDIR"    , "/prog/LSF/9.1/linux2.6-glibc2.3-x86_64/lib" );
  util_setenv( "XLSF_UIDDIR"   , "/prog/LSF/9.1/linux2.6-glibc2.3-x86_64/lib/uid" );
  util_setenv( "LSF_SERVERDIR" , "/prog/LSF/9.1/linux2.6-glibc2.3-x86_64/etc");
  util_setenv( "LSF_ENVDIR"    , "/prog/LSF/conf");
  
  util_update_path_var( "PATH"               , "/prog/LSF/9.1/linux2.6-glibc2.3-x86_64/bin" , false);
  util_update_path_var( "LD_LIBRARY_PATH"    , "/prog/LSF/9.1/linux2.6-glibc2.3-x86_64/lib" , false);

  
  lsf_driver = lsf_driver_alloc();
  if (lsf_driver_get_submit_method( lsf_driver ) != LSF_SUBMIT_INTERNAL)
    util_exit("Sorry - the block_node program must be invoked on a proper LSF node \n");

  {
    
    int iarg;
    int total_blocked_target = 0;
    nodes       = hash_alloc();
    for (iarg = 1; iarg < argc; iarg++) {
      char   *node_name;
      int    num_slots;
      
      {
        char * num_slots_string;
        util_binary_split_string( argv[iarg] , ":" , true , &node_name , &num_slots_string);
        if (num_slots_string)
          util_sscanf_int( num_slots_string , &num_slots);
        else
          num_slots = 1;
      }
      
      if (!hash_has_key( nodes , node_name))
        hash_insert_hash_owned_ref( nodes , node_name , count_pair_alloc() , free);

      {
        count_pair_type * pair = hash_get( nodes , node_name);
        pair->target += num_slots;
      }
      total_blocked_target += num_slots;
    }

    signal(SIGINT , block_node_exit );
    {
      const int sleep_time    = 5;
      const int chunk_size    = 10;    /* We submit this many at a time. */
      const int max_pool_size = 1000;  /* The absolute total maximum of jobs we will submit. */  

      bool           cont        = true;
      int            pending     = 0;   
      bool           all_blocked;
      job_pool                   = vector_alloc_new();

      while (cont) {
        printf("[Ctrl-C to give up] "); fflush( stdout );
        if (cont) sleep( sleep_time );
        if (pending == 0) {
          if (vector_get_size( job_pool ) < max_pool_size)
            add_jobs( chunk_size );
        }
        
        update_pool_status( &all_blocked , &pending);
        print_status();

        if (all_blocked)
          cont = false;
      }
      if (!all_blocked)
        printf("Sorry - failed to block all the nodes \n");
      
      block_node_exit( 0 );
      hash_free( nodes );
    }
  }
}
Exemplo n.º 25
0
int main(int argc, char ** argv) {
  int num_files = argc - 1;
  if (num_files >= 1) {
    /* File type and formatted / unformatted is determined from the first argument on the command line. */
    char * ecl_base;
    char * path;
    ecl_file_enum file_type , target_type;
    bool fmt_file;

    /** Look at the first command line argument to determine type and formatted/unformatted status. */
    file_type = ecl_util_get_file_type( argv[1] , &fmt_file , NULL);
    if (file_type == ECL_SUMMARY_FILE)
      target_type = ECL_UNIFIED_SUMMARY_FILE;
    else if (file_type == ECL_RESTART_FILE)
      target_type = ECL_UNIFIED_RESTART_FILE;
    else {
      util_exit("The ecl_pack program can only be used with ECLIPSE restart files or summary files.\n");
      target_type = -1;
    }
    util_alloc_file_components( argv[1] , &path , &ecl_base , NULL);

    
    /**
       Will pack to cwd, even though the source files might be
       somewhere else. To unpack to the same directory as the source
       files, just send in @path as first argument when creating the
       target_file.
    */

    {
      msg_type * msg;
      int i , report_step , prev_report_step;
      char *  target_file_name   = ecl_util_alloc_filename( NULL , ecl_base , target_type , fmt_file , -1);
      stringlist_type * filelist = stringlist_alloc_argv_copy( (const char **) &argv[1] , num_files );
      ecl_kw_type * seqnum_kw    = NULL;
      fortio_type * target       = fortio_open_writer( target_file_name , fmt_file , ECL_ENDIAN_FLIP);

      if (target_type == ECL_UNIFIED_RESTART_FILE) {
        int dummy;
        seqnum_kw = ecl_kw_alloc_new("SEQNUM" , 1 , ECL_INT_TYPE , &dummy);
      } 
      
      {
        char * msg_format = util_alloc_sprintf("Packing %s <= " , target_file_name);
        msg = msg_alloc( msg_format , false);
        free( msg_format );
      }
      

      msg_show( msg );
      stringlist_sort( filelist , ecl_util_fname_report_cmp);
      prev_report_step = -1;
      for (i=0; i < num_files; i++) {
        ecl_file_enum this_file_type;
        this_file_type = ecl_util_get_file_type( stringlist_iget(filelist , i)  , NULL , &report_step);
        if (this_file_type == file_type) {
          if (report_step == prev_report_step)
            util_exit("Tried to write same report step twice: %s / %s \n",
                      stringlist_iget(filelist , i-1) , 
                      stringlist_iget(filelist , i));

          prev_report_step = report_step;
          msg_update(msg , stringlist_iget( filelist , i));
          {
            ecl_file_type * src_file = ecl_file_open( stringlist_iget( filelist , i) , 0 );
            if (target_type == ECL_UNIFIED_RESTART_FILE) {
              /* Must insert the SEQNUM keyword first. */
              ecl_kw_iset_int(seqnum_kw , 0 , report_step);
              ecl_kw_fwrite( seqnum_kw , target );
            }
            ecl_file_fwrite_fortio( src_file , target , 0);
            ecl_file_close( src_file );
          }
        }  /* Else skipping file of incorrect type. */
      }
      msg_free(msg , false);
      fortio_fclose( target );
      free(target_file_name);
      stringlist_free( filelist );
      if (seqnum_kw != NULL) ecl_kw_free(seqnum_kw);
    }
    free(ecl_base);
    util_safe_free(path);
  }
}
Exemplo n.º 26
0
void unpack_file(const char * filename) {
  ecl_file_enum target_type = ECL_OTHER_FILE;
  ecl_file_enum file_type;
  bool fmt_file;
  file_type = ecl_util_get_file_type(filename , &fmt_file , NULL);
  if (file_type == ECL_UNIFIED_SUMMARY_FILE)
    target_type = ECL_SUMMARY_FILE;
  else if (file_type == ECL_UNIFIED_RESTART_FILE)
    target_type = ECL_RESTART_FILE;
  else 
    util_exit("Can only unpack unified ECLIPSE summary and restart files\n");
  
  if (target_type == ECL_SUMMARY_FILE) {
    printf("** Warning: when unpacking unified summary files it as ambigous - starting with 0001  -> \n");
  }
  {
    ecl_file_type * src_file = ecl_file_open( filename , 0 );
    int    size;
    int    offset;
    int    report_step = 0;
    int    block_index = 0;
    char * path; 
    char * base;
    msg_type * msg;
    util_alloc_file_components( filename , &path , &base , NULL);
    {
      char * label  = util_alloc_sprintf("Unpacking %s => ", filename);
      msg = msg_alloc( label , false);
      free( label );
    }
    msg_show(msg);

    if (target_type == ECL_SUMMARY_FILE) 
      size = ecl_file_get_num_named_kw( src_file , "SEQHDR" );
    else
      size = ecl_file_get_num_named_kw( src_file , "SEQNUM" );
    
    
    while (true) {
      if (block_index == size)
        break;

      if (target_type == ECL_SUMMARY_FILE) {
        ecl_file_select_block( src_file , SEQHDR_KW , block_index );
        report_step += 1;
        offset = 0;
      } else {
        ecl_kw_type * seqnum_kw;
        ecl_file_select_block( src_file , SEQNUM_KW , block_index );
        seqnum_kw = ecl_file_iget_named_kw( src_file , SEQNUM_KW , 0);
        report_step = ecl_kw_iget_int( seqnum_kw , 0);
        offset = 1;
      }

      /**
         Will unpack to cwd, even though the source files might be
         somewhere else. To unpack to the same directory as the source
         files, just send in @path as first argument when creating the
         target_file.
      */
      
      {
        char * target_file = ecl_util_alloc_filename( NULL , base , target_type , fmt_file , report_step);
        fortio_type * fortio_target = fortio_open_writer( target_file , fmt_file , ECL_ENDIAN_FLIP );
        msg_update(msg , target_file);
        ecl_file_fwrite_fortio( src_file , fortio_target , offset);
        
        fortio_fclose(fortio_target);
        free(target_file);
      }
      block_index++;
    } 
    ecl_file_close( src_file );
    util_safe_free(path);
    free(base);
    msg_free(msg , true);
  }
}
Exemplo n.º 27
0
Arquivo: util.c Projeto: Govelius/dmd
void err_exit()
{
    util_exit(EXIT_FAILURE);
}
Exemplo n.º 28
0
void ecl_config_init(ecl_config_type * ecl_config, const config_content_type * config)
{
  if (config_content_has_item(config, ECLBASE_KEY)) {
    ui_return_type * ui_return = ecl_config_validate_eclbase(ecl_config, config_content_iget(config, ECLBASE_KEY, 0, 0));
    if (ui_return_get_status(ui_return) == UI_RETURN_OK)
      ecl_config_set_eclbase(ecl_config, config_content_iget(config, ECLBASE_KEY, 0, 0));
    else
      util_abort("%s: failed to set eclbase format. Error:%s\n", __func__ , ui_return_get_last_error(ui_return));
    ui_return_free(ui_return);
  }

  if (config_content_has_item(config, DATA_FILE_KEY))
  {
    ui_return_type * ui_return = ecl_config_validate_data_file(ecl_config, config_content_iget(config, DATA_FILE_KEY, 0, 0));
    if (ui_return_get_status( ui_return ) == UI_RETURN_OK)
      ecl_config_set_data_file( ecl_config, config_content_iget(config, DATA_FILE_KEY, 0, 0) );
    else
      util_abort("%s: problem setting ECLIPSE data file\n",__func__ , ui_return_get_last_error(ui_return));

    ui_return_free(ui_return);
  }

  if (config_content_has_item(config, SCHEDULE_FILE_KEY)) {
    const char * schedule_target_file = config_content_safe_iget(config, SCHEDULE_FILE_KEY, 0, 1);
    if (schedule_target_file) {
      ui_return_type * ui_return_sched_target_file = ecl_config_validate_schedule_file(ecl_config, schedule_target_file);
      if (!ui_return_get_status(ui_return_sched_target_file) == UI_RETURN_OK) {
         util_abort("%s: failed to set target schedule file. Error:%s\n",__func__ , ui_return_get_last_error(ui_return_sched_target_file));
      }
      ui_return_free(ui_return_sched_target_file);
    }

    ui_return_type * ui_return = ecl_config_validate_schedule_file(ecl_config, config_content_iget(config, SCHEDULE_FILE_KEY, 0, 0));
    if (ui_return_get_status(ui_return) == UI_RETURN_OK)
      ecl_config_set_schedule_file(ecl_config, config_content_iget(config, SCHEDULE_FILE_KEY, 0, 0), schedule_target_file);
    else
      util_abort("%s: failed to set schedule file. Error:%s\n",__func__ , ui_return_get_last_error(ui_return));

    ui_return_free(ui_return);
  }

  if (config_content_has_item(config, GRID_KEY)) {
    const char * grid_file = config_content_iget(config, GRID_KEY, 0, 0);
    ui_return_type * ui_return = ecl_config_validate_grid( ecl_config , grid_file);
    if (ui_return_get_status(ui_return) == UI_RETURN_OK)
      ecl_config_set_grid(ecl_config, grid_file );
    else
      util_abort("%s: failed to set grid file:%s  Error:%s \n",__func__ , grid_file , ui_return_get_last_error(ui_return));

    ui_return_free( ui_return );
  }


  if (config_content_has_item(config, ADD_FIXED_LENGTH_SCHEDULE_KW_KEY))
  {
    int iocc;
    for (iocc = 0; iocc < config_content_get_occurences(config, ADD_FIXED_LENGTH_SCHEDULE_KW_KEY); iocc++)
      ecl_config_add_fixed_length_schedule_kw(ecl_config,
                                              config_content_iget(config, ADD_FIXED_LENGTH_SCHEDULE_KW_KEY, iocc, 0),
                                              config_content_iget_as_int(config, ADD_FIXED_LENGTH_SCHEDULE_KW_KEY, iocc, 1));
  }

  if (config_content_has_item(config, REFCASE_KEY))
  {
    const char * refcase_path = config_content_get_value_as_path(config, REFCASE_KEY);
    if (!ecl_config_load_refcase(ecl_config, refcase_path))
      fprintf(stderr, "** Warning: loading refcase:%s failed \n", refcase_path);
  }

  if (config_content_has_item(config, REFCASE_LIST_KEY))
  {
    config_content_item_type * item = config_content_get_item(config, REFCASE_LIST_KEY);
    int i;
    for (i = 0; i < config_content_item_get_size(item); i++)
    {
      config_content_node_type * node = config_content_item_iget_node(item, i);
      int j;
      for (j = 0; j < config_content_node_get_size(node); j++)
      {
        const char * case_glob = config_content_node_iget_as_path(node, j);
        ecl_refcase_list_add_matching(ecl_config->refcase_list, case_glob);
      }
    }
  }

  if (config_content_has_item(config, INIT_SECTION_KEY))
    ecl_config_set_init_section(ecl_config, config_content_get_value(config, INIT_SECTION_KEY));
  else if (ecl_config->can_restart)
    /**
     This is a hard error - the datafile contains <INIT>, however
     the config file does NOT contain INIT_SECTION, i.e. we have
     no information to fill in for the <INIT> section. This case
     will not be able to initialize an ECLIPSE model, and that is
     broken behaviour.
     */
    util_exit("Sorry: when the datafile contains <INIT> the config file MUST have the INIT_SECTION keyword. \n");

  /*
   The user has not supplied a INIT_SECTION keyword whatsoever,
   this essentially means that we can not restart - because:

   1. The EQUIL section must be inlined in the DATAFILE without any
   special markup.

   2. ECLIPSE will fail hard if the datafile contains both an EQUIL
   section and a restart statement, and when we have not marked
   the EQUIL section specially with the INIT_SECTION keyword it
   is impossible for ERT to dynamically change between a
   datafile with initialisation and a datafile for restart.

   IFF the user has no intentitions of any form of restart, this is
   perfectly legitemate.
   */
  if (config_content_has_item(config, END_DATE_KEY))
  {
    const char * date_string = config_content_get_value(config, END_DATE_KEY);
    time_t end_date;
    if (util_sscanf_date_utc(date_string, &end_date))
      ecl_config_set_end_date(ecl_config, end_date);
    else
      fprintf(stderr, "** WARNING **: Failed to parse %s as a date - should be in format dd/mm/yyyy \n", date_string);
  }
}
Exemplo n.º 29
0
void output_run_line( const output_type * output , ensemble_type * ensemble) {

  const int    data_columns = vector_get_size( output->keys );
  const int    data_rows    = time_t_vector_size( ensemble->interp_time );
  double     ** data;
  int row_nr, column_nr;

  data = util_calloc( data_rows , sizeof * data );
  /*
    time-direction, i.e. the row index is the first index and the
    column number (i.e. the different keys) is the second index.
  */
  for (row_nr=0; row_nr < data_rows; row_nr++)
    data[row_nr] = util_calloc( data_columns , sizeof * data[row_nr] );

  printf("Creating output file: %s \n",output->file );


  /*
     Go through all the cases and check that they have this key;
     exit if missing. Could also ignore the missing keys and just
     continue; and even defer the checking to the inner loop.
  */
  for (column_nr = 0; column_nr < vector_get_size( output->keys ); column_nr++) {
    const quant_key_type * qkey = vector_iget( output->keys , column_nr );
    {
      bool OK = true;

      for (int iens = 0; iens < vector_get_size( ensemble->data ); iens++) {
        const sum_case_type * sum_case = vector_iget_const( ensemble->data , iens );

        if (!ecl_sum_has_general_var(sum_case->ecl_sum , qkey->sum_key)) {
          OK = false;
          fprintf(stderr,"** Sorry: the case:%s does not have the summary key:%s \n", ecl_sum_get_case( sum_case->ecl_sum ), qkey->sum_key);
        }
      }

      if (!OK)
        util_exit("Exiting due to missing summary vector(s).\n");
    }
  }


  /* The main loop - outer loop is running over time. */
  {
    /**
       In the quite typical case that we are asking for several
       quantiles of the quantity, i.e.

       WWCT:OP_1:0.10  WWCT:OP_1:0.50  WWCT:OP_1:0.90

       the interp_data_cache construction will ensure that the
       underlying ecl_sum object is only queried once; and also the
       sorting will be performed once.
    */

    hash_type * interp_data_cache = hash_alloc();

    for (row_nr = 0; row_nr < data_rows; row_nr++) {
      time_t interp_time = time_t_vector_iget( ensemble->interp_time , row_nr);
      for (column_nr = 0; column_nr < vector_get_size( output->keys ); column_nr++) {
        const quant_key_type * qkey = vector_iget( output->keys , column_nr );
        double_vector_type * interp_data;

        /* Check if we have the vector in the cache table - if not create it. */
        if (!hash_has_key( interp_data_cache , qkey->sum_key)) {
          interp_data = double_vector_alloc(0 , 0);
          hash_insert_hash_owned_ref( interp_data_cache , qkey->sum_key , interp_data , double_vector_free__);
        }
        interp_data = hash_get( interp_data_cache , qkey->sum_key );

        /* Check if the vector has data - if not initialize it. */
        if (double_vector_size( interp_data ) == 0) {
          for (int iens = 0; iens < vector_get_size( ensemble->data ); iens++) {
            const sum_case_type * sum_case = vector_iget_const( ensemble->data , iens );

            if ((interp_time >= sum_case->start_time) && (interp_time <= sum_case->end_time))  /* We allow the different simulations to have differing length */
              double_vector_append( interp_data , ecl_sum_get_general_var_from_sim_time( sum_case->ecl_sum , interp_time , qkey->sum_key)) ;

            double_vector_sort( interp_data );
          }
        }
        data[row_nr][column_nr] = statistics_empirical_quantile__( interp_data , qkey->quantile );
      }
      hash_apply( interp_data_cache , double_vector_reset__ );
    }
    hash_free( interp_data_cache );
  }

  output_save( output , ensemble , (const double **) data);
  for (row_nr=0; row_nr < data_rows; row_nr++)
    free( data[row_nr] );
  free( data );
}
Exemplo n.º 30
0
int main(int argc, char *argv[])
{
	int i, j, flag, len = DEFAULT_LEN;
	unsigned int memaddr = 0;
	volatile void * mappedaddr = NULL;
	unsigned char cmd[MAX_CMD_LEN];
	unsigned char cmd_temp[MAX_CMD_LEN];
	FILE * cmd_fd = NULL;
	unsigned char * cmd_data = NULL;
	unsigned char * cmd1_data = NULL;
	unsigned char * cmd2_data = NULL;
	unsigned int showoffset, showlen, writeoffset;

	unsigned char writedata = 0;

	if(argc < 2){
		printf("Usage: ./memtool addr\n");
		exit(1);
	}

	util_init();

//	cpld_version();

	memaddr = strtoul(argv[1], NULL, 16);
	
	printf("\nYou input address: 0x%x\n", memaddr);
	
	mappedaddr = mmap(0, MAP_LEN, PROT_READ | PROT_WRITE, MAP_SHARED, util_fd, memaddr & ~MAP_MASK);
	if(mappedaddr == (void *) -1){
		perror("Error mapping memory");
		close(util_fd);
		return -1;
	}

	printf("    | ");

	for(i = 0; i < 16; i ++){
		printf("%02x ", i);
	}
	
	printf("\n-----------------------------------------------------");
	
	flag = 0;
	for(i = 1, j = 0; i <= len; i ++){
		if(flag == 0){
			printf("\n[%02x]| ", j);
			j += 1;
			flag = 1;
		}
			
		printf("%02x ", *((unsigned char *)mappedaddr+i-1));
		if(i%16 == 0){
			 flag = 0;
		}
	}	
	printf("\n");

	cmd_fd = fopen("/dev/console", "r");
	if( cmd_fd == NULL){
		perror("Console open");
		exit(1);
	}

	for(;;){
		printf("\nPlease input a command, like: d 0x100 0x10\n:");
	
		if(NULL == fgets(cmd, MAX_CMD_LEN, cmd_fd)){
			printf("Please input a command.\n");
			continue;
		}

		memset(cmd_temp, 0, MAX_CMD_LEN);

		switch(cmd[0]){
			case 'd':
			case 'D':
				cmd_data = strchr(cmd, ' ');
				if(cmd_data == NULL){
					printf("Please input a valid command.\n");
					continue;
				}
				cmd_data ++;
				cmd1_data = strchr(cmd_data, ' ');
				if(cmd1_data != NULL){
					memcpy(cmd_temp, cmd_data, cmd1_data-cmd_data);
				}else{
					printf("Please input valid command.\n");
					continue;
				}
				showoffset = strtoul(cmd_temp, NULL, 16);
				if(showoffset + showlen >= MAP_LEN){
				       	showoffset = 0;
					showlen = DEFAULT_LEN;
					printf("The offset should less than 0x%x\n", MAP_LEN);
				}
				showlen = strtoul(cmd1_data, NULL, 16);
				
				if(showlen == 0) showlen = DEFAULT_LEN;
				
				printf("\nAddr: %p, len: 0x%x\n", memaddr+showoffset, showlen);
				memshow(mappedaddr+showoffset, showlen);
			break;
			
			case 'e':
			case 'E':

				cmd_data = strchr(cmd, ' ');
				cmd_data ++;
				
				writeoffset = strtoul(cmd_data, NULL, 16);
				
				if(writeoffset >= MAP_LEN){
					writeoffset = 0;
					printf("The offset should less than 0x%x\n", MAP_LEN);
				}

				for(i = 0; ; i ++){
					memset(cmd, 0, MAX_CMD_LEN);
					printf("%p[%02x]:", memaddr+writeoffset+i, *(volatile unsigned char *)(mappedaddr+writeoffset+i));
					if(NULL == fgets(cmd, MAX_CMD_LEN, cmd_fd)){
						printf("Please input a command.\n");
						continue;
					}
					
//					printf("cmd: %s, 0:%x\n", cmd, cmd[0]);
					
					if(cmd[0] == '\n'){
//						printf("Aborted\n");
						break;	
					}
					
					for(j = 0; ; j ++){
						if(cmd[j] == '\n') break;
						if(isxdigit(cmd[j]) == 0){
							printf("Please input a valid hex data.");
							break;
						}
					}
					
					if(cmd[j] != '\n') break;
					
					writedata = strtoul(cmd, NULL, 16);
//					printf("We write 0x%x to %p\n", writedata, memaddr+writeoffset+i);
					*(volatile unsigned char *)(mappedaddr+writeoffset+i) = writedata;

				}
				
			break;
			
			case 'q':
			case 'Q':

				i = munmap((void *)mappedaddr, MAP_LEN);
				if(i == -1){
					printf("error unmapping memory\n");
					return -1;
				}
			
				util_exit();
				
				fclose(cmd_fd);
				
				exit(0);
			break;
			
			default:
				printf("Please input a command, like: d 0x100 0x10\n");
			continue;
		}

	}

}