Exemple #1
0
/**
 * Read the next line from a file.
 * The returned string must be freed by the invoker.
 */
char* reader_get_line() {
	int length = ReaderLineLengthInit;
	int position = 0;
	char *line = (char*)malloc(length);

	if (!line)
		error_fatal(ErrorMemoryAlloc);

	do {
	    line[position++] = getc(reader_file);

	    /* If the position is divisible by the initial size, then more space is
	     * needed for the line. */
	    if(!(position % ReaderLineLengthInit)) {
	    	/* Increase the line length by the initial size. */
			length += ReaderLineLengthInit;
			line = (char*)realloc(line, length);
			if (!line)
				error_fatal(ErrorMemoryAlloc);
		}
	} while (line[position - 1] != '\n' && line[position - 1] != EOF);

	if (line[0] == EOF) {
		free(line);
		return NULL;
	}

	line[position - 1] = '\0';
	return line;
}
Exemple #2
0
static void process_header(seq_t *seq, char *header) {
  char *id, *comm, *p, *q;
  int i, n, l;

  n = 0;
  p = header;

  /* skip > */
  p++;

  while(*p && isascii((int)*p) && !isspace((int)*p)) {
    p++; n++;
  }

  /* check if sequence is named or not */
  if (n == 1 && strchr( ".,;", (int)header[1])) n = 0;
  l = ( n == 0) ? 9 : n;

  if((id = malloc(sizeof(char)*(l+1))) == NULL){
    error_fatal("memory", NULL);
  }
  p = header;
  p++;
  
  /* check if sequence is named or not */
  if ( n == 0 ){
    error_warn("anonymous sequence",
	       "name will be forced to \"anonymous\"");
    snprintf(id,10, "anonymous");
  }
  else {
    q = id;
    for (i=0; i<n; i++) {
      /* replace all non alnum character by '_' */
      if (isalnum((int)*p))  *q++ = *p++;
      else { *q++ = '_'; p++; }
    }
    *q = '\0';
  }


  /* skip spaces */
  while(*p && (isspace((int)*p))) { p++; n++; }

  /* get comment */

  if((comm = malloc(sizeof(char) * (strlen(header) - n))) == NULL){
    error_fatal("memory", "COMLEN");
  }
  q = comm;
  while(*p && *p != '\n') { *q++ = *p++; }
  *q = '\0';

  seq->id = id;
  seq->comment = comm;
}
/*************************** info_digitalizador *****************************
	Función para solicitar información al digitalizador sobre los valores
	máximos y mínimos de los parámetros modificables del digitalizador, y
	comprobar que los valores que se desean fijar para la adquisición de
	imágenes está dentro de los valores permitidos.
*****************************************************************************/
int  info_digitalizador(MIL_ID digitalizador)
{
	char t[LONGITUD_TEXTO];

	MdigInquire(digitalizador, M_BRIGHTNESS + M_MAX_VALUE, &limCam.MaxBrillo);
	MdigInquire(digitalizador, M_BRIGHTNESS + M_MIN_VALUE, &limCam.MinBrillo);
	if (paramAux->Cam.brillo < limCam.MinBrillo || paramAux->Cam.brillo > limCam.MaxBrillo)  {
		sprintf(t, "Valor del parámetro de brillo inaceptable: [%5d, %5d] = %d",
			limCam.MinBrillo, limCam.MaxBrillo, paramAux->Cam.brillo);
		error_fatal("info_digitalizador", t, 0);
		Sleep(1000);
		return 1;
	}

	MdigInquire(digitalizador, M_GAIN+M_MAX_VALUE, &limCam.MaxGanancia);
	MdigInquire(digitalizador, M_GAIN+M_MIN_VALUE, &limCam.MinGanancia);
	if (paramAux->Cam.ganancia < limCam.MinGanancia || paramAux->Cam.ganancia > limCam.MaxGanancia)  {
		sprintf(t, "Valor del parámetro de ganancia inaceptable: [%5d, %5d] = %d",
			limCam.MinGanancia, limCam.MaxGanancia, paramAux->Cam.ganancia);
		error_fatal("info_digitalizador", t, 0);
		Sleep(1000);
		return 1;
	}

	MdigInquire(digitalizador, M_SHUTTER+M_MAX_VALUE, &limCam.MaxExposicion);
	MdigInquire(digitalizador, M_SHUTTER+M_MIN_VALUE, &limCam.MinExposicion);
    GetLimitesBaseExposicion(limCam.MinBaseExposicion,limCam.MaxBaseExposicion);
	//Debemos comprobar si es correcta la exposicion en todos los filtros
	for (int i=0; i<MAX_FILTROS_DTA;i++)
    {
		if (paramAux->Rueda.exposicion[i] < limCam.MinExposicion || paramAux->Rueda.exposicion[i] > limCam.MaxExposicion)  {
			sprintf(t, "Valor del parámetro de exposicion para la banda %d inaceptable: [%5d, %5d] = %d",
				i,limCam.MinExposicion, limCam.MaxExposicion, paramAux->Rueda.exposicion[i]);
			error_fatal("info_digitalizador", t, 0);
			Sleep(1000);
			return 1;
		}
		if (paramAux->Rueda.base_exp[i] < limCam.MinBaseExposicion || paramAux->Rueda.base_exp[i] > limCam.MaxBaseExposicion)  {
			sprintf(t, "Valor del parámetro de base de exposicion para la banda %d inaceptable: [%5d, %5d] = %d",
				i,limCam.MinExposicion, limCam.MaxExposicion, paramAux->Rueda.base_exp[i]);
			error_fatal("info_digitalizador", t, 0);
			Sleep(1000);
			return 1;
		}
    }


	return 0;
}
Exemple #4
0
int main(int argc, char *argv[])
{

    int sock, sock_listen, sock_acept, length, fromlen, n;
    struct sockaddr_in server;
    struct sockaddr_in from;
    char buffer[TAMANO];

    /* creacion del socket del servidor*/
    sock=socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
        error_fatal("Creando el socket");

    length = sizeof(server);
    memset(&server,0,length); /*limpio la direccion del socket del servidor*/

    /* vinculo la direccion IP y puerto local al socket creado anteriormente */
    server.sin_family=AF_INET;
    server.sin_addr.s_addr=INADDR_ANY;
    server.sin_port=htons(atoi(argv[1]));

    if (bind(sock,(struct sockaddr *)&server,length)<0)
        error_fatal("binding");

    /* se avisa al sistema que comience a atender llamadas de clientes*/

    sock_listen = listen (sock, 1);
    if (sock_listen == -1)
        error_fatal("listen");

    fromlen = sizeof(struct sockaddr_in);

    sock_acept = accept(sock, (struct sockaddr *) &from, &fromlen);

    if (sock_acept == -1)
        error_fatal("accept");

    /* bucle principal. Pongo a recibir y responder mensajes a traves del socket*/
    while (1) {
        n = recv(sock_acept, buffer, sizeof(buffer), 0);
        /* datagrama recibido*/
        buffer[n]='\0'; /* para poder imprimirlo con prinft*/
        printf("%s\n", buffer+4);
        /*enviar respuesta*/
        memset(buffer,0,strlen(buffer)); /*limpio el buffer*/

    }

}
Exemple #5
0
/*
 keep that for compatibility with old export python.
 */
result_t * access_search_deprecated(char *dbase, char *name) {
  result_t * res;
  // result_t * adr_res=&res;
  int nb_AC_not_found=1;
  
  if ((res=malloc(sizeof(result_t)))==NULL) error_fatal("memory", NULL);
  
  res->name=strdup(name);
  res->dbase=strdup(dbase);
  res->filenb=NOT_FOUND;
  
  WDBQueryData wData;
  wData.len_l=1;
  wData.start_l=&res;
  
  access_search(wData,dbase,&nb_AC_not_found);
#ifdef DEBUG
  if (res->filenb!=NOT_FOUND) {
    printf("access_search_deprecated, found : \n");
    printf("%s:%s\n,real_dbase; %s\n, filenb=%d\n, offset=%lld\n",res->dbase,res->name,res->real_dbase,res->filenb,res->offset);
  } else {
    printf("access_search_deprecated, didn't find : %s:%s \n",res->dbase,res->name);
  }
#endif
  return res;}
Exemple #6
0
char *alphabet_maker (char *alphabet) {

  char  *res, *p;
  int j;

  if ((res = calloc(255, sizeof(char))) == NULL) {
    error_fatal("memory", NULL);
  }

  p = alphabet;
  while(*p) {
    j = (int)*p;
    if ( islower(j) ){
      res[j] = toupper((int)*p);
      res[j-32] = toupper((int)*p);
    }
    else{
      res[j] = *p;
      res[j+32] = *p;
    }
    p++;
  }

  return res;
}
/**************************  graba_imagen_campo  ****************************
   Función para efectuar la grabación en disco de una imagen del campo.
   "nombre" es el nombre del archivo a almacenar.
   "buffer" es el buffer que quiero copiar a disco.
****************************************************************************/
int graba_imagen_campo(char *nombre, MIL_ID buffer, int nBits, double dEscala)
{
	char  nombre_ext[1024], *ext, mensaje[1024], *fn = "graba_imagen_campo";

	strcpy(nombre_ext, nombre);		// Se copia en nombre_ext el nombre de la imagen a cargar
	ext = strrchr(nombre_ext, '.');	// Se busca la extensión del fichero que se desea guardar
	strcpy(nombre_ext, ext+1);

	// Copiamos el buffer seleccionado en el archivo seleccionado (nombre_ext).
	if ( strcmp(nombre_ext,"jpg")==0 )  MbufExport(nombre, M_JPEG_LOSSLESS, buffer);
	if ( strcmp(nombre_ext,"tif")==0 )
    {
        MbufExport(nombre, M_TIFF, buffer);
        if (nBits >0 && dEscala > 0)
            INTERFAZ_LIBTIF::EscribirTags(nombre, nBits, dEscala);
        else if (dEscala > 0)
            INTERFAZ_LIBTIF::EscribirTags(nombre, 0, dEscala);
        else if (nBits > 0)
            INTERFAZ_LIBTIF::EscribirTags(nombre, nBits, 0);
        else 
            INTERFAZ_LIBTIF::EscribirTags(nombre, 0, 0);
    }
	if ( strcmp(nombre_ext,"mim")==0 )  MbufExport(nombre, M_MIL, buffer);

	/* Compruebo que no ha habido ningún error durante el proceso de grabación a disco. */

	if ( MbufDiskInquire(nombre, M_SIZE_X, M_NULL) == 0)  {
		sprintf(mensaje, "No puedo crear la imagen %s", nombre_ext);
		error_fatal(fn, mensaje, 0);
		return 1;
	}

	return  0;
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
//	char  *raiz_paramIni;	// raiz del directorio del fichero inicial
	int nRetCode = 0;

	int i, c;
	int aplicaLutColor = 0;
	char mensaje[512], nombre_ext[512];
	FILE *fich;
    int nCampo = 0;
    char nombreToma[MAX_NOMBRE_TOMA] = "Toma"; //Para pedir el nombre de la toma y guardar las imagenes
    char directorioToma[512] = ""; //Directorio que crearemos para las imagenes de las tomas
    CCorreccionGeometrica correccionGeometrica;

    //  Procesamos los argumentos de la línea de comandos
 	procesa_argumentos(argc, argv,directorioToma);
   /*
	raiz_paramIni = procesa_argumentos(argc, argv,directorioToma);
	if ( raiz_paramIni==NULL || directorioToma == "")		
	{
		return (nRetCode = 1);
	}
	
    strcpy(paramIni.raiz_patrones,raiz_paramIni);
*/
	// Compongo el nombre de log de la aplicación
	sprintf(fichLog, "TomaUnica%s",EXT_LOG);
	if ( (fich = fopen(fichLog, "wt")) == NULL )  {
		sprintf(mensaje, "NO se puede crear el fichero: %s", fichLog);
		error_fatal("TomaUnica.exe", mensaje, 0);
		goto final;
	}
Exemple #9
0
/* VL: keep db_name parameter for recursive calls when searching in virtual database indexes.
 * lst_notFound points to a memory area allocated by the caller to store adresses of result_t structures for which no match was found.
 * It is used and "free" by the caller.
 * For recursive calls to access_search and calls to index_search, use memory areas allocated by access_search.
 */
void access_search(WDBQueryData wData, char * db_name, int * nb_AC_not_found) {
  FILE *f;
  char *p, *file, buf[1024];
  int nb_AC_found;
#ifdef DEBUG
  result_t ** start_l=wData.start_l; // for printing debug info
#endif
  // cur_base may be virtual.
  /* Virtual database indexes */
  file = index_file(NULL, db_name, VIRSUF);
  //printf("Searching in file : %s \n",file);
  if (access(file, F_OK) != -1) {
    if ((f = fopen(file, "r")) == NULL) {
      error_fatal("memory", NULL); }

    while (fgets(buf, 1023, f) != NULL) {
      if ((p = strrchr(buf, '\n')) != NULL) { *p = '\0'; }
      access_search(wData, buf, nb_AC_not_found);
#ifdef DEBUG
      // dump list of accession numbers that were not found yet.
      print_wrk_struct(start_l,wData.len_l,1);
#endif
      if (*nb_AC_not_found!=0) {
#ifdef DEBUG
        printf("access_search : all results were not found ; continue \n");
#endif
        continue;
      }
      break;
    }
    if (fclose(f) == EOF) {
      error_fatal("memory", NULL); }
    free(file);
    return;  }

  /* Real database indexes */
  file = index_file(NULL, db_name, ACCSUF);
#ifdef DEBUG
  printf("Searching in file : %s \n",file);
#endif
    nb_AC_found=index_search(file, db_name, wData, nb_AC_not_found);
#ifdef DEBUG
  printf("access_search : returned from index_search DB : %s : nb_not_found_for_db=%d, nb_res_found=%d \n",db_name,*nb_AC_not_found,nb_AC_found);
#endif
  free(file);
  return;	}
//---------------------------------------------------------------
// Purpose: 
//---------------------------------------------------------------
IEditorEntityFactory::IEditorEntityFactory( const char *type )
{
	std::string sType(type);
	auto list = GetList();
	if( list.find(sType) != list.end() )
		error_fatal( "Type %s is already there, have a look into your Factory Registrations!!" );

	GetList()[sType] = this;
}
Exemple #11
0
void doublearray_resize(doublearray_t array, unsigned n_values) {
    for (unsigned i = 0; array[i] != NULL; i++) {
		array[i] = realloc(array[i], sizeof(double) * n_values);
        
        if (array[i] == NULL) {
            error_fatal("Failed to allocate more memory for dobule array");
        }
	}
}
Exemple #12
0
int machine_gen_code (Machine *m, int op){
  assert(m != NULL) ;
  //assert(op >= add && op <= sub) ;

  if (m->IP == SEGMENT_CODE_SIZE) 
    error_fatal("Segment de code plein") ;
  
  m->segment_code[m->IP] = op ;
  m->IP++ ;
  return 0 ;
}
Exemple #13
0
/* Check aligment file format */
alifmt_t align_format(FILE *f) {
  int i;
  off_t off;
  alifmt_t fmt;

  if ((off = ftello(f)) == -1) {
    error_fatal("file position", NULL); }

  for (fmt = ALIFMT_UNKWN + 1; fmt != ALIFMT_NONE; fmt++) {

    i = align_check(f, fmt);

    if (fseeko(f, off, SEEK_SET) != 0) {
      error_fatal("file position", NULL); }

    if (i == 0) { break; }

  }

  return fmt; }
Exemple #14
0
static int puissance (int v1, int v2){
  if (v1 == 0 && v2 == 0)
    error_fatal("elévation à la puissance") ;

  long res = v1 ;

  while (v2--)
    res *= v1 ;

  if (res > INT_MAX)
    warning("Pw debordement de capacité");

  return (int) res ;
}
Exemple #15
0
char* reader_get_file_name(const char* extension) {
	char* file_name;
	unsigned int full_length, base_length = strlen(reader_file_name_base);
	full_length = base_length + strlen(extension) + 1;
	file_name = (char*)malloc(full_length);
	if (!file_name)
		error_fatal(ErrorMemoryAlloc);

	strcpy(file_name, reader_file_name_base);
	/* Add the file extension. */
	file_name[base_length] = '.';
	strcpy(file_name + base_length + 1, extension);
	file_name[full_length] = '\0';

	return file_name;
}
Exemple #16
0
int machine_gen_chaine (Machine *m, const char *chaine) {
  assert(m != NULL) ;
  assert(chaine != NULL);

  if (m->IP == SEGMENT_CODE_SIZE) 
    error_fatal("Segment de code plein") ;

  m->segment_code[m->IP++] = outc ;  

  while (*chaine) {
    m->segment_code[m->IP++] = *chaine ;
    chaine++ ;
  }

  m->segment_code[m->IP++] = *chaine ;  
  return 0 ;
}
Exemple #17
0
/**
 * Open a file for reading.
 * Store the file pointer in the reader's global variable.
 */
void reader_open_file(const char* file_name) {
	char* full_file_name;
	/* Create a string with the file name and extension. */
	/* Store the file name for error reporting and for creating output files. */
	reader_file_name_base = (char*)malloc(strlen(file_name) + 1);
	if (!reader_file_name_base)
		error_fatal(ErrorMemoryAlloc);
	strcpy(reader_file_name_base, file_name);

	full_file_name = reader_get_file_name(ReaderFileExtension);
	/* Open the file. */
	reader_file = fopen(full_file_name, "r");
	if (!reader_file) {
		fprintf(stderr, ErrorCantRead, full_file_name);
		fprintf(stderr, "\n");
		free(full_file_name);
		exit(EXIT_FAILURE);
	}
	free(full_file_name);
}
Exemple #18
0
symbol_handle symbol_lookup() {
  string_done();
  symbol_handle place = _symbol_hash;

  for (;;) {
    if (_symbol_table[place] == STRING_NULL) {
      // add symbol to table
      _symbol_table[place] = _symbol_string;
      string_accept();
      return place;
    }
    if (!string_eq(_symbol_table[place], _symbol_string)) {
      // symbol is already in the table
      string_reject();
      return place;
    }
    place += 1;
    if (place == SYMBOL_SIZE) place = 0;
    if (place == _symbol_hash) error_fatal(ER_HASHFULL, "Symbol table");
  }
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    char nombre_aplicacion[20] = "TomaPatron.exe";
	char  *tipo_patron = NULL;		// Tipo de patron: claro(CL); oscuro(OS) que se desea adquirir.
	int nRetCode = 0;
    // variable que indica la necesidad de ajustar automaticamente las exposiciones justo antes de comenzar el barrido del patron (en caso de que no se haya hecho manualmente antes)
    bool bExposicionAjustada = false;

	int i, c;
	char mensaje[512], nombre_ext[512];
	FILE *fich;

	//  Procesamos los argumentos de la línea de comandos
//	if (procesa_argumentos(argc, argv, paramIni.raiz_patrones, &tipo_patron)==0 )		return (nRetCode = 1);
	
	// Compongo el nombre de log de la aplicación
	sprintf(fichLog, "TomaPatron%s", EXT_LOG);
	if ( (fich = fopen(fichLog, "wt")) == NULL )  {
		sprintf(mensaje, "NO se puede crear el fichero: %s", fichLog);
		error_fatal(nombre_aplicacion, mensaje, 0);
		goto final;
	}
Exemple #20
0
int begin(char* base_file_name, unsigned char *png_buf, long long png_length) {

  MY_PNG_READ_OFFSET = 0;
  PNG_LENGTH = png_length; 
  ENTIRE_PNG_BUF = png_buf;

  if (png_sig_cmp(ENTIRE_PNG_BUF, 0, 8) != 0) {
    error(-1, "png_sig_cmp", E_INVALID);
    return -1;
  }

  DEBUG_PRINT(("Initial png size is %lld bytes\n", PNG_LENGTH));

  my_png_meta *pm = calloc(1, sizeof(my_png_meta));
  my_init_libpng(pm);

  //If libpng errors, we end up here
  if (setjmp(png_jmpbuf(pm->read_ptr))) {
    DEBUG_PRINT(("libpng called setjmp!\n"));
    my_deinit_libpng(pm);
    free(ENTIRE_PNG_BUF);
    error(-1, "libpng", "libpng encountered an error\n");
    return -1;
  }

  //Normally a file, but instead make it our buffer
  void *read_io_ptr = png_get_io_ptr(pm->read_ptr);
  png_set_read_fn(pm->read_ptr, read_io_ptr, my_png_read_fn);

  //Transform all PNG image types to RGB
  int transforms = 
    PNG_TRANSFORM_GRAY_TO_RGB |
    PNG_TRANSFORM_STRIP_ALPHA | 
    PNG_TRANSFORM_EXPAND;

  png_read_png(pm->read_ptr, pm->info_ptr, transforms, NULL);

  //Now that it was read and transformed, its size will differ
  PNG_LENGTH = 0; 

  //Lets collect our metadata
  struct ihdr_infos_s ihdr_infos;
  ihdr_infos.bit_depth        = png_get_bit_depth(pm->read_ptr, pm->info_ptr);
  ihdr_infos.color_type       = png_get_color_type(pm->read_ptr, pm->info_ptr);
  ihdr_infos.filter_method    = png_get_filter_type(pm->read_ptr, pm->info_ptr);
  ihdr_infos.compression_type = png_get_compression_type(pm->read_ptr, pm->info_ptr);
  ihdr_infos.interlace_type   = png_get_interlace_type(pm->read_ptr, pm->info_ptr);
  ihdr_infos.height           = png_get_image_height(pm->read_ptr, pm->info_ptr);
  ihdr_infos.width            = png_get_image_width(pm->read_ptr, pm->info_ptr);

  if (ihdr_infos.color_type != 2) {
    DEBUG_PRINT((E_INVALID));
    free(ENTIRE_PNG_BUF);
    my_deinit_libpng(pm);
    DEBUG_PRINT(("Looks like libpng could not correctly convert to RGB\n"));
    return -1;
  }

  //Just in case we want to enable alpha, etc
  switch(ihdr_infos.color_type) {
    case 0:  //greyscale
    case 3:  //indexed
      ihdr_infos.bytes_per_pixel = 1;
      break;
    case 4: ihdr_infos.bytes_per_pixel = 2; break; //greyscale w/ alpha 
    case 2: ihdr_infos.bytes_per_pixel = 3; break; //Truecolour (RGB)
    case 6: ihdr_infos.bytes_per_pixel = 4; break; //Truecolour w/ alpha
    default: error_fatal(1, "ihdr_infos", "Unknown image type"); //should never happen
  }

  ihdr_infos.scanline_len = (ihdr_infos.bytes_per_pixel * ihdr_infos.width) + 1;

  DEBUG_PRINT(("HEIGHT: %u\n", ihdr_infos.height));
  DEBUG_PRINT(("WIDTH: %u\n", ihdr_infos.width));
  DEBUG_PRINT(("BIT_DEPTH: %u\n", ihdr_infos.bit_depth));

  // Don't compress, since we are merely copying it to memory,
  // we will be decompressing it again anyway
  png_set_compression_level(pm->write_ptr, Z_NO_COMPRESSION);

  void *write_io_ptr = png_get_io_ptr(pm->write_ptr);
  png_set_write_fn(pm->write_ptr, write_io_ptr, my_png_write_fn, my_png_dummy_flush);

  //Make sure we use all filters
  png_set_filter(pm->write_ptr, 0,
      PNG_FILTER_NONE  | PNG_FILTER_VALUE_NONE |
      PNG_FILTER_SUB   | PNG_FILTER_VALUE_SUB  |
      PNG_FILTER_UP    | PNG_FILTER_VALUE_UP   |
      PNG_FILTER_AVG   | PNG_FILTER_VALUE_AVG  |
      PNG_FILTER_PAETH | PNG_FILTER_VALUE_PAETH);

  //Set our comment
  struct png_text_struct comment_struct;

  comment_struct.compression = -1;
  comment_struct.key = " Glitched by pnglitch.xyz ";
  comment_struct.text = NULL;
  comment_struct.text_length = 0;
  
  png_set_text(pm->write_ptr, pm->info_ptr, &comment_struct, 1);

  //Buffer is Written using callback my_png_write_fn to buffer
  //ENTIRE_PNG_BUF. PNG_LENGTH will be updated automatically by it
  png_write_png(pm->write_ptr, pm->info_ptr, PNG_TRANSFORM_IDENTITY, NULL);

  my_deinit_libpng(pm);

  DEBUG_PRINT(("libpng output buf is %lld bytes\n", PNG_LENGTH));

  //Now that libpng has converted the image
  //and we have it in a buffer, we process it by hand with zlib
  struct z_stream_s inflate_stream;
  my_init_zlib(&inflate_stream);
  inflateInit(&inflate_stream);

  //Pointer to keep track of where we are
  unsigned char *pngp = ENTIRE_PNG_BUF;

  //Skip PNG Signature
  pngp += 8; 

  //Get Header
  unsigned char ihdr_bytes_buf[4+4+13+4]; // size + label + content + crc
  buf_read(ihdr_bytes_buf, &pngp, 4+4+13+4);

  //When we run into non-idat chunks, we will want to preserve them.
  //The spec says there's no chunk that needs to go after IDAT,
  //so we can simply concatenate all of these chunks into a buffer
  //then write them all at once after the IHDR
  
  //ancillary chunks, eg comments
  unsigned char *ancil_chunks_buf = calloc(1,1);
  long long ancil_chunks_len = 0;

  unsigned char *unzip_idats_buf = calloc(1, 1);
  long unzip_buf_len = 1;
  long unzip_buf_offset = 0;

  long long zipped_idats_len = 0; //Length of all idats as we read them

  unsigned long accum_png_len = 8 + (4+4+13+4);

  int chunk_count = 0;

  printf("Uncompressing image data...\n");
  while (1) {
    unsigned char chunk_label[4];
    unsigned char chunk_len_buf[4];

    buf_read(chunk_len_buf, &pngp, 4);

    //first 4 bytes are the length of data section
    long chunk_len = four_bytes_to_int(chunk_len_buf);

    accum_png_len += chunk_len + 4 + 4 + 4; // plus len, crc, label
    DEBUG_PRINT(("at %lu --> %lld\n", accum_png_len, PNG_LENGTH));

    //leave at end of buffer
    if (accum_png_len >= PNG_LENGTH)
      break;

    //read the chunk label (name of this header)
    buf_read(chunk_label, &pngp, 4);

    DEBUG_PRINT(("Reading chunk %d with label '%c%c%c%c', size %ld\n",
          chunk_count, chunk_label[0], chunk_label[1], chunk_label[2],
          chunk_label[3], chunk_len));

    chunk_count += 1;

    if (memcmp(chunk_label, "IDAT", 4) == 0) {

      zipped_idats_len += chunk_len;

      //read the chunk's data section
      unsigned char *raw_chunk_buf = calloc(chunk_len, 1);
      buf_read(raw_chunk_buf, &pngp, chunk_len);

      //Tell inflate to uncompress it
      inflate_stream.next_in = raw_chunk_buf; 
      inflate_stream.avail_in = chunk_len; 

      //Now uncompress it (resizes buffer automatically)
      unsigned char *check_uncompress = uncompress_buffer(&inflate_stream, 
          unzip_idats_buf, &unzip_buf_len, &unzip_buf_offset);

      //Stop if error
      if (check_uncompress == NULL) {
        DEBUG_PRINT((E_GLITCH));
        free(ancil_chunks_buf);
        free(raw_chunk_buf);
        free(unzip_idats_buf);
        free(ENTIRE_PNG_BUF);
        return -1;
      }

      //Moving on
      unzip_idats_buf = check_uncompress;
      free(raw_chunk_buf);
      pngp += 4; // skip CRC

    } else { //This is not an idat

      ancil_chunks_buf = realloc(ancil_chunks_buf, 
          ancil_chunks_len + 4 + 4 + chunk_len + 4); //make room for new data

      //append length and label bytes
      append_bytes(ancil_chunks_buf, chunk_len_buf, &ancil_chunks_len, 4);
      append_bytes(ancil_chunks_buf, chunk_label, &ancil_chunks_len, 4);

      //append chunk data
      unsigned char *raw_chunk_buf = calloc(chunk_len, 1);
      buf_read(raw_chunk_buf, &pngp, chunk_len);
      append_bytes(ancil_chunks_buf, raw_chunk_buf, &ancil_chunks_len, chunk_len );

      //append chunk crc
      unsigned char chunk_crc_buf[4];
      buf_read(chunk_crc_buf, &pngp, 4);
      append_bytes(ancil_chunks_buf, chunk_crc_buf, &ancil_chunks_len, 4);

      free(raw_chunk_buf);

      DEBUG_PRINT(("ancillary chunks length: %lld\n", ancil_chunks_len));

    }
  }

  //buf contains all idats uncompressed, concatenated
  unsigned long unzipped_idats_len = inflate_stream.total_out; 
  unzip_idats_buf = realloc(unzip_idats_buf, unzipped_idats_len);

  //we already have ancillary chunks and idats, don't need the original
  free(ENTIRE_PNG_BUF);
  inflateEnd(&inflate_stream);

  printf("Uncompressed %lld bytes to %ld bytes\n", zipped_idats_len, unzipped_idats_len);

  printf("Glitching image data...\n");

  for (int g=0;g<NUM_OUTPUT_FILES;g++) {

    //do glitches
    switch(g) {
      case 5:
        glitch_random(unzip_idats_buf, unzipped_idats_len,
            ihdr_infos.scanline_len, 0.0005);
        break;
      case 6:
        glitch_random_filter(unzip_idats_buf, unzipped_idats_len,
            ihdr_infos.scanline_len);
        break;
      default:
        glitch_filter(unzip_idats_buf, unzipped_idats_len,
            ihdr_infos.scanline_len, g);
    }

    //recompress so we can write them to file
    long long glitched_idats_len = 0;
    unsigned char *glitched_idats = zip_idats(unzip_idats_buf,
        unzipped_idats_len, &glitched_idats_len);

    if (glitched_idats == NULL) {
      DEBUG_PRINT((E_GLITCH));
      free (unzip_idats_buf);
      free (ancil_chunks_buf);
      return -1;
    }

    char path[MAX_PATH_LENGTH];
    bzero(path, MAX_PATH_LENGTH);

    snprintf(path, MAX_PATH_LENGTH, "%s%s%s-%d.png", OUTPUT_DIRECTORY, DIR_SEP,
        base_file_name, g);

    DEBUG_PRINT(("Output file name is %s\n", path));

    FILE *outfp = fopen(path, "wb");

    write_glitched_image(glitched_idats, glitched_idats_len, ihdr_bytes_buf,
        ancil_chunks_buf, ancil_chunks_len, outfp);

    printf("%s\n", path);
    fflush(stdout);

    fclose(outfp);
    free(glitched_idats);
  }

  free(ancil_chunks_buf);
  free(unzip_idats_buf);
  return 0;
}
Exemple #21
0
int machine_execute (Machine *m) {
  assert (m != NULL);

  m->IP = 0 ;
  
  int op = m->segment_code[m->IP] ;
  int v1, v2 ;
  char c ;
  int stop = 0 ;

  while (!stop) {
    switch (op) {
    case add :
      v1 = m->segment_data[m->SP-1] ;
      v2 = m->segment_data[m->SP-2] ;
      m->segment_data[m->SP-2] = v1 + v2 ;
      m->SP -- ;
      m->IP ++ ;
      break ;

    case and :
      v1 = m->segment_data[m->SP-1] ;
      v2 = m->segment_data[m->SP-2] ;
      m->segment_data[m->SP-2] = v1 & v2 ;
      m->SP -- ;
      m->IP ++ ;      
      break ;

    case call :
      m->segment_data[m->SP] = m->IP + 2 ;
      m->IP = m->segment_code[m->IP+1] ;
      m->SP ++ ;
      break ;

    case calls :
      break ;

    case cont :
      v1 = m->segment_data[m->segment_data[m->SP-1]] ;
      m->segment_data[m->SP-1] = v1 ;
      m->IP ++ ;
      break ;

    case cpy :
      v1 = m->segment_code[m->IP+1];
      v2 = m->segment_data[m->SP-1] ;

      for(c = 0 ; c < v1 ; c++)
	m->segment_data[m->SP-1+c] = m->segment_data[v2+c];

      m->SP += (v1-1);
      m->IP += 2 ;
      break ;
      
    case dec :
      v1 = m->segment_code [m->IP+1] ;
      m->SP -= v1;
      if (m->SP < 0)
	error_fatal ("pointeur de pile incorrect") ;

      m->IP += 2 ;
      break ;

    case divi :
      v1 = m->segment_data[m->SP-1] ;
      v2 = m->segment_data[m->SP-2] ;
      m->segment_data[m->SP-2] = v1 / v2 ;
      m->SP -- ;
      m->IP ++ ;
      break ;

    case eq :
      v1 = m->segment_data[m->SP-1] ;
      v2 = m->segment_data[m->SP-2] ;
      if (v1 == v2)
	m->segment_data[m->SP-2] = 1 ;
      else 
	m->segment_data[m->SP-2] = 0 ;
      m->SP -- ;
      m->IP ++ ;
      break ;

    case gt :
      v1 = m->segment_data[m->SP-1] ;
      v2 = m->segment_data[m->SP-2] ;
      if (v1 < v2)
	m->segment_data[m->SP-2] = 1 ;
      else 
	m->segment_data[m->SP-2] = 0 ;
      m->SP -- ;
      m->IP ++ ;
      break ;

    case halt :
      stop = 1 ;
      break ;

    case in :
      scanf ("%d", &v1);
      m->segment_data[m->segment_data[m->SP-1]] = v1 ;
      m->SP -- ;
      m->IP ++ ;
      break ;

    case inc :
      v1 = m->segment_code [m->IP+1] ;
      m->SP += v1;
      if (m->SP >= SEGMENT_DATA_SIZE)
	error_fatal ("pointeur de pile incorrect") ;

      m->IP += 2 ;
      break ;

    case jp :
      m->IP = m->segment_code[m->IP+1];
      break ;

    case jf :
      if (m->segment_data[m->SP-1] == 0)
	m->IP = m->segment_code[m->IP+1];
      else 
	m->IP += 2 ;

      m->SP -- ;
      break ;

    case jl :
      v1 = m->segment_data[m->SP-1] ;
      v2 = m->segment_data[m->SP-2] ;
      if (v1 > v2)
	m->IP = m->segment_code[m->IP+1];
      else 
	m->IP += 2 ;

      m->SP -= 2 ;
      break ;

    case jg :
      v1 = m->segment_data[m->SP-1] ;
      v2 = m->segment_data[m->SP-2] ;
      if (v1 < v2)
	m->IP = m->segment_code[m->IP+1];
      else 
	m->IP += 2 ;

      m->SP -= 2 ;
      break ;

    case les :
      v1 = m->segment_data[m->SP-1] ;
      v2 = m->segment_data[m->SP-2] ;
      if (v1 > v2)
	m->segment_data[m->SP-2] = 1 ;
      else 
	m->segment_data[m->SP-2] = 0 ;
      m->SP -- ;
      m->IP ++ ;
      break ;

    case libp :
      v1 = m->segment_code[m->IP+1] ;
      //v2 = m->segment_data[m->BP + v1] ; pour la donnée et
      v2 = m->BP + v1 ; // pour l'adresse

      m->segment_data[m->SP] = v2 ;
      m->SP ++ ;
      m->IP += 2 ;
      break ;

    case move :
      v1 = m->segment_code[m->IP+1] ;
      v2 = m->segment_data[m->SP - v1 - 1] ;

      for (c = 0 ; c < v1 ; c++)
	m->segment_data[v2+c] = m->segment_data[m->SP - v1 + c] ;

      m->SP -= (v1 + 1) ;
      m->IP += 2 ;
      break ;

    case mult :
      v1 = m->segment_data[m->SP-1] ;
      v2 = m->segment_data[m->SP-2] ;
      m->segment_data[m->SP-2] = v1 * v2 ;
      m->SP -- ;
      m->IP ++ ;
      break ;

    case neg :
      v1 = m->segment_data[m->SP-1] ;
      m->segment_data[m->SP-1] = -v1 ;
      m->IP ++ ;
      break ;

    case not :
      v1 = m->segment_data[m->SP-1] ;
      if (v1 == 0)
	m->segment_data[m->SP-1] = 1 ;
      else 
	m->segment_data[m->SP-1] = 0 ;
      m->IP ++ ;
      break ;

    case or :
      v1 = m->segment_data[m->SP-1] ;
      v2 = m->segment_data[m->SP-2] ;
      m->segment_data[m->SP-2] = v1 | v2 ;
      m->SP -- ;
      m->IP ++ ;
      break ;

    case out :
      fprintf (stdout, "%d\n", m->segment_data[m->SP-1]) ;
      m->SP -- ;
      m->IP ++ ;
      break ;

    case outc :
      m->IP++ ;
      while ((c = m->segment_code[m->IP++]) != 0)
	fprintf (stdout, "%c", c);
      break ;

    case pow :
      v1 = m->segment_data[m->SP-1] ;
      v2 = m->segment_data[m->SP-2] ;
      m->segment_data[m->SP-2] = puissance (v2,v1);
      m->SP -- ;
      m->IP ++ ;
      break ;

    case push :
      m->segment_data[m->SP] = m->segment_code[m->IP+1] ;
      m->SP ++ ;
      m->IP += 2 ;
      break ;

    case pushr:
      break ;

    case ret :
      m->IP = m->segment_data[m->SP-1] ;
      m->SP -- ;
      break ;

    case rstrbp :
      m->BP =m->segment_data[m->SP-1] ;
      m->SP -- ;
      m->IP ++ ;
      break ;

    case savebp :
      m->segment_data[m->SP] = m->BP ;
      m->BP = m->SP + 1 ;
      m->SP ++ ;
      m->IP ++ ;
      break ;

    case sub :
      v1 = m->segment_data[m->SP-1] ;
      v2 = m->segment_data[m->SP-2] ;
      m->segment_data[m->SP-2] = v1 - v2 ;
      m->SP -- ;
      m->IP ++ ;
      break ;

    default :
      error_fatal ("instruction inconnu") ;
    }

    op = m->segment_code[m->IP] ;
  }
  return 0 ;
}
Exemple #22
0
//-----------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------
void Fehler( const char* message )
{
    error_fatal( message );
};
// Optional change of configuration (if different from default)
Revolver::Revolver(rpf_parameters& parameters)
{
	m_Addr = 0;
	m_currentFilter = -1;
	char	str[80];

	m_RPF_parameters.nfw		= parameters.nfw	;
	m_RPF_parameters.nfilt		= parameters.nfilt	;
	// filter steps
	m_RPF_parameters.step		= parameters.step	;

	m_RPF_parameters.com		= parameters.com	;
	m_RPF_parameters.baud		= parameters.baud	;
	m_RPF_parameters.hold		= parameters.hold	;
	m_RPF_parameters.torque		= parameters.torque	;
	m_RPF_parameters.offset		= parameters.offset	;
	m_RPF_parameters.calspd		= parameters.calspd	;
	m_RPF_parameters.slope		= parameters.slope	;
	m_RPF_parameters.stspd		= parameters.stspd	;
	m_RPF_parameters.enspd		= parameters.enspd	;
	m_RPF_parameters.feed		= parameters.feed	;
	m_RPF_parameters.dly		= parameters.dly	;

	int er = SioReset(m_RPF_parameters.com, 64, 64);
	if (er != 0)
	{
		if (er == IE_BADID)
			error_fatal("Init Revolver", "Imposible abrir COM: Puerto inexistente", 0);
		if (er == IE_OPEN)
			error_fatal("Init Revolver", "Imposible abrir COM: Puerto ya abierto", 0);
		if (er == IE_MEMORY)
			error_fatal("Init Revolver", "Imposible abrir COM: No hay memoria suficiente", 0);
		else
			error_fatal("Init Revolver", "Imposible abrir COM", 0);
		return;
	}
	er = SioBaud(m_RPF_parameters.com, m_RPF_parameters.baud);
	if (er == IE_BAUDRATE )
	{
		error_fatal("Init Revolver", "Unsupported boud rate", 0);
		return;
	}
	for(int n = 0; n < m_RPF_parameters.nfw; n++)
	{	
		m_Addr = n;
		// Hold
		sprintf(str, "9%d", m_RPF_parameters.hold);
		Cmd(str);
		// Torque value
		sprintf(str, "3%04X", m_RPF_parameters.torque);
		Cmd(str);
		// Offset value
		sprintf(str, "4%02X", m_RPF_parameters.offset + 127);
		Cmd(str);
		// Num. of filters
		sprintf(str, "5%02X", m_RPF_parameters.nfilt);
		Cmd(str);
		// Num. of filters
		sprintf(str, "6%03X", m_RPF_parameters.step);
		Cmd(str);
		// Calibration speed
		sprintf(str, "8%04X", m_RPF_parameters.calspd);
		Cmd(str);
		// Slope
		sprintf(str, "A%02X", m_RPF_parameters.slope);
		Cmd(str);
		// Start speed
		sprintf(str, "B%04X", m_RPF_parameters.stspd);
		Cmd(str);
		// End speed
		sprintf(str, "C%04X", m_RPF_parameters.enspd);
		Cmd(str);
		// Enable feedback
		sprintf(str, "L%d", m_RPF_parameters.feed);
		Cmd(str);
		// Delay after pos.
		sprintf(str, "K%04X", m_RPF_parameters.dly);
		Cmd(str);
		// Calibrate
		Calibrate();
	}
}
Revolver::Revolver()
{
	m_Addr = 0;
	m_currentFilter = -1;
	char	str[80];

	// Inicializamos
	m_RPF_parameters.nfw		= 1;
	m_RPF_parameters.nfilt		= MAX_FILTROS_DTA;
	// filter steps
	m_RPF_parameters.step		= 800 / m_RPF_parameters.nfilt;

	m_RPF_parameters.com		= COM5;
	m_RPF_parameters.baud		= Baud19200;
	m_RPF_parameters.hold		= 1;
	m_RPF_parameters.torque		= 15984;
	m_RPF_parameters.offset		= 0;
	m_RPF_parameters.calspd		= 20000;
	m_RPF_parameters.slope		= 255;
	m_RPF_parameters.stspd		= 65535;
	m_RPF_parameters.enspd		= 6144;
	m_RPF_parameters.feed		= 1;
	m_RPF_parameters.dly		= 125;

	//Cargamos
	LoadCFG(m_RPF_parameters);

	int er = SioReset(m_RPF_parameters.com, 64, 64);
	if (er != 0)
	{
		if (er == IE_BADID)
			error_fatal("Init Revolver", "Imposible abrir COM: Puerto inexistente", 0);
		if (er == IE_OPEN)
			error_fatal("Init Revolver", "Imposible abrir COM: Puerto ya abierto", 0);
		if (er == IE_MEMORY)
			error_fatal("Init Revolver", "Imposible abrir COM: No hay memoria suficiente", 0);
		else
			error_fatal("Init Revolver", "Imposible abrir COM", 0);
		return;
	}
	er = SioBaud(m_RPF_parameters.com, m_RPF_parameters.baud);
	if (er == IE_BAUDRATE )
	{
		error_fatal("Init Revolver", "Unsupported boud rate", 0);
		return;
	}
 	for(int n = 0; n < m_RPF_parameters.nfw; n++)
	{	
		m_Addr = n;
		// Hold
		sprintf(str, "9%d", m_RPF_parameters.hold);
		if (Cmd(str) == false)
        {
			AfxMessageBox("***  Init Revolver: No hay respuesta por el puerto COM, asegurese que el dispositivo esta conectado");
            exit(-1);
        }

		// Torque value
		sprintf(str, "3%04X", m_RPF_parameters.torque);
		Cmd(str);
		// Offset value
		sprintf(str, "4%02X", m_RPF_parameters.offset + 127);
		Cmd(str);
		// Num. of filters
		sprintf(str, "5%02X", m_RPF_parameters.nfilt);
		Cmd(str);
		// Num. of filters
		sprintf(str, "6%03X", m_RPF_parameters.step);
		Cmd(str);
		// Calibration speed
		sprintf(str, "8%04X", m_RPF_parameters.calspd);
		Cmd(str);
		// Slope
		sprintf(str, "A%02X", m_RPF_parameters.slope);
		Cmd(str);
		// Start speed
		sprintf(str, "B%04X", m_RPF_parameters.stspd);
		Cmd(str);
		// End speed
		sprintf(str, "C%04X", m_RPF_parameters.enspd);
		Cmd(str);
		// Enable feedback
		sprintf(str, "L%d", m_RPF_parameters.feed);
		Cmd(str);
		// Delay after pos.
		sprintf(str, "K%04X", m_RPF_parameters.dly);
		Cmd(str);
		// Calibrate
		Calibrate();
	}
}
/*************************** configura_digitalizador *************************
	Función para configurar el digitalizador para el formato de imagen que
	se desea emplear en la adquisición.
*****************************************************************************/
int configura_digitalizador(int formato)
{
    static bool bConfigurado = false;

	//	Compruebo si los digitalizadores son iguales. Si no son iguales
	//	libero el digitalizador antiguo, para reservarlo según las nuevas
	//	especificaciones. 
	if ( strcmp(paramAux->Cam.formatoDig, paramAux->Cam.formatoDig_e) || !bConfigurado)  
    {

	//	Si el digitalizador esta reservado, libero la memoria reservada, para
	//		poder configurarlo. 
		if ( M_digitalizador != M_NULL )	libera_digitalizador();

		switch (formato) {
			case FORMATO_NORMAL:
				MdigAlloc (M_sistema, M_DEV0, paramAux->Cam.formatoDig, M_DEFAULT, &M_digitalizador);
				break;
			case FORMATO_ENFOQUE:
				MdigAlloc (M_sistema, M_DEV0, paramAux->Cam.formatoDig_e, M_DEFAULT, &M_digitalizador);
				break;
			default:
				error_fatal("configura_digitalizador", "Formato de digitalización inaceptable", 0);
				return 1;
		}

		// Fijamos los parámetros de adquisición, según los datos leidos del fichero ini. 
		MdigControl(M_digitalizador, M_BRIGHTNESS, paramAux->Cam.brillo);
		MdigControl(M_digitalizador, M_GAIN, paramAux->Cam.ganancia);
        ModificaExposicion(paramAux->Rueda.exposicion[paramAux->Rueda.posFiltro]);
        ModificaBaseExposicion(paramAux->Rueda.base_exp[paramAux->Rueda.posFiltro]);
	}

	if (paramAux->Cam.anchoImagen != paramAux->Cam.anchoImagen_e    || 
        paramAux->Cam.altoImagen != paramAux->Cam.altoImagen_e      || 
        !bConfigurado)
    {

	    //	Selecciono la configuración del digitalizador. 
	    MdigControl(M_digitalizador, M_SOURCE_OFFSET_X, 0); // Necesario para evitar salirnos del cuadro
	    MdigControl(M_digitalizador, M_SOURCE_OFFSET_Y, 0); // al modificar el tamaño de la captura
	    switch (formato) {
		    case FORMATO_NORMAL:
			    MdigControl(M_digitalizador, M_SOURCE_SIZE_X, paramAux->Cam.anchoImagen);
			    MdigControl(M_digitalizador, M_SOURCE_OFFSET_X, (limCam.anchoDig - paramAux->Cam.anchoImagen) / 2);

                MdigControl(M_digitalizador, M_SOURCE_SIZE_Y, paramAux->Cam.altoImagen);
			    MdigControl(M_digitalizador, M_SOURCE_OFFSET_Y, (limCam.altoDig - paramAux->Cam.altoImagen) / 2);

    //			ModificaExposicion(paramAux->Cam.exposicion[paramAux->Mtb.posFiltro]);
			    break;
		    case FORMATO_ENFOQUE:
			    MdigControl(M_digitalizador, M_SOURCE_SIZE_X, paramAux->Cam.anchoImagen_e);
			    MdigControl(M_digitalizador, M_SOURCE_OFFSET_X, (limCam.anchoDig_e - paramAux->Cam.anchoImagen_e) / 2);

			    MdigControl(M_digitalizador, M_SOURCE_SIZE_Y, paramAux->Cam.altoImagen_e);
			    MdigControl(M_digitalizador, M_SOURCE_OFFSET_Y, (limCam.altoDig_e - paramAux->Cam.altoImagen_e) / 2);

    //			ModificaExposicion(paramAux->Cam.exposicion[paramAux->Mtb.posFiltro]);
			    break;
	    }
    }

    // Nos aseguramos de que lo anterior sólo se ejecuta una vez si el formato y las dimensiones 
    // del digitalizador son iguales para adquisición normal y autoenfoque
    bConfigurado = true;

	return 0;
}
/**
 * \brief Main application
 */
int main(void)
{
	char test_file_name[] = "0:sd_image.bin";
	FRESULT res;
	FATFS fs;
	FIL file_object;
	uint32_t len=0;
	uint32_t curr_prog_addr=APP_START_ADDRESS;
	struct nvm_config config;
	UINT iRead=0;
    
	check_boot_mode();
	system_init();
	delay_init();

	irq_initialize_vectors();
	cpu_irq_enable();

	/* Initialize SD MMC stack */
	sd_mmc_init();
	
	nvm_get_config_defaults(&config);
	nvm_set_config(&config);
		/* Turn ON  LED */
	port_pin_set_output_level(BOOT_LED, false);
#ifdef __DEBUG_PRINT__	
    serial_port_init();
	printf("\x0C\n\r-- SD/MMC Card FatFs Boot Loader --\n\r");
	printf("-- Compiled: %s %s --\n\r", __DATE__, __TIME__);
	printf("Please plug an SD/MMC card in slot.\n\r");
#endif	

		/* Wait card present and ready */
	sd_mmc_ready();
	memset(&fs, 0, sizeof(FATFS));
	res = f_mount(LUN_ID_SD_MMC_0_MEM, &fs);
	if (FR_INVALID_DRIVE == res) {
		#ifdef __DEBUG_PRINT__	
		printf("[FAIL] Mounting SD card failed result= %d\r\n", res);
		#endif
			
	}
	#ifdef __DEBUG_PRINT__	
	printf("Mounting the SD card successful...\r\n");
	#endif
   
	res =f_open(&file_object,(const char *)test_file_name,FA_READ);
	if(res != FR_OK) error_fatal(FILE_OPEN_ERROR);
	do {
		if(file_object.fsize > MAX_CODE_SIZE) error_fatal(MAX_SIZE_ERROR);
		res = f_read(&file_object, (void *) buff, MAX_BUF_SIZE, &iRead);
		if(res != FR_OK) error_fatal(FILE_READ_ERROR);
	
		/* Program the read data into Flash */
		if(iRead)
		{
			program_memory(curr_prog_addr, buff,iRead);
			#ifdef __DEBUG_PRINT__
			printf("*");
			#endif
		}

		/* Increment the current programming address */
		curr_prog_addr += iRead;
		len += iRead;
	
		if(len > MAX_CODE_SIZE)
		error_fatal(MAX_SIZE_ERROR);

		/* Do this till end of file */
	} while (iRead != 0);

#ifdef __DEBUG_PRINT__		
printf("\r\n[PROGRAMMING COMPLETED]..Resetting !!!!\r\n");
#endif
		// Intentionally not closing the file object to reduce code size !!!.
		start_application();
		while(1);
		 // Should have reset by now !!!.		
}
/*************************** ini_control_digitalizador  *********************
	Función para reservar memoria para los diferentes formatos de
	digitalizadores que se utilizarán en la toma de imágenes.
	Previamente, se comprueba que los parámetros iniciales son válidos para
	el formato y tipo de digitalizador reservado.
	Seguidamente se reserva el display y los buffers que se utilizan en el
	proceso de adquisición de imágenes.
*****************************************************************************/
int ini_control_digitalizador(parametros *param)
{
	char	*fn = "ini_control_digitalizador - ";
	int		i;

	paramAux = param; //para usar en otras funciones

	//	SI DEFINO UN TAMAÑO DE DIGITALIZADOR DE ENFOQUE...	(DIGITALIZADOR)
	//	Reservo memoria para un nuevo display en el que se mostrarán los campos
	//	recorridos y los que se han podido enfocar. 
	if (param->Cam.formatoDig_e[0] != '\0' &&
		strcmp(param->Cam.formatoDig, param->Cam.formatoDig_e) )  
    {

		//	Configuro el digitalizador en formato enfoque
		if (M_digitalizador != M_NULL)
			libera_digitalizador();
		if ( MdigAlloc (M_sistema, M_DEV0, param->Cam.formatoDig_e, M_DEFAULT, &M_digitalizador)
			== M_NULL )  
        {
			error_fatal("ini_control_digitalizador", "Formato incorrecto", 0);
#if !defined (__BORLANDC__)
			putch('\a');
#endif
			return 1;
		}
		MdigInquire(M_digitalizador, M_SIZE_X, &limCam.anchoDig_e);
		if ( limCam.anchoDig_e > MAX_ANCHO_IMAGEN ||
				limCam.anchoDig_e < param->Cam.anchoImagen_e )  
        {
			error_fatal(fn, "Error en los parámetros iniciales", 0);
#if !defined (__BORLANDC__)
			putch('\a');
#endif
			return 1;
		}

		MdigInquire(M_digitalizador, M_SIZE_Y, &limCam.altoDig_e);
		if ( limCam.altoDig_e > MAX_ALTO_IMAGEN || 
                limCam.altoDig_e < param->Cam.altoImagen_e )  
        {
			error_fatal(fn, "Error en los parámetros iniciales", 0);
#if !defined (__BORLANDC__)
			putch('\a');
#endif
			return 1;
		}
	}


	//	Configuro el digitalizador en formato normal. 
	if (M_digitalizador != M_NULL)
		libera_digitalizador();

	if ( MdigAlloc (M_sistema, M_DEV0, param->Cam.formatoDig, M_DEFAULT, &M_digitalizador)
		== M_NULL )  {
		error_fatal("ini_control_proceso_imagenes", "Formato incorrecto", 0);
		return 1;
	}
	MdigInquire(M_digitalizador, M_SIZE_X, &limCam.anchoDig);
	if ( limCam.anchoDig > MAX_ANCHO_IMAGEN ||
			limCam.anchoDig < param->Cam.anchoImagen )  {
		error_fatal(fn, "Error en los parámetros iniciales", 0);
#if !defined (__BORLANDC__)
		putch('\a');
#endif
		return 1;
	}

	MdigInquire(M_digitalizador, M_SIZE_Y, &limCam.altoDig);
	if ( limCam.altoDig > MAX_ALTO_IMAGEN || 
            limCam.altoDig < param->Cam.altoImagen )  {
		error_fatal(fn, "Error en los parámetros iniciales", 0);
#if !defined (__BORLANDC__)
		putch('\a');
#endif
		return 1;
	}

	//	Si el formato del digitalizador de enfoque es el mismo que el de
	//	captura normal, copiamos las dimensiones porque no se leyeron. 
	if ( strcmp(param->Cam.formatoDig, param->Cam.formatoDig_e) == 0 )  {
		limCam.anchoDig_e = limCam.anchoDig;
		limCam.altoDig_e = limCam.altoDig;
	}

	//	Compruebo los valores iniciales de brillo, ganancia y exposición. 
	if ( info_digitalizador(M_digitalizador) )  {
		error_fatal(fn, "Error en los parámetros iniciales", 0);
		return 1;
	}

    // Se centra la camara en el caso de que se haya configurado un tamaño de toma diferente al maximo de la camara
	if ( configura_digitalizador(FORMATO_NORMAL) )  
        return 1;

	//	Buffer auxiliar de PROFUNDIDAD_ACUMULACION bits para acumular valores.
	MbufAlloc2d(M_sistema, param->Cam.anchoImagen, param->Cam.altoImagen, PROFUNDIDAD_ACUMULACION+M_UNSIGNED,
		M_IMAGE+M_DISP+M_PROC+M_GRAB, &M_imagen_acum);
	if ( M_imagen_acum == M_NULL )  {
		error_fatal(fn, "M_imagen_acum", 0);
		return 1;
	}

    // Obtenemos la profundidad de la camara
	MdigInquire(M_digitalizador, M_SIZE_BIT , &param->Cam.profundidad);

    if ( (BITS_CAMARA > 8 && param->Cam.profundidad <= 8) ||
         (BITS_CAMARA <= 8 && param->Cam.profundidad > 8) )
    {
		error_fatal(fn, "BITS_CAMARA (DEFINE en codigo) y profundidad camara no coherentes", 0);
		return 1;
	}

    //Si la profundidad no es de 8bit, hay que configurar el display.
    //El display siempre es de 8 bit
    if (param->Cam.profundidad == 16)
    {
        MdispControl(M_display_normal,M_VIEW_MODE,M_BIT_SHIFT);
        MdispControl(M_display_normal,M_VIEW_BIT_SHIFT,4); //despreciamos los 4 bits menos significativos
		MdispLut(M_display_normal, M_PSEUDO); //esto es necesario para que la intensidad no sea anormalmente elevada
    }

	//	Reservamos los buffers donde se almacenarán y procesarán las imágenes. 
	//	M_imagen1 será el buffer que normalmente estará asociado al display_normal.

	// En modo VGA no permite grabar datos en el buffer.
    long nSD_size;
    MsysInquire(M_sistema,M_SYSTEM_DESCRIPTOR_SIZE,&nSD_size);
    char* systemDescriptor = new char[nSD_size];
    MsysInquire(M_sistema,M_SYSTEM_DESCRIPTOR,systemDescriptor);
	if (systemDescriptor == M_SYSTEM_VGA)
		MbufAlloc2d(M_sistema, param->Cam.anchoImagen, param->Cam.altoImagen, param->Cam.profundidad+M_UNSIGNED,
			M_IMAGE+M_DISP+M_PROC, &M_imagen1 );
	else
		MbufAlloc2d(M_sistema, param->Cam.anchoImagen, param->Cam.altoImagen, param->Cam.profundidad+M_UNSIGNED,
			M_IMAGE+M_DISP+M_GRAB+M_PROC, &M_imagen1 );
    delete [ ] systemDescriptor;
	if ( M_imagen1 == M_NULL)  {
		error_fatal(fn, "M_imagen1", 0);
		return -1;
	}
	if ( M_imagen1 != M_NULL )  
    {
	//	Seleccionamos el display para imagen normal, asociando el overlay. 
#if !defined (__BORLANDC__)
	    configura_overlay(M_display_normal, M_imagen1, &M_overlay_normal, 1);
#else
	    configura_overlay(M_display_normal, M_imagen1, HWindow, &M_overlay_normal, 1);
        borra_buffer(M_imagen1, NEGRO, 0, 0, NULL, NULL);
#endif
/*
*/
	    if (param->Cam.anchoImagen != param->Cam.anchoImagen_e    || 
            param->Cam.altoImagen != param->Cam.altoImagen_e)  
        {
            // Reservo un child buffer de M_imagen1 con el tamaño de enfoque.
            MbufChild2d(M_imagen1, (param->Cam.anchoImagen - param->Cam.anchoImagen_e) /2,
                (param->Cam.altoImagen- param->Cam.altoImagen_e) /2,
                param->Cam.anchoImagen_e, param->Cam.altoImagen_e, &M_centro_imagen);
            if (M_centro_imagen == M_NULL)  
            {
                error_fatal(fn, "M_centro_imagen", 0);
                return -1;
		    }
        }
        else
            M_centro_imagen = M_imagen1;
	}

	MbufAlloc2d(M_sistema, param->Cam.anchoImagen, param->Cam.altoImagen, param->Cam.profundidad+M_UNSIGNED,
		M_IMAGE+M_DISP+M_PROC, &M_imagen2 );
	if ( M_imagen2 == M_NULL )  {
		error_fatal(fn, "M_imagen2", 0);
		return -1;
	}

	MbufAlloc2d(M_sistema, param->Cam.anchoImagen, param->Cam.altoImagen, param->Cam.profundidad+M_UNSIGNED,
		M_IMAGE+M_DISP+M_PROC, &M_imagen3);
	if ( M_imagen3 == M_NULL )  {
		error_fatal(fn, "M_imagen3", 0);
		return -1;
	}

	MbufAlloc2d(M_sistema, param->Cam.anchoImagen, param->Cam.altoImagen, param->Cam.profundidad+M_UNSIGNED,
		M_IMAGE+M_DISP+M_PROC, &M_imagen4);
	if ( M_imagen4 == M_NULL )  {
		error_fatal(fn, "M_imagen4", 0);
		return -1;
	}

	MbufAlloc2d(M_sistema, param->Cam.anchoImagen, param->Cam.altoImagen, param->Cam.profundidad+M_UNSIGNED,
		M_IMAGE+M_DISP+M_PROC, &M_imagen5);
	if ( M_imagen5 == M_NULL )  {
		error_fatal(fn, "M_imagen5", 0);
		return -1;
	}

	MbufAlloc2d(M_sistema, param->Cam.anchoImagen, param->Cam.altoImagen, param->Cam.profundidad+M_UNSIGNED,
		M_IMAGE+M_DISP+M_PROC, &M_imagen6);
	if ( M_imagen6 == M_NULL )  {
		error_fatal(fn, "M_imagen6", 0);
		return -1;
	}

	//	Reservo memoria para los buffers utilizados en la adquisición
	//	de las bandas y en la correccion de la iluminación.
	for (i=0; i < param->nBandas; i++) {
		MbufAlloc2d(M_sistema, param->Cam.anchoImagen, param->Cam.altoImagen, param->Cam.profundidad+M_UNSIGNED,
			M_IMAGE+M_DISP+M_PROC, &M_banda[i]);
		MbufAlloc2d(M_sistema, param->Cam.anchoImagen, param->Cam.altoImagen, 32+M_FLOAT,
			M_IMAGE+M_PROC, &M_correc_denom[i]);
		MbufAlloc2d(M_sistema, param->Cam.anchoImagen, param->Cam.altoImagen, 32+M_FLOAT,
			M_IMAGE+M_PROC, &M_correc_numer[i]);

		if ( M_banda[i] == M_NULL ||
				M_correc_numer[i] == M_NULL || M_correc_denom[i] == M_NULL )  {
			error_fatal(fn, "M_banda", 0);
			return 1;
		}
	}
    //El resto de filtros no usados a NULL
	for (; i < MAX_FILTROS_DTA; i++)
		M_banda[i] = M_correc_numer[i] = M_correc_denom[i] = M_NULL;

	MbufAlloc2d(M_sistema, param->Cam.anchoImagen, param->Cam.altoImagen, 32+M_FLOAT,
		M_IMAGE+M_PROC, &M_correc_aux);
	if ( M_correc_aux == M_NULL )  {
		error_fatal(fn, "M_correc_aux", 0);
		return 1;
	}

	//	SI DEFINO UN TAMAÑO DE DIGITALIZADOR DE ENFOQUE...	(BUFFERS)
    //	Reservo memoria para los buffers empleados durante el enfoque mediante la funcion determina_contraste2
	if ( param->Cam.formatoDig_e[0] != '\0' )  {
		MbufAlloc2d(M_sistema, param->Cam.anchoImagen_e, param->Cam.altoImagen_e, param->Cam.profundidad+M_UNSIGNED,
			M_IMAGE+M_DISP+M_GRAB+M_PROC, &M_enfoque);
		if ( M_enfoque == M_NULL )  {
			error_fatal(fn, "M_enfoque", 0);
			return 1;
		}
	}

	return 0;
}
Exemple #28
0
int read_seq (FILE *IN, seq_t *seq_holder, char *alphabet) {

  char *BUFF, *stock, *p, *q;
  int i, state, l;
  size_t buffsize, bufflen, seq_len;

  /* check if there is something to read */
  if ((i = fgetc(IN)) == EOF && feof(IN) != 0) {
    return NO_SEQ; }

  ungetc(i, IN);

  state = SEQ_NONE;
  seq_len = bufflen = 0;
  buffsize = BUFFSIZE;
  seq_holder->seq = NULL;

  if ((BUFF = (char *) malloc(sizeof(char) * buffsize+1 )) == NULL)
    error_fatal ("memory1" , NULL);
  if ((stock = (char *) malloc(sizeof(char) * buffsize+1 )) == NULL)
    error_fatal ("memory2" , NULL);

  *stock = '\0';
  q = stock;

  while ((i = fgetc(IN)) != EOF) {
    /* skip empty lines */
    if (isspace(i)) {continue;}
    
    if ( ungetc(i, IN) == EOF ) error_fatal ("ungetc", NULL);

    /* end entry or start entry */
    if ( i == '>' ) {
      if (state == SEQ_NONE )  state = HEADER;
      if (state == SEQ) break ;
    }

    if (fgets(BUFF, BUFFSIZE + 1, IN) == NULL)  break;

    /* header processing */
    if ( state == HEADER ) {

      /* memcopy with '/0' inclusion */
      memcpy(q, BUFF, BUFFSIZE+1);
      /* is header line completly read */
      if (strrchr(BUFF, '\n') == NULL) {
	if((stock = realloc(stock, buffsize + BUFFSIZE + 1)) == NULL)
	  error_fatal("realloc", NULL);
	q = stock + buffsize ;
	buffsize += BUFFSIZE ;
	continue;
      }
      process_header(seq_holder, stock);
      state = SEQ;
      buffsize = BUFFSIZE;
      p = stock;
      *p ='\0';
      continue;
    }

    if ( state == SEQ || state == DUMP ){
      /* we clean the buffer before any further use */
      if ((l = clean_buff(&BUFF,  alphabet)) == -1)
	error_fatal(seq_holder->id, "sequence contain spurious characters");
    }

    if (state == SEQ ) {
      bufflen = l;
      /* is stock buffer long enough */
      if ( seq_len + bufflen >= buffsize ) {
	buffsize += BUFFSIZE;
	if ((stock = realloc(stock, sizeof(char) * buffsize+1)) == NULL)
	  error_fatal("Memory3", "Reallocating seq");
      }
      q = stock + seq_len;
      strncpy (q, BUFF, bufflen);
      seq_len += bufflen;
    }

    if ( state == SEQ_NONE ) {
      error_fatal("Sequence", "is NOT fasta formated");
    }
  }


  free(BUFF);
  if ( state == SEQ ) {
    *(stock+seq_len) = '\0';
    seq_holder->seq = stock;
  }
  seq_holder->size = seq_len;

  return state;

}
Exemple #29
0
int main(int argc, char* argv[]) {

  int mkdir_ret = mkdir(OUTPUT_DIRECTORY, S_IRWXU);

  if (mkdir_ret == -1 && errno != EEXIST)
    error_fatal(1, "problem creating directory", strerror(errno));
  else if (access(OUTPUT_DIRECTORY, W_OK | X_OK))
    error_fatal(1, "Problem accessing directory", strerror(errno));

  char path[500];

  //No commandline arguments, so prompt for path
  while (argc <= 1) {
    printf("Enter PNG file path: ");
    char *s = fgets(path, 499, stdin);

    if (s == NULL)
      continue;

    char *newline = strrchr(s, '\n');
    *newline = '\0';

    FILE *f = fopen(s, "r");

    if (f == NULL) {
      printf("Could not open file '%s'\n", s);
      continue;
    }

    fclose(f);
    argc++;
    
    argv[1] = path; //Is this out of bounds?
  }


  for (int i=1;i<argc;i++) {

    char *file_path = argv[i];

    FILE *f = fopen(file_path, "rb");

    if (f == NULL) {
      printf("Cannot open file '%s'\n", file_path);
      continue;
    }

    unsigned char* png_buf = calloc(1, 1);

    PNG_LENGTH = get_file_buf(f, &png_buf); 
    printf("Glitching file '%s' (%.2lfM)\n", file_path, PNG_LENGTH / 1024.0 / 1024.0);

    if (PNG_LENGTH <= 0) {
      printf("File '%s' is empty!\n", file_path);
      free(png_buf);
      continue;
    }

    file_path = basename(file_path);
    remove_filename_extension(file_path);

    //png_buf is passed around to callbacks for libpng, it will be free'd there
    begin(file_path, png_buf, PNG_LENGTH);
    fclose(f);
  }

  return 0;
}
/**************************  adquierePat  ***********************************
Menu previo a la funcion haz_movimiento. Se pide el plano de regresion y los extremos del barrido
Devuelve '-1' si se ha cancelado la toma
    bExposicionAjustada - si false, habrá que ajustar la exposicion justo antes de comenzar el barrido
INTERFAZ
SOLO VISUAL
*****************************************************************************/
int adquierePat(parametros *param, char *tipoPat, bool bExposicionAjustada)
{
    int nRes;
	char mensaje[LONGITUD_TEXTO*2], linea[LONGITUD_TEXTO/2];
	point inicio, final;
	plane planoRegresion;
	plane* pPlanoRegresion = NULL; //si es NULL, no hay plano de regresion definido


	// Primero se pide que se enfoque las cuatro esquinas del patron y se calcula el plano de regresion
	if (definePlanoRegresion(*param, planoRegresion) == 0)
    {
		pPlanoRegresion = &planoRegresion;
	    sprintf(mensaje,"\n+-  DEFINE PUNTOS DE ADQUISICIÓN   ---------------------------------------+");
	    strcat(mensaje, "\n| Seleccione (NO ES NECESARIO ENFOCAR) los puntos extremos de una región en la que    |");
    }
    else
    {
	    sprintf(mensaje,"\n+-  DEFINE PUNTOS DE ADQUISICIÓN   ---------------------------------------+");
	    strcat(mensaje, "\n| Seleccione (ENFOCANDO) los puntos extremos de una región en la que      |");
    }

	sprintf(linea, "\n| desee adquirir las imágenes del patrón. Se recorrerán %d campos.        |", 
        param->BarridoPatrones.camposEjeX*param->BarridoPatrones.camposEjeY);
	strcat(mensaje, linea);
	sprintf(linea,  "\n| Se capturan las imágenes correspondientes al patrón: %s             |",
		tipoPat);
	strcat(mensaje, linea);
	strcat(mensaje, "\n+-------------------------------------------------------------------------+");
	CharToOem(mensaje,mensaje);
	printf(mensaje);

    if (TomaAutomatica.bAutomatica == true)
    {
        // Caso para realizar la toma de patrones sin iteraccion del usuario
	    return haz_movimiento(param, &TomaAutomatica.Puntos[0], &TomaAutomatica.Puntos[3], pPlanoRegresion, tipoPat);
    }
    else
    {
        if (pPlanoRegresion == NULL)
        {
            // El usuario debe enfocar
            // Se ha de enfocar con el filtro "de enfoque" (o "de referencia", es decir el monocromatico)
            Rueda.ChangeFilter(param->filtro[param.Rueda.posEnfoque]);
        }

	    sprintf(mensaje, "Sitúese en un extremo de la región del patrón");
	    sendop(mensaje);
	    printf("\n");

        nRes = pideP(&inicio);
        // OJO: esto se hace porque puede ser que el usuario haya enfocado manualmente antes
        // Estamos en el filtro "de enfoque" y sin embargo zPredefinido debe ser calculado para el pancromatico
        Rueda.zPredefinido = mspWhere(Z_) + param->Rueda.diferencia_z[param->Rueda.posFiltro] - param->Rueda.diferencia_z[param->filtro[param.Rueda.posEnfoque]] ;
	    if ( nRes < 0)
        {
            // se ha punsado ESC
            if (pPlanoRegresion == NULL) // si hay plano de regresion, el punto de enfoque nos da igual 
                // Regresamos al filtro predefinido (o de usuario)
                Rueda.ChangeFilter(param->Rueda.posFiltro);
		    return -1;
        }

	    sprintf(mensaje, "Sitúese en el extremo opuesto de la región del patrón\n");
	    sendop(mensaje);

        nRes = pideP(&final);
        // OJO: esto se hace porque puede ser que el usuario haya enfocado manualmente antes
        // Estamos en el filtro "de enfoque" y sin embargo zPredefinido debe ser calculado para el pancromatico
        Rueda.zPredefinido = mspWhere(Z_) + param->Rueda.diferencia_z[param->Rueda.posFiltro] - param->Rueda.diferencia_z[param->filtro[param.Rueda.posEnfoque]] ;
	    if ( nRes < 0)
        {
            // se ha punsado ESC
            if (pPlanoRegresion == NULL)
                // Regresamos al filtro predefinido (o de usuario)
                Rueda.ChangeFilter(param->Rueda.posFiltro);
		    return -1;
        }

	    printf("\n");
        if (pPlanoRegresion == NULL)
        {
            // El usuario debe enfocar
            // Regresamos al filtro predefinido (o de usuario)
            Rueda.ChangeFilter(param->Rueda.posFiltro);
        }

        if (tipoPat == "PAT_CL" && bExposicionAjustada == false)
        {
            //Ajustamos las exposiciones en el primer extremo antes de barrer 
            if (pPlanoRegresion != NULL)
            {
                // Z de enfoque (para el filtro de enfoque) segun el plano de regresion
                inicio.coord[Z_] = pPlanoRegresion->A * inicio.coord[X_] + pPlanoRegresion->B * inicio.coord[Y_] + pPlanoRegresion->C;
            }
            inicio.coord[Z_] += BACKSLASHZ;
	        mspGoP(inicio); //BACKSLASHZ
            inicio.coord[Z_] -= BACKSLASHZ;
	        mspGoP(inicio);
		    sendop ("Es obligatorio realizar el ajuste automatico de exposicion al menos una vez. Ajustando exposiciones ...");
            AjusteAutomaticoExposicion(M_digitalizador, param);
		    sendop ("Exposiciones ajustadas. Salvamos las nuevas exposiciones en el archivo de configuracion.");

		    if (crea_paramRevolver(param->raiz_patrones, param) )  {
			    error_fatal("control_parametros", "ERROR: No se puede crear el fichero de configuracion. Continuamos con la toma", 0);
		    }
        }

	    return haz_movimiento(param, &inicio, &final, pPlanoRegresion, tipoPat);
    }

}