/*---------------------------------------------------------------------------*
  C MODULE  cf_tai64n_p.c

  Copyright (c) 2003-2006, James H. Woodyatt
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions
  are met:

    Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.

    Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in
    the documentation and/or other materials provided with the
    distribution

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  OF THE POSSIBILITY OF SUCH DAMAGE. 
 *---------------------------------------------------------------------------*/

#include "cf_tai64n_p.h"

#include <errno.h>
#include <math.h>
#include <sys/time.h>

#define INVALID_ARGUMENT(S)     (invalid_argument("Cf_tai64n." S))

static int cf_tai64n_op_compare(value v1, value v2);
static long cf_tai64n_op_hash(value v);
static void cf_tai64n_op_serialize
   (value v, unsigned long* z32, unsigned long* z64);
static unsigned long cf_tai64n_op_deserialize(void* buffer);

static value cf_tai64n_first_val = Val_unit;
static value cf_tai64n_last_val = Val_unit;

static struct custom_operations cf_tai64n_op = {
    "org.conjury.ocnae.cf.tai64n",
    custom_finalize_default,
    cf_tai64n_op_compare,
    cf_tai64n_op_hash,
    cf_tai64n_op_serialize,
    cf_tai64n_op_deserialize
};

static int cf_tai64n_op_compare(value v1, value v2)
{
    CAMLparam2(v1, v2);
    
    const Cf_tai64n_t* v1Ptr;
    const Cf_tai64n_t* v2Ptr;
    int result;
    
    v1Ptr = Cf_tai64n_val(v1);
    v2Ptr = Cf_tai64n_val(v2);
    
    if (v2Ptr->s > v1Ptr->s)
        result = 1;
    else if (v1Ptr->s > v2Ptr->s)
        result = -1;
    else if (v2Ptr->ns > v1Ptr->ns)
        result = 1;
    else if (v1Ptr->ns > v2Ptr->ns)
        result = -1;
    else
        result = 0;
    
    CAMLreturn(result);
}

static long cf_tai64n_op_hash(value v)
{
    CAMLparam1(v);
    Cf_tai64n_t* vPtr;
    
     vPtr = Cf_tai64n_val(v);
    
    CAMLreturn((uint32) vPtr->s ^ vPtr->ns);
}

static void cf_tai64n_op_serialize
   (value v, unsigned long* size32Ptr, unsigned long* size64Ptr)
{
    CAMLparam1(v);
    
    char buffer[12];
    unsigned long long x;
    uint32 y;
    int i;
    
    x = Cf_tai64n_val(v)->s;
    for (i = 7; i >= 0; --i) {
        u_int8_t ch = x & 0xFFULL;
        x >>= 8;
        buffer[i] = (char) ch;
    }
    
    y = Cf_tai64n_val(v)->ns;
    for (i = 11; i >= 8; --i) {
        u_int8_t ch = y & 0xFFUL;
        y >>= 8;
        buffer[i] = (char) ch;
    }
    
    serialize_block_1(buffer, 12);
    *size32Ptr = 12;
    *size64Ptr = 12;
    
    CAMLreturn0;
}

static unsigned long cf_tai64n_op_deserialize(void* data)
{
    char buffer[12];
    unsigned long long x;
    uint32 y;
    int i;
    
    deserialize_block_1(buffer, 8);

    x = 0ULL;
    for (i = 7; i >= 0; --i) {
        u_int8_t ch = (u_int8_t) buffer[i];
        x <<= 8;
        x |= (unsigned long long) ch;
    }
    
    y = 0UL;
    for (i = 11; i >= 8; --i) {
        u_int8_t ch = (u_int8_t) buffer[i];
        y <<= 8;
        y |= (unsigned long long) ch;
    }

    ((Cf_tai64n_t*) data)->s = x;
    ((Cf_tai64n_t*) data)->ns = y;
    return 12;
}

/*---
  Compare primitive
  ---*/
CAMLprim value cf_tai64n_compare(value v1, value v2)
{
    CAMLparam2(v1, v2);
    int dt;
    
    dt = cf_tai64n_op_compare(v1, v2);
    CAMLreturn(Val_int(dt));
}

/*---
  Allocate an initialized structure
  ---*/
extern value cf_tai64n_alloc(const Cf_tai64n_t* tai64nPtr)
{
    value result;
    
    result = alloc_custom(&cf_tai64n_op, sizeof *tai64nPtr, 0, 1);
    *Cf_tai64n_val(result) = *tai64nPtr;
    return result;
}

/*---
  Set to current time

    1972-01-01 00:00:00 UTC was 1972-01-01 00:00:10 TAI
    Unix time values include all currently defined leap seconds
  ---*/
extern void cf_tai64n_update(Cf_tai64n_t* tai64nPtr)
{
    uint64 epoch;
    struct timeval tv;
    struct timezone tz;
    
    if (gettimeofday(&tv, &tz))
        unix_error(errno, "gettimeofday", Nothing);
    
    epoch = CF_TAI64_EPOCH;
    epoch += cf_tai64_current_offset;
    tai64nPtr->s = epoch + ((uint64) tv.tv_sec);
    tai64nPtr->ns = tv.tv_usec * 1000;
}

/*---
  Allocate and set to current time
  ---*/
CAMLprim value cf_tai64n_now(value unit)
{
    CAMLparam0();
    CAMLlocal1(result);

    Cf_tai64n_t x;
    
    cf_tai64n_update(&x);
    result = cf_tai64n_alloc(&x);
    
    CAMLreturn(result);
}

/*---
  Allocate global value of the first representable TAI64N
  ---*/
CAMLprim value cf_tai64n_first(value unit)
{
    CAMLparam0();
    CAMLreturn(cf_tai64n_first_val);
}

/*---
  Allocate global value of the last representable TAI64N
  ---*/
CAMLprim value cf_tai64n_last(value unit)
{
    CAMLparam0();
    CAMLreturn(cf_tai64n_last_val);
}

/*---
    external compose: Cf_tai64.t -> int -> t = "cf_tai64n_compose"
  ---*/
CAMLprim value cf_tai64n_compose(value tai64Val, value nsVal)
{
    CAMLparam2(tai64Val, nsVal);
    CAMLlocal1(resultVal);
    
    Cf_tai64_t* tai64Ptr;
    uint32 ns;
    Cf_tai64n_t tai64n;
    
    tai64Ptr = Cf_tai64_val(tai64Val);
    ns = (uint32) Int_val(nsVal);
    if (ns < 0 || ns > 999999999) INVALID_ARGUMENT("compose: ns > 10^9");
    
    tai64n.s = tai64Ptr->s;
    tai64n.ns = ns;
    
    resultVal = cf_tai64n_alloc(&tai64n);
    CAMLreturn(resultVal);
}

/*---
    external decompose: t -> Cf_tai64.t * int = "cf_tai64n_decompose"
  ---*/
CAMLprim value cf_tai64n_decompose(value tai64nVal)
{
    CAMLparam1(tai64nVal);
    CAMLlocal2(resultVal, tai64Val);
    Cf_tai64_t tai64;
    
    tai64.s = Cf_tai64n_val(tai64nVal)->s;
    tai64Val = cf_tai64_alloc(&tai64);
    
    resultVal = alloc_small(2, 0);
    Store_field(resultVal, 0, tai64Val);
    Store_field(resultVal, 1, Val_int(Cf_tai64n_val(tai64nVal)->ns));
    
    CAMLreturn(resultVal);
}

/*---
  Convert a floating point Unix.time result to TAI
  ---*/
CAMLprim value cf_tai64n_of_unix_time(value v)
{
    CAMLparam1(v);
    CAMLlocal1(result);

    static const double cf_tai64_unix_limit[2] = {
        -((double)CF_TAI64_EPOCH),
        ((double)(CF_TAI64_EPOCH << 1) - CF_TAI64_EPOCH - 1),
    };
    
    Cf_tai64n_t tai64n;
    double x, y;
    
    y = (uint64) modf(Double_val(v), &x);
    x += (double) cf_tai64_current_offset;
    if (x < cf_tai64_unix_limit[0] || x > cf_tai64_unix_limit[1])
        cf_tai64_range_error();
    
    tai64n.s = CF_TAI64_EPOCH + ((uint64) x);
    tai64n.ns = (uint32) (y * 1E9);
    result = cf_tai64n_alloc(&tai64n);
    
    CAMLreturn(result);
}

/*---
  Convert a TAI value to a floating point Unix.time result
  ---*/
CAMLprim value cf_tai64n_to_unix_time(value v)
{
    CAMLparam1(v);
    CAMLlocal1(result);

    double x, y;
    uint64 epoch;
    
    epoch = CF_TAI64_EPOCH;
    epoch += cf_tai64_current_offset;
    
    x = (double) (Cf_tai64n_val(v)->s - epoch);
    y = ((double) Cf_tai64n_val(v)->ns) * 1E-9;
    
    result = copy_double(x + y);

    CAMLreturn(result);
}

/*---
  Convert a string containing a TAI64N label into the corresponding value
  ---*/
CAMLprim value cf_tai64n_of_label(value v)
{
    CAMLparam1(v);
    CAMLlocal1(result);
    
    Cf_tai64n_t tai64n;
    int i;
    uint64 x;
    uint32 y;
    
    if (string_length(v) != 12) cf_tai64_label_error();
    for (i = 0, x = 0; i < 8; ++i) x = (x << 8) | Byte_u(v, i);
    for (i = 8, y = 0; i < 12; ++i) y = (y << 8) | Byte_u(v, i);
    tai64n.s = x;
    tai64n.ns = y;
    result = cf_tai64n_alloc(&tai64n);
    
    CAMLreturn(result);
}

/*---
  Convert a TAI64N value to a Caml string containing its label
  ---*/
CAMLprim value cf_tai64n_to_label(value v)
{
    CAMLparam1(v);
    CAMLlocal1(result);
    
    uint64 x;
    uint32 y;
    int i;
    
    result = alloc_string(12);
    x = Cf_tai64n_val(v)->s;
    for (i = 7; i >= 0; --i, x >>= 8)
        Byte_u(result, i) = (unsigned char) x;
    y = Cf_tai64n_val(v)->ns;
    for (i = 11; i >= 8; --i, y >>= 8)
        Byte_u(result, i) = (unsigned char) y;
    
    CAMLreturn(result);
}

/*---
  Addition of float
  ---*/
CAMLprim value cf_tai64n_add(value tai64nVal, value dtVal)
{
    CAMLparam2(tai64nVal, dtVal);
    CAMLlocal1(result);

    Cf_tai64n_t tai64n;
    double zInt, zFrac;
    int64 x;
    int32 y;

    zFrac = modf(Double_val(dtVal), &zInt);
    x = (int64) zInt;
    y = (int32) (zFrac * 1E9);
    
    tai64n.s = Cf_tai64n_val(tai64nVal)->s + x;
    tai64n.ns = Cf_tai64n_val(tai64nVal)->ns + y;
    if (tai64n.ns < 0) {
        tai64n.ns += 1000000000;
        tai64n.s -= 1;
    }
    else if (tai64n.ns >= 1000000000) {
        tai64n.ns -= 1000000000;
        tai64n.s += 1;
    }

    if (tai64n.s >= (CF_TAI64_EPOCH << 1)) cf_tai64_range_error();
    result = cf_tai64n_alloc(&tai64n);    
    CAMLreturn(result);
}

/*---
  Subtraction of TAI64N values
  ---*/
CAMLprim value cf_tai64n_sub(value v1, value v2)
{
    CAMLparam2(v1, v2);
    CAMLlocal1(resultVal);
        
    double dt;
    dt = ((int64) Cf_tai64n_val(v1)->s) - ((int64) Cf_tai64n_val(v2)->s);
    dt += (((int32) Cf_tai64n_val(v1)->ns) - ((int32) Cf_tai64n_val(v2)->ns))
        * 1E-9;
    
    resultVal = copy_double(dt);
    CAMLreturn(resultVal);
}

/*---
  Initialization primtive
  ---*/
CAMLprim value cf_tai64n_init(value unit)
{
    static const Cf_tai64n_t first = { 0ULL, 0UL };
    static const Cf_tai64n_t last = { (CF_TAI64_EPOCH << 1) - 1, 999999999UL };

    register_custom_operations(&cf_tai64n_op);        
    
    register_global_root(&cf_tai64n_first_val);
    cf_tai64n_first_val = cf_tai64n_alloc(&first);
    
    register_global_root(&cf_tai64n_last_val);
    cf_tai64n_last_val = cf_tai64n_alloc(&last);

    return Val_unit;
}

/*--- End of File [ cf_tai64n_p.c ] ---*/
