Remove typos from comments and man pages
[openjpeg.git] / src / bin / jp2 / opj_compress.c
index ae41b575b1aa5cd93c23b2624fad06995256fc98..aa8091ab8234f6afe26381c618091c363e6de370 100644 (file)
@@ -1,9 +1,15 @@
 /*
- * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
- * Copyright (c) 2002-2007, Professor Benoit Macq
+ * The copyright in this software is being made available under the 2-clauses 
+ * BSD License, included below. This software may be subject to other third 
+ * party and contributor rights, including patent rights, and no such rights
+ * are granted under this license.
+ *
+ * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2014, Professor Benoit Macq
  * Copyright (c) 2001-2003, David Janssens
  * Copyright (c) 2002-2003, Yannick Verschueren
- * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
+ * Copyright (c) 2003-2007, Francois-Olivier Devaux 
+ * Copyright (c) 2003-2014, Antonin Descampe
  * Copyright (c) 2005, Herve Drolon, FreeImage Team
  * Copyright (c) 2006-2007, Parvatha Elangovan
  * Copyright (c) 2008, Jerome Fimes, Communications & Systemes <jerome.fimes@c-s.fr>
@@ -51,6 +57,9 @@
 #define strncasecmp _strnicmp
 #else
 #include <strings.h>
+#include <sys/time.h>
+#include <sys/resource.h>
+#include <sys/times.h>
 #endif /* _WIN32 */
 
 #include "opj_apps_config.h"
 #include "index.h"
 
 #include "format_defs.h"
-
-#define CINEMA_24_CS 1302083   /*Codestream length for 24fps*/
-#define CINEMA_48_CS 651041            /*Codestream length for 48fps*/
-#define COMP_24_CS 1041666             /*Maximum size per color component for 2K & 4K @ 24fps*/
-#define COMP_48_CS 520833              /*Maximum size per color component for 2K @ 48fps*/
+#include "opj_string.h"
 
 typedef struct dircnt{
     /** Buffer for holding images read from Directory*/
@@ -85,28 +90,16 @@ typedef struct img_folder{
 }img_fol_t;
 
 static void encode_help_display(void) {
-    fprintf(stdout,"HELP for opj_compress\n----\n\n");
-    fprintf(stdout,"- the -h option displays this help information on screen\n\n");
+    fprintf(stdout,"\nThis is the opj_compress utility from the OpenJPEG project.\n"
+            "It compresses various image formats with the JPEG 2000 algorithm.\n"
+            "It has been compiled against openjp2 library v%s.\n\n",opj_version());
 
-    /* UniPG>> */
-    fprintf(stdout,"List of parameters for the JPEG 2000 "
-        #ifdef USE_JPWL
-            "+ JPWL "
-        #endif /* USE_JPWL */
-            "encoder:\n");
-    /* <<UniPG */
-    fprintf(stdout,"\n");
-    fprintf(stdout,"REMARKS:\n");
-    fprintf(stdout,"---------\n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"The markers written to the main_header are : SOC SIZ COD QCD COM.\n");
-    fprintf(stdout,"COD and QCD never appear in the tile_header.\n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"By default:\n");
-    fprintf(stdout,"------------\n");
+    fprintf(stdout,"Default encoding options:\n");
+    fprintf(stdout,"-------------------------\n");
     fprintf(stdout,"\n");
     fprintf(stdout," * Lossless\n");
     fprintf(stdout," * 1 tile\n");
+    fprintf(stdout," * RGB->YCC conversion if at least 3 components\n");
     fprintf(stdout," * Size of precinct : 2^15 x 2^15 (means 1 precinct)\n");
     fprintf(stdout," * Size of code-block : 64 x 64\n");
     fprintf(stdout," * Number of resolutions: 6\n");
@@ -115,7 +108,9 @@ static void encode_help_display(void) {
     fprintf(stdout," * No sub-sampling in x or y direction\n");
     fprintf(stdout," * No mode switch activated\n");
     fprintf(stdout," * Progression order: LRCP\n");
+    #ifdef FIXME_INDEX
     fprintf(stdout," * No index file\n");
+    #endif /* FIXME_INDEX */
     fprintf(stdout," * No ROI upshifted\n");
     fprintf(stdout," * No offset of the origin of the image\n");
     fprintf(stdout," * No offset of the origin of the tiles\n");
@@ -126,170 +121,204 @@ static void encode_help_display(void) {
 #endif /* USE_JPWL */
     /* <<UniPG */
     fprintf(stdout,"\n");
+
+    fprintf(stdout,"Note:\n");
+    fprintf(stdout,"-----\n");
+    fprintf(stdout,"\n");
+    fprintf(stdout,"The markers written to the main_header are : SOC SIZ COD QCD COM.\n");
+    fprintf(stdout,"COD and QCD never appear in the tile_header.\n");
+    fprintf(stdout,"\n");
+
     fprintf(stdout,"Parameters:\n");
-    fprintf(stdout,"------------\n");
+    fprintf(stdout,"-----------\n");
     fprintf(stdout,"\n");
     fprintf(stdout,"Required Parameters (except with -h):\n");
     fprintf(stdout,"One of the two options -ImgDir or -i must be used\n");
     fprintf(stdout,"\n");
-    fprintf(stdout,"-ImgDir      : Image file Directory path (example ../Images) \n");
+    fprintf(stdout,"-i <file>\n");
+    fprintf(stdout,"    Input file\n");
+    fprintf(stdout,"    Known extensions are <PBM|PGM|PPM|PNM|PAM|PGX|PNG|BMP|TIF|RAW|RAWL|TGA>\n");
+    fprintf(stdout,"    If used, '-o <file>' must be provided\n");
+    fprintf(stdout,"-o <compressed file>\n");
+    fprintf(stdout,"    Output file (accepted extensions are j2k or jp2).\n");
+    fprintf(stdout,"-ImgDir <dir>\n");
+    fprintf(stdout,"    Image file Directory path (example ../Images) \n");
     fprintf(stdout,"    When using this option -OutFor must be used\n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"-OutFor \n");
-    fprintf(stdout,"    REQUIRED only if -ImgDir is used\n");
-    fprintf(stdout,"     Need to specify only format without filename <BMP>  \n");
-    fprintf(stdout,"    Currently accepts PBM, PGM, PPM, PNM, PAM, PGX, PNG, BMP, TIF, RAW, RAWL and TGA formats\n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"-i           : source file  (-i source.pnm also *pbm, *.pgm, *.ppm, *.pam, *.pgx, *png, *.bmp, *.tif, *.raw, *.tga) \n");
-    fprintf(stdout,"    When using this option -o must be used\n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"-o           : destination file (-o dest.j2k or .jp2) \n");
+    fprintf(stdout,"-OutFor <J2K|J2C|JP2>\n");
+    fprintf(stdout,"    Output format for compressed files.\n");
+    fprintf(stdout,"    Required only if -ImgDir is used\n");
+    fprintf(stdout,"-F <width>,<height>,<ncomp>,<bitdepth>,{s,u}@<dx1>x<dy1>:...:<dxn>x<dyn>\n");
+    fprintf(stdout,"    Characteristics of the raw input image\n");
+    fprintf(stdout,"    If subsampling is omitted, 1x1 is assumed for all components\n");
+    fprintf(stdout,"      Example: -F 512,512,3,8,u@1x1:2x2:2x2\n");
+    fprintf(stdout,"               for raw 512x512 image with 4:2:0 subsampling\n");
+    fprintf(stdout,"    Required only if RAW or RAWL input file is provided.\n");
     fprintf(stdout,"\n");
     fprintf(stdout,"Optional Parameters:\n");
     fprintf(stdout,"\n");
-    fprintf(stdout,"-h           : display the help information \n ");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"-cinema2K    : Digital Cinema 2K profile compliant codestream for 2K resolution.(-CINEMA2K 24 or 48) \n");
-    fprintf(stdout,"     Need to specify the frames per second for a 2K resolution. Only 24 or 48 fps is allowed\n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"-cinema4K    : Digital Cinema 4K profile compliant codestream for 4K resolution \n");
-    fprintf(stdout,"     Frames per second not required. Default value is 24fps\n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"-r           : different compression ratios for successive layers (-r 20,10,5)\n ");
-    fprintf(stdout,"            - The rate specified for each quality level is the desired \n");
-    fprintf(stdout,"              compression factor.\n");
-    fprintf(stdout,"              Example: -r 20,10,1 means quality 1: compress 20x, \n");
-    fprintf(stdout,"                quality 2: compress 10x and quality 3: compress lossless\n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"               (options -r and -q cannot be used together)\n ");
-    fprintf(stdout,"\n");
-
-    fprintf(stdout,"-q           : different psnr for successive layers (-q 30,40,50) \n ");
-
-    fprintf(stdout,"               (options -r and -q cannot be used together)\n ");
-
-    fprintf(stdout,"\n");
-    fprintf(stdout,"-n           : number of resolutions (-n 3) \n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"-b           : size of code block (-b 32,32) \n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"-c           : size of precinct (-c 128,128) \n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"-t           : size of tile (-t 512,512) \n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"-p           : progression order (-p LRCP) [LRCP, RLCP, RPCL, PCRL, CPRL] \n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"-s           : subsampling factor (-s 2,2) [-s X,Y] \n");
-    fprintf(stdout,"        Remark: subsampling bigger than 2 can produce error\n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"-POC         : Progression order change (-POC T1=0,0,1,5,3,CPRL/T1=5,0,1,6,3,CPRL) \n");
-    fprintf(stdout,"      Example: T1=0,0,1,5,3,CPRL \n");
-    fprintf(stdout,"                    : Ttilenumber=Resolution num start,Component num start,Layer num end,Resolution num end,Component num end,Progression order\n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"-SOP         : write SOP marker before each packet \n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"-EPH         : write EPH marker after each header packet \n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"-M           : mode switch (-M 3) [1=BYPASS(LAZY) 2=RESET 4=RESTART(TERMALL)\n");
-    fprintf(stdout,"                 8=VSC 16=ERTERM(SEGTERM) 32=SEGMARK(SEGSYM)] \n");
-    fprintf(stdout,"                 Indicate multiple modes by adding their values. \n");
-    fprintf(stdout,"                 ex: RESTART(4) + RESET(2) + SEGMARK(32) = -M 38\n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"-TP          : divide packets of every tile into tile-parts (-TP R) [R, L, C]\n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"-x           : create an index file *.Idx (-x index_name.Idx) \n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"-ROI         : c=%%d,U=%%d : quantization indices upshifted \n");
-    fprintf(stdout,"               for component c=%%d [%%d = 0,1,2]\n");
-    fprintf(stdout,"               with a value of U=%%d [0 <= %%d <= 37] (i.e. -ROI c=0,U=25) \n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"-d           : offset of the origin of the image (-d 150,300) \n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"-T           : offset of the origin of the tiles (-T 100,75) \n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"-I           : use the irreversible DWT 9-7 (-I) \n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"-F           : characteristics of the raw input image\n");
-    fprintf(stdout,"               -F rawWidth,rawHeight,rawComp,rawBitDepth,s/u (Signed/Unsigned)\n");
-    fprintf(stdout,"               Example: -i lena.raw -o lena.j2k -F 512,512,3,8,u\n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"-m           : use array-based MCT, values are coma separated, line by line\n");
-    fprintf(stdout,"                      no specific separators between lines, no space allowed between values\n");
-    fprintf(stdout,"-jpip        : write jpip codestream index box in JP2 output file\n");
-    fprintf(stdout,"               NOTICE: currently supports only RPCL order\n");
-    fprintf(stdout,"\n");
+    fprintf(stdout,"-h\n");
+    fprintf(stdout,"    Display the help information.\n");
+    fprintf(stdout,"-r <compression ratio>,<compression ratio>,...\n");
+    fprintf(stdout,"    Different compression ratios for successive layers.\n");
+    fprintf(stdout,"    The rate specified for each quality level is the desired\n");
+    fprintf(stdout,"    compression factor.\n");
+    fprintf(stdout,"    Decreasing ratios required.\n");
+    fprintf(stdout,"      Example: -r 20,10,1 means \n");
+    fprintf(stdout,"            quality layer 1: compress 20x, \n");
+    fprintf(stdout,"            quality layer 2: compress 10x \n");
+    fprintf(stdout,"            quality layer 3: compress lossless\n");
+    fprintf(stdout,"    Options -r and -q cannot be used together.\n");
+    fprintf(stdout,"-q <psnr value>,<psnr value>,<psnr value>,...\n");
+    fprintf(stdout,"    Different psnr for successive layers (-q 30,40,50).\n");
+    fprintf(stdout,"    Increasing PSNR values required.\n");
+    fprintf(stdout,"    Options -r and -q cannot be used together.\n");
+    fprintf(stdout,"-n <number of resolutions>\n");
+    fprintf(stdout,"    Number of resolutions.\n");
+    fprintf(stdout,"    It corresponds to the number of DWT decompositions +1. \n");
+    fprintf(stdout,"    Default: 6.\n");
+    fprintf(stdout,"-b <cblk width>,<cblk height>\n");
+    fprintf(stdout,"    Code-block size. The dimension must respect the constraint \n");
+    fprintf(stdout,"    defined in the JPEG-2000 standard (no dimension smaller than 4 \n");
+    fprintf(stdout,"    or greater than 1024, no code-block with more than 4096 coefficients).\n");
+    fprintf(stdout,"    The maximum value authorized is 64x64. \n");
+    fprintf(stdout,"    Default: 64x64.\n");
+    fprintf(stdout,"-c [<prec width>,<prec height>],[<prec width>,<prec height>],...\n");
+    fprintf(stdout,"    Precinct size. Values specified must be power of 2. \n");
+    fprintf(stdout,"    Multiple records may be supplied, in which case the first record refers\n");
+    fprintf(stdout,"    to the highest resolution level and subsequent records to lower \n");
+    fprintf(stdout,"    resolution levels. The last specified record is right-shifted for each \n");
+    fprintf(stdout,"    remaining lower resolution levels.\n");
+    fprintf(stdout,"    Default: 215x215 at each resolution.\n");
+    fprintf(stdout,"-t <tile width>,<tile height>\n");
+    fprintf(stdout,"    Tile size.\n");
+    fprintf(stdout,"    Default: the dimension of the whole image, thus only one tile.\n");
+    fprintf(stdout,"-p <LRCP|RLCP|RPCL|PCRL|CPRL>\n");
+    fprintf(stdout,"    Progression order.\n");
+    fprintf(stdout,"    Default: LRCP.\n");
+    fprintf(stdout,"-s  <subX,subY>\n");
+    fprintf(stdout,"    Subsampling factor.\n");
+    fprintf(stdout,"    Subsampling bigger than 2 can produce error\n");
+    fprintf(stdout,"    Default: no subsampling.\n");
+    fprintf(stdout,"-POC <progression order change>/<progression order change>/...\n");
+    fprintf(stdout,"    Progression order change.\n");
+    fprintf(stdout,"    The syntax of a progression order change is the following:\n");
+    fprintf(stdout,"    T<tile>=<resStart>,<compStart>,<layerEnd>,<resEnd>,<compEnd>,<progOrder>\n");
+    fprintf(stdout,"      Example: -POC T1=0,0,1,5,3,CPRL/T1=5,0,1,6,3,CPRL\n");
+    fprintf(stdout,"-SOP\n");
+    fprintf(stdout,"    Write SOP marker before each packet.\n");
+    fprintf(stdout,"-EPH\n");
+    fprintf(stdout,"    Write EPH marker after each header packet.\n");
+    fprintf(stdout,"-M <key value>\n");
+    fprintf(stdout,"    Mode switch.\n");
+    fprintf(stdout,"    [1=BYPASS(LAZY) 2=RESET 4=RESTART(TERMALL)\n");
+    fprintf(stdout,"    8=VSC 16=ERTERM(SEGTERM) 32=SEGMARK(SEGSYM)]\n");
+    fprintf(stdout,"    Indicate multiple modes by adding their values.\n");
+    fprintf(stdout,"      Example: RESTART(4) + RESET(2) + SEGMARK(32) => -M 38\n");
+    fprintf(stdout,"-TP <R|L|C>\n");
+    fprintf(stdout,"    Divide packets of every tile into tile-parts.\n");
+    fprintf(stdout,"    Division is made by grouping Resolutions (R), Layers (L)\n");
+    fprintf(stdout,"    or Components (C).\n");
+    #ifdef FIXME_INDEX
+    fprintf(stdout,"-x  <index file>\n");
+    fprintf(stdout,"    Create an index file.\n");
+    #endif /*FIXME_INDEX*/
+    fprintf(stdout,"-ROI c=<component index>,U=<upshifting value>\n");
+    fprintf(stdout,"    Quantization indices upshifted for a component. \n");
+    fprintf(stdout,"    Warning: This option does not implement the usual ROI (Region of Interest).\n");
+    fprintf(stdout,"    It should be understood as a 'Component of Interest'. It offers the \n");
+    fprintf(stdout,"    possibility to upshift the value of a component during quantization step.\n");
+    fprintf(stdout,"    The value after c= is the component number [0, 1, 2, ...] and the value \n");
+    fprintf(stdout,"    after U= is the value of upshifting. U must be in the range [0, 37].\n");
+    fprintf(stdout,"-d <image offset X,image offset Y>\n");
+    fprintf(stdout,"    Offset of the origin of the image.\n");
+    fprintf(stdout,"-T <tile offset X,tile offset Y>\n");
+    fprintf(stdout,"    Offset of the origin of the tiles.\n");
+    fprintf(stdout,"-I\n");
+    fprintf(stdout,"    Use the irreversible DWT 9-7.\n");
+    fprintf(stdout,"-mct <0|1|2>\n");
+    fprintf(stdout,"    Explicitly specifies if a Multiple Component Transform has to be used.\n");
+    fprintf(stdout,"    0: no MCT ; 1: RGB->YCC conversion ; 2: custom MCT.\n");
+    fprintf(stdout,"    If custom MCT, \"-m\" option has to be used (see hereunder).\n");
+    fprintf(stdout,"    By default, RGB->YCC conversion is used if there are 3 components or more,\n");
+    fprintf(stdout,"    no conversion otherwise.\n");
+    fprintf(stdout,"-m <file>\n");
+    fprintf(stdout,"    Use array-based MCT, values are coma separated, line by line\n");
+    fprintf(stdout,"    No specific separators between lines, no space allowed between values.\n");
+    fprintf(stdout,"    If this option is used, it automatically sets \"-mct\" option to 2.\n");
+    fprintf(stdout,"-cinema2K <24|48>\n");
+    fprintf(stdout,"    Digital Cinema 2K profile compliant codestream.\n");
+    fprintf(stdout,"   Need to specify the frames per second for a 2K resolution.\n");
+    fprintf(stdout,"    Only 24 or 48 fps are currently allowed.\n");
+    fprintf(stdout,"-cinema4K\n");
+    fprintf(stdout,"    Digital Cinema 4K profile compliant codestream.\n");
+    fprintf(stdout,"   Frames per second not required. Default value is 24fps.\n");
+    fprintf(stdout,"-jpip\n");
+    fprintf(stdout,"    Write jpip codestream index box in JP2 output file.\n");
+    fprintf(stdout,"    Currently supports only RPCL order.\n");
+    fprintf(stdout,"-C <comment>\n");
+    fprintf(stdout,"    Add <comment> in the comment marker segment.\n");
     /* UniPG>> */
 #ifdef USE_JPWL
-    fprintf(stdout,"-W           : adoption of JPWL (Part 11) capabilities (-W params)\n");
-    fprintf(stdout,"               The parameters can be written and repeated in any order:\n");
-    fprintf(stdout,"               [h<tilepart><=type>,s<tilepart><=method>,a=<addr>,...\n");
-    fprintf(stdout,"                ...,z=<size>,g=<range>,p<tilepart:pack><=type>]\n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"                 h selects the header error protection (EPB): 'type' can be\n");
-    fprintf(stdout,"                   [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\n");
-    fprintf(stdout,"                   if 'tilepart' is absent, it is for main and tile headers\n");
-    fprintf(stdout,"                   if 'tilepart' is present, it applies from that tile\n");
-    fprintf(stdout,"                     onwards, up to the next h<> spec, or to the last tilepart\n");
-    fprintf(stdout,"                     in the codestream (max. %d specs)\n", JPWL_MAX_NO_TILESPECS);
-    fprintf(stdout,"\n");
-    fprintf(stdout,"                 p selects the packet error protection (EEP/UEP with EPBs)\n");
-    fprintf(stdout,"                  to be applied to raw data: 'type' can be\n");
-    fprintf(stdout,"                   [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\n");
-    fprintf(stdout,"                   if 'tilepart:pack' is absent, it is from tile 0, packet 0\n");
-    fprintf(stdout,"                   if 'tilepart:pack' is present, it applies from that tile\n");
-    fprintf(stdout,"                     and that packet onwards, up to the next packet spec\n");
-    fprintf(stdout,"                     or to the last packet in the last tilepart in the stream\n");
-    fprintf(stdout,"                     (max. %d specs)\n", JPWL_MAX_NO_PACKSPECS);
-    fprintf(stdout,"\n");
-    fprintf(stdout,"                 s enables sensitivity data insertion (ESD): 'method' can be\n");
-    fprintf(stdout,"                   [-1=NO ESD 0=RELATIVE ERROR 1=MSE 2=MSE REDUCTION 3=PSNR\n");
-    fprintf(stdout,"                    4=PSNR INCREMENT 5=MAXERR 6=TSE 7=RESERVED]\n");
-    fprintf(stdout,"                   if 'tilepart' is absent, it is for main header only\n");
-    fprintf(stdout,"                   if 'tilepart' is present, it applies from that tile\n");
-    fprintf(stdout,"                     onwards, up to the next s<> spec, or to the last tilepart\n");
-    fprintf(stdout,"                     in the codestream (max. %d specs)\n", JPWL_MAX_NO_TILESPECS);
-    fprintf(stdout,"\n");
-    fprintf(stdout,"                 g determines the addressing mode: <range> can be\n");
-    fprintf(stdout,"                   [0=PACKET 1=BYTE RANGE 2=PACKET RANGE]\n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"                 a determines the size of data addressing: <addr> can be\n");
-    fprintf(stdout,"                   2/4 bytes (small/large codestreams). If not set, auto-mode\n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"                 z determines the size of sensitivity values: <size> can be\n");
-    fprintf(stdout,"                   1/2 bytes, for the transformed pseudo-floating point value\n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"                 ex.:\n");
-    fprintf(stdout,"                   h,h0=64,h3=16,h5=32,p0=78,p0:24=56,p1,p3:0=0,p3:20=32,s=0,\n");
-    fprintf(stdout,"                     s0=6,s3=-1,a=0,g=1,z=1\n");
-    fprintf(stdout,"                 means\n");
-    fprintf(stdout,"                   predefined EPB in MH, rs(64,32) from TPH 0 to TPH 2,\n");
-    fprintf(stdout,"                   CRC-16 in TPH 3 and TPH 4, CRC-32 in remaining TPHs,\n");
-    fprintf(stdout,"                   UEP rs(78,32) for packets 0 to 23 of tile 0,\n");
-    fprintf(stdout,"                   UEP rs(56,32) for packs. 24 to the last of tilepart 0,\n");
-    fprintf(stdout,"                   UEP rs default for packets of tilepart 1,\n");
-    fprintf(stdout,"                   no UEP for packets 0 to 19 of tilepart 3,\n");
-    fprintf(stdout,"                   UEP CRC-32 for packs. 20 of tilepart 3 to last tilepart,\n");
-    fprintf(stdout,"                   relative sensitivity ESD for MH,\n");
-    fprintf(stdout,"                   TSE ESD from TPH 0 to TPH 2, byte range with automatic\n");
-    fprintf(stdout,"                   size of addresses and 1 byte for each sensitivity value\n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"                 ex.:\n");
-    fprintf(stdout,"                       h,s,p\n");
-    fprintf(stdout,"                 means\n");
-    fprintf(stdout,"                   default protection to headers (MH and TPHs) as well as\n");
-    fprintf(stdout,"                   data packets, one ESD in MH\n");
-    fprintf(stdout,"\n");
-    fprintf(stdout,"                 N.B.: use the following recommendations when specifying\n");
-    fprintf(stdout,"                       the JPWL parameters list\n");
-    fprintf(stdout,"                   - when you use UEP, always pair the 'p' option with 'h'\n");
-    fprintf(stdout,"                 \n");
+    fprintf(stdout,"-W <params>\n");
+    fprintf(stdout,"    Adoption of JPWL (Part 11) capabilities (-W params)\n");
+    fprintf(stdout,"    The <params> field can be written and repeated in any order:\n");
+    fprintf(stdout,"    [h<tilepart><=type>,s<tilepart><=method>,a=<addr>,...\n");
+    fprintf(stdout,"    ...,z=<size>,g=<range>,p<tilepart:pack><=type>]\n");
+    fprintf(stdout,"     h selects the header error protection (EPB): 'type' can be\n");
+    fprintf(stdout,"       [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\n");
+    fprintf(stdout,"       if 'tilepart' is absent, it is for main and tile headers\n");
+    fprintf(stdout,"       if 'tilepart' is present, it applies from that tile\n");
+    fprintf(stdout,"         onwards, up to the next h<> spec, or to the last tilepart\n");
+    fprintf(stdout,"         in the codestream (max. %d specs)\n", JPWL_MAX_NO_TILESPECS);
+    fprintf(stdout,"     p selects the packet error protection (EEP/UEP with EPBs)\n");
+    fprintf(stdout,"      to be applied to raw data: 'type' can be\n");
+    fprintf(stdout,"       [0=none 1,absent=predefined 16=CRC-16 32=CRC-32 37-128=RS]\n");
+    fprintf(stdout,"       if 'tilepart:pack' is absent, it is from tile 0, packet 0\n");
+    fprintf(stdout,"       if 'tilepart:pack' is present, it applies from that tile\n");
+    fprintf(stdout,"         and that packet onwards, up to the next packet spec\n");
+    fprintf(stdout,"         or to the last packet in the last tilepart in the stream\n");
+    fprintf(stdout,"         (max. %d specs)\n", JPWL_MAX_NO_PACKSPECS);
+    fprintf(stdout,"     s enables sensitivity data insertion (ESD): 'method' can be\n");
+    fprintf(stdout,"       [-1=NO ESD 0=RELATIVE ERROR 1=MSE 2=MSE REDUCTION 3=PSNR\n");
+    fprintf(stdout,"        4=PSNR INCREMENT 5=MAXERR 6=TSE 7=RESERVED]\n");
+    fprintf(stdout,"       if 'tilepart' is absent, it is for main header only\n");
+    fprintf(stdout,"       if 'tilepart' is present, it applies from that tile\n");
+    fprintf(stdout,"         onwards, up to the next s<> spec, or to the last tilepart\n");
+    fprintf(stdout,"         in the codestream (max. %d specs)\n", JPWL_MAX_NO_TILESPECS);
+    fprintf(stdout,"     g determines the addressing mode: <range> can be\n");
+    fprintf(stdout,"       [0=PACKET 1=BYTE RANGE 2=PACKET RANGE]\n");
+    fprintf(stdout,"     a determines the size of data addressing: <addr> can be\n");
+    fprintf(stdout,"       2/4 bytes (small/large codestreams). If not set, auto-mode\n");
+    fprintf(stdout,"     z determines the size of sensitivity values: <size> can be\n");
+    fprintf(stdout,"       1/2 bytes, for the transformed pseudo-floating point value\n");
+    fprintf(stdout,"     ex.:\n");
+    fprintf(stdout,"       h,h0=64,h3=16,h5=32,p0=78,p0:24=56,p1,p3:0=0,p3:20=32,s=0,\n");
+    fprintf(stdout,"         s0=6,s3=-1,a=0,g=1,z=1\n");
+    fprintf(stdout,"     means\n");
+    fprintf(stdout,"       predefined EPB in MH, rs(64,32) from TPH 0 to TPH 2,\n");
+    fprintf(stdout,"       CRC-16 in TPH 3 and TPH 4, CRC-32 in remaining TPHs,\n");
+    fprintf(stdout,"       UEP rs(78,32) for packets 0 to 23 of tile 0,\n");
+    fprintf(stdout,"       UEP rs(56,32) for packs. 24 to the last of tilepart 0,\n");
+    fprintf(stdout,"       UEP rs default for packets of tilepart 1,\n");
+    fprintf(stdout,"       no UEP for packets 0 to 19 of tilepart 3,\n");
+    fprintf(stdout,"       UEP CRC-32 for packs. 20 of tilepart 3 to last tilepart,\n");
+    fprintf(stdout,"       relative sensitivity ESD for MH,\n");
+    fprintf(stdout,"       TSE ESD from TPH 0 to TPH 2, byte range with automatic\n");
+    fprintf(stdout,"       size of addresses and 1 byte for each sensitivity value\n");
+    fprintf(stdout,"     ex.:\n");
+    fprintf(stdout,"           h,s,p\n");
+    fprintf(stdout,"     means\n");
+    fprintf(stdout,"       default protection to headers (MH and TPHs) as well as\n");
+    fprintf(stdout,"       data packets, one ESD in MH\n");
+    fprintf(stdout,"     N.B.: use the following recommendations when specifying\n");
+    fprintf(stdout,"           the JPWL parameters list\n");
+    fprintf(stdout,"       - when you use UEP, always pair the 'p' option with 'h'\n");
 #endif /* USE_JPWL */
     /* <<UniPG */
-    fprintf(stdout,"IMPORTANT:\n");
-    fprintf(stdout,"-----------\n");
     fprintf(stdout,"\n");
-    fprintf(stdout,"The index file has the structure below:\n");
-    fprintf(stdout,"---------------------------------------\n");
+#ifdef FIXME_INDEX
+    fprintf(stdout,"Index structure:\n");
+    fprintf(stdout,"----------------\n");
     fprintf(stdout,"\n");
     fprintf(stdout,"Image_height Image_width\n");
     fprintf(stdout,"progression order\n");
@@ -319,10 +348,9 @@ static void encode_help_display(void) {
     fprintf(stdout,"Tpacket_0 Tile layer res. comp. prec. start_pos end_pos disto\n");
     fprintf(stdout,"...\n");
     fprintf(stdout,"Tpacket_Np ''   ''    ''   ''    ''       ''       ''     ''\n");
-
     fprintf(stdout,"MaxDisto\n");
-
     fprintf(stdout,"TotalDisto\n\n");
+#endif /*FIXME_INDEX*/
 }
 
 static OPJ_PROG_ORDER give_progression(const char progression[4]) {
@@ -364,6 +392,7 @@ static unsigned int get_num_images(char *imgdirpath){
             continue;
         num_images++;
     }
+    closedir(dir);
     return num_images;
 }
 
@@ -389,6 +418,7 @@ static int load_images(dircnt_t *dirptr, char *imgdirpath){
         strcpy(dirptr->filename[i],content->d_name);
         i++;
     }
+       closedir(dir);
     return 0;
 }
 
@@ -413,9 +443,7 @@ static int get_file_format(char *filename) {
 }
 
 static char * get_file_name(char *name){
-    char *fname;
-    fname= (char*)malloc(OPJ_PATH_LEN*sizeof(char));
-    fname= strtok(name,".");
+    char *fname = strtok(name,".");
     return fname;
 }
 
@@ -429,8 +457,10 @@ static char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_c
     if (parameters->decod_format == -1)
         return 1;
     sprintf(infilename,"%s/%s",img_fol->imgdirpath,image_filename);
-    strncpy(parameters->infile, infilename, sizeof(infilename));
-
+    if (opj_strcpy_s(parameters->infile, sizeof(parameters->infile), infilename) != 0) {
+        return 1;
+    }
+       
     /*Set output file*/
     strcpy(temp_ofname,get_file_name(image_filename));
     while((temp_p = strtok(NULL,".")) != NULL){
@@ -439,258 +469,17 @@ static char get_next_file(int imageno,dircnt_t *dirptr,img_fol_t *img_fol, opj_c
     }
     if(img_fol->set_out_format==1){
         sprintf(outfilename,"%s/%s.%s",img_fol->imgdirpath,temp_ofname,img_fol->out_format);
-        strncpy(parameters->outfile, outfilename, sizeof(outfilename));
-    }
-    return 0;
-}
-
-static int initialise_4K_poc(opj_poc_t *POC, int numres){
-    POC[0].tile  = 1;
-    POC[0].resno0  = 0;
-    POC[0].compno0 = 0;
-    POC[0].layno1  = 1;
-    POC[0].resno1  = numres-1;
-    POC[0].compno1 = 3;
-    POC[0].prg1 = OPJ_CPRL;
-    POC[1].tile  = 1;
-    POC[1].resno0  = numres-1;
-    POC[1].compno0 = 0;
-    POC[1].layno1  = 1;
-    POC[1].resno1  = numres;
-    POC[1].compno1 = 3;
-    POC[1].prg1 = OPJ_CPRL;
-    return 2;
-}
-
-static void set_cinema_parameters(opj_cparameters_t *parameters)
-{
-    /* Configure cinema parameters */
-    float max_rate = 0;
-    float temp_rate = 0;
-    int i;
-
-    /* profile (Rsiz) */
-    switch (parameters->cp_cinema){
-    case OPJ_CINEMA2K_24:
-    case OPJ_CINEMA2K_48:
-        parameters->cp_rsiz = OPJ_CINEMA2K;
-        break;
-    case OPJ_CINEMA4K_24:
-        parameters->cp_rsiz = OPJ_CINEMA4K;
-        break;
-    }
-
-    /* No tiling */
-    parameters->tile_size_on = OPJ_FALSE;
-    parameters->cp_tdx=1;
-    parameters->cp_tdy=1;
-
-    /* One tile part for each component */
-    parameters->tp_flag = 'C';
-    parameters->tp_on = 1;
-
-    /* Tile and Image shall be at (0,0) */
-    parameters->cp_tx0 = 0;
-    parameters->cp_ty0 = 0;
-    parameters->image_offset_x0 = 0;
-    parameters->image_offset_y0 = 0;
-
-    /* Codeblock size= 32*32 */
-    parameters->cblockw_init = 32;
-    parameters->cblockh_init = 32;
-
-    /* Codeblock style: no mode switch enabled */
-    parameters->mode = 0;
-
-    /* No ROI */
-    parameters->roi_compno = -1;
-
-    /* No subsampling */
-    parameters->subsampling_dx = 1;
-    parameters->subsampling_dy = 1;
-
-    /* 9-7 transform */
-    parameters->irreversible = 1;
-
-    /* Number of layers */
-    if (parameters->tcp_numlayers > 1){
-        fprintf(stdout,"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
-                "1 single quality layer"
-                "-> Number of layers forced to 1 (rather than %d)\n",
-                parameters->tcp_numlayers);
-        parameters->tcp_numlayers = 1;
-    }
-
-    /* Resolution levels */
-    switch (parameters->cp_cinema){
-    case OPJ_CINEMA2K_24:
-    case OPJ_CINEMA2K_48:
-        if(parameters->numresolution > 6){
-            fprintf(stdout,"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
-                    "Number of decomposition levels <= 5\n"
-                    "-> Number of decomposition levels forced to 5 (rather than %d)\n",
-                    parameters->numresolution+1);
-            parameters->numresolution = 6;
-        }
-        break;
-    case OPJ_CINEMA4K_24:
-        if(parameters->numresolution < 2){
-            fprintf(stdout,"JPEG 2000 Profile-4 (4k dc profile) requires:\n"
-                    "Number of decomposition levels >= 1 && <= 6\n"
-                    "-> Number of decomposition levels forced to 1 (rather than %d)\n",
-                    parameters->numresolution+1);
-            parameters->numresolution = 1;
-        }else if(parameters->numresolution > 7){
-            fprintf(stdout,"JPEG 2000 Profile-4 (4k dc profile) requires:\n"
-                    "Number of decomposition levels >= 1 && <= 6\n"
-                    "-> Number of decomposition levels forced to 6 (rather than %d)\n",
-                    parameters->numresolution+1);
-            parameters->numresolution = 7;
-        }
-        break;
-    default :
-        break;
-    }
-
-    /* Precincts */
-    parameters->csty |= 0x01;
-    parameters->res_spec = parameters->numresolution-1;
-    for (i = 0; i<parameters->res_spec; i++) {
-        parameters->prcw_init[i] = 256;
-        parameters->prch_init[i] = 256;
-    }
-
-    /* The progression order shall be CPRL */
-    parameters->prog_order = OPJ_CPRL;
-
-    /* Progression order changes for 4K, disallowed for 2K */
-    if (parameters->cp_cinema == OPJ_CINEMA4K_24) {
-        parameters->numpocs = initialise_4K_poc(parameters->POC,parameters->numresolution);
-    } else {
-        parameters->numpocs = 0;
-    }
-}
-
-static void set_cinema_rate(opj_cparameters_t *parameters, opj_image_t *image)
-{
-    /* Limited bit-rate */
-    float max_rate = 0;
-    float temp_rate = 0;
-    parameters->cp_disto_alloc = 1;
-    switch (parameters->cp_cinema){
-    case OPJ_CINEMA2K_24:
-    case OPJ_CINEMA4K_24:
-        max_rate = ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/
-                (CINEMA_24_CS * 8 * image->comps[0].dx * image->comps[0].dy);
-        if (parameters->tcp_rates[0] == 0){
-            parameters->tcp_rates[0] = max_rate;
-        }else{
-            temp_rate =((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/
-                    (parameters->tcp_rates[0] * 8 * image->comps[0].dx * image->comps[0].dy);
-            if (temp_rate > CINEMA_24_CS ){
-                fprintf(stdout,"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
-                        "Maximum 1302083 compressed bytes @ 24fps\n"
-                        "-> Specified rate (%3.1f) exceeds this limit. Rate will be forced to %3.1f.\n",
-                        parameters->tcp_rates[0], max_rate);
-                parameters->tcp_rates[0]= max_rate;
-            }else{
-                fprintf(stdout,"JPEG 2000 Profile-3 and 4 (2k/4k dc profile):\n"
-                        "INFO : Specified rate (%3.1f) is below the 2k/4k limit @ 24fps.\n",
-                        parameters->tcp_rates[0]);
-            }
-        }
-        parameters->max_comp_size = COMP_24_CS;
-        break;
-    case OPJ_CINEMA2K_48:
-        max_rate = ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/
-                (CINEMA_48_CS * 8 * image->comps[0].dx * image->comps[0].dy);
-        if (parameters->tcp_rates[0] == 0){
-            parameters->tcp_rates[0] = max_rate;
-        }else{
-            temp_rate =((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/
-                    (parameters->tcp_rates[0] * 8 * image->comps[0].dx * image->comps[0].dy);
-            if (temp_rate > CINEMA_48_CS ){
-                fprintf(stdout,"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
-                        "Maximum 651041 compressed bytes @ 48fps\n"
-                        "-> Specified rate (%3.1f) exceeds this limit. Rate will be forced to %3.1f.\n",
-                        parameters->tcp_rates[0], max_rate);
-                parameters->tcp_rates[0]= max_rate;
-            }else{
-                fprintf(stdout,"JPEG 2000 Profile-3 (2k dc profile):\n"
-                        "INFO : Specified rate (%3.1f) is below the 2k limit @ 48 fps.\n",
-                        parameters->tcp_rates[0]);
-            }
-        }
-        parameters->max_comp_size = COMP_48_CS;
-        break;
-    default:
-        break;
-    }
-}
-
-static OPJ_BOOL is_cinema_compliant(opj_image_t *image, OPJ_CINEMA_MODE cinema_mode)
-{
-    OPJ_UINT32 i;
-
-    /* Number of components */
-    if (image->numcomps != 3){
-        fprintf(stdout,"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
-                "3 components"
-                "-> Number of components of input image (%d) is not compliant\n"
-                "-> Non-profile-3 codestream will be generated\n",
-                image->numcomps);
-        return OPJ_FALSE;
-    }
-
-    /* Bitdepth */
-    for (i = 0; i < image->numcomps; i++) {
-        if ((image->comps[i].bpp != 12) | (image->comps[i].sgnd)){
-            char signed_str[] = "signed";
-            char unsigned_str[] = "unsigned";
-            char *tmp_str = image->comps[i].sgnd?signed_str:unsigned_str;
-            fprintf(stdout,"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
-                    "Precision of each component shall be 12 bits unsigned"
-                    "-> At least component %d of input image (%d bits, %s) is not compliant\n"
-                    "-> Non-profile-3 codestream will be generated\n",
-                    i,image->comps[i].bpp, tmp_str);
-            return OPJ_FALSE;
-        }
-    }
-
-    /* Image size */
-    switch (cinema_mode){
-    case OPJ_CINEMA2K_24:
-    case OPJ_CINEMA2K_48:
-        if (((image->comps[0].w > 2048) | (image->comps[0].h > 1080))){
-            fprintf(stdout,"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
-                    "width <= 2048 and height <= 1080\n"
-                    "-> Input image size %d x %d is not compliant\n"
-                    "-> Non-profile-3 codestream will be generated\n",
-                    image->comps[0].w,image->comps[0].h);
-            return OPJ_FALSE;
-        }
-        break;
-    case OPJ_CINEMA4K_24:
-        if (((image->comps[0].w > 4096) | (image->comps[0].h > 2160))){
-            fprintf(stdout,"JPEG 2000 Profile-4 (4k dc profile) requires:\n"
-                    "width <= 4096 and height <= 2160\n"
-                    "-> Image size %d x %d is not compliant\n"
-                    "-> Non-profile-4 codestream will be generated\n",
-                    image->comps[0].w,image->comps[0].h);
-            return OPJ_FALSE;
+        if (opj_strcpy_s(parameters->outfile, sizeof(parameters->outfile), outfilename) != 0) {
+            return 1;
         }
-        break;
-    default :
-        break;
     }
-
-    return OPJ_TRUE;
+    return 0;
 }
 
 /* ------------------------------------------------------------------------------------ */
 
 static int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *parameters,
-                                 img_fol_t *img_fol, raw_cparameters_t *raw_cp, char *indexfilename) {
+                                 img_fol_t *img_fol, raw_cparameters_t *raw_cp, char *indexfilename, size_t indexfilename_size) {
     OPJ_UINT32 i, j;
     int totlen, c;
     opj_option_t long_option[]={
@@ -703,11 +492,12 @@ static int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *param
         {"OutFor",REQ_ARG, NULL ,'O'},
         {"POC",REQ_ARG, NULL ,'P'},
         {"ROI",REQ_ARG, NULL ,'R'},
-        {"jpip",NO_ARG, NULL, 'J'}
+        {"jpip",NO_ARG, NULL, 'J'},
+        {"mct",REQ_ARG, NULL, 'Y'}
     };
 
     /* parse the command line */
-    const char optlist[] = "i:o:r:q:n:b:c:t:p:s:SEM:x:R:d:T:If:P:C:F:u:J"
+    const char optlist[] = "i:o:r:q:n:b:c:t:p:s:SEM:x:R:d:T:If:P:C:F:u:JY:"
         #ifdef USE_JPWL
             "W:"
         #endif /* USE_JPWL */
@@ -738,12 +528,14 @@ static int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *param
                 break;
             default:
                 fprintf(stderr,
-                        "!! Unrecognized format for infile : %s "
-                        "[accept only *.pnm, *.pgm, *.ppm, *.pgx, *png, *.bmp, *.tif, *.raw or *.tga] !!\n\n",
+                        "[ERROR] Unknown input file format: %s \n"
+                        "        Known file formats are *.pnm, *.pgm, *.ppm, *.pgx, *png, *.bmp, *.tif, *.raw or *.tga\n",
                         infile);
                 return 1;
             }
-            strncpy(parameters->infile, infile, sizeof(parameters->infile)-1);
+            if (opj_strcpy_s(parameters->infile, sizeof(parameters->infile), infile) != 0) {
+                return 1;
+            }
         }
             break;
 
@@ -761,7 +553,9 @@ static int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *param
                 fprintf(stderr, "Unknown output format image %s [only *.j2k, *.j2c or *.jp2]!! \n", outfile);
                 return 1;
             }
-            strncpy(parameters->outfile, outfile, sizeof(parameters->outfile)-1);
+            if (opj_strcpy_s(parameters->outfile, sizeof(parameters->outfile), outfile) != 0) {
+                return 1;
+            }
         }
             break;
 
@@ -811,31 +605,89 @@ static int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *param
 
         case 'F':                      /* Raw image format parameters */
         {
+            OPJ_BOOL wrong = OPJ_FALSE;
+            char *substr1;
+            char *substr2;
+            char *sep;
             char signo;
-            char *s = opj_optarg;
-            if (sscanf(s, "%d,%d,%d,%d,%c", &raw_cp->rawWidth, &raw_cp->rawHeight, &raw_cp->rawComp, &raw_cp->rawBitDepth, &signo) == 5) {
+            int width,height,bitdepth,ncomp;
+            OPJ_UINT32 len;
+            OPJ_BOOL raw_signed = OPJ_FALSE;
+            substr2 = strchr(opj_optarg,'@');
+            if (substr2 == NULL) {
+                len = (OPJ_UINT32) strlen(opj_optarg);
+            } else {
+                len = (OPJ_UINT32) (substr2 - opj_optarg);
+                substr2++; /* skip '@' character */
+            }
+            substr1 = (char*) malloc((len+1)*sizeof(char));
+            if (substr1 == NULL) {
+                return 1;
+            }
+            memcpy(substr1,opj_optarg,len);
+            substr1[len] = '\0';
+            if (sscanf(substr1, "%d,%d,%d,%d,%c", &width, &height, &ncomp, &bitdepth, &signo) == 5) {
                 if (signo == 's') {
-                    raw_cp->rawSigned = OPJ_TRUE;
-                    fprintf(stdout,"\nRaw file parameters: %d,%d,%d,%d Signed\n", raw_cp->rawWidth, raw_cp->rawHeight, raw_cp->rawComp, raw_cp->rawBitDepth);
+                    raw_signed = OPJ_TRUE;
+                } else if (signo == 'u') {
+                    raw_signed = OPJ_FALSE;
+                } else {
+                    wrong = OPJ_TRUE;
                 }
-                else if (signo == 'u') {
-                    raw_cp->rawSigned = OPJ_FALSE;
-                    fprintf(stdout,"\nRaw file parameters: %d,%d,%d,%d Unsigned\n", raw_cp->rawWidth, raw_cp->rawHeight, raw_cp->rawComp, raw_cp->rawBitDepth);
-                }
-                else {
-                    fprintf(stderr,"\nError: invalid raw image parameters: Unknown sign of raw file\n");
-                    fprintf(stderr,"Please use the Format option -F:\n");
-                    fprintf(stderr,"-F rawWidth,rawHeight,rawComp,rawBitDepth,s/u (Signed/Unsigned)\n");
-                    fprintf(stderr,"Example: -i lena.raw -o lena.j2k -F 512,512,3,8,u\n");
-                    fprintf(stderr,"Aborting\n");
+            } else {
+                wrong = OPJ_TRUE;
+            }
+            if (!wrong) {
+                int compno;
+                int lastdx = 1;
+                int lastdy = 1;
+                raw_cp->rawWidth = width;
+                raw_cp->rawHeight = height;
+                raw_cp->rawComp = ncomp;
+                raw_cp->rawBitDepth = bitdepth;
+                raw_cp->rawSigned  = raw_signed;
+                raw_cp->rawComps = (raw_comp_cparameters_t*) malloc(((OPJ_UINT32)(ncomp))*sizeof(raw_comp_cparameters_t));
+                               if(raw_cp->rawComps == NULL){
+                                       free(substr1);
+                                       return 1;
+                               }
+                for (compno = 0; compno < ncomp && !wrong; compno++) {
+                    if (substr2 == NULL) {
+                        raw_cp->rawComps[compno].dx = lastdx;
+                        raw_cp->rawComps[compno].dy = lastdy;
+                    } else {
+                        int dx,dy;
+                        sep = strchr(substr2,':');
+                        if (sep == NULL) {
+                            if (sscanf(substr2, "%dx%d", &dx, &dy) == 2) {
+                                lastdx = dx;
+                                lastdy = dy;
+                                raw_cp->rawComps[compno].dx = dx;
+                                raw_cp->rawComps[compno].dy = dy;
+                                substr2 = NULL;
+                            } else {
+                                wrong = OPJ_TRUE;
+                            }
+                        } else {
+                            if (sscanf(substr2, "%dx%d:%s", &dx, &dy, substr2) == 3) {
+                                raw_cp->rawComps[compno].dx = dx;
+                                raw_cp->rawComps[compno].dy = dy;
+                            } else {
+                                wrong = OPJ_TRUE;
+                            }
+                        }
+                    }
                 }
             }
-            else {
+            free(substr1);
+            if (wrong) {
                 fprintf(stderr,"\nError: invalid raw image parameters\n");
                 fprintf(stderr,"Please use the Format option -F:\n");
-                fprintf(stderr,"-F rawWidth,rawHeight,rawComp,rawBitDepth,s/u (Signed/Unsigned)\n");
-                fprintf(stderr,"Example: -i lena.raw -o lena.j2k -F 512,512,3,8,u\n");
-                fprintf(stderr,"Aborting\n");
+                fprintf(stderr,"-F <width>,<height>,<ncomp>,<bitdepth>,{s,u}@<dx1>x<dy1>:...:<dxn>x<dyn>\n");
+                fprintf(stderr,"If subsampling is omitted, 1x1 is assumed for all components\n");
+                fprintf(stderr,"Example: -i image.raw -o image.j2k -F 512,512,3,8,u@1x1:2x2:2x2\n");
+                fprintf(stderr,"         for raw 512x512 image with 4:2:0 subsampling\n");
+                fprintf(stderr,"Aborting.\n");
                 return 1;
             }
         }
@@ -868,15 +720,18 @@ static int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *param
             OPJ_UINT32 numlayers = 0, numresolution = 0, matrix_width = 0;
 
             char *s = opj_optarg;
-            sscanf(s, "%d", &numlayers);
+            sscanf(s, "%u", &numlayers);
             s++;
             if (numlayers > 9)
                 s++;
 
-            parameters->tcp_numlayers = numlayers;
-            numresolution = parameters->numresolution;
+            parameters->tcp_numlayers = (int)numlayers;
+            numresolution = (OPJ_UINT32)parameters->numresolution;
             matrix_width = numresolution * 3;
             parameters->cp_matrice = (int *) malloc(numlayers * matrix_width * sizeof(int));
+                       if(parameters->cp_matrice == NULL){
+                               return 1;
+                       }
             s = s + 2;
 
             for (i = 0; i < numlayers; i++) {
@@ -931,10 +786,17 @@ static int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *param
             int res_spec = 0;
 
             char *s = opj_optarg;
+            int ret;
             do {
                 sep = 0;
-                sscanf(s, "[%d,%d]%c", &parameters->prcw_init[res_spec],
+                ret = sscanf(s, "[%d,%d]%c", &parameters->prcw_init[res_spec],
                        &parameters->prch_init[res_spec], &sep);
+                if( !(ret == 2 && sep == 0) && !(ret == 3 && sep == ',') )
+                  {
+                  fprintf(stderr,"\nError: could not parse precinct dimension: '%s' %x\n", s, sep);
+                  fprintf(stderr,"Example: -i lena.raw -o lena.j2k -c [128,128],[128,128]\n");
+                  return 1;
+                  }
                 parameters->csty |= 0x01;
                 res_spec++;
                 s = strpbrk(s, "]") + 2;
@@ -966,8 +828,14 @@ static int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *param
 
         case 'x':                      /* creation of index file */
         {
-            char *index = opj_optarg;
-            strncpy(indexfilename, index, OPJ_PATH_LEN);
+            if (opj_strcpy_s(indexfilename, indexfilename_size, opj_optarg) != 0) {
+                return 1;
+            }
+            /* FIXME ADE INDEX >> */
+            fprintf(stderr,
+                    "[WARNING] Index file generation is currently broken.\n"
+                    "          '-x' option ignored.\n");
+            /* << FIXME ADE INDEX */
         }
             break;
 
@@ -1028,7 +896,7 @@ static int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *param
             char *s = opj_optarg;
             POC = parameters->POC;
 
-            while (sscanf(s, "T%d=%d,%d,%d,%d,%d,%4s", &POC[numpocs].tile,
+            while (sscanf(s, "T%u=%u,%u,%u,%u,%u,%4s", &POC[numpocs].tile,
                           &POC[numpocs].resno0, &POC[numpocs].compno0,
                           &POC[numpocs].layno1, &POC[numpocs].resno1,
                           &POC[numpocs].compno1, POC[numpocs].progorder) == 7) {
@@ -1042,7 +910,7 @@ static int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *param
                 }
                 s++;
             }
-            parameters->numpocs = numpocs;
+            parameters->numpocs = (OPJ_UINT32)numpocs;
         }
             break;
 
@@ -1134,6 +1002,9 @@ static int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *param
         case 'z':                      /* Image Directory path */
         {
             img_fol->imgdirpath = (char*)malloc(strlen(opj_optarg) + 1);
+                       if(img_fol->imgdirpath == NULL){
+                               return 1;
+                       }
             strcpy(img_fol->imgdirpath,opj_optarg);
             img_fol->set_imgdir=1;
         }
@@ -1146,15 +1017,19 @@ static int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *param
             int fps=0;
             sscanf(opj_optarg,"%d",&fps);
             if(fps == 24){
-                parameters->cp_cinema = OPJ_CINEMA2K_24;
+                parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
+                parameters->max_comp_size = OPJ_CINEMA_24_COMP;
+                parameters->max_cs_size = OPJ_CINEMA_24_CS;
             }else if(fps == 48 ){
-                parameters->cp_cinema = OPJ_CINEMA2K_48;
+                parameters->rsiz = OPJ_PROFILE_CINEMA_2K;
+                parameters->max_comp_size = OPJ_CINEMA_48_COMP;
+                parameters->max_cs_size = OPJ_CINEMA_48_CS;
             }else {
                 fprintf(stderr,"Incorrect value!! must be 24 or 48\n");
                 return 1;
             }
             fprintf(stdout,"CINEMA 2K profile activated\n"
-                    "Other options specified could be overriden\n");
+                    "Other options specified could be overridden\n");
 
         }
             break;
@@ -1163,13 +1038,29 @@ static int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *param
 
         case 'y':                      /* Digital Cinema 4K profile compliance*/
         {
-            parameters->cp_cinema = OPJ_CINEMA4K_24;
+            parameters->rsiz = OPJ_PROFILE_CINEMA_4K;
             fprintf(stdout,"CINEMA 4K profile activated\n"
-                    "Other options specified could be overriden\n");
+                    "Other options specified could be overridden\n");
         }
             break;
 
             /* ------------------------------------------------------ */
+
+        case 'Y':                      /* Shall we do an MCT ? 0:no_mct;1:rgb->ycc;2:custom mct (-m option required)*/
+        {
+            int mct_mode=0;
+            sscanf(opj_optarg,"%d",&mct_mode);
+            if(mct_mode < 0 || mct_mode > 2){
+                fprintf(stderr,"MCT incorrect value!! Current accepted values are 0, 1 or 2.\n");
+                return 1;
+            }
+            parameters->tcp_mct = (char) mct_mode;
+        }
+            break;
+
+            /* ------------------------------------------------------ */
+
+
         case 'm':                      /* mct input file */
         {
             char *lFilename = opj_optarg;
@@ -1178,7 +1069,8 @@ static int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *param
             float *lCurrentDoublePtr;
             float *lSpace;
             int *l_int_ptr;
-            int lNbComp = 0, lTotalComp, lMctComp, i, lStrLen;
+            int lNbComp = 0, lTotalComp, lMctComp, i2;
+            size_t lStrLen, lStrFread;
 
             /* Open file */
             FILE * lFile = fopen(lFilename,"r");
@@ -1188,11 +1080,19 @@ static int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *param
 
             /* Set size of file and read its content*/
             fseek(lFile,0,SEEK_END);
-            lStrLen = ftell(lFile);
+            lStrLen = (size_t)ftell(lFile);
             fseek(lFile,0,SEEK_SET);
             lMatrix = (char *) malloc(lStrLen + 1);
-            fread(lMatrix, lStrLen, 1, lFile);
+            if (lMatrix == NULL) {
+                fclose(lFile);
+                return 1;
+            }
+            lStrFread = fread(lMatrix, 1, lStrLen, lFile);
             fclose(lFile);
+            if( lStrLen != lStrFread ) {
+                free(lMatrix);
+                return 1;
+            }
 
             lMatrix[lStrLen] = 0;
             lCurrentPtr = lMatrix;
@@ -1211,23 +1111,27 @@ static int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *param
             lNbComp = (int) (sqrt(4*lNbComp + 1)/2. - 0.5);
             lMctComp = lNbComp * lNbComp;
             lTotalComp = lMctComp + lNbComp;
-            lSpace = (float *) malloc(lTotalComp * sizeof(float));
+            lSpace = (float *) malloc((size_t)lTotalComp * sizeof(float));
+            if(lSpace == NULL) {
+                free(lMatrix);
+                return 1;
+            }
             lCurrentDoublePtr = lSpace;
-            for (i=0;i<lMctComp;++i) {
+            for (i2=0;i2<lMctComp;++i2) {
                 lStrLen = strlen(lCurrentPtr) + 1;
                 *lCurrentDoublePtr++ = (float) atof(lCurrentPtr);
                 lCurrentPtr += lStrLen;
             }
 
             l_int_ptr = (int*) lCurrentDoublePtr;
-            for (i=0;i<lNbComp;++i) {
+            for (i2=0;i2<lNbComp;++i2) {
                 lStrLen = strlen(lCurrentPtr) + 1;
                 *l_int_ptr++ = atoi(lCurrentPtr);
                 lCurrentPtr += lStrLen;
             }
 
             /* TODO should not be here ! */
-            opj_set_MCT(parameters, lSpace, (int *)(lSpace + lMctComp), lNbComp);
+            opj_set_MCT(parameters, lSpace, (int *)(lSpace + lMctComp), (OPJ_UINT32)lNbComp);
 
             /* Free memory*/
             free(lSpace);
@@ -1249,7 +1153,9 @@ static int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *param
 
             /* we need to enable indexing */
             if (!indexfilename || !*indexfilename) {
-                strncpy(indexfilename, JPWL_PRIVATEINDEX_NAME, OPJ_PATH_LEN);
+                if (opj_strcpy_s(indexfilename, indexfilename_size, JPWL_PRIVATEINDEX_NAME) != 0) {
+                    return 1;
+                }
             }
 
             /* search for different protection methods */
@@ -1568,37 +1474,38 @@ static int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *param
 
 
         default:
-            fprintf(stderr, "ERROR -> Command line not valid\n");
-            return 1;
+            fprintf(stderr, "[WARNING] An invalid option has been ignored\n");
+            break;
         }
     }while(c != -1);
 
     if(img_fol->set_imgdir == 1){
         if(!(parameters->infile[0] == 0)){
-            fprintf(stderr, "Error: options -ImgDir and -i cannot be used together !!\n");
+            fprintf(stderr, "[ERROR] options -ImgDir and -i cannot be used together !!\n");
             return 1;
         }
         if(img_fol->set_out_format == 0){
-            fprintf(stderr, "Error: When -ImgDir is used, -OutFor <FORMAT> must be used !!\n");
+            fprintf(stderr, "[ERROR] When -ImgDir is used, -OutFor <FORMAT> must be used !!\n");
             fprintf(stderr, "Only one format allowed! Valid formats are j2k and jp2!!\n");
             return 1;
         }
         if(!((parameters->outfile[0] == 0))){
-            fprintf(stderr, "Error: options -ImgDir and -o cannot be used together !!\n");
+            fprintf(stderr, "[ERROR] options -ImgDir and -o cannot be used together !!\n");
             fprintf(stderr, "Specify OutputFormat using -OutFor<FORMAT> !!\n");
             return 1;
         }
     }else{
         if((parameters->infile[0] == 0) || (parameters->outfile[0] == 0)) {
-            fprintf(stderr, "Example: %s -i image.ppm  -o image.j2k\n",argv[0]);
-            fprintf(stderr, "    Try: %s -h\n",argv[0]);
+            fprintf(stderr, "[ERROR] Required parameters are missing\n"
+                            "Example: %s -i image.pgm -o image.j2k\n",argv[0]);
+            fprintf(stderr, "   Help: %s -h\n",argv[0]);
             return 1;
         }
     }
 
     if ( (parameters->decod_format == RAW_DFMT && raw_cp->rawWidth == 0)
          || (parameters->decod_format == RAWL_DFMT && raw_cp->rawWidth == 0)) {
-        fprintf(stderr,"\nError: invalid raw image parameters\n");
+        fprintf(stderr,"[ERROR] invalid raw image parameters\n");
         fprintf(stderr,"Please use the Format option -F:\n");
         fprintf(stderr,"-F rawWidth,rawHeight,rawComp,rawBitDepth,s/u (Signed/Unsigned)\n");
         fprintf(stderr,"Example: -i lena.raw -o lena.j2k -F 512,512,3,8,u\n");
@@ -1608,7 +1515,7 @@ static int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *param
 
     if ((parameters->cp_disto_alloc || parameters->cp_fixed_alloc || parameters->cp_fixed_quality)
             && (!(parameters->cp_disto_alloc ^ parameters->cp_fixed_alloc ^ parameters->cp_fixed_quality))) {
-        fprintf(stderr, "Error: options -r -q and -f cannot be used together !!\n");
+        fprintf(stderr, "[ERROR] options -r -q and -f cannot be used together !!\n");
         return 1;
     }                          /* mod fixed_quality */
 
@@ -1621,7 +1528,7 @@ static int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *param
 
     if((parameters->cp_tx0 > parameters->image_offset_x0) || (parameters->cp_ty0 > parameters->image_offset_y0)) {
         fprintf(stderr,
-                "Error: Tile offset dimension is unnappropriate --> TX0(%d)<=IMG_X0(%d) TYO(%d)<=IMG_Y0(%d) \n",
+                "[ERROR] Tile offset dimension is unnappropriate --> TX0(%d)<=IMG_X0(%d) TYO(%d)<=IMG_Y0(%d) \n",
                 parameters->cp_tx0, parameters->image_offset_x0, parameters->cp_ty0, parameters->image_offset_y0);
         return 1;
     }
@@ -1634,33 +1541,20 @@ static int parse_cmdline_encoder(int argc, char **argv, opj_cparameters_t *param
         }
     }
 
+    /* If subsampled image is provided, automatically disable MCT */
+    if ( ((parameters->decod_format == RAW_DFMT) || (parameters->decod_format == RAWL_DFMT))
+         && (   ((raw_cp->rawComp > 1 ) && ((raw_cp->rawComps[1].dx > 1) || (raw_cp->rawComps[1].dy > 1)))
+             || ((raw_cp->rawComp > 2 ) && ((raw_cp->rawComps[2].dx > 1) || (raw_cp->rawComps[2].dy > 1)))
+                                               )) {
+        parameters->tcp_mct = 0;
+    }
+
     return 0;
+
 }
 
 /* -------------------------------------------------------------------------- */
 
-/**
-sample error callback expecting a FILE* client object
-*/
-static void error_file_callback(const char *msg, void *client_data) {
-    FILE *stream = (FILE*)client_data;
-    fprintf(stream, "[ERROR] %s", msg);
-}
-/**
-sample warning callback expecting a FILE* client object
-*/
-static void warning_file_callback(const char *msg, void *client_data) {
-    FILE *stream = (FILE*)client_data;
-    fprintf(stream, "[WARNING] %s", msg);
-}
-/**
-sample debug callback expecting a FILE* client object
-*/
-static void info_file_callback(const char *msg, void *client_data) {
-    FILE *stream = (FILE*)client_data;
-    fprintf(stream, "[INFO] %s", msg);
-}
-
 /**
 sample error debug callback expecting no client object
 */
@@ -1683,6 +1577,31 @@ static void info_callback(const char *msg, void *client_data) {
     fprintf(stdout, "[INFO] %s", msg);
 }
 
+OPJ_FLOAT64 opj_clock(void) {
+#ifdef _WIN32
+       /* _WIN32: use QueryPerformance (very accurate) */
+    LARGE_INTEGER freq , t ;
+    /* freq is the clock speed of the CPU */
+    QueryPerformanceFrequency(&freq) ;
+       /* cout << "freq = " << ((double) freq.QuadPart) << endl; */
+    /* t is the high resolution performance counter (see MSDN) */
+    QueryPerformanceCounter ( & t ) ;
+    return freq.QuadPart ? ( t.QuadPart /(OPJ_FLOAT64) freq.QuadPart ) : 0 ;
+#else
+       /* Unix or Linux: use resource usage */
+    struct rusage t;
+    OPJ_FLOAT64 procTime;
+    /* (1) Get the rusage data structure at this moment (man getrusage) */
+    getrusage(0,&t);
+    /* (2) What is the elapsed time ? - CPU time = User time + System time */
+       /* (2a) Get the seconds */
+    procTime = (OPJ_FLOAT64)(t.ru_utime.tv_sec + t.ru_stime.tv_sec);
+    /* (2b) More precisely! Get the microseconds part ! */
+    return ( procTime + (OPJ_FLOAT64)(t.ru_utime.tv_usec + t.ru_stime.tv_usec) * 1e-6 ) ;
+#endif
+}
+
+
 /* -------------------------------------------------------------------------- */
 /**
  * OPJ_COMPRESS MAIN
@@ -1696,6 +1615,7 @@ int main(int argc, char **argv) {
     opj_codec_t* l_codec = 00;
     opj_image_t *image = NULL;
     raw_cparameters_t raw_cp;
+    OPJ_SIZE_T num_compressed_files = 0;
 
     char indexfilename[OPJ_PATH_LEN];  /* index file name */
 
@@ -1706,6 +1626,7 @@ int main(int argc, char **argv) {
     OPJ_BOOL bSuccess;
     OPJ_BOOL bUseTiles = OPJ_FALSE; /* OPJ_TRUE */
     OPJ_UINT32 l_nb_tiles = 4;
+    OPJ_FLOAT64 t = opj_clock();
 
     /* set encoding parameters to default values */
     opj_set_default_encoder_parameters(&parameters);
@@ -1714,29 +1635,18 @@ int main(int argc, char **argv) {
     *indexfilename = 0;
     memset(&img_fol,0,sizeof(img_fol_t));
 
-    /* parse input and get user encoding parameters */
-    if(parse_cmdline_encoder(argc, argv, &parameters,&img_fol, &raw_cp, indexfilename) == 1) {
-        return 1;
-    }
-
-    if (parameters.cp_cinema){
-        set_cinema_parameters(&parameters);
-    }
+    /* raw_cp initialization */
+    raw_cp.rawBitDepth = 0;
+    raw_cp.rawComp = 0;
+    raw_cp.rawComps = 0;
+    raw_cp.rawHeight = 0;
+    raw_cp.rawSigned = 0;
+    raw_cp.rawWidth = 0;
 
-    /* Create comment for codestream */
-    if(parameters.cp_comment == NULL) {
-        const char comment[] = "Created by OpenJPEG version ";
-        const size_t clen = strlen(comment);
-        const char *version = opj_version();
-        /* UniPG>> */
-#ifdef USE_JPWL
-        parameters.cp_comment = (char*)malloc(clen+strlen(version)+11);
-        sprintf(parameters.cp_comment,"%s%s with JPWL", comment, version);
-#else
-        parameters.cp_comment = (char*)malloc(clen+strlen(version)+1);
-        sprintf(parameters.cp_comment,"%s%s", comment, version);
-#endif
-        /* <<UniPG */
+    /* parse input and get user encoding parameters */
+    parameters.tcp_mct = (char) 255; /* This will be set later according to the input image or the provided option */
+    if(parse_cmdline_encoder(argc, argv, &parameters,&img_fol, &raw_cp, indexfilename, sizeof(indexfilename)) == 1) {
+        goto fails;
     }
 
     /* Read directory if necessary */
@@ -1769,7 +1679,7 @@ int main(int argc, char **argv) {
         fprintf(stderr,"\n");
 
         if(img_fol.set_imgdir==1){
-            if (get_next_file(imageno, dirptr,&img_fol, &parameters)) {
+            if (get_next_file((int)imageno, dirptr,&img_fol, &parameters)) {
                 fprintf(stderr,"skipping file...\n");
                 continue;
             }
@@ -1878,14 +1788,19 @@ int main(int argc, char **argv) {
         }
 
         /* Decide if MCT should be used */
-        parameters.tcp_mct = image->numcomps == 3 ? 1 : 0;
-
-        if(parameters.cp_cinema){
-            if (!is_cinema_compliant(image,parameters.cp_cinema)) {
-                parameters.cp_rsiz = OPJ_STD_RSIZ;
+        if (parameters.tcp_mct == (char) 255) { /* mct mode has not been set in commandline */
+            parameters.tcp_mct = (image->numcomps >= 3) ? 1 : 0;
+        } else {            /* mct mode has been set in commandline */
+            if ((parameters.tcp_mct == 1) && (image->numcomps < 3)){
+                fprintf(stderr, "RGB->YCC conversion cannot be used:\n");
+                fprintf(stderr, "Input image has less than 3 components\n");
+                return 1;
+            }
+            if ((parameters.tcp_mct == 2) && (!parameters.mct_data)){
+                fprintf(stderr, "Custom MCT has been set but no array-based MCT\n");
+                fprintf(stderr, "has been provided. Aborting.\n");
+                return 1;
             }
-            /* This cannot be in set_cinema_parameters because we need size and precision of the input image */
-            set_cinema_rate(&parameters,image);
         }
 
         /* encode the destination image */
@@ -1906,7 +1821,7 @@ int main(int argc, char **argv) {
         }
         default:
             fprintf(stderr, "skipping file..\n");
-            opj_stream_destroy_v3(l_stream);
+            opj_stream_destroy(l_stream);
             continue;
         }
 
@@ -1922,10 +1837,15 @@ int main(int argc, char **argv) {
             parameters.cp_tdx = 512;
             parameters.cp_tdy = 512;
         }
-        opj_setup_encoder(l_codec, &parameters, image);
+        if (! opj_setup_encoder(l_codec, &parameters, image)) {
+            fprintf(stderr, "failed to encode image: opj_setup_encoder\n");
+            opj_destroy_codec(l_codec);
+            opj_image_destroy(image);
+            return 1;
+        }
 
         /* open a byte stream for writing and allocate memory for all tiles */
-        l_stream = opj_stream_create_default_file_stream_v3(parameters.outfile,OPJ_FALSE);
+        l_stream = opj_stream_create_default_file_stream(parameters.outfile,OPJ_FALSE);
         if (! l_stream){
             return 1;
         }
@@ -1935,16 +1855,17 @@ int main(int argc, char **argv) {
         if (!bSuccess)  {
             fprintf(stderr, "failed to encode image: opj_start_compress\n");
         }
-        if( bUseTiles ) {
+        if( bSuccess && bUseTiles ) {
             OPJ_BYTE *l_data;
             OPJ_UINT32 l_data_size = 512*512*3;
-            l_data = (OPJ_BYTE*) malloc( l_data_size * sizeof(OPJ_BYTE));
-            memset(l_data, 0, l_data_size );
-            assert( l_data );
+            l_data = (OPJ_BYTE*) calloc( 1,l_data_size);
+            if(l_data == NULL){
+                               goto fails;
+                       }
             for (i=0;i<l_nb_tiles;++i) {
                 if (! opj_write_tile(l_codec,i,l_data,l_data_size,l_stream)) {
                     fprintf(stderr, "ERROR -> test_tile_encoder: failed to write the tile %d!\n",i);
-                    opj_stream_destroy_v3(l_stream);
+                    opj_stream_destroy(l_stream);
                     opj_destroy_codec(l_codec);
                     opj_image_destroy(image);
                     return 1;
@@ -1964,16 +1885,18 @@ int main(int argc, char **argv) {
         }
 
         if (!bSuccess)  {
-            opj_stream_destroy_v3(l_stream);
+            opj_stream_destroy(l_stream);
             opj_destroy_codec(l_codec);
             opj_image_destroy(image);
             fprintf(stderr, "failed to encode image\n");
+                       remove(parameters.outfile);
             return 1;
         }
 
-        fprintf(stderr,"Generated outfile %s\n",parameters.outfile);
+               num_compressed_files++;
+        fprintf(stdout,"[INFO] Generated outfile %s\n",parameters.outfile);
         /* close and free the byte stream */
-        opj_stream_destroy_v3(l_stream);
+        opj_stream_destroy(l_stream);
 
         /* free remaining compression structures */
         opj_destroy_codec(l_codec);
@@ -1986,6 +1909,24 @@ int main(int argc, char **argv) {
     /* free user parameters structure */
     if(parameters.cp_comment)   free(parameters.cp_comment);
     if(parameters.cp_matrice)   free(parameters.cp_matrice);
+    if(raw_cp.rawComps) free(raw_cp.rawComps);
+       
+    t = opj_clock() - t;
+    if (num_compressed_files) {
+                   fprintf(stdout, "encode time: %d ms \n", (int)((t * 1000.0)/(OPJ_FLOAT64)num_compressed_files));
+    }
 
     return 0;
+
+fails:
+       if(parameters.cp_comment)   free(parameters.cp_comment);
+       if(parameters.cp_matrice)   free(parameters.cp_matrice);
+       if(raw_cp.rawComps) free(raw_cp.rawComps);
+       if(img_fol.imgdirpath) free(img_fol.imgdirpath);
+       if(dirptr){
+           if(dirptr->filename_buf) free(dirptr->filename_buf);
+           if(dirptr->filename) free(dirptr->filename);
+           free(dirptr);
+       }
+       return 1;
 }