/* '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"
#include "simple_string.h"
/*
#define DEBUG
*/

/* checks if TIF with tag and type ASCII */
ret_t check_tag_has_valid_asciivalue(ctiff_t * ctif, tag_t tag) {
  GET_EMPTY_RET(ret);
  TIFP_CHECK( ctif, ret);
  EXIST_TAG(ctif, tag, ret);
  TIFFDataType datatype =  TIFFGetRawTagType( ctif,ctif->ifd0,  tag );
  if (datatype == TIFF_ASCII) {
    char *val=NULL;
    uint32 count=0;
    ret = TIFFGetFieldASCII(ctif, ctif->ifd0, tag, &val, &count);
    if (ret.returncode != is_valid) { return ret; }
    if (0 < count) { /* there exists a tag */
      char hexdump[8192];
      sprint_string_as_hexdump(hexdump, 8192, val, count);
      if (val[count - 1] != '\0') {
        ret = set_value_found_ret_formatted_with_returncode(&ret, tagerror_no_zero_as_end_of_string_in_asciivalue, "'%c' (at position %u: %s)", val[count - 1], count - 1, hexdump);
        return ret;
      }
      unsigned int r = count_multiple_zero_bytes(val, count);
      if (0 != r) {
        ret = set_value_found_ret_formatted_with_returncode(&ret, tagerror_multiple_zeros_in_asciivalue, "%s (\\0 at position %u in %u-len)", hexdump, r, count);
      } else {
        ret.returncode=is_valid;
      }
    } else {
      ret.returncode = tagerror_expected_count_iszero;
            free(val);
            return ret;
    }
  } else {
    ret = set_value_found_ret_with_returncode(&ret, const_str(TIFFTypeName(datatype)), tagerror_unexpected_type_found);
    return ret;
  }
  return ret;
}


/* vim: set tabstop=2 softtabstop=2 shiftwidth=2 smarttab expandtab :*/
