/* 'checkit_tiff' is a conformance checker for baseline TIFFs
 *
 * author: Andreas Romeyke, 2015-2022
 * licensed under conditions of libtiff
 * (see http://libtiff.maptools.org/misc.html)
 *
 */

#include "check.h"
#include "check_helper.h"
#include "ctstring.h"

/* check if offsets are greater zero */
ret_t check_all_offsets_are_greater_zero(ctiff_t * ctif) {
  GET_EMPTY_RET(ret);
  TIFP_CHECK( ctif, ret);
  uint16 count = get_ifd0_count( ctif);
  for (int tagidx = 0; tagidx< count; tagidx++) {
    ifd_entry_t ifd_entry = TIFFGetRawTagIFDListEntry( ctif, ctif->ifd0, tagidx );
    uint32 tag = TIFFGetRawTagListEntry( ctif, ctif->ifd0, tagidx);
    if (ifd_entry.value_or_offset==is_offset || tag == TIFFTAG_EXIFIFD) {
      uint32 offset=0;
      if (ifd_entry.value_or_offset==is_offset) offset = ifd_entry.data32offset;
      else if (tag == TIFFTAG_EXIFIFD) {
        if (ifd_entry.count > 1) {
          string_t msg = uint2str(ifd_entry.count);
          ret = set_value_found_ret_with_returncode(&ret, msg, tagerror_expected_count_isgreaterone);
          return ret;
        }
        switch (ifd_entry.datatype) {
          case TIFF_LONG: { /*  correct type */
                            offset = ifd_entry.data32;
                            break;
                          }
          default: { /*  incorrect type for EXIF IFD */
                     ret = set_value_found_ret_with_returncode(&ret, str(TIFFTypeName(ifd_entry.datatype)),
                                                               tagerror_unexpected_type_found);
                     return ret;
                     /* break; */
                   };

        }
      } /*  end else if tag == TIFFTAG_EXIFIFD */
      if ( 0 == offset) {
        // FIXME: tif_fails?
        ret = set_value_found_ret_formatted_with_returncode( &ret, tagerror_offset_is_zero, "tag %u pointing to 0x%08x", tag, offset);
        return ret;
      }
    }
  }
  ret.returncode=is_valid;
  return ret;
}
/* vim: set tabstop=2 softtabstop=2 shiftwidth=2 smarttab expandtab :*/
