[trunk] refactoring of rsiz, profiles, and extensions management
[openjpeg.git] / src / bin / jp2 / convert.c
index 4144a395006415c0473edaeea14c14bc32af8a08..1b2d3618ef8debf5977147b97b3b29ae1d542d73 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
  * All rights reserved.
@@ -94,7 +100,7 @@ struct tga_header
 
 static unsigned short get_ushort(unsigned short val) {
 
-#ifdef WORDS_BIGENDIAN
+#ifdef OPJ_BIG_ENDIAN
     return( ((val & 0xff) << 8) + (val >> 8) );
 #else
     return( val );
@@ -109,10 +115,10 @@ static int tga_readheader(FILE *fp, unsigned int *bits_per_pixel,
 {
     int palette_size;
     unsigned char *tga ;
-    unsigned char id_len, cmap_type, image_type;
+    unsigned char id_len, /*cmap_type,*/ image_type;
     unsigned char pixel_depth, image_desc;
-    unsigned short cmap_index, cmap_len, cmap_entry_size;
-    unsigned short x_origin, y_origin, image_w, image_h;
+    unsigned short /*cmap_index,*/ cmap_len, cmap_entry_size;
+    unsigned short /*x_origin, y_origin,*/ image_w, image_h;
 
     if (!bits_per_pixel || !width || !height || !flip_image)
         return 0;
@@ -124,15 +130,17 @@ static int tga_readheader(FILE *fp, unsigned int *bits_per_pixel,
         return 0 ;
     }
     id_len = (unsigned char)tga[0];
-    cmap_type = (unsigned char)tga[1];
+    /*cmap_type = (unsigned char)tga[1];*/
     image_type = (unsigned char)tga[2];
-    cmap_index = get_ushort(*(unsigned short*)(&tga[3]));
+    /*cmap_index = get_ushort(*(unsigned short*)(&tga[3]));*/
     cmap_len = get_ushort(*(unsigned short*)(&tga[5]));
     cmap_entry_size = (unsigned char)tga[7];
 
 
+#if 0
     x_origin = get_ushort(*(unsigned short*)(&tga[8]));
     y_origin = get_ushort(*(unsigned short*)(&tga[10]));
+#endif
     image_w = get_ushort(*(unsigned short*)(&tga[12]));
     image_h = get_ushort(*(unsigned short*)(&tga[14]));
     pixel_depth = (unsigned char)tga[16];
@@ -179,9 +187,9 @@ static int tga_readheader(FILE *fp, unsigned int *bits_per_pixel,
     return 1;
 }
 
-#if WORDS_BIGENDIAN == 1
+#ifdef OPJ_BIG_ENDIAN
 
-static inline int16_t swap16(int16_t x)
+static INLINE int16_t swap16(int16_t x)
 {
     return((((u_int16_t)x & 0x00ffU) <<  8) |
            (((u_int16_t)x & 0xff00U) >>  8));
@@ -226,7 +234,7 @@ static int tga_writeheader(FILE *fp, int bits_per_pixel, int width, int height,
     image_w = (unsigned short)width;
     image_h = (unsigned short) height;
 
-#if WORDS_BIGENDIAN == 0
+#ifndef OPJ_BIG_ENDIAN
     if(fwrite(&image_w, 2, 1, fp) != 1) goto fails;
     if(fwrite(&image_h, 2, 1, fp) != 1) goto fails;
 #else
@@ -300,23 +308,23 @@ opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters) {
         cmptparm[i].prec = 8;
         cmptparm[i].bpp = 8;
         cmptparm[i].sgnd = 0;
-        cmptparm[i].dx = subsampling_dx;
-        cmptparm[i].dy = subsampling_dy;
+        cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
+        cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
         cmptparm[i].w = image_width;
         cmptparm[i].h = image_height;
     }
 
     /* create the image */
-    image = opj_image_create(numcomps, &cmptparm[0], color_space);
+    image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
 
     if (!image)
         return NULL;
 
     /* set image offset and reference grid */
-    image->x0 = parameters->image_offset_x0;
-    image->y0 = parameters->image_offset_y0;
-    image->x1 =        !image->x0 ? (image_width - 1) * subsampling_dx + 1 : image->x0 + (image_width - 1) * subsampling_dx + 1;
-    image->y1 =        !image->y0 ? (image_height - 1) * subsampling_dy + 1 : image->y0 + (image_height - 1) * subsampling_dy + 1;
+    image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
+    image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
+    image->x1 =        !image->x0 ? (OPJ_UINT32)(image_width - 1)  * (OPJ_UINT32)subsampling_dx + 1 : image->x0 + (OPJ_UINT32)(image_width - 1)  * (OPJ_UINT32)subsampling_dx + 1;
+    image->y1 =        !image->y0 ? (OPJ_UINT32)(image_height - 1) * (OPJ_UINT32)subsampling_dy + 1 : image->y0 + (OPJ_UINT32)(image_height - 1) * (OPJ_UINT32)subsampling_dy + 1;
 
     /* set image data */
     for (y=0; y < image_height; y++)
@@ -324,9 +332,9 @@ opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters) {
         int index;
 
         if (flip_image)
-            index = (image_height-y-1)*image_width;
+            index = (int)((image_height-y-1)*image_width);
         else
-            index = y*image_width;
+            index = (int)(y*image_width);
 
         if (numcomps==3)
         {
@@ -406,13 +414,15 @@ opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters) {
 int imagetotga(opj_image_t * image, const char *outfile) {
     int width, height, bpp, x, y;
     OPJ_BOOL write_alpha;
-    int i, adjustR, adjustG, adjustB;
+    unsigned int i;
+    int adjustR, adjustG, adjustB, fails;
     unsigned int alpha_channel;
     float r,g,b,a;
     unsigned char value;
     float scale;
     FILE *fdest;
     size_t res;
+    fails = 1;
 
     fdest = fopen(outfile, "wb");
     if (!fdest) {
@@ -429,16 +439,17 @@ int imagetotga(opj_image_t * image, const char *outfile) {
         }
     }
 
-    width image->comps[0].w;
-    height = image->comps[0].h;
+    width  = (int)image->comps[0].w;
+    height = (int)image->comps[0].h;
 
     /* Mono with alpha, or RGB with alpha. */
     write_alpha = (image->numcomps==2) || (image->numcomps==4);
 
     /* Write TGA header  */
     bpp = write_alpha ? 32 : 24;
+
     if (!tga_writeheader(fdest, bpp, width , height, OPJ_TRUE))
-        return 1;
+               goto fin;
 
     alpha_channel = image->numcomps-1;
 
@@ -448,56 +459,74 @@ int imagetotga(opj_image_t * image, const char *outfile) {
     adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
     adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
 
-    for (y=0; y < height; y++) {
-        unsigned int index=y*width;
-
-        for (x=0; x < width; x++, index++)     {
-            r = (float)(image->comps[0].data[index] + adjustR);
-
-            if (image->numcomps>2) {
-                g = (float)(image->comps[1].data[index] + adjustG);
-                b = (float)(image->comps[2].data[index] + adjustB);
-            }
-            else  {/* Greyscale ... */
-                g = r;
-                b = r;
-            }
-
-            /* TGA format writes BGR ... */
-            value = (unsigned char)(b*scale);
-            res = fwrite(&value,1,1,fdest);
-            if( res < 1 ) {
-                fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
-                return 1;
-            }
-
-            value = (unsigned char)(g*scale);
-            res = fwrite(&value,1,1,fdest);
-            if( res < 1 ) {
-                fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
-                return 1;
-            }
-
-            value = (unsigned char)(r*scale);
-            res = fwrite(&value,1,1,fdest);
-            if( res < 1 ) {
-                fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
-                return 1;
-            }
-
-            if (write_alpha) {
-                a = (float)(image->comps[alpha_channel].data[index]);
-                value = (unsigned char)(a*scale);
-                res = fwrite(&value,1,1,fdest);
-                if( res < 1 ) {
-                    fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
-                    return 1;
-                }
-            }
-        }
-    }
+       for (y=0; y < height; y++) 
+   {
+       unsigned int index= (unsigned int)(y*width);
+
+       for (x=0; x < width; x++, index++)      
+  {
+       r = (float)(image->comps[0].data[index] + adjustR);
+
+       if (image->numcomps > 2) 
+ {
+       g = (float)(image->comps[1].data[index] + adjustG);
+       b = (float)(image->comps[2].data[index] + adjustB);
+ }
+       else  
+ {/* Greyscale ... */
+       g = r;
+       b = r;
+ }
+
+/* TGA format writes BGR ... */
+       if(b > 255.) b = 255.; else if(b < 0.) b = 0.;
+       value = (unsigned char)(b*scale);
+       res = fwrite(&value,1,1,fdest);
+
+       if( res < 1 ) 
+ {
+       fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
+       goto fin;
+ }
+       if(g > 255.) g = 255.; else if(g < 0.) g = 0.;
+       value = (unsigned char)(g*scale);
+       res = fwrite(&value,1,1,fdest);
+
+       if( res < 1 ) 
+ {
+       fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
+       goto fin;
+ }
+       if(r > 255.) r = 255.; else if(r < 0.) r = 0.;
+       value = (unsigned char)(r*scale);
+       res = fwrite(&value,1,1,fdest);
+
+       if( res < 1 ) 
+ {
+       fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
+       goto fin;
+ }
+
+       if (write_alpha) 
+ {
+       a = (float)(image->comps[alpha_channel].data[index]);
+       if(a > 255.) a = 255.; else if(a < 0.) a = 0.;
+       value = (unsigned char)(a*scale);
+       res = fwrite(&value,1,1,fdest);
+
+               if( res < 1 ) 
+          {
+               fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
+               goto fin;
+          }
+ }
+  }
+   }
+       fails = 0;
+fin:
+       fclose(fdest);
 
-    return 0;
+       return fails;
 }
 
 /* -->> -->> -->> -->>
@@ -551,7 +580,8 @@ opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters)
     unsigned char *table_R, *table_G, *table_B;
     unsigned int j, PAD = 0;
 
-    int x, y, index;
+    unsigned int x, y;
+    int index;
     int gray_scale = 1;
     int has_color;
     DWORD W, H;
@@ -563,8 +593,8 @@ opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters)
         return NULL;
     }
 
-    File_h.bfType = getc(IN);
-    File_h.bfType = (getc(IN) << 8) + File_h.bfType;
+    File_h.bfType = (WORD)getc(IN);
+    File_h.bfType = (WORD)((getc(IN) << 8) + File_h.bfType);
 
     if (File_h.bfType != 19778)
     {
@@ -574,29 +604,29 @@ opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters)
     }
     /* FILE HEADER */
     /* ------------- */
-    File_h.bfSize = getc(IN);
-    File_h.bfSize = (getc(IN) << 8) + File_h.bfSize;
-    File_h.bfSize = (getc(IN) << 16) + File_h.bfSize;
-    File_h.bfSize = (getc(IN) << 24) + File_h.bfSize;
+    File_h.bfSize = (DWORD)getc(IN);
+    File_h.bfSize = (DWORD)(getc(IN) << 8) + File_h.bfSize;
+    File_h.bfSize = (DWORD)(getc(IN) << 16) + File_h.bfSize;
+    File_h.bfSize = (DWORD)(getc(IN) << 24) + File_h.bfSize;
 
-    File_h.bfReserved1 = getc(IN);
-    File_h.bfReserved1 = (getc(IN) << 8) + File_h.bfReserved1;
+    File_h.bfReserved1 = (WORD)getc(IN);
+    File_h.bfReserved1 = (WORD)((getc(IN) << 8) + File_h.bfReserved1);
 
-    File_h.bfReserved2 = getc(IN);
-    File_h.bfReserved2 = (getc(IN) << 8) + File_h.bfReserved2;
+    File_h.bfReserved2 = (WORD)getc(IN);
+    File_h.bfReserved2 = (WORD)((getc(IN) << 8) + File_h.bfReserved2);
 
-    File_h.bfOffBits = getc(IN);
-    File_h.bfOffBits = (getc(IN) << 8) + File_h.bfOffBits;
-    File_h.bfOffBits = (getc(IN) << 16) + File_h.bfOffBits;
-    File_h.bfOffBits = (getc(IN) << 24) + File_h.bfOffBits;
+    File_h.bfOffBits = (DWORD)getc(IN);
+    File_h.bfOffBits = (DWORD)(getc(IN) << 8) + File_h.bfOffBits;
+    File_h.bfOffBits = (DWORD)(getc(IN) << 16) + File_h.bfOffBits;
+    File_h.bfOffBits = (DWORD)(getc(IN) << 24) + File_h.bfOffBits;
 
     /* INFO HEADER */
     /* ------------- */
 
-    Info_h.biSize = getc(IN);
-    Info_h.biSize = (getc(IN) << 8) + Info_h.biSize;
-    Info_h.biSize = (getc(IN) << 16) + Info_h.biSize;
-    Info_h.biSize = (getc(IN) << 24) + Info_h.biSize;
+    Info_h.biSize = (DWORD)getc(IN);
+    Info_h.biSize = (DWORD)(getc(IN) << 8) + Info_h.biSize;
+    Info_h.biSize = (DWORD)(getc(IN) << 16) + Info_h.biSize;
+    Info_h.biSize = (DWORD)(getc(IN) << 24) + Info_h.biSize;
 
     if(Info_h.biSize != 40)
     {
@@ -604,53 +634,53 @@ opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters)
         fclose(IN);
         return NULL;
     }
-    Info_h.biWidth = getc(IN);
-    Info_h.biWidth = (getc(IN) << 8) + Info_h.biWidth;
-    Info_h.biWidth = (getc(IN) << 16) + Info_h.biWidth;
-    Info_h.biWidth = (getc(IN) << 24) + Info_h.biWidth;
-    w = Info_h.biWidth;
-
-    Info_h.biHeight = getc(IN);
-    Info_h.biHeight = (getc(IN) << 8) + Info_h.biHeight;
-    Info_h.biHeight = (getc(IN) << 16) + Info_h.biHeight;
-    Info_h.biHeight = (getc(IN) << 24) + Info_h.biHeight;
-    h = Info_h.biHeight;
-
-    Info_h.biPlanes = getc(IN);
-    Info_h.biPlanes = (getc(IN) << 8) + Info_h.biPlanes;
-
-    Info_h.biBitCount = getc(IN);
-    Info_h.biBitCount = (getc(IN) << 8) + Info_h.biBitCount;
-
-    Info_h.biCompression = getc(IN);
-    Info_h.biCompression = (getc(IN) << 8) + Info_h.biCompression;
-    Info_h.biCompression = (getc(IN) << 16) + Info_h.biCompression;
-    Info_h.biCompression = (getc(IN) << 24) + Info_h.biCompression;
-
-    Info_h.biSizeImage = getc(IN);
-    Info_h.biSizeImage = (getc(IN) << 8) + Info_h.biSizeImage;
-    Info_h.biSizeImage = (getc(IN) << 16) + Info_h.biSizeImage;
-    Info_h.biSizeImage = (getc(IN) << 24) + Info_h.biSizeImage;
-
-    Info_h.biXpelsPerMeter = getc(IN);
-    Info_h.biXpelsPerMeter = (getc(IN) << 8) + Info_h.biXpelsPerMeter;
-    Info_h.biXpelsPerMeter = (getc(IN) << 16) + Info_h.biXpelsPerMeter;
-    Info_h.biXpelsPerMeter = (getc(IN) << 24) + Info_h.biXpelsPerMeter;
-
-    Info_h.biYpelsPerMeter = getc(IN);
-    Info_h.biYpelsPerMeter = (getc(IN) << 8) + Info_h.biYpelsPerMeter;
-    Info_h.biYpelsPerMeter = (getc(IN) << 16) + Info_h.biYpelsPerMeter;
-    Info_h.biYpelsPerMeter = (getc(IN) << 24) + Info_h.biYpelsPerMeter;
-
-    Info_h.biClrUsed = getc(IN);
-    Info_h.biClrUsed = (getc(IN) << 8) + Info_h.biClrUsed;
-    Info_h.biClrUsed = (getc(IN) << 16) + Info_h.biClrUsed;
-    Info_h.biClrUsed = (getc(IN) << 24) + Info_h.biClrUsed;
-
-    Info_h.biClrImportant = getc(IN);
-    Info_h.biClrImportant = (getc(IN) << 8) + Info_h.biClrImportant;
-    Info_h.biClrImportant = (getc(IN) << 16) + Info_h.biClrImportant;
-    Info_h.biClrImportant = (getc(IN) << 24) + Info_h.biClrImportant;
+    Info_h.biWidth = (DWORD)getc(IN);
+    Info_h.biWidth = (DWORD)(getc(IN) << 8) + Info_h.biWidth;
+    Info_h.biWidth = (DWORD)(getc(IN) << 16) + Info_h.biWidth;
+    Info_h.biWidth = (DWORD)(getc(IN) << 24) + Info_h.biWidth;
+    w = (int)Info_h.biWidth;
+
+    Info_h.biHeight = (DWORD)getc(IN);
+    Info_h.biHeight = (DWORD)(getc(IN) << 8) + Info_h.biHeight;
+    Info_h.biHeight = (DWORD)(getc(IN) << 16) + Info_h.biHeight;
+    Info_h.biHeight = (DWORD)(getc(IN) << 24) + Info_h.biHeight;
+    h = (int)Info_h.biHeight;
+
+    Info_h.biPlanes = (WORD)getc(IN);
+    Info_h.biPlanes = (WORD)((getc(IN) << 8) + Info_h.biPlanes);
+
+    Info_h.biBitCount = (WORD)getc(IN);
+    Info_h.biBitCount = (WORD)((getc(IN) << 8) + Info_h.biBitCount);
+
+    Info_h.biCompression = (DWORD)getc(IN);
+    Info_h.biCompression = (DWORD)(getc(IN) << 8) + Info_h.biCompression;
+    Info_h.biCompression = (DWORD)(getc(IN) << 16) + Info_h.biCompression;
+    Info_h.biCompression = (DWORD)(getc(IN) << 24) + Info_h.biCompression;
+
+    Info_h.biSizeImage = (DWORD)getc(IN);
+    Info_h.biSizeImage = (DWORD)(getc(IN) << 8) + Info_h.biSizeImage;
+    Info_h.biSizeImage = (DWORD)(getc(IN) << 16) + Info_h.biSizeImage;
+    Info_h.biSizeImage = (DWORD)(getc(IN) << 24) + Info_h.biSizeImage;
+
+    Info_h.biXpelsPerMeter = (DWORD)getc(IN);
+    Info_h.biXpelsPerMeter = (DWORD)(getc(IN) << 8) + Info_h.biXpelsPerMeter;
+    Info_h.biXpelsPerMeter = (DWORD)(getc(IN) << 16) + Info_h.biXpelsPerMeter;
+    Info_h.biXpelsPerMeter = (DWORD)(getc(IN) << 24) + Info_h.biXpelsPerMeter;
+
+    Info_h.biYpelsPerMeter = (DWORD)getc(IN);
+    Info_h.biYpelsPerMeter = (DWORD)(getc(IN) << 8) + Info_h.biYpelsPerMeter;
+    Info_h.biYpelsPerMeter = (DWORD)(getc(IN) << 16) + Info_h.biYpelsPerMeter;
+    Info_h.biYpelsPerMeter = (DWORD)(getc(IN) << 24) + Info_h.biYpelsPerMeter;
+
+    Info_h.biClrUsed = (DWORD)getc(IN);
+    Info_h.biClrUsed = (DWORD)(getc(IN) << 8) + Info_h.biClrUsed;
+    Info_h.biClrUsed = (DWORD)(getc(IN) << 16) + Info_h.biClrUsed;
+    Info_h.biClrUsed = (DWORD)(getc(IN) << 24) + Info_h.biClrUsed;
+
+    Info_h.biClrImportant = (DWORD)getc(IN);
+    Info_h.biClrImportant = (DWORD)(getc(IN) << 8) + Info_h.biClrImportant;
+    Info_h.biClrImportant = (DWORD)(getc(IN) << 16) + Info_h.biClrImportant;
+    Info_h.biClrImportant = (DWORD)(getc(IN) << 24) + Info_h.biClrImportant;
 
     /* Read the data and store them in the OUT file */
 
@@ -665,13 +695,13 @@ opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters)
             cmptparm[i].prec = 8;
             cmptparm[i].bpp = 8;
             cmptparm[i].sgnd = 0;
-            cmptparm[i].dx = subsampling_dx;
-            cmptparm[i].dy = subsampling_dy;
-            cmptparm[i].w = w;
-            cmptparm[i].h = h;
+            cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
+            cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
+            cmptparm[i].w = (OPJ_UINT32)w;
+            cmptparm[i].h = (OPJ_UINT32)h;
         }
         /* create the image */
-        image = opj_image_create(numcomps, &cmptparm[0], color_space);
+        image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
         if(!image)
         {
             fclose(IN);
@@ -679,16 +709,16 @@ opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters)
         }
 
         /* set image offset and reference grid */
-        image->x0 = parameters->image_offset_x0;
-        image->y0 = parameters->image_offset_y0;
-        image->x1 =    !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
-        image->y1 =    !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
+        image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
+        image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
+        image->x1 =    !image->x0 ? (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1 : image->x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;
+        image->y1 =    !image->y0 ? (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1 : image->y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;
 
         /* set image data */
 
         /* Place the cursor at the beginning of the image information */
         fseek(IN, 0, SEEK_SET);
-        fseek(IN, File_h.bfOffBits, SEEK_SET);
+        fseek(IN, (long)File_h.bfOffBits, SEEK_SET);
 
         W = Info_h.biWidth;
         H = Info_h.biHeight;
@@ -710,10 +740,10 @@ opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters)
 
         index = 0;
 
-        for(y = 0; y < (int)H; y++)
+        for(y = 0; y < H; y++)
         {
-            unsigned char *scanline = RGB + (3 * W + PAD) * (H - 1 - y);
-            for(x = 0; x < (int)W; x++)
+            unsigned char *scanline = RGB + (3 * (unsigned int)W + PAD) * ((unsigned int)H - 1 - (unsigned int)y);
+            for(x = 0; x < W; x++)
             {
                 unsigned char *pixel = &scanline[3 * x];
                 image->comps[0].data[index] = pixel[2];        /* R */
@@ -749,7 +779,7 @@ opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters)
 
             /* Place the cursor at the beginning of the image information */
             fseek(IN, 0, SEEK_SET);
-            fseek(IN, File_h.bfOffBits, SEEK_SET);
+            fseek(IN, (long)File_h.bfOffBits, SEEK_SET);
 
             W = Info_h.biWidth;
             H = Info_h.biHeight;
@@ -765,13 +795,13 @@ opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters)
                 cmptparm[i].prec = 8;
                 cmptparm[i].bpp = 8;
                 cmptparm[i].sgnd = 0;
-                cmptparm[i].dx = subsampling_dx;
-                cmptparm[i].dy = subsampling_dy;
-                cmptparm[i].w = w;
-                cmptparm[i].h = h;
+                cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
+                cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
+                cmptparm[i].w = (OPJ_UINT32)w;
+                cmptparm[i].h = (OPJ_UINT32)h;
             }
             /* create the image */
-            image = opj_image_create(numcomps, &cmptparm[0], color_space);
+            image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
             if(!image)
             {
                 fclose(IN);
@@ -780,10 +810,10 @@ opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters)
             }
 
             /* set image offset and reference grid */
-            image->x0 = parameters->image_offset_x0;
-            image->y0 = parameters->image_offset_y0;
-            image->x1 =        !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w - 1) * subsampling_dx + 1;
-            image->y1 =        !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h - 1) * subsampling_dy + 1;
+            image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
+            image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
+            image->x1 =        !image->x0 ? (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1 : image->x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;
+            image->y1 =        !image->y0 ? (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1 : image->y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;
 
             /* set image data */
 
@@ -840,8 +870,8 @@ opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters)
             {
                 unsigned char *pix, *beyond;
                 int *gray, *red, *green, *blue;
-                unsigned int x, y, max;
-                int i, c, c1;
+                unsigned int max;
+                int c, c1;
                 unsigned char uc;
 
                 if (Info_h.biClrUsed == 0)
@@ -875,13 +905,13 @@ opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters)
                     cmptparm[i].prec = 8;
                     cmptparm[i].bpp = 8;
                     cmptparm[i].sgnd = 0;
-                    cmptparm[i].dx = subsampling_dx;
-                    cmptparm[i].dy = subsampling_dy;
-                    cmptparm[i].w = w;
-                    cmptparm[i].h = h;
+                    cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
+                    cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
+                    cmptparm[i].w = (OPJ_UINT32)w;
+                    cmptparm[i].h = (OPJ_UINT32)h;
                 }
                 /* create the image */
-                image = opj_image_create(numcomps, &cmptparm[0], color_space);
+                image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
                 if (!image)
                 {
                     fclose(IN);
@@ -892,18 +922,16 @@ opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters)
                 }
 
                 /* set image offset and reference grid */
-                image->x0 = parameters->image_offset_x0;
-                image->y0 = parameters->image_offset_y0;
-                image->x1 = !image->x0 ? (w - 1) * subsampling_dx + 1 : image->x0 + (w
-                                                                                     - 1) * subsampling_dx + 1;
-                image->y1 = !image->y0 ? (h - 1) * subsampling_dy + 1 : image->y0 + (h
-                                                                                     - 1) * subsampling_dy + 1;
+                image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
+                image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
+                image->x1 = !image->x0 ? (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1 : image->x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;
+                image->y1 = !image->y0 ? (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1 : image->y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;
 
                 /* set image data */
 
                 /* Place the cursor at the beginning of the image information */
                 fseek(IN, 0, SEEK_SET);
-                fseek(IN, File_h.bfOffBits, SEEK_SET);
+                fseek(IN, (long)File_h.bfOffBits, SEEK_SET);
 
                 W = Info_h.biWidth;
                 H = Info_h.biHeight;
@@ -938,9 +966,9 @@ opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters)
                         else if (c == 0x02) /* MOVE by dxdy */
                         {
                             c = getc(IN);
-                            x += c;
+                            x += (unsigned int)c;
                             c = getc(IN);
-                            y += c;
+                            y += (unsigned int)c;
                             pix = RGB + (H - y - 1) * W + x;
                         }
                         else /* 03 .. 255 */
@@ -1031,8 +1059,8 @@ int imagetobmp(opj_image_t * image, const char *outfile) {
             return 1;
         }
 
-        w = image->comps[0].w;
-        h = image->comps[0].h;
+        w = (int)image->comps[0].w;
+        h = (int)image->comps[0].h;
 
         fprintf(fdest, "BM");
 
@@ -1070,19 +1098,19 @@ int imagetobmp(opj_image_t * image, const char *outfile) {
         fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff);
 
         if (image->comps[0].prec > 8) {
-            adjustR = image->comps[0].prec - 8;
+            adjustR = (int)image->comps[0].prec - 8;
             printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec);
         }
         else
             adjustR = 0;
         if (image->comps[1].prec > 8) {
-            adjustG = image->comps[1].prec - 8;
+            adjustG = (int)image->comps[1].prec - 8;
             printf("BMP CONVERSION: Truncating component 1 from %d bits to 8 bits\n", image->comps[1].prec);
         }
         else
             adjustG = 0;
         if (image->comps[2].prec > 8) {
-            adjustB = image->comps[2].prec - 8;
+            adjustB = (int)image->comps[2].prec - 8;
             printf("BMP CONVERSION: Truncating component 2 from %d bits to 8 bits\n", image->comps[2].prec);
         }
         else
@@ -1125,8 +1153,8 @@ int imagetobmp(opj_image_t * image, const char *outfile) {
         <<-- <<-- <<-- <<-- */
 
         fdest = fopen(outfile, "wb");
-        w = image->comps[0].w;
-        h = image->comps[0].h;
+        w = (int)image->comps[0].w;
+        h = (int)image->comps[0].h;
 
         fprintf(fdest, "BM");
 
@@ -1165,7 +1193,7 @@ int imagetobmp(opj_image_t * image, const char *outfile) {
         fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff);
 
         if (image->comps[0].prec > 8) {
-            adjustR = image->comps[0].prec - 8;
+            adjustR = (int)image->comps[0].prec - 8;
             printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec);
         }else
             adjustR = 0;
@@ -1227,9 +1255,9 @@ static unsigned short readushort(FILE * f, int bigendian)
         return 0;
     }
     if (bigendian)
-        return (c1 << 8) + c2;
+        return (unsigned short)((c1 << 8) + c2);
     else
-        return (c2 << 8) + c1;
+        return (unsigned short)((c2 << 8) + c1);
 }
 
 static unsigned int readuint(FILE * f, int bigendian)
@@ -1256,9 +1284,9 @@ static unsigned int readuint(FILE * f, int bigendian)
         return 0;
     }
     if (bigendian)
-        return (c1 << 24) + (c2 << 16) + (c3 << 8) + c4;
+        return (unsigned int)(c1 << 24) + (unsigned int)(c2 << 16) + (unsigned int)(c3 << 8) + c4;
     else
-        return (c4 << 24) + (c3 << 16) + (c2 << 8) + c1;
+        return (unsigned int)(c4 << 24) + (unsigned int)(c3 << 16) + (unsigned int)(c2 << 8) + c1;
 }
 
 opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) {
@@ -1315,10 +1343,10 @@ opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) {
 
     /* initialize image component */
 
-    cmptparm.x0 = parameters->image_offset_x0;
-    cmptparm.y0 = parameters->image_offset_y0;
-    cmptparm.w = !cmptparm.x0 ? (w - 1) * parameters->subsampling_dx + 1 : cmptparm.x0 + (w - 1) * parameters->subsampling_dx + 1;
-    cmptparm.h = !cmptparm.y0 ? (h - 1) * parameters->subsampling_dy + 1 : cmptparm.y0 + (h - 1) * parameters->subsampling_dy + 1;
+    cmptparm.x0 = (OPJ_UINT32)parameters->image_offset_x0;
+    cmptparm.y0 = (OPJ_UINT32)parameters->image_offset_y0;
+    cmptparm.w = !cmptparm.x0 ? (OPJ_UINT32)((w - 1) * parameters->subsampling_dx + 1) : cmptparm.x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)parameters->subsampling_dx + 1;
+    cmptparm.h = !cmptparm.y0 ? (OPJ_UINT32)((h - 1) * parameters->subsampling_dy + 1) : cmptparm.y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)parameters->subsampling_dy + 1;
 
     if (sign == '-') {
         cmptparm.sgnd = 1;
@@ -1335,13 +1363,13 @@ opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) {
     }
     else ushift = dshift = force8 = adjustS = 0;
 
-    cmptparm.prec = prec;
-    cmptparm.bpp = prec;
-    cmptparm.dx = parameters->subsampling_dx;
-    cmptparm.dy = parameters->subsampling_dy;
+    cmptparm.prec = (OPJ_UINT32)prec;
+    cmptparm.bpp = (OPJ_UINT32)prec;
+    cmptparm.dx = (OPJ_UINT32)parameters->subsampling_dx;
+    cmptparm.dy = (OPJ_UINT32)parameters->subsampling_dy;
 
     /* create the image */
-    image = opj_image_create(numcomps, &cmptparm, color_space);
+    image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm, color_space);
     if(!image) {
         fclose(f);
         return NULL;
@@ -1382,7 +1410,7 @@ opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) {
             }
         } else {
             if (!comp->sgnd) {
-                v = readuint(f, bigendian);
+                v = (int)readuint(f, bigendian);
             } else {
                 v = (int) readuint(f, bigendian);
             }
@@ -1392,75 +1420,107 @@ opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) {
         comp->data[i] = v;
     }
     fclose(f);
-    comp->bpp = int_floorlog2(max) + 1;
+    comp->bpp = (OPJ_UINT32)int_floorlog2(max) + 1;
 
     return image;
 }
 
-int imagetopgx(opj_image_t * image, const char *outfile) {
-    int w, h;
-    int i, j, compno;
-    FILE *fdest = NULL;
+#define CLAMP(x,a,b) x < a ? a : (x > b ? b : x)
 
-    for (compno = 0; compno < image->numcomps; compno++) {
-        opj_image_comp_t *comp = &image->comps[compno];
-        char bname[256]; /* buffer for name */
-        char *name = bname; /* pointer */
-        int nbytes = 0;
-        size_t res;
-        const size_t olen = strlen(outfile);
-        const size_t dotpos = olen - 4;
-        const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */
-        if( outfile[dotpos] != '.' ) {
-            /* `pgx` was recognized but there is no dot at expected position */
-            fprintf(stderr, "ERROR -> Impossible happen." );
-            return 1;
-        }
-        if( total > 256 ) {
-            name = (char*)malloc(total+1);
-        }
-        strncpy(name, outfile, dotpos);
-        /*if (image->numcomps > 1) {*/
-        sprintf(name+dotpos, "_%d.pgx", compno);
-        /*} else {
-            strcpy(name+dotpos, ".pgx");
-        }*/
-        fdest = fopen(name, "wb");
-        if (!fdest) {
-            fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
-            return 1;
-        }
-        /* dont need name anymore */
-        if( total > 256 ) {
-            free(name);
-        }
+static INLINE int clamp( const int value, const int prec, const int sgnd )
+{
+  if( sgnd )
+    {
+    if (prec <= 8)       return CLAMP(value,-128,127);
+    else if (prec <= 16) return CLAMP(value,-32768,32767);
+    else                 return CLAMP(value,-2147483647-1,2147483647);
+    }
+  else
+    {
+    if (prec <= 8)       return CLAMP(value,0,255);
+    else if (prec <= 16) return CLAMP(value,0,65535);
+    else                 return value; /*CLAMP(value,0,4294967295);*/
+    }
+}
 
-        w = image->comps[compno].w;
-        h = image->comps[compno].h;
+int imagetopgx(opj_image_t * image, const char *outfile) 
+{
+  int w, h;
+  int i, j, fails = 1;
+  unsigned int compno;
+  FILE *fdest = NULL;
 
-        fprintf(fdest, "PG ML %c %d %d %d\n", comp->sgnd ? '-' : '+', comp->prec, w, h);
-        if (comp->prec <= 8) {
-            nbytes = 1;
-        } else if (comp->prec <= 16) {
-            nbytes = 2;
-        } else {
-            nbytes = 4;
-        }
-        for (i = 0; i < w * h; i++) {
-            int v = image->comps[compno].data[i];
-            for (j = nbytes - 1; j >= 0; j--) {
-                char byte = (char) (v >> (j * 8));
-                res = fwrite(&byte, 1, 1, fdest);
-                if( res < 1 ) {
-                    fprintf(stderr, "failed to write 1 byte for %s\n", name);
-                    return 1;
-                }
-            }
+  for (compno = 0; compno < image->numcomps; compno++) 
+    {
+    opj_image_comp_t *comp = &image->comps[compno];
+    char bname[256]; /* buffer for name */
+    char *name = bname; /* pointer */
+    int nbytes = 0;
+    size_t res;
+    const size_t olen = strlen(outfile);
+    const size_t dotpos = olen - 4;
+    const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */
+
+    if( outfile[dotpos] != '.' ) 
+      {
+      /* `pgx` was recognized but there is no dot at expected position */
+      fprintf(stderr, "ERROR -> Impossible happen." );
+      goto fin;
+      }
+    if( total > 256 ) 
+      {
+      name = (char*)malloc(total+1);
+      }
+    strncpy(name, outfile, dotpos);
+    sprintf(name+dotpos, "_%d.pgx", compno);
+    fdest = fopen(name, "wb");
+    /* dont need name anymore */
+    if( total > 256 ) free(name);
+    if (!fdest) 
+      {
+      fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
+      goto fin;
+      }
+
+    w = (int)image->comps[compno].w;
+    h = (int)image->comps[compno].h;
+
+    fprintf(fdest, "PG ML %c %d %d %d\n", comp->sgnd ? '-' : '+', comp->prec,
+      w, h);
+
+    if (comp->prec <= 8) 
+      nbytes = 1;
+    else if (comp->prec <= 16)
+      nbytes = 2;
+    else
+      nbytes = 4;
+
+    for (i = 0; i < w * h; i++) 
+      {
+      /* FIXME: clamp func is being called within a loop */
+      const int val = clamp(image->comps[compno].data[i],
+        (int)comp->prec, (int)comp->sgnd);
+
+      for (j = nbytes - 1; j >= 0; j--) 
+        {
+        int v = (int)(val >> (j * 8));
+        unsigned char byte = (unsigned char)v;
+        res = fwrite(&byte, 1, 1, fdest);
+
+        if( res < 1 ) 
+          {
+          fprintf(stderr, "failed to write 1 byte for %s\n", name);
+          goto fin;
+          }
         }
-        fclose(fdest);
+      }
+    fclose(fdest); fdest = NULL;
     }
+  fails = 0;
+fin:
+  if(fdest) fclose(fdest);
 
-    return 0;
+  return fails;
 }
 
 /* -->> -->> -->> -->>
@@ -1662,7 +1722,7 @@ static void read_pnm_header(FILE *reader, struct pnm_header *ph)
         }
         if(ph->depth < 1 || ph->depth > 4) return;
 
-        if(ph->width && ph->height && ph->depth & ph->maxval && ttype)
+        if(ph->width && ph->height && ph->depth && ph->maxval && ttype)
             ph->ok = 1;
     }
     else
@@ -1760,27 +1820,27 @@ opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters) {
     subsampling_dx = parameters->subsampling_dx;
     subsampling_dy = parameters->subsampling_dy;
 
-    memset(&cmptparm[0], 0, numcomps * sizeof(opj_image_cmptparm_t));
+    memset(&cmptparm[0], 0, (size_t)numcomps * sizeof(opj_image_cmptparm_t));
 
     for(i = 0; i < numcomps; i++)
     {
-        cmptparm[i].prec = prec;
-        cmptparm[i].bpp = prec;
+        cmptparm[i].prec = (OPJ_UINT32)prec;
+        cmptparm[i].bpp = (OPJ_UINT32)prec;
         cmptparm[i].sgnd = 0;
-        cmptparm[i].dx = subsampling_dx;
-        cmptparm[i].dy = subsampling_dy;
-        cmptparm[i].w = w;
-        cmptparm[i].h = h;
+        cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
+        cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
+        cmptparm[i].w = (OPJ_UINT32)w;
+        cmptparm[i].h = (OPJ_UINT32)h;
     }
-    image = opj_image_create(numcomps, &cmptparm[0], color_space);
+    image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
 
     if(!image) { fclose(fp); return NULL; }
 
     /* set image offset and reference grid */
-    image->x0 = parameters->image_offset_x0;
-    image->y0 = parameters->image_offset_y0;
-    image->x1 = parameters->image_offset_x0 + (w - 1) *        subsampling_dx + 1;
-    image->y1 = parameters->image_offset_y0 + (h - 1) *        subsampling_dy + 1;
+    image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
+    image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
+    image->x1 = (OPJ_UINT32)(parameters->image_offset_x0 + (w - 1) * subsampling_dx + 1);
+    image->y1 = (OPJ_UINT32)(parameters->image_offset_y0 + (h - 1) * subsampling_dy + 1);
 
     if((format == 2) || (format == 3)) /* ascii pixmap */
     {
@@ -1794,7 +1854,7 @@ opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters) {
                 if (fscanf(fp, "%u", &index) != 1)
                     fprintf(stderr, "\nWARNING: fscanf return a number of element different from the expected.\n");
 
-                image->comps[compno].data[i] = (index * 255)/header_info.maxval;
+                image->comps[compno].data[i] = (OPJ_INT32)(index * 255)/header_info.maxval;
             }
         }
     }
@@ -1813,8 +1873,12 @@ opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters) {
             {
                 for(compno = 0; compno < numcomps; compno++)
                 {
-                    if ( !fread(&c0, 1, 1, fp) )
-                        fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
+                if ( !fread(&c0, 1, 1, fp) )
+                  {
+                  fprintf(stderr, "\nError: fread return a number of element different from the expected.\n");
+                  opj_image_destroy(image);
+                  return NULL;
+                  }
                     if(one)
                     {
                         image->comps[compno].data[i] = c0;
@@ -1886,15 +1950,18 @@ int imagetopnm(opj_image_t * image, const char *outfile)
 {
     int *red, *green, *blue, *alpha;
     int wr, hr, max;
-    int i, compno, ncomp;
+    int i;
+    unsigned int compno, ncomp;
     int adjustR, adjustG, adjustB, adjustA;
     int fails, two, want_gray, has_alpha, triple;
     int prec, v;
     FILE *fdest = NULL;
     const char *tmp = outfile;
     char *destname;
-    alpha = NULL;
-    if((prec = image->comps[0].prec) > 16)
+
+       alpha = NULL;
+
+    if((prec = (int)image->comps[0].prec) > 16)
     {
         fprintf(stderr,"%s:%d:imagetopnm\n\tprecision %d is larger than 16"
                 "\n\t: refused.\n",__FILE__,__LINE__,prec);
@@ -1928,7 +1995,7 @@ int imagetopnm(opj_image_t * image, const char *outfile)
         }
         two = (prec > 8);
         triple = (ncomp > 2);
-        wr = image->comps[0].w; hr = image->comps[0].h;
+        wr = (int)image->comps[0].w; hr = (int)image->comps[0].h;
         max = (1<<prec) - 1; has_alpha = (ncomp == 4 || ncomp == 2);
 
         red = image->comps[0].data;
@@ -1971,16 +2038,22 @@ int imagetopnm(opj_image_t * image, const char *outfile)
             if(two)
             {
                 v = *red + adjustR; ++red;
+if(v > 65535) v = 65535; else if(v < 0) v = 0;
+
                 /* netpbm: */
                 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
 
                 if(triple)
                 {
                     v = *green + adjustG; ++green;
+if(v > 65535) v = 65535; else if(v < 0) v = 0;
+
                     /* netpbm: */
                     fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
 
                     v =  *blue + adjustB; ++blue;
+if(v > 65535) v = 65535; else if(v < 0) v = 0;
+
                     /* netpbm: */
                     fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
 
@@ -1989,6 +2062,8 @@ int imagetopnm(opj_image_t * image, const char *outfile)
                 if(has_alpha)
                 {
                     v = *alpha + adjustA; ++alpha;
+               if(v > 65535) v = 65535; else if(v < 0) v = 0;
+
                     /* netpbm: */
                     fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
                 }
@@ -1997,14 +2072,28 @@ int imagetopnm(opj_image_t * image, const char *outfile)
             }  /* if(two) */
 
             /* prec <= 8: */
+       v = *red++;
+       if(v > 255) v = 255; else if(v < 0) v = 0;
 
-            fprintf(fdest, "%c", (unsigned char)*red++);
+       fprintf(fdest, "%c", (unsigned char)v);
             if(triple)
-                fprintf(fdest, "%c%c",(unsigned char)*green++, (unsigned char)*blue++);
+ {
+       v = *green++;
+       if(v > 255) v = 255; else if(v < 0) v = 0;
+
+       fprintf(fdest, "%c", (unsigned char)v);
+       v = *blue++;
+       if(v > 255) v = 255; else if(v < 0) v = 0;
 
+       fprintf(fdest, "%c", (unsigned char)v);
+ }
             if(has_alpha)
-                fprintf(fdest, "%c", (unsigned char)*alpha++);
+ {
+       v = *alpha++;
+       if(v > 255) v = 255; else if(v < 0) v = 0;
 
+       fprintf(fdest, "%c", (unsigned char)v);
+ }
         }      /* for(i */
 
         fclose(fdest); return 0;
@@ -2021,8 +2110,15 @@ int imagetopnm(opj_image_t * image, const char *outfile)
 
     for (compno = 0; compno < ncomp; compno++)
     {
-        if (ncomp > 1)
-            sprintf(destname, "%d.%s", compno, outfile);
+    if (ncomp > 1)
+      {
+      /*sprintf(destname, "%d.%s", compno, outfile);*/
+      const size_t olen = strlen(outfile);
+      const size_t dotpos = olen - 4;
+
+      strncpy(destname, outfile, dotpos);
+      sprintf(destname+dotpos, "_%d.pgm", compno);
+      }
         else
             sprintf(destname, "%s", outfile);
 
@@ -2033,8 +2129,8 @@ int imagetopnm(opj_image_t * image, const char *outfile)
             free(destname);
             return 1;
         }
-        wr = image->comps[compno].w; hr = image->comps[compno].h;
-        prec = image->comps[compno].prec;
+        wr = (int)image->comps[compno].w; hr = (int)image->comps[compno].h;
+        prec = (int)image->comps[compno].prec;
         max = (1<<prec) - 1;
 
         fprintf(fdest, "P5\n#OpenJPEG-%s\n%d %d\n%d\n",
@@ -2049,12 +2145,16 @@ int imagetopnm(opj_image_t * image, const char *outfile)
             for (i = 0; i < wr * hr; i++)
             {
                 v = *red + adjustR; ++red;
+if(v > 65535) v = 65535; else if(v < 0) v = 0;
+
                 /* netpbm: */
                 fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
 
                 if(has_alpha)
                 {
                     v = *alpha++;
+if(v > 65535) v = 65535; else if(v < 0) v = 0;
+
                     /* netpbm: */
                     fprintf(fdest, "%c%c",(unsigned char)(v>>8), (unsigned char)v);
                 }
@@ -2064,7 +2164,10 @@ int imagetopnm(opj_image_t * image, const char *outfile)
         {
             for(i = 0; i < wr * hr; ++i)
             {
-                fprintf(fdest, "%c", (unsigned char)(*red + adjustR)); ++red;
+       v = *red + adjustR; ++red;
+       if(v > 255) v = 255; else if(v < 0) v = 0;
+
+        fprintf(fdest, "%c", (unsigned char)v);
             }
         }
         fclose(fdest);
@@ -2092,7 +2195,7 @@ int imagetotif(opj_image_t * image, const char *outfile)
     tsize_t strip_size;
 
     ushift = dshift = force16 = has_alpha = 0;
-    bps = image->comps[0].prec;
+    bps = (int)image->comps[0].prec;
 
     if(bps > 8 && bps < 16)
     {
@@ -2114,7 +2217,7 @@ int imagetotif(opj_image_t * image, const char *outfile)
         fprintf(stderr, "imagetotif:failed to open %s for writing\n", outfile);
         return 1;
     }
-    sgnd = image->comps[0].sgnd;
+    sgnd = (int)image->comps[0].sgnd;
     adjust = sgnd ? 1 << (image->comps[0].prec - 1) : 0;
 
     if(image->numcomps >= 3
@@ -2127,8 +2230,8 @@ int imagetotif(opj_image_t * image, const char *outfile)
     {
         has_alpha = (image->numcomps == 4);
 
-        width   = image->comps[0].w;
-        height  = image->comps[0].h;
+        width   = (int)image->comps[0].w;
+        height  = (int)image->comps[0].h;
         imgsize = width * height ;
 
         TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
@@ -2174,10 +2277,17 @@ int imagetotif(opj_image_t * image, const char *outfile)
                             b += adjust;
                             if(has_alpha) a += adjust;
                         }
-                        dat8[i+0] = r ;
-                        dat8[i+1] = g ;
-                        dat8[i+2] = b ;
-                        if(has_alpha) dat8[i+3] = a;
+               if(r > 255) r = 255; else if(r < 0) r = 0;
+                        dat8[i+0] = (unsigned char)r ;
+               if(g > 255) g = 255; else if(g < 0) g = 0;
+                        dat8[i+1] = (unsigned char)g ;
+               if(b > 255) b = 255; else if(b < 0) b = 0;
+                        dat8[i+2] = (unsigned char)b ;
+               if(has_alpha) 
+        {
+               if(a > 255) a = 255; else if(a < 0) a = 0;
+               dat8[i+3] = (unsigned char)a;
+        }
 
                         index++;
                         last_i = i + step;
@@ -2206,12 +2316,18 @@ int imagetotif(opj_image_t * image, const char *outfile)
                                 b += adjust;
                                 if(has_alpha) a += adjust;
                             }
-                            dat8[i+0] = r ;
-                            if(i+1 < ssize) dat8[i+1] = g ;  else break;
-                            if(i+2 < ssize) dat8[i+2] = b ;  else break;
+               if(r > 255) r = 255; else if(r < 0) r = 0;
+               if(g > 255) g = 255; else if(g < 0) g = 0;
+               if(b > 255) b = 255; else if(b < 0) b = 0;
+
+                            dat8[i+0] = (unsigned char)r ;
+                            if(i+1 < ssize) dat8[i+1] = (unsigned char)g ;  else break;
+                            if(i+2 < ssize) dat8[i+2] = (unsigned char)b ;  else break;
                             if(has_alpha)
                             {
-                                if(i+3 < ssize) dat8[i+3] = a ;  else break;
+               if(a > 255) a = 255; else if(a < 0) a = 0;
+
+                                if(i+3 < ssize) dat8[i+3] = (unsigned char)a ;  else break;
                             }
                             index++;
                         }
@@ -2252,16 +2368,21 @@ int imagetotif(opj_image_t * image, const char *outfile)
                                 b = (b<<ushift) + (b>>dshift);
                                 if(has_alpha) a = (a<<ushift) + (a>>dshift);
                             }
-                            dat8[i+0] =  r;/*LSB*/
-                            dat8[i+1] = (r >> 8);/*MSB*/
-                            dat8[i+2] =  g;
-                            dat8[i+3] = (g >> 8);
-                            dat8[i+4] =  b;
-                            dat8[i+5] = (b >> 8);
+               if(r > 65535) r = 65535; else if(r < 0) r = 0;
+               if(g > 65535) g = 65535; else if(g < 0) g = 0;
+               if(b > 65535) b = 65535; else if(b < 0) b = 0;
+
+                            dat8[i+0] =  (unsigned char)r;/*LSB*/
+                            dat8[i+1] = (unsigned char)(r >> 8);/*MSB*/
+                            dat8[i+2] =  (unsigned char)g;
+                            dat8[i+3] = (unsigned char)(g >> 8);
+                            dat8[i+4] =  (unsigned char)b;
+                            dat8[i+5] = (unsigned char)(b >> 8);
                             if(has_alpha)
                             {
-                                dat8[i+6] =  a;
-                                dat8[i+7] = (a >> 8);
+               if(a > 65535) a = 65535; else if(a < 0) a = 0;
+                                dat8[i+6] =  (unsigned char)a;
+                                dat8[i+7] = (unsigned char)(a >> 8);
                             }
                             index++;
                             last_i = i + step;
@@ -2297,17 +2418,22 @@ int imagetotif(opj_image_t * image, const char *outfile)
                                     b = (b<<ushift) + (b>>dshift);
                                     if(has_alpha) a = (a<<ushift) + (a>>dshift);
                                 }
-                                dat8[i+0] =  r;/*LSB*/
-                                if(i+1 < ssize) dat8[i+1] = (r >> 8);else break;/*MSB*/
-                                if(i+2 < ssize) dat8[i+2] =  g;      else break;
-                                if(i+3 < ssize) dat8[i+3] = (g >> 8);else break;
-                                if(i+4 < ssize) dat8[i+4] =  b;      else break;
-                                if(i+5 < ssize) dat8[i+5] = (b >> 8);else break;
+               if(r > 65535) r = 65535; else if(r < 0) r = 0;
+               if(g > 65535) g = 65535; else if(g < 0) g = 0;
+               if(b > 65535) b = 65535; else if(b < 0) b = 0;
+
+                                dat8[i+0] = (unsigned char) r;/*LSB*/
+                                if(i+1 < ssize) dat8[i+1] = (unsigned char)(r >> 8);else break;/*MSB*/
+                                if(i+2 < ssize) dat8[i+2] = (unsigned char) g;      else break;
+                                if(i+3 < ssize) dat8[i+3] = (unsigned char)(g >> 8);else break;
+                                if(i+4 < ssize) dat8[i+4] = (unsigned char) b;      else break;
+                                if(i+5 < ssize) dat8[i+5] = (unsigned char)(b >> 8);else break;
 
                                 if(has_alpha)
                                 {
-                                    if(i+6 < ssize) dat8[i+6] = a; else break;
-                                    if(i+7 < ssize) dat8[i+7] = (a >> 8); else break;
+               if(a > 65535) a = 65535; else if(a < 0) a = 0;
+                                    if(i+6 < ssize) dat8[i+6] = (unsigned char)a; else break;
+                                    if(i+7 < ssize) dat8[i+7] = (unsigned char)(a >> 8); else break;
                                 }
                                 index++;
                             }
@@ -2336,8 +2462,8 @@ int imagetotif(opj_image_t * image, const char *outfile)
 
         has_alpha = (image->numcomps == 2);
 
-        width   = image->comps[0].w;
-        height  = image->comps[0].h;
+        width   = (int)image->comps[0].w;
+        height  = (int)image->comps[0].h;
         imgsize = width * height;
 
         /* Set tags */
@@ -2379,13 +2505,19 @@ int imagetotif(opj_image_t * image, const char *outfile)
                             r += adjust;
                             if(has_alpha) a += adjust;
                         }
-                        dat8[i+0] = r;
-                        if(has_alpha) dat8[i+1] = a;
-                        index++;
+               if(r > 255) r = 255; else if(r < 0) r = 0;
+                        dat8[i+0] = (unsigned char)r;
+
+               if(has_alpha) 
+        {
+               if(a > 255) a = 255; else if(a < 0) a = 0;
+               dat8[i+1] = (unsigned char)a;
                     }
+               index++;
+         }
                     else
                         break;
-                }/*for(i )*/
+          }/*for(i )*/
             }/*if(bps == 8*/
             else
                 if(bps == 16)
@@ -2411,12 +2543,14 @@ int imagetotif(opj_image_t * image, const char *outfile)
                                 r = (r<<ushift) + (r>>dshift);
                                 if(has_alpha) a = (a<<ushift) + (a>>dshift);
                             }
-                            dat8[i+0] = r;/*LSB*/
-                            dat8[i+1] = r >> 8;/*MSB*/
+               if(r > 65535) r = 65535; else if(r < 0) r = 0;
+                            dat8[i+0] = (unsigned char)r;/*LSB*/
+                            dat8[i+1] = (unsigned char)(r >> 8);/*MSB*/
                             if(has_alpha)
                             {
-                                dat8[i+2] = a;
-                                dat8[i+3] = a >> 8;
+               if(a > 65535) a = 65535; else if(a < 0) a = 0;
+                                dat8[i+2] = (unsigned char)a;
+                                dat8[i+3] = (unsigned char)(a >> 8);
                             }
                             index++;
                         }/*if(index < imgsize)*/
@@ -2463,6 +2597,7 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)
     int has_alpha = 0;
     unsigned short tiBps, tiPhoto, tiSf, tiSpp, tiPC;
     unsigned int tiWidth, tiHeight;
+    OPJ_BOOL is_cinema = OPJ_IS_CINEMA(parameters->rsiz);
 
     tif = TIFFOpen(filename, "r");
 
@@ -2481,8 +2616,8 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)
     TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &tiSpp);
     TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &tiPhoto);
     TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &tiPC);
-    w= tiWidth;
-    h= tiHeight;
+    w= (int)tiWidth;
+    h= (int)tiHeight;
 
     if(tiBps != 8 && tiBps != 16 && tiBps != 12) tiBps = 0;
     if(tiPhoto != 1 && tiPhoto != 2) tiPhoto = 0;
@@ -2490,7 +2625,7 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)
     if( !tiBps || !tiPhoto)
     {
         if( !tiBps)
-            fprintf(stderr,"imagetotif: Bits=%d, Only 8 and 16 bits"
+     fprintf(stderr,"tiftoimage: Bits=%d, Only 8 and 16 bits"
                     " implemented\n",tiBps);
         else
             if( !tiPhoto)
@@ -2535,6 +2670,14 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)
 */ 
     memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
 
+    if ((tiPhoto == PHOTOMETRIC_RGB) && (is_cinema)) {
+        fprintf(stdout,"WARNING:\n"
+                "Input image bitdepth is %d bits\n"
+                "TIF conversion has automatically rescaled to 12-bits\n"
+                "to comply with cinema profiles.\n",
+                tiBps);
+    }
+
     if(tiPhoto == PHOTOMETRIC_RGB) /* RGB(A) */
     {
         numcomps = 3 + has_alpha;
@@ -2543,7 +2686,7 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)
         /*#define USETILEMODE*/
         for(j = 0; j < numcomps; j++)
         {
-            if(parameters->cp_cinema)
+            if(is_cinema)
             {
                 cmptparm[j].prec = 12;
                 cmptparm[j].bpp = 12;
@@ -2553,10 +2696,10 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)
                 cmptparm[j].prec = tiBps;
                 cmptparm[j].bpp = tiBps;
             }
-            cmptparm[j].dx = subsampling_dx;
-            cmptparm[j].dy = subsampling_dy;
-            cmptparm[j].w = w;
-            cmptparm[j].h = h;
+            cmptparm[j].dx = (OPJ_UINT32)subsampling_dx;
+            cmptparm[j].dy = (OPJ_UINT32)subsampling_dy;
+            cmptparm[j].w = (OPJ_UINT32)w;
+            cmptparm[j].h = (OPJ_UINT32)h;
 #ifdef USETILEMODE
             cmptparm[j].x0 = 0;
             cmptparm[j].y0 = 0;
@@ -2566,7 +2709,7 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)
 #ifdef USETILEMODE
         image = opj_image_tile_create(numcomps,&cmptparm[0],color_space);
 #else
-        image = opj_image_create(numcomps, &cmptparm[0], color_space);
+        image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
 #endif
 
         if(!image)
@@ -2576,18 +2719,18 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)
         }
         /* set image offset and reference grid
 */
-        image->x0 = parameters->image_offset_x0;
-        image->y0 = parameters->image_offset_y0;
-        image->x1 =    !image->x0 ? (w - 1) * subsampling_dx + 1 :
-                                 image->x0 + (w - 1) * subsampling_dx + 1;
-        image->y1 =    !image->y0 ? (h - 1) * subsampling_dy + 1 :
-                                 image->y0 + (h - 1) * subsampling_dy + 1;
+        image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
+        image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
+        image->x1 =    !image->x0 ? (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1 :
+                                 image->x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;
+        image->y1 =    !image->y0 ? (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1 :
+                                 image->y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;
 
         buf = _TIFFmalloc(TIFFStripSize(tif));
 
         strip_size=TIFFStripSize(tif);
         index = 0;
-        imgsize = image->comps[0].w * image->comps[0].h ;
+        imgsize = (int)(image->comps[0].w * image->comps[0].h);
         /* Read the Image components
 */
         for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++)
@@ -2612,7 +2755,7 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)
                         if(has_alpha)
                             image->comps[3].data[index] = ( dat8[i+7] << 8 ) | dat8[i+6];
 
-                        if(parameters->cp_cinema)
+                        if(is_cinema)
                         {
                             /* Rounding 16 to 12 bits
 */
@@ -2649,7 +2792,7 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)
                                 image->comps[3].data[index] = dat8[i+3];
 #endif
 
-                            if(parameters->cp_cinema)
+                            if(is_cinema)
                             {
                                 /* Rounding 8 to 12 bits
 */
@@ -2708,15 +2851,15 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)
         {
             cmptparm[j].prec = tiBps;
             cmptparm[j].bpp = tiBps;
-            cmptparm[j].dx = subsampling_dx;
-            cmptparm[j].dy = subsampling_dy;
-            cmptparm[j].w = w;
-            cmptparm[j].h = h;
+            cmptparm[j].dx = (OPJ_UINT32)subsampling_dx;
+            cmptparm[j].dy = (OPJ_UINT32)subsampling_dy;
+            cmptparm[j].w = (OPJ_UINT32)w;
+            cmptparm[j].h = (OPJ_UINT32)h;
         }
 #ifdef USETILEMODE
         image = opj_image_tile_create(numcomps,&cmptparm[0],color_space);
 #else
-        image = opj_image_create(numcomps, &cmptparm[0], color_space);
+        image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
 #endif
 
         if(!image)
@@ -2726,18 +2869,18 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)
         }
         /* set image offset and reference grid
 */
-        image->x0 = parameters->image_offset_x0;
-        image->y0 = parameters->image_offset_y0;
-        image->x1 =    !image->x0 ? (w - 1) * subsampling_dx + 1 :
-                                 image->x0 + (w - 1) * subsampling_dx + 1;
-        image->y1 =    !image->y0 ? (h - 1) * subsampling_dy + 1 :
-                                 image->y0 + (h - 1) * subsampling_dy + 1;
+        image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
+        image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
+        image->x1 =    !image->x0 ? (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1 :
+                                 image->x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;
+        image->y1 =    !image->y0 ? (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1 :
+                                 image->y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;
 
         buf = _TIFFmalloc(TIFFStripSize(tif));
 
         strip_size = TIFFStripSize(tif);
         index = 0;
-        imgsize = image->comps[0].w * image->comps[0].h ;
+        imgsize = (int)(image->comps[0].w * image->comps[0].h);
         /* Read the Image components
 */
         for(strip = 0; strip < TIFFNumberOfStrips(tif); strip++)
@@ -2817,9 +2960,11 @@ static opj_image_t* rawtoimage_common(const char *filename, opj_cparameters_t *p
     {
         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 NULL;
     }
 
@@ -2830,39 +2975,51 @@ static opj_image_t* rawtoimage_common(const char *filename, opj_cparameters_t *p
         return NULL;
     }
     numcomps = raw_cp->rawComp;
-    color_space = OPJ_CLRSPC_SRGB;
+
+    /* FIXME ADE at this point, tcp_mct has not been properly set in calling function */
+    if (numcomps == 0) {
+        color_space = OPJ_CLRSPC_GRAY;
+    } else if ((numcomps >= 3) && (parameters->tcp_mct == 0)) {
+        color_space = OPJ_CLRSPC_SYCC;
+    } else if ((numcomps >= 3) && (parameters->tcp_mct != 2)) {
+        color_space = OPJ_CLRSPC_SRGB;
+    } else {
+        color_space = OPJ_CLRSPC_UNKNOWN;
+    }
     w = raw_cp->rawWidth;
     h = raw_cp->rawHeight;
-    cmptparm = (opj_image_cmptparm_t*) malloc(numcomps * sizeof(opj_image_cmptparm_t));
+    cmptparm = (opj_image_cmptparm_t*) malloc((size_t)numcomps * sizeof(opj_image_cmptparm_t));
 
     /* initialize image components */
-    memset(&cmptparm[0], 0, numcomps * sizeof(opj_image_cmptparm_t));
+    memset(&cmptparm[0], 0, (size_t)numcomps * sizeof(opj_image_cmptparm_t));
     for(i = 0; i < numcomps; i++) {
-        cmptparm[i].prec = raw_cp->rawBitDepth;
-        cmptparm[i].bpp = raw_cp->rawBitDepth;
-        cmptparm[i].sgnd = raw_cp->rawSigned;
-        cmptparm[i].dx = subsampling_dx;
-        cmptparm[i].dy = subsampling_dy;
-        cmptparm[i].w = w;
-        cmptparm[i].h = h;
+        cmptparm[i].prec = (OPJ_UINT32)raw_cp->rawBitDepth;
+        cmptparm[i].bpp = (OPJ_UINT32)raw_cp->rawBitDepth;
+        cmptparm[i].sgnd = (OPJ_UINT32)raw_cp->rawSigned;
+        cmptparm[i].dx = (OPJ_UINT32)(subsampling_dx * raw_cp->rawComps[i].dx);
+        cmptparm[i].dy = (OPJ_UINT32)(subsampling_dy * raw_cp->rawComps[i].dy);
+        cmptparm[i].w = (OPJ_UINT32)w;
+        cmptparm[i].h = (OPJ_UINT32)h;
     }
     /* create the image */
-    image = opj_image_create(numcomps, &cmptparm[0], color_space);
+    image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
+    free(cmptparm);
     if(!image) {
         fclose(f);
         return NULL;
     }
     /* set image offset and reference grid */
-    image->x0 = parameters->image_offset_x0;
-    image->y0 = parameters->image_offset_y0;
-    image->x1 = parameters->image_offset_x0 + (w - 1) *        subsampling_dx + 1;
-    image->y1 = parameters->image_offset_y0 + (h - 1) *        subsampling_dy + 1;
+    image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
+    image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
+    image->x1 = (OPJ_UINT32)parameters->image_offset_x0 + (OPJ_UINT32)(w - 1) *        (OPJ_UINT32)subsampling_dx + 1;
+    image->y1 = (OPJ_UINT32)parameters->image_offset_y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;
 
     if(raw_cp->rawBitDepth <= 8)
     {
         unsigned char value = 0;
         for(compno = 0; compno < numcomps; compno++) {
-            for (i = 0; i < w * h; i++) {
+            int nloop = (w*h)/(raw_cp->rawComps[compno].dx*raw_cp->rawComps[compno].dx);
+            for (i = 0; i < nloop; i++) {
                 if (!fread(&value, 1, 1, f)) {
                     fprintf(stderr,"Error reading raw file. End of file probably reached.\n");
                     return NULL;
@@ -2875,7 +3032,8 @@ static opj_image_t* rawtoimage_common(const char *filename, opj_cparameters_t *p
     {
         unsigned short value;
         for(compno = 0; compno < numcomps; compno++) {
-            for (i = 0; i < w * h; i++) {
+            int nloop = (w*h)/(raw_cp->rawComps[compno].dx*raw_cp->rawComps[compno].dx);
+            for (i = 0; i < nloop; i++) {
                 unsigned char temp1;
                 unsigned char temp2;
                 if (!fread(&temp1, 1, 1, f)) {
@@ -2888,13 +3046,11 @@ static opj_image_t* rawtoimage_common(const char *filename, opj_cparameters_t *p
                 }
                 if( big_endian )
                 {
-                    value = temp1 << 8;
-                    value += temp2;
+                    value = (unsigned short)((temp1 << 8) + temp2);
                 }
                 else
                 {
-                    value = temp2 << 8;
-                    value += temp1;
+                    value = (unsigned short)((temp2 << 8) + temp1);
                 }
                 image->comps[compno].data[i] = raw_cp->rawSigned?(short)value:value;
             }
@@ -2925,10 +3081,12 @@ static int imagetoraw_common(opj_image_t * image, const char *outfile, OPJ_BOOL
 {
     FILE *rawFile = NULL;
     size_t res;
-    int compno;
-    int w, h;
-    int line, row;
+    unsigned int compno;
+    int w, h, fails;
+    int line, row, curr, mask;
     int *ptr;
+    unsigned char uc;
+    (void)big_endian;
 
     if((image->numcomps * image->x1 * image->y1) == 0)
     {
@@ -2942,6 +3100,7 @@ static int imagetoraw_common(opj_image_t * image, const char *outfile, OPJ_BOOL
         return 1;
     }
 
+    fails = 1;
     fprintf(stdout,"Raw image characteristics: %d components\n", image->numcomps);
 
     for(compno = 0; compno < image->numcomps; compno++)
@@ -2949,23 +3108,24 @@ static int imagetoraw_common(opj_image_t * image, const char *outfile, OPJ_BOOL
         fprintf(stdout,"Component %d characteristics: %dx%dx%d %s\n", compno, image->comps[compno].w,
                 image->comps[compno].h, image->comps[compno].prec, image->comps[compno].sgnd==1 ? "signed": "unsigned");
 
-        w = image->comps[compno].w;
-        h = image->comps[compno].h;
+        w = (int)image->comps[compno].w;
+        h = (int)image->comps[compno].h;
 
         if(image->comps[compno].prec <= 8)
         {
             if(image->comps[compno].sgnd == 1)
             {
-                signed char curr;
-                int mask = (1 << image->comps[compno].prec) - 1;
+                mask = (1 << image->comps[compno].prec) - 1;
                 ptr = image->comps[compno].data;
                 for (line = 0; line < h; line++) {
                     for(row = 0; row < w; row++)       {
-                        curr = (signed char) (*ptr & mask);
-                        res = fwrite(&curr, sizeof(signed char), 1, rawFile);
+                        curr = *ptr;
+                        if(curr > 127) curr = 127; else if(curr < -128) curr = -128;
+                        uc = (unsigned char) (curr & mask);
+                        res = fwrite(&uc, 1, 1, rawFile);
                         if( res < 1 ) {
                             fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
-                            return 1;
+                            goto fin;
                         }
                         ptr++;
                     }
@@ -2973,16 +3133,17 @@ static int imagetoraw_common(opj_image_t * image, const char *outfile, OPJ_BOOL
             }
             else if(image->comps[compno].sgnd == 0)
             {
-                unsigned char curr;
-                int mask = (1 << image->comps[compno].prec) - 1;
+                mask = (1 << image->comps[compno].prec) - 1;
                 ptr = image->comps[compno].data;
                 for (line = 0; line < h; line++) {
                     for(row = 0; row < w; row++)       {
-                        curr = (unsigned char) (*ptr & mask);
-                        res = fwrite(&curr, sizeof(unsigned char), 1, rawFile);
+                        curr = *ptr;
+                        if(curr > 255) curr = 255; else if(curr < 0) curr = 0;
+                        uc = (unsigned char) (curr & mask);
+                        res = fwrite(&uc, 1, 1, rawFile);
                         if( res < 1 ) {
                             fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
-                            return 1;
+                            goto fin;
                         }
                         ptr++;
                     }
@@ -2993,33 +3154,18 @@ static int imagetoraw_common(opj_image_t * image, const char *outfile, OPJ_BOOL
         {
             if(image->comps[compno].sgnd == 1)
             {
-                signed short int curr;
-                int mask = (1 << image->comps[compno].prec) - 1;
+                union { signed short val; signed char vals[2]; } uc16;
+                mask = (1 << image->comps[compno].prec) - 1;
                 ptr = image->comps[compno].data;
                 for (line = 0; line < h; line++) {
                     for(row = 0; row < w; row++)       {
-                        unsigned char temp1;
-                        unsigned char temp2;
-                        curr = (signed short int) (*ptr & mask);
-                        if( big_endian )
-                        {
-                            temp1 = (unsigned char) (curr >> 8);
-                            temp2 = (unsigned char) curr;
-                        }
-                        else
-                        {
-                            temp2 = (unsigned char) (curr >> 8);
-                            temp1 = (unsigned char) curr;
-                        }
-                        res = fwrite(&temp1, 1, 1, rawFile);
-                        if( res < 1 ) {
-                            fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
-                            return 1;
-                        }
-                        res = fwrite(&temp2, 1, 1, rawFile);
-                        if( res < 1 ) {
-                            fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
-                            return 1;
+                        curr = *ptr;
+                        if(curr > 32767 ) curr = 32767; else if( curr < -32768) curr = -32768;
+                        uc16.val = (signed short)(curr & mask);
+                        res = fwrite(uc16.vals, 1, 2, rawFile);
+                        if( res < 2 ) {
+                            fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
+                            goto fin;
                         }
                         ptr++;
                     }
@@ -3027,33 +3173,18 @@ static int imagetoraw_common(opj_image_t * image, const char *outfile, OPJ_BOOL
             }
             else if(image->comps[compno].sgnd == 0)
             {
-                unsigned short int curr;
-                int mask = (1 << image->comps[compno].prec) - 1;
+                union { unsigned short val; unsigned char vals[2]; } uc16;
+                mask = (1 << image->comps[compno].prec) - 1;
                 ptr = image->comps[compno].data;
                 for (line = 0; line < h; line++) {
                     for(row = 0; row < w; row++)       {
-                        unsigned char temp1;
-                        unsigned char temp2;
-                        curr = (unsigned short int) (*ptr & mask);
-                        if( big_endian )
-                        {
-                            temp1 = (unsigned char) (curr >> 8);
-                            temp2 = (unsigned char) curr;
-                        }
-                        else
-                        {
-                            temp2 = (unsigned char) (curr >> 8);
-                            temp1 = (unsigned char) curr;
-                        }
-                        res = fwrite(&temp1, 1, 1, rawFile);
-                        if( res < 1 ) {
-                            fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
-                            return 1;
-                        }
-                        res = fwrite(&temp2, 1, 1, rawFile);
-                        if( res < 1 ) {
-                            fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
-                            return 1;
+                        curr = *ptr;
+                        if(curr > 65536 ) curr = 65536; else if( curr < 0) curr = 0;
+                        uc16.val = (unsigned short)(curr & mask);
+                        res = fwrite(uc16.vals, 1, 2, rawFile);
+                        if( res < 2 ) {
+                            fprintf(stderr, "failed to write 2 byte for %s\n", outfile);
+                            goto fin;
                         }
                         ptr++;
                     }
@@ -3063,16 +3194,18 @@ static int imagetoraw_common(opj_image_t * image, const char *outfile, OPJ_BOOL
         else if (image->comps[compno].prec <= 32)
         {
             fprintf(stderr,"More than 16 bits per component no handled yet\n");
-            return 1;
+            goto fin;
         }
         else
         {
             fprintf(stderr,"Error: invalid precision: %d\n", image->comps[compno].prec);
-            return 1;
+            goto fin;
         }
     }
+  fails = 0;
+fin:
     fclose(rawFile);
-    return 0;
+    return fails;
 }
 
 int imagetoraw(opj_image_t * image, const char *outfile)
@@ -3110,7 +3243,7 @@ opj_image_t *pngtoimage(const char *read_idf, opj_cparameters_t * params)
     opj_image_cmptparm_t cmptparm[4];
     int sub_dx, sub_dy;
     unsigned int nr_comp;
-    int *r, *g, *b, *a;
+    int *r, *g, *b, *a = NULL;
     unsigned char sigbuf[8];
 
     if((reader = fopen(read_idf, "rb")) == NULL)
@@ -3190,7 +3323,7 @@ opj_image_t *pngtoimage(const char *read_idf, opj_cparameters_t * params)
 
     has_alpha = (color_type == PNG_COLOR_TYPE_RGB_ALPHA);
 
-    nr_comp = 3 + has_alpha;
+    nr_comp = 3 + (unsigned int)has_alpha;
 
     bit_depth = png_get_bit_depth(png, info);
 
@@ -3200,35 +3333,35 @@ opj_image_t *pngtoimage(const char *read_idf, opj_cparameters_t * params)
 
     png_read_image(png, rows);
 
-    memset(&cmptparm, 0, 4 * sizeof(opj_image_cmptparm_t));
+    memset(cmptparm, 0, sizeof(cmptparm));
 
     sub_dx = params->subsampling_dx; sub_dy = params->subsampling_dy;
 
     for(i = 0; i < nr_comp; ++i)
     {
-        cmptparm[i].prec = bit_depth;
+        cmptparm[i].prec = (OPJ_UINT32)bit_depth;
         /* bits_per_pixel: 8 or 16 */
-        cmptparm[i].bpp = bit_depth;
+        cmptparm[i].bpp = (OPJ_UINT32)bit_depth;
         cmptparm[i].sgnd = 0;
-        cmptparm[i].dx = sub_dx;
-        cmptparm[i].dy = sub_dy;
-        cmptparm[i].w = width;
-        cmptparm[i].h = height;
+        cmptparm[i].dx = (OPJ_UINT32)sub_dx;
+        cmptparm[i].dy = (OPJ_UINT32)sub_dy;
+        cmptparm[i].w = (OPJ_UINT32)width;
+        cmptparm[i].h = (OPJ_UINT32)height;
     }
 
     image = opj_image_create(nr_comp, &cmptparm[0], OPJ_CLRSPC_SRGB);
 
     if(image == NULL) goto fin;
 
-    image->x0 = params->image_offset_x0;
-    image->y0 = params->image_offset_y0;
-    image->x1 = image->x0 + (width  - 1) * sub_dx + 1 + image->x0;
-    image->y1 = image->y0 + (height - 1) * sub_dy + 1 + image->y0;
+    image->x0 = (OPJ_UINT32)params->image_offset_x0;
+    image->y0 = (OPJ_UINT32)params->image_offset_y0;
+    image->x1 = (OPJ_UINT32)(image->x0 + (width  - 1) * (OPJ_UINT32)sub_dx + 1 + image->x0);
+    image->y1 = (OPJ_UINT32)(image->y0 + (height - 1) * (OPJ_UINT32)sub_dy + 1 + image->y0);
 
     r = image->comps[0].data;
     g = image->comps[1].data;
     b = image->comps[2].data;
-    a = image->comps[3].data;
+    if(has_alpha) a = image->comps[3].data;
 
     for(i = 0; i < height; ++i)
     {
@@ -3283,8 +3416,8 @@ int imagetopng(opj_image_t * image, const char *write_idf)
     png_color_8 sig_bit;
 
     is16 = force16 = force8 = ushift = dshift = 0; fails = 1;
-    prec = image->comps[0].prec;
-    nr_comp = image->numcomps;
+    prec = (int)image->comps[0].prec;
+    nr_comp = (int)image->numcomps;
 
     if(prec > 8 && prec < 16)
     {
@@ -3380,18 +3513,18 @@ int imagetopng(opj_image_t * image, const char *write_idf)
 
         is16 = (prec == 16);
 
-        width = image->comps[0].w;
-        height = image->comps[0].h;
+        width = (int)image->comps[0].w;
+        height = (int)image->comps[0].h;
 
         red = image->comps[0].data;
         green = image->comps[1].data;
         blue = image->comps[2].data;
 
-        sig_bit.red = sig_bit.green = sig_bit.blue = prec;
+        sig_bit.red = sig_bit.green = sig_bit.blue = (png_byte)prec;
 
         if(has_alpha)
         {
-            sig_bit.alpha = prec;
+            sig_bit.alpha = (png_byte)prec;
             alpha = image->comps[3].data;
             color_type = PNG_COLOR_TYPE_RGB_ALPHA;
             adjustA = (image->comps[3].sgnd ? 1 << (image->comps[3].prec - 1) : 0);
@@ -3404,7 +3537,7 @@ int imagetopng(opj_image_t * image, const char *write_idf)
         }
         png_set_sBIT(png, info, &sig_bit);
 
-        png_set_IHDR(png, info, width, height, prec,
+        png_set_IHDR(png, info, (png_uint_32)width, (png_uint_32)height, prec,
                      color_type,
                      PNG_INTERLACE_NONE,
                      PNG_COMPRESSION_TYPE_BASE,  PNG_FILTER_TYPE_BASE);
@@ -3418,11 +3551,15 @@ int imagetopng(opj_image_t * image, const char *write_idf)
         {
             png_set_packing(png);
         }
+printf("%s:%d:sgnd(%d,%d,%d) w(%d) h(%d) alpha(%d)\n",__FILE__,__LINE__,
+image->comps[0].sgnd,
+image->comps[1].sgnd,image->comps[2].sgnd,width,height,has_alpha);
+
         adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);
         adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
         adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
 
-        row_buf = (unsigned char*)malloc(width * nr_comp * 2);
+        row_buf = (unsigned char*)malloc((size_t)width * (size_t)nr_comp * 2);
 
         for(y = 0; y < height; ++y)
         {
@@ -3433,18 +3570,21 @@ int imagetopng(opj_image_t * image, const char *write_idf)
                 if(is16)
                 {
                     v = *red + adjustR; ++red;
+               if(v > 65535) v = 65535; else if(v < 0) v = 0;
 
                     if(force16) { v = (v<<ushift) + (v>>dshift); }
 
                     *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
 
                     v = *green + adjustG; ++green;
+               if(v > 65535) v = 65535; else if(v < 0) v = 0;
 
                     if(force16) { v = (v<<ushift) + (v>>dshift); }
 
                     *d++ = (unsigned char)(v>>8); *d++ = (unsigned char)v;
 
                     v =  *blue + adjustB; ++blue;
+               if(v > 65535) v = 65535; else if(v < 0) v = 0;
 
                     if(force16) { v = (v<<ushift) + (v>>dshift); }
 
@@ -3453,6 +3593,7 @@ int imagetopng(opj_image_t * image, const char *write_idf)
                     if(has_alpha)
                     {
                         v = *alpha + adjustA; ++alpha;
+               if(v > 65535) v = 65535; else if(v < 0) v = 0;
 
                         if(force16) { v = (v<<ushift) + (v>>dshift); }
 
@@ -3462,18 +3603,21 @@ int imagetopng(opj_image_t * image, const char *write_idf)
                 }/* if(is16) */
 
                 v = *red + adjustR; ++red;
+               if(v > 255) v = 255; else if(v < 0) v = 0;
 
                 if(force8) { v = (v<<ushift) + (v>>dshift); }
 
                 *d++ = (unsigned char)(v & mask);
 
                 v = *green + adjustG; ++green;
+               if(v > 255) v = 255; else if(v < 0) v = 0;
 
                 if(force8) { v = (v<<ushift) + (v>>dshift); }
 
                 *d++ = (unsigned char)(v & mask);
 
                 v = *blue + adjustB; ++blue;
+               if(v > 255) v = 255; else if(v < 0) v = 0;
 
                 if(force8) { v = (v<<ushift) + (v>>dshift); }
 
@@ -3482,6 +3626,7 @@ int imagetopng(opj_image_t * image, const char *write_idf)
                 if(has_alpha)
                 {
                     v = *alpha + adjustA; ++alpha;
+               if(v > 255) v = 255; else if(v < 0) v = 0;
 
                     if(force8) { v = (v<<ushift) + (v>>dshift); }
 
@@ -3506,22 +3651,22 @@ int imagetopng(opj_image_t * image, const char *write_idf)
 
             red = image->comps[0].data;
 
-            sig_bit.gray = prec;
+            sig_bit.gray = (png_byte)prec;
             sig_bit.red = sig_bit.green = sig_bit.blue = sig_bit.alpha = 0;
             alpha = NULL; adjustA = 0;
             color_type = PNG_COLOR_TYPE_GRAY;
 
             if(nr_comp == 2)
             {
-                has_alpha = 1; sig_bit.alpha = prec;
+                has_alpha = 1; sig_bit.alpha = (png_byte)prec;
                 alpha = image->comps[1].data;
                 color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
                 adjustA = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
             }
-            width = image->comps[0].w;
-            height = image->comps[0].h;
+            width = (int)image->comps[0].w;
+            height = (int)image->comps[0].h;
 
-            png_set_IHDR(png, info, width, height, sig_bit.gray,
+            png_set_IHDR(png, info, (png_uint_32)width, (png_uint_32)height, sig_bit.gray,
                          color_type,
                          PNG_INTERLACE_NONE,
                          PNG_COMPRESSION_TYPE_BASE,  PNG_FILTER_TYPE_BASE);
@@ -3543,7 +3688,7 @@ int imagetopng(opj_image_t * image, const char *write_idf)
             if(prec > 8)
             {
                 row_buf = (unsigned char*)
-                        malloc(width * nr_comp * sizeof(unsigned short));
+                        malloc((size_t)width * (size_t)nr_comp * sizeof(unsigned short));
 
                 for(y = 0; y < height; ++y)
                 {
@@ -3552,6 +3697,7 @@ int imagetopng(opj_image_t * image, const char *write_idf)
                     for(x = 0; x < width; ++x)
                     {
                         v = *red + adjustR; ++red;
+               if(v > 65535) v = 65535; else if(v < 0) v = 0;
 
                         if(force16) { v = (v<<ushift) + (v>>dshift); }
 
@@ -3560,6 +3706,7 @@ int imagetopng(opj_image_t * image, const char *write_idf)
                         if(has_alpha)
                         {
                             v = *alpha++;
+               if(v > 65535) v = 65535; else if(v < 0) v = 0;
 
                             if(force16) { v = (v<<ushift) + (v>>dshift); }
 
@@ -3573,7 +3720,7 @@ int imagetopng(opj_image_t * image, const char *write_idf)
             }
             else /* prec <= 8 */
             {
-                row_buf = (unsigned char*)calloc(width, nr_comp * 2);
+                row_buf = (unsigned char*)calloc((size_t)width, (size_t)nr_comp * 2);
 
                 for(y = 0; y < height; ++y)
                 {
@@ -3582,6 +3729,7 @@ int imagetopng(opj_image_t * image, const char *write_idf)
                     for(x = 0; x < width; ++x)
                     {
                         v = *red + adjustR; ++red;
+               if(v > 255) v = 255; else if(v < 0) v = 0;
 
                         if(force8) { v = (v<<ushift) + (v>>dshift); }
 
@@ -3590,6 +3738,7 @@ int imagetopng(opj_image_t * image, const char *write_idf)
                         if(has_alpha)
                         {
                             v = *alpha + adjustA; ++alpha;
+               if(v > 255) v = 255; else if(v < 0) v = 0;
 
                             if(force8) { v = (v<<ushift) + (v>>dshift); }