]> Creatis software - gdcm.git/blob - src/gdcmJpeg.cxx
inclusion of code for jpeg compression
[gdcm.git] / src / gdcmJpeg.cxx
1 // gdcmJpeg.cxx
2 //-----------------------------------------------------------------------------
3 #include <stdio.h>
4 #include "gdcmFile.h"
5
6 #define BITS_IN_JSAMPLE 8
7
8 #ifdef GDCM_DEBUG
9 #define GDCM_jpr_DEBUG 0
10 #endif   //GDCM_DEBUG
11
12 /*
13 DICOM provides a mechanism for supporting the use of JPEG Image Compression 
14 through the Encapsulated Format (see PS 3.3 of the DICOM Standard). 
15 Annex A defines a number of Transfer Syntaxes which reference 
16 the JPEG Standard and provide a number of lossless (bit preserving) 
17 and lossy compression schemes.
18 In order to facilitate interoperability of implementations conforming 
19 to the DICOM Standard which elect to use one or more 
20 of the Transfer Syntaxes for JPEG Image Compression, the following policy is specified:
21
22   Any implementation which conforms to the DICOM Standard and has elected 
23   to support any one of the Transfer Syntaxes for lossless JPEG Image Compression, 
24   shall support the following lossless compression: 
25   The subset (first-order horizontal prediction [Selection Value 1) of JPEG Process 14 
26   (DPCM, non-hierarchical with Huffman coding) (see Annex F of the DICOM Standard).
27
28    Any implementation which conforms to the DICOM Standard and has elected 
29    to support any one of the Transfer Syntaxes for 8-bit lossy JPEG Image Compression, 
30    shall support the JPEG Baseline Compression (coding Process 1).
31
32    Any implementation which conforms to the DICOM Standard and has elected 
33    to support any one of the Transfer Syntaxes for 12-bit lossy JPEG Image Compression, 
34    shall support the JPEG Compression Process 4.
35
36 Note: The DICOM conformance statement shall differentiate between implementations 
37 that can simply receive JPEG encoded images and those that can receive and process 
38 JPEG encoded images (see PS 3.2 of the DICOM Standard).
39
40 The use of the DICOM Encapsulated Format to support JPEG Compressed Pixel Data 
41 implies that the Data Elements which are related to the Native Format Pixel Data encoding
42 (e.g. Bits Allocated, Bits Stored, High Bit, Pixel Representation, Rows, Columns, etc.) 
43 shall contain values which are consistent with the characteristics 
44 of the uncompressed pixel data from which the compressed Data Stream was derived. 
45 The Pixel Data characteristics included in the JPEG Interchange Format 
46 shall be used to decode the compressed data stream.
47
48 Run Length Encoding Compression
49
50 DICOM provides a mechanism for supporting the use of Run Length Encoding (RLE) 
51 Compression which is a byte oriented lossless compression scheme through 
52 the encapsulated Format (see PS 3.3 of this Standard). 
53 Annex G of the DICOM Standard defines RLE Compression and its Transfer Syntax.
54
55 Note: The RLE Compression algorithm described in Annex G 
56 of the DICOM Standard is the compression used in 
57 the TIFF 6.0 specification known as the "PackBits" scheme.
58
59 The use of the DICOM Encapsulated Format to support RLE Compressed Pixel Data 
60 implies that the Data Elements which are related to the Native Format Pixel Data encoding (
61 e.g. Bits Allocated, Bits Stored, High Bit, Pixel Representation, Rows, Columns, etc.) 
62 shall contain values which are consistent with the characteristics 
63 of the uncompressed pixel data from which the compressed data is derived
64 */
65
66 /*
67  * <setjmp.h> is used for the optional error recovery mechanism shown in
68  * the second part of the example.
69  */
70
71 /*
72  * Include file for users of JPEG library.
73  * You will need to have included system headers that define at least
74  * the typedefs FILE and size_t before you can include jpeglib.h.
75  * (stdio.h is sufficient on ANSI-conforming systems.)
76  * You may also wish to include "jerror.h".
77  */
78
79 extern "C" {
80 #include "jpeglib.h"
81 #include <setjmp.h>
82 }
83
84
85 /******************** JPEG COMPRESSION SAMPLE INTERFACE *******************/
86
87 /* This half of the example shows how to feed data into the JPEG compressor.
88  * We present a minimal version that does not worry about refinements such
89  * as error recovery (the JPEG code will just exit() if it gets an error).
90  */
91
92 /*
93  * IMAGE DATA FORMATS:
94  *
95  * The standard input image format is a rectangular array of pixels, with
96  * each pixel having the same number of "component" values (color channels).
97  * Each pixel row is an array of JSAMPLEs (which typically are unsigned chars).
98  * If you are working with color data, then the color values for each pixel
99  * must be adjacent in the row; for example, R,G,B,R,G,B,R,G,B,... for 24-bit
100  * RGB color.
101  *
102  * For this example, we'll assume that this data structure matches the way
103  * our application has stored the image in memory, so we can just pass a
104  * pointer to our image buffer.  In particular, let's say that the image is
105  * RGB color and is described by:
106  */
107
108 // FIXME : JPR
109
110 //extern JSAMPLE * image_buffer; /* Points to large array of R,G,B-order data */
111 //extern int image_height;       /* Number of rows in image */
112 //extern int image_width;        /* Number of columns in image */
113
114
115
116 /*
117  * Sample routine for JPEG compression.  We assume that the target file name
118  * and a compression quality factor are passed in.
119  */
120
121  /**
122  * \ingroup gdcmFile
123  * \brief   routine for JPEG decompression 
124  * @param fp pointer to an already open file descriptor 
125  *                      8 significant bits per pixel
126  * @param image_buffer Points to array (of R,G,B-order) data to compress
127  * @param quality compression quality
128  * @param image_height Number of rows in image 
129  * @param image_width Number of columns in image
130  * @return 1 on success, 0 on error
131  */
132  
133 bool gdcm_write_JPEG_file (FILE *fp, void * im_buf, 
134                            int image_width, int image_height, int quality)
135 {
136
137    JSAMPLE* image_buffer = (JSAMPLE*) im_buf;
138
139   /* This struct contains the JPEG compression parameters and pointers to
140    * working space (which is allocated as needed by the JPEG library).
141    * It is possible to have several such structures, representing multiple
142    * compression/decompression processes, in existence at once.  We refer
143    * to any one struct (and its associated working data) as a "JPEG object".
144    */
145   struct jpeg_compress_struct cinfo;
146   /* This struct represents a JPEG error handler.  It is declared separately
147    * because applications often want to supply a specialized error handler
148    * (see the second half of this file for an example).  But here we just
149    * take the easy way out and use the standard error handler, which will
150    * print a message on stderr and call exit() if compression fails.
151    * Note that this struct must live as long as the main JPEG parameter
152    * struct, to avoid dangling-pointer problems.
153    */
154   struct jpeg_error_mgr jerr;
155   /* More stuff */
156   //FILE * outfile;    /* target file */
157   JSAMPROW row_pointer[1];   /* pointer to JSAMPLE row[s] */
158   int row_stride;            /* physical row width in image buffer */
159
160   /* Step 1: allocate and initialize JPEG compression object */
161
162   /* We have to set up the error handler first, in case the initialization
163    * step fails.  (Unlikely, but it could happen if you are out of memory.)
164    * This routine fills in the contents of struct jerr, and returns jerr's
165    * address which we place into the link field in cinfo.
166    */
167   cinfo.err = jpeg_std_error(&jerr);
168   /* Now we can initialize the JPEG compression object. */
169   jpeg_create_compress(&cinfo);
170
171   /* Step 2: specify data destination (eg, a file) */
172   /* Note: steps 2 and 3 can be done in either order. */
173
174   /* Here we use the library-supplied code to send compressed data to a
175    * stdio stream.  You can also write your own code to do something else.
176    * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
177    * requires it in order to write binary files.
178    */
179  // if ((outfile = fopen(filename, "wb")) == NULL) {
180  //   fprintf(stderr, "can't open %s\n", filename);
181  //   exit(1);
182  //
183  // }
184   jpeg_stdio_dest(&cinfo, fp);
185
186   /* Step 3: set parameters for compression */
187
188   /* First we supply a description of the input image.
189    * Four fields of the cinfo struct must be filled in:
190    */
191   cinfo.image_width = image_width;/* image width and height, in pixels */
192   cinfo.image_height = image_height;
193   cinfo.input_components = 3;     /* # of color components per pixel */
194   cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
195   /* Now use the library's routine to set default compression parameters.
196    * (You must set at least cinfo.in_color_space before calling this,
197    * since the defaults depend on the source color space.)
198    */
199   jpeg_set_defaults(&cinfo);
200   /* Now you can set any non-default parameters you wish to.
201    * Here we just illustrate the use of quality (quantization table) scaling:
202    */
203   jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
204
205   /* Step 4: Start compressor */
206
207   /* TRUE ensures that we will write a complete interchange-JPEG file.
208    * Pass TRUE unless you are very sure of what you're doing.
209    */
210   jpeg_start_compress(&cinfo, TRUE);
211
212   /* Step 5: while (scan lines remain to be written) */
213   /*           jpeg_write_scanlines(...); */
214
215   /* Here we use the library's state variable cinfo.next_scanline as the
216    * loop counter, so that we don't have to keep track ourselves.
217    * To keep things simple, we pass one scanline per call; you can pass
218    * more if you wish, though.
219    */
220   row_stride = image_width * 3;/* JSAMPLEs per row in image_buffer */
221
222   while (cinfo.next_scanline < cinfo.image_height) {
223     /* jpeg_write_scanlines expects an array of pointers to scanlines.
224      * Here the array is only one element long, but you could pass
225      * more than one scanline at a time if that's more convenient.
226      */
227     row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
228
229     (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
230   }
231
232   /* Step 6: Finish compression */
233
234   jpeg_finish_compress(&cinfo);
235   
236   /* After finish_compress, we can close the output file. */
237   
238  // fclose(fp); --> the caller will close (multiframe treatement)
239
240   /* Step 7: release JPEG compression object */
241
242   /* This is an important step since it will release a good deal of memory. */
243   jpeg_destroy_compress(&cinfo);
244
245   /* And we're done! */
246 }
247
248
249
250 /*
251  * SOME FINE POINTS:
252  *
253  * In the above loop, we ignored the return value of jpeg_write_scanlines,
254  * which is the number of scanlines actually written.  We could get away
255  * with this because we were only relying on the value of cinfo.next_scanline,
256  * which will be incremented correctly.  If you maintain additional loop
257  * variables then you should be careful to increment them properly.
258  * Actually, for output to a stdio stream you needn't worry, because
259  * then jpeg_write_scanlines will write all the lines passed (or else exit
260  * with a fatal error).  Partial writes can only occur if you use a data
261  * destination module that can demand suspension of the compressor.
262  * (If you don't know what that's for, you don't need it.)
263  *
264  * If the compressor requires full-image buffers (for entropy-coding
265  * optimization or a multi-scan JPEG file), it will create temporary
266  * files for anything that doesn't fit within the maximum-memory setting.
267  * (Note that temp files are NOT needed if you use the default parameters.)
268  * On some systems you may need to set up a signal handler to ensure that
269  * temporary files are deleted if the program is interrupted.  See libjpeg.doc.
270  *
271  * Scanlines MUST be supplied in top-to-bottom order if you want your JPEG
272  * files to be compatible with everyone else's.  If you cannot readily read
273  * your data in that order, you'll need an intermediate array to hold the
274  * image.  See rdtarga.c or rdbmp.c for examples of handling bottom-to-top
275  * source data using the JPEG code's internal virtual-array mechanisms.
276  */
277
278
279
280 /******************** JPEG DECOMPRESSION SAMPLE INTERFACE *******************/
281
282 /* This half of the example shows how to read data from the JPEG decompressor.
283  * It's a bit more refined than the above, in that we show:
284  *   (a) how to modify the JPEG library's standard error-reporting behavior;
285  *   (b) how to allocate workspace using the library's memory manager.
286  *
287  * Just to make this example a little different from the first one, we'll
288  * assume that we do not intend to put the whole image into an in-memory
289  * buffer, but to send it line-by-line someplace else.  We need a one-
290  * scanline-high JSAMPLE array as a work buffer, and we will let the JPEG
291  * memory manager allocate it for us.  This approach is actually quite useful
292  * because we don't need to remember to deallocate the buffer separately: it
293  * will go away automatically when the JPEG object is cleaned up.
294  */
295
296 /*
297  * ERROR HANDLING:
298  *
299  * The JPEG library's standard error handler (jerror.c) is divided into
300  * several "methods" which you can override individually.  This lets you
301  * adjust the behavior without duplicating a lot of code, which you might
302  * have to update with each future release.
303  *
304  * Our example here shows how to override the "error_exit" method so that
305  * control is returned to the library's caller when a fatal error occurs,
306  * rather than calling exit() as the standard error_exit method does.
307  *
308  * We use C's setjmp/longjmp facility to return control.  This means that the
309  * routine which calls the JPEG library must first execute a setjmp() call to
310  * establish the return point.  We want the replacement error_exit to do a
311  * longjmp().  But we need to make the setjmp buffer accessible to the
312  * error_exit routine.  To do this, we make a private extension of the
313  * standard JPEG error handler object.  (If we were using C++, we'd say we
314  * were making a subclass of the regular error handler.)
315  *
316  * Here's the extended error handler struct:
317  */
318
319 //-----------------------------------------------------------------------------
320 struct my_error_mgr {
321    struct jpeg_error_mgr pub; /* "public" fields */
322    jmp_buf setjmp_buffer;     /* for return to caller */
323 };
324
325 //-----------------------------------------------------------------------------
326 typedef struct my_error_mgr * my_error_ptr;
327
328 /*
329  * Here's the routine that will replace the standard error_exit method:
330  */
331 METHODDEF(void) my_error_exit (j_common_ptr cinfo) {
332    /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
333    my_error_ptr myerr = (my_error_ptr) cinfo->err;
334
335    /* Always display the message. */
336    /* We could postpone this until after returning, if we chose. */
337    (*cinfo->err->output_message) (cinfo);
338
339    /* Return control to the setjmp point */
340    longjmp(myerr->setjmp_buffer, 1);
341 }
342
343 //-----------------------------------------------------------------------------
344 /*
345  * Sample routine for JPEG decompression.  We assume that the source file name
346  * is passed in.  We want to return 1 on success, 0 on error.
347  */
348  
349  /**
350  * \ingroup gdcmFile
351  * \brief   routine for JPEG decompression 
352  * @param fp pointer to an already open file descriptor 
353  *                      8 significant bits per pixel
354  * @param image_buffer to receive uncompressed pixels
355  * @return 1 on success, 0 on error
356  */
357  
358 bool gdcmFile::gdcm_read_JPEG_file (FILE *fp,void * image_buffer) {
359    char *pimage;
360
361    /* This struct contains the JPEG decompression parameters and pointers to
362     * working space (which is allocated as needed by the JPEG library).
363     */
364    struct jpeg_decompress_struct cinfo;
365
366    /* -------------- inside, we found :
367     * JDIMENSION image_width;       // input image width 
368     * JDIMENSION image_height;      // input image height 
369     * int input_components;         // nb of color components in input image 
370     * J_COLOR_SPACE in_color_space; // colorspace of input image 
371     * double input_gamma;           // image gamma of input image 
372     * -------------- */
373
374    /* We use our private extension JPEG error handler.
375     * Note that this struct must live as long as the main JPEG parameter
376     * struct, to avoid dangling-pointer problems.
377     */
378    struct my_error_mgr jerr;
379    /* More stuff */
380
381    JSAMPARRAY buffer;/* Output row buffer */
382   
383    // rappel :
384    // ------
385    // typedef unsigned char JSAMPLE;
386    // typedef JSAMPLE FAR *JSAMPROW;/* ptr to one image row of pixel samples. */
387    // typedef JSAMPROW *JSAMPARRAY;/* ptr to some rows (a 2-D sample array) */
388    // typedef JSAMPARRAY *JSAMPIMAGE;/* a 3-D sample array: top index is color */
389
390    int row_stride;/* physical row width in output buffer */
391   
392 #ifdef GDCM_JPG_DEBUG
393    printf("entree dans gdcmFile::gdcm_read_JPEG_file (i.e. 8), depuis gdcmJpeg\n");
394 #endif //GDCM_JPG_DEBUG
395
396    /* In this example we want to open the input file before doing anything else,
397     * so that the setjmp() error recovery below can assume the file is open.
398     * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
399     * requires it in order to read binary files.
400     */
401     
402   /* Step 1: allocate and initialize JPEG decompression object */  
403 #ifdef GDCM_JPG_DEBUG
404   printf("Entree Step 1\n");
405 #endif //GDCM_JPG_DEBUG
406   
407   /* We set up the normal JPEG error routines, then override error_exit. */
408   
409   cinfo.err = jpeg_std_error(&jerr.pub);
410   jerr.pub.error_exit = my_error_exit;
411   
412   /* Establish the setjmp return context for my_error_exit to use. */  
413   if (setjmp(jerr.setjmp_buffer)) {
414     /* If we get here, the JPEG code has signaled an error.
415      * We need to clean up the JPEG object, close the input file, and return.
416      */
417     jpeg_destroy_decompress(&cinfo);
418     return 0;
419   }
420   /* Now we can initialize the JPEG decompression object. */
421   jpeg_create_decompress(&cinfo);
422
423    /* Step 2: specify data source (eg, a file) */
424 #ifdef GDCM_JPG_DEBUG
425   printf("Entree Step 2\n");
426 #endif //GDCM_JPG_DEBUG
427
428    jpeg_stdio_src(&cinfo, fp);
429
430    /* Step 3: read file parameters with jpeg_read_header() */
431 #ifdef GDCM_JPG_DEBUG
432   printf("Entree Step 3\n");
433 #endif //GDCM_JPG_DEBUG
434
435    (void) jpeg_read_header(&cinfo, TRUE);
436    
437    /* We can ignore the return value from jpeg_read_header since
438     *   (a) suspension is not possible with the stdio data source, and
439     *   (b) we passed TRUE to reject a tables-only JPEG file as an error.
440     * See libjpeg.doc for more info.
441     */
442
443 #ifdef GDCM_JPG_DEBUG
444       printf("--------------Header contents :----------------\n");
445       printf("image_width %d image_height %d\n", 
446               cinfo.image_width , cinfo.image_height);
447       printf("bits of precision in image data  %d \n", 
448               cinfo.output_components);
449       printf("nb of color components returned  %d \n", 
450               cinfo.data_precision);
451 #endif //GDCM_JPG_DEBUG
452
453
454    /*
455     * JDIMENSION image_width;       // input image width 
456     * JDIMENSION image_height;      // input image height 
457     * int output_components;        // # of color components returned 
458     * J_COLOR_SPACE in_color_space; // colorspace of input image 
459     * double input_gamma;           // image gamma of input image
460     * int data_precision;           // bits of precision in image data 
461     */
462
463    /* Step 4: set parameters for decompression */
464 #ifdef GDCM_JPG_DEBUG
465   printf("Entree Step 4\n");
466 #endif //GDCM_JPG_DEBUG
467    /* In this example, we don't need to change any of the defaults set by
468     * jpeg_read_header(), so we do nothing here.
469     */
470
471    /* Step 5: Start decompressor */
472 #ifdef GDCM_JPG_DEBUG
473    printf("Entree Step 5\n");
474 #endif //GDCM_JPG_DEBUG
475
476    (void) jpeg_start_decompress(&cinfo);
477    /* We can ignore the return value since suspension is not possible
478     * with the stdio data source.
479     */
480
481    /* We may need to do some setup of our own at this point before reading
482     * the data.  After jpeg_start_decompress() we have the correct scaled
483     * output image dimensions available, as well as the output colormap
484     * if we asked for color quantization.
485     * In this example, we need to make an output work buffer of the right size.
486     */ 
487
488    /* JSAMPLEs per row in output buffer */
489    row_stride = cinfo.output_width * cinfo.output_components;
490   
491 #ifdef GDCM_JPG_DEBUG
492   printf ("cinfo.output_width %d cinfo.output_components %d  row_stride %d\n",
493                       cinfo.output_width, cinfo.output_components,row_stride);
494 #endif //GDCM_JPG_DEBUG
495
496    /* Make a one-row-high sample array that will go away when done with image */
497    buffer = (*cinfo.mem->alloc_sarray)
498             ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
499
500    /* Step 6: while (scan lines remain to be read) */
501 #ifdef GDCM_JPG_DEBUG
502     printf("Entree Step 6\n"); 
503 #endif //GDCM_JPG_DEBUG
504    /*           jpeg_read_scanlines(...); */
505
506    /* Here we use the library's state variable cinfo.output_scanline as the
507     * loop counter, so that we don't have to keep track ourselves.
508     */
509 #ifdef GDCM_JPG_DEBUG
510       printf ("cinfo.output_height %d  cinfo.output_width %d\n",
511                cinfo.output_height,cinfo.output_width);
512 #endif //GDCM_JPG_DEBUG
513    pimage=(char *)image_buffer;
514   
515    while (cinfo.output_scanline < cinfo.output_height) {
516       /* jpeg_read_scanlines expects an array of pointers to scanlines.
517        * Here the array is only one element long, but you could ask for
518        * more than one scanline at a time if that's more convenient.
519        */
520      
521      // l'image est deja allouée (et passée en param)
522      // on ecrit directement les pixels
523      // (on DEVRAIT pouvoir)
524     
525     //(void) jpeg_read_scanlines(&cinfo, pimage, 1);
526     
527      (void) jpeg_read_scanlines(&cinfo, buffer, 1);
528       
529      if ( BITS_IN_JSAMPLE == 8) {
530          memcpy( pimage, buffer[0],row_stride); 
531          pimage+=row_stride;
532      } else {
533          memcpy( pimage, buffer[0],row_stride*2 ); // FIXME : *2  car 16 bits?!?
534          pimage+=row_stride*2;                     // FIXME : *2 car 16 bits?!?     
535      }
536   }
537  
538   /* Step 7: Finish decompression */
539 #ifdef GDCM_JPG_DEBUG
540    printf("Entree Step 7\n");
541 #endif //GDCM_JPG_DEBUG
542
543    (void) jpeg_finish_decompress(&cinfo);
544    
545    /* We can ignore the return value since suspension is not possible
546     * with the stdio data source.
547     */
548
549    /* Step 8: Release JPEG decompression object */
550
551 #ifdef GDCM_JPG_DEBUG
552   printf("Entree Step 8\n");
553 #endif //GDCM_JPG_DEBUG
554
555    /* This is an important step since it will release a good deal of memory. */
556
557    jpeg_destroy_decompress(&cinfo);
558
559    /* After finish_decompress, we can close the input file.
560     * Here we postpone it until after no more JPEG errors are possible,
561     * so as to simplify the setjmp error logic above.  (Actually, I don't
562     * think that jpeg_destroy can do an error exit, but why assume anything...)
563     */
564
565    /* At this point you may want to check to see whether any corrupt-data
566     * warnings occurred (test whether jerr.pub.num_warnings is nonzero).
567     */
568
569    /* And we're done! */
570
571    return(true);
572 }
573
574
575 /*
576  * SOME FINE POINTS:
577  *
578  * In the above code, we ignored the return value of jpeg_read_scanlines,
579  * which is the number of scanlines actually read.  We could get away with
580  * this because we asked for only one line at a time and we weren't using
581  * a suspending data source.  See libjpeg.doc for more info.
582  *
583  * We cheated a bit by calling alloc_sarray() after jpeg_start_decompress();
584  * we should have done it beforehand to ensure that the space would be
585  * counted against the JPEG max_memory setting.  In some systems the above
586  * code would risk an out-of-memory error.  However, in general we don't
587  * know the output image dimensions before jpeg_start_decompress(), unless we
588  * call jpeg_calc_output_dimensions().  See libjpeg.doc for more about this.
589  *
590  * Scanlines are returned in the same order as they appear in the JPEG file,
591  * which is standardly top-to-bottom.  If you must emit data bottom-to-top,
592  * you can use one of the virtual arrays provided by the JPEG memory manager
593  * to invert the data.  See wrbmp.c for an example.
594  *
595  * As with compression, some operating modes may require temporary files.
596  * On some systems you may need to set up a signal handler to ensure that
597  * temporary files are deleted if the program is interrupted.  See libjpeg.doc.
598  */
599  
600 //----------------------------------------------------------------------------