#include <caml/memory.h>
#include <caml/fail.h>
#include <netinet/in.h>

CAMLprim value ml_read_int16_from_string(value buffvalue offset) {
  CAMLparam2(buff,offset);
  int c_offset = Int_val(offset);
  unsigned short r;
  if (string_length(buff) < (c_offset+2) || c_offset < 0) {
    invalid_argument("ml__read_int16_from_string");
  }

  r = *((unsigned short *)(String_val(buff)+c_offset));
  CAMLreturn(Val_int(ntohs(r)));
}
      
let test_read_int16_from_string () =
  let buffer = "ab" in
  let test_value = read_int16_from_string buffer 0 in
  let value = (Char.code buffer.[0])*256+(Char.code buffer.[1]) in
  if test_value = value then
    print_endline "Ok: read_int16_from_string"
  else
    print_endline "Ko: read_int16_from_string";;

test_read_int16_from_string ();;