/*---------------------------------------------------------------------------*
  C MODULE  cf_tai64_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_tai64_p.h"

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


static int cf_tai64_op_compare(value v1, value v2);
static long cf_tai64_op_hash(value v);
static void cf_tai64_op_serialize
   (value v, unsigned long* z32, unsigned long* z64);
static unsigned long cf_tai64_op_deserialize(void* buffer);

static value* cf_tai64_range_error_exn = 0;
static value* cf_tai64_label_error_exn = 0;

static value cf_tai64_epoch_val = Val_unit;
static value cf_tai64_first_val = Val_unit;
static value cf_tai64_last_val = Val_unit;
static value cf_tai64_mjd_epoch_val = Val_unit;

int cf_tai64_current_offset = 10;

void cf_tai64_range_error(void)
{
    CAMLparam0();
    CAMLlocal1(exnVal);
    
    if (!cf_tai64_range_error_exn)
        cf_tai64_range_error_exn = caml_named_value("Cf_tai64.Range_error");
    
    if (!cf_tai64_range_error_exn)
        invalid_argument
           ("Cf_tai64: Range_error exception unavailable in primitive.");
    
    exnVal = alloc_small(1, 0);
    Store_field(exnVal, 0, *cf_tai64_range_error_exn);
    mlraise(exnVal);

    CAMLreturn0;
}

void cf_tai64_label_error(void)
{
    CAMLparam0();
    CAMLlocal1(exnVal);
    
    if (!cf_tai64_label_error_exn)
        cf_tai64_label_error_exn = caml_named_value("Cf_tai64.Label_error");
    
    if (!cf_tai64_label_error_exn)
        invalid_argument
           ("Cf_tai64: Label_error exception unavailable in primitive.");
    
    exnVal = alloc_small(1, 0);
    Store_field(exnVal, 0, *cf_tai64_label_error_exn);
    caml_raise(exnVal);

    CAMLreturn0;
}

static struct custom_operations cf_tai64_op = {
    "org.conjury.ocnae.cf.tai64",
    custom_finalize_default,
    cf_tai64_op_compare,
    cf_tai64_op_hash,
    cf_tai64_op_serialize,
    cf_tai64_op_deserialize
};

static int cf_tai64_op_compare(value v1, value v2)
{
    CAMLparam2(v1, v2);
    
    const Cf_tai64_t* v1Ptr;
    const Cf_tai64_t* v2Ptr;
    int result;
    
    v1Ptr = Cf_tai64_val(v1);
    v2Ptr = Cf_tai64_val(v2);
    
    if (v2Ptr->s > v1Ptr->s)
        result = 1;
    else if (v1Ptr->s > v2Ptr->s)
        result = -1;
    else
        result = 0;
    
    CAMLreturn(result);
}

static long cf_tai64_op_hash(value v)
{
    CAMLparam1(v);
    CAMLreturn((long) Cf_tai64_val(v)->s);
}

static void cf_tai64_op_serialize
   (value v, unsigned long* size32Ptr, unsigned long* size64Ptr)
{
    CAMLparam1(v);
    
    char buffer[8];
    unsigned long long x;
    int i;
    
    x = Cf_tai64_val(v)->s;
    for (i = 7; i >= 0; --i) {
        u_int8_t ch = x & 0xFFULL;
        x >>= 8;
        buffer[i] = (char) ch;
    }
    
    serialize_block_1(buffer, 8);
    *size32Ptr = 8;
    *size64Ptr = 8;
    
    CAMLreturn0;
}

static unsigned long cf_tai64_op_deserialize(void* data)
{
    char buffer[8];
    unsigned long long x;
    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;
    }

    ((Cf_tai64_t*) data)->s = x;
    return 8;
}

/*---
  Allocate an initialized structure
  ---*/
extern value cf_tai64_alloc(const Cf_tai64_t* tai64Ptr)
{
    value result;
    
    result = alloc_custom(&cf_tai64_op, sizeof *tai64Ptr, 0, 1);
    *Cf_tai64_val(result) = *tai64Ptr;
    return result;
}

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

/*---
  Set to current time

    1972-01-01 00:00:00 UTC was 1972-01-01 00:00:10 TAI
    Unix time_t values include all currently defined leap seconds
  ---*/
extern void cf_tai64_update(Cf_tai64_t* tai64Ptr)
{
    uint64 epoch;
    
    epoch = CF_TAI64_EPOCH;
    epoch += cf_tai64_current_offset;
    tai64Ptr->s = epoch + ((uint64) time(0));
}

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

    Cf_tai64_t x;
    
    cf_tai64_update(&x);
    result = cf_tai64_alloc(&x);
    
    CAMLreturn(result);
}

/*---
  Allocate global value of TAI64 epoch
  ---*/
CAMLprim value cf_tai64_epoch(value unit)
{
    CAMLparam0();
    CAMLreturn(cf_tai64_epoch_val);
}

/*---
  Allocate global value of the first representable TAI64 
  ---*/
CAMLprim value cf_tai64_first(value unit)
{
    CAMLparam0();
    CAMLreturn(cf_tai64_first_val);
}

/*---
  Allocate global value of the last representable TAI64
  ---*/
CAMLprim value cf_tai64_last(value unit)
{
    CAMLparam0();
    CAMLreturn(cf_tai64_last_val);
}

/*---
  Allocate global value of the Modified Julian Date (MJD) epoch
  ---*/
CAMLprim value cf_tai64_mjd_epoch(value unit)
{
    CAMLparam0();
    CAMLreturn(cf_tai64_mjd_epoch_val);
}

/*---
  Set the current offset between UTC and TAI
  ---*/
CAMLprim void cf_tai64_set_current_offset(value v)
{
    CAMLparam1(v);
    cf_tai64_current_offset = Int_val(v);
    CAMLreturn0;
}

/*---
  Convert a floating point Unix.time result to TAI
  ---*/
CAMLprim value cf_tai64_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_tai64_t tai64;
    double x;
    
    x = ceil(Double_val(v));
    x += (double) cf_tai64_current_offset;
    if (x < cf_tai64_unix_limit[0] || x > cf_tai64_unix_limit[1])
        cf_tai64_range_error();
    
    tai64.s = CF_TAI64_EPOCH + ((int64) x);
    result = cf_tai64_alloc(&tai64);
    
    CAMLreturn(result);
}

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

    double x;
    uint64 epoch;
    
    epoch = CF_TAI64_EPOCH;
    epoch += cf_tai64_current_offset;
    
    x = (double) (Cf_tai64_val(v)->s - epoch);
    result = copy_double(x);

    CAMLreturn(result);
}

/*---
  Convert a string containing a TAI label into the corresponding value
  ---*/
CAMLprim value cf_tai64_of_label(value v)
{
    CAMLparam1(v);
    CAMLlocal1(result);
    
    Cf_tai64_t tai64;
    int i;
    uint64 x;
    
    if (string_length(v) != 8) cf_tai64_label_error();
    for (i = 0, x = 0; i < 8; ++i) x = (x << 8) | Byte_u(v, i);
    tai64.s = x;
    result = cf_tai64_alloc(&tai64);
    
    CAMLreturn(result);
}

/*---
  Convert a TAI value to a Caml string containing its label
  ---*/
CAMLprim value cf_tai64_to_label(value v)
{
    CAMLparam1(v);
    CAMLlocal1(result);
    
    uint64 x;
    int i;
    
    result = alloc_string(8);
    x = Cf_tai64_val(v)->s;
    for (i = 7, x = Cf_tai64_val(v)->s; i >= 0; --i, x >>= 8)
        Byte_u(result, i) = (unsigned char) x;
    
    CAMLreturn(result);
}

/*---
  Addition of integer
  ---*/
CAMLprim value cf_tai64_add_int(value tai64Val, value dtVal)
{
    CAMLparam2(tai64Val, dtVal);
    CAMLlocal1(result);

    Cf_tai64_t x;
    
    x.s = Cf_tai64_val(tai64Val)->s + Int_val(dtVal);
    if (x.s >= (CF_TAI64_EPOCH << 1)) cf_tai64_range_error();
    result = cf_tai64_alloc(&x);
    
    CAMLreturn(result);
}

/*---
  Addition of int32
  ---*/
CAMLprim value cf_tai64_add_int32(value tai64Val, value dt32Val)
{
    CAMLparam2(tai64Val, dt32Val);
    CAMLlocal1(result);

    Cf_tai64_t x;
    
    x.s = Cf_tai64_val(tai64Val)->s + Int32_val(dt32Val);
    if (x.s >= (CF_TAI64_EPOCH << 1)) cf_tai64_range_error();
    result = cf_tai64_alloc(&x);
    
    CAMLreturn(result);
}

/*---
  Addition of int64
  ---*/
CAMLprim value cf_tai64_add_int64(value tai64Val, value dt64Val)
{
    CAMLparam2(tai64Val, dt64Val);
    CAMLlocal1(result);

    Cf_tai64_t x;
    int64 dt64;
    
    dt64 = Int64_val(dt64Val);
    if (dt64 >= (CF_TAI64_EPOCH << 1)) cf_tai64_range_error();
    
    x.s = Cf_tai64_val(tai64Val)->s + dt64;
    if (x.s >= (CF_TAI64_EPOCH << 1)) cf_tai64_range_error();
    result = cf_tai64_alloc(&x);
    
    CAMLreturn(result);
}

/*---
  Subtraction of tai64 values
  ---*/
CAMLprim value cf_tai64_sub(value v1, value v2)
{
    CAMLparam2(v1, v2);
    
    int64 dt;
    dt = Cf_tai64_val(v1)->s - Cf_tai64_val(v2)->s;
    
    CAMLreturn(copy_int64(dt));
}

/*---
  Initialization primtive
  ---*/
CAMLprim value cf_tai64_init(value unit)
{
    static const Cf_tai64_t epoch = { CF_TAI64_EPOCH };
    static const Cf_tai64_t first = { 0ULL };
    static const Cf_tai64_t last = { (CF_TAI64_EPOCH << 1) - 1 };
    static const Cf_tai64_t mjd_epoch = { CF_TAI64_MJD_EPOCH };
    
    register_custom_operations(&cf_tai64_op);
    
    register_global_root(&cf_tai64_epoch_val);
    cf_tai64_epoch_val = cf_tai64_alloc(&epoch);
    
    register_global_root(&cf_tai64_first_val);
    cf_tai64_first_val = cf_tai64_alloc(&first);
    
    register_global_root(&cf_tai64_last_val);
    cf_tai64_last_val = cf_tai64_alloc(&last);
    
    register_global_root(&cf_tai64_mjd_epoch_val);
    cf_tai64_mjd_epoch_val = cf_tai64_alloc(&mjd_epoch);
        
    return Val_unit;
}

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