// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html

#include "unicode/utypes.h"
#include <float.h>

#if !UCONFIG_NO_FORMATTING

#include "unicode/gregocal.h"
#include "gregoimp.h"
#include "umutex.h"
#include "uassert.h"

// *****************************************************************************
// class GregorianCalendar
// *****************************************************************************

/**
* Note that the Julian date used here is not a true Julian date, since
* it is measured from midnight, not noon.  This value is the Julian
* day number of January 1, 1970 (Gregorian calendar) at noon UTC. [LIU]
*/

static const int16_t kNumDays[]
= {0,31,59,90,120,151,181,212,243,273,304,334}; // 0-based, for day-in-year
static const int16_t kLeapNumDays[]
= {0,31,60,91,121,152,182,213,244,274,305,335}; // 0-based, for day-in-year
static const int8_t kMonthLength[]
= {31,28,31,30,31,30,31,31,30,31,30,31}; // 0-based
static const int8_t kLeapMonthLength[]
= {31,29,31,30,31,30,31,31,30,31,30,31}; // 0-based

// setTimeInMillis() limits the Julian day range to +/-7F000000.
// This would seem to limit the year range to:
//  ms=+183882168921600000  jd=7f000000  December 20, 5828963 AD
//  ms=-184303902528000000  jd=81000000  September 20, 5838270 BC
// HOWEVER, CalendarRegressionTest/Test4167060 shows that the actual
// range limit on the year field is smaller (~ +/-140000). [alan 3.0]

static const int32_t kGregorianCalendarLimits[UCAL_FIELD_COUNT][4] = {
    // Minimum  Greatest    Least  Maximum
    //           Minimum  Maximum
    {        0,        0,        1,        1}, // ERA
    {        1,        1,   140742,   144683}, // YEAR
    {        0,        0,       11,       11}, // MONTH
    {        1,        1,       52,       53}, // WEEK_OF_YEAR
    {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // WEEK_OF_MONTH
    {        1,        1,       28,       31}, // DAY_OF_MONTH
    {        1,        1,      365,      366}, // DAY_OF_YEAR
    {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DAY_OF_WEEK
    {       -1,       -1,        4,        5}, // DAY_OF_WEEK_IN_MONTH
    {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // AM_PM
    {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // HOUR
    {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // HOUR_OF_DAY
    {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MINUTE
    {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // SECOND
    {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MILLISECOND
    {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // ZONE_OFFSET
    {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DST_OFFSET
    {  -140742,  -140742,   140742,   144683}, // YEAR_WOY
    {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DOW_LOCAL
    {  -140742,  -140742,   140742,   144683}, // EXTENDED_YEAR
    {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // JULIAN_DAY
    {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MILLISECONDS_IN_DAY
    {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // IS_LEAP_MONTH
};

/*
* <pre>
*                            Greatest       Least
* Field name        Minimum   Minimum     Maximum     Maximum
* ----------        -------   -------     -------     -------
* ERA                     0         0           1           1
* YEAR                    1         1      140742      144683
* MONTH                   0         0          11          11
* WEEK_OF_YEAR            1         1          52          53
* WEEK_OF_MONTH           0         0           4           6
* DAY_OF_MONTH            1         1          28          31
* DAY_OF_YEAR             1         1         365         366
* DAY_OF_WEEK             1         1           7           7
* DAY_OF_WEEK_IN_MONTH   -1        -1           4           5
* AM_PM                   0         0           1           1
* HOUR                    0         0          11          11
* HOUR_OF_DAY             0         0          23          23
* MINUTE                  0         0          59          59
* SECOND                  0         0          59          59
* MILLISECOND             0         0         999         999
* ZONE_OFFSET           -12*      -12*         12*         12*
* DST_OFFSET              0         0           1*          1*
* YEAR_WOY                1         1      140742      144683
* DOW_LOCAL               1         1           7           7
* </pre>
* (*) In units of one-hour
*/

#if defined( U_DEBUG_CALSVC ) || defined (U_DEBUG_CAL)
#include <stdio.h>
#endif

U_NAMESPACE_BEGIN

UOBJECT_DEFINE_RTTI_IMPLEMENTATION(GregorianCalendar)

// 00:00:00 UTC, October 15, 1582, expressed in ms from the epoch.
// Note that only Italy and other Catholic countries actually
// observed this cutover.  Most other countries followed in
// the next few centuries, some as late as 1928. [LIU]
// in Java, -12219292800000L
//const UDate GregorianCalendar::kPapalCutover = -12219292800000L;
static const uint32_t kCutoverJulianDay = 2299161;
static const UDate kPapalCutover = (2299161.0 - kEpochStartAsJulianDay) * U_MILLIS_PER_DAY;
//static const UDate kPapalCutoverJulian = (2299161.0 - kEpochStartAsJulianDay);

// -------------------------------------

GregorianCalendar::GregorianCalendar(UErrorCode& status)
:   Calendar(status),
fGregorianCutover(kPapalCutover),
fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582),
fIsGregorian(TRUE), fInvertGregorian(FALSE)
{
    setTimeInMillis(getNow(), status);
}

// -------------------------------------

GregorianCalendar::GregorianCalendar(TimeZone* zone, UErrorCode& status)
:   Calendar(zone, Locale::getDefault(), status),
fGregorianCutover(kPapalCutover),
fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582),
fIsGregorian(TRUE), fInvertGregorian(FALSE)
{
    setTimeInMillis(getNow(), status);
}

// -------------------------------------

GregorianCalendar::GregorianCalendar(const TimeZone& zone, UErrorCode& status)
:   Calendar(zone, Locale::getDefault(), status),
fGregorianCutover(kPapalCutover),
fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582),
fIsGregorian(TRUE), fInvertGregorian(FALSE)
{
    setTimeInMillis(getNow(), status);
}

// -------------------------------------

GregorianCalendar::GregorianCalendar(const Locale& aLocale, UErrorCode& status)
:   Calendar(TimeZone::createDefault(), aLocale, status),
fGregorianCutover(kPapalCutover),
fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582),
fIsGregorian(TRUE), fInvertGregorian(FALSE)
{
    setTimeInMillis(getNow(), status);
}

// -------------------------------------

GregorianCalendar::GregorianCalendar(TimeZone* zone, const Locale& aLocale,
                                     UErrorCode& status)
                                     :   Calendar(zone, aLocale, status),
                                     fGregorianCutover(kPapalCutover),
                                     fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582),
                                     fIsGregorian(TRUE), fInvertGregorian(FALSE)
{
    setTimeInMillis(getNow(), status);
}

// -------------------------------------

GregorianCalendar::GregorianCalendar(const TimeZone& zone, const Locale& aLocale,
                                     UErrorCode& status)
                                     :   Calendar(zone, aLocale, status),
                                     fGregorianCutover(kPapalCutover),
                                     fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582),
                                     fIsGregorian(TRUE), fInvertGregorian(FALSE)
{
    setTimeInMillis(getNow(), status);
}

// -------------------------------------

GregorianCalendar::GregorianCalendar(int32_t year, int32_t month, int32_t date,
                                     UErrorCode& status)
                                     :   Calendar(TimeZone::createDefault(), Locale::getDefault(), status),
                                     fGregorianCutover(kPapalCutover),
                                     fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582),
                                     fIsGregorian(TRUE), fInvertGregorian(FALSE)
{
    set(UCAL_ERA, AD);
    set(UCAL_YEAR, year);
    set(UCAL_MONTH, month);
    set(UCAL_DATE, date);
}

// -------------------------------------

GregorianCalendar::GregorianCalendar(int32_t year, int32_t month, int32_t date,
                                     int32_t hour, int32_t minute, UErrorCode& status)
                                     :   Calendar(TimeZone::createDefault(), Locale::getDefault(), status),
                                     fGregorianCutover(kPapalCutover),
                                     fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582),
                                     fIsGregorian(TRUE), fInvertGregorian(FALSE)
{
    set(UCAL_ERA, AD);
    set(UCAL_YEAR, year);
    set(UCAL_MONTH, month);
    set(UCAL_DATE, date);
    set(UCAL_HOUR_OF_DAY, hour);
    set(UCAL_MINUTE, minute);
}

// -------------------------------------

GregorianCalendar::GregorianCalendar(int32_t year, int32_t month, int32_t date,
                                     int32_t hour, int32_t minute, int32_t second,
                                     UErrorCode& status)
                                     :   Calendar(TimeZone::createDefault(), Locale::getDefault(), status),
                                     fGregorianCutover(kPapalCutover),
                                     fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582),
                                     fIsGregorian(TRUE), fInvertGregorian(FALSE)
{
    set(UCAL_ERA, AD);
    set(UCAL_YEAR, year);
    set(UCAL_MONTH, month);
    set(UCAL_DATE, date);
    set(UCAL_HOUR_OF_DAY, hour);
    set(UCAL_MINUTE, minute);
    set(UCAL_SECOND, second);
}

// -------------------------------------

GregorianCalendar::~GregorianCalendar()
{
}

// -------------------------------------

GregorianCalendar::GregorianCalendar(const GregorianCalendar &source)
:   Calendar(source),
fGregorianCutover(source.fGregorianCutover),
fCutoverJulianDay(source.fCutoverJulianDay), fNormalizedGregorianCutover(source.fNormalizedGregorianCutover), fGregorianCutoverYear(source.fGregorianCutoverYear),
fIsGregorian(source.fIsGregorian), fInvertGregorian(source.fInvertGregorian)
{
}

// -------------------------------------

GregorianCalendar* GregorianCalendar::clone() const
{
    return new GregorianCalendar(*this);
}

// -------------------------------------

GregorianCalendar &
GregorianCalendar::operator=(const GregorianCalendar &right)
{
    if (this != &right)
    {
        Calendar::operator=(right);
        fGregorianCutover = right.fGregorianCutover;
        fNormalizedGregorianCutover = right.fNormalizedGregorianCutover;
        fGregorianCutoverYear = right.fGregorianCutoverYear;
        fCutoverJulianDay = right.fCutoverJulianDay;
    }
    return *this;
}

// -------------------------------------

UBool GregorianCalendar::isEquivalentTo(const Calendar& other) const
{
    // Calendar override.
    return Calendar::isEquivalentTo(other) &&
        fGregorianCutover == ((GregorianCalendar*)&other)->fGregorianCutover;
}

// -------------------------------------

void
GregorianCalendar::setGregorianChange(UDate date, UErrorCode& status)
{
    if (U_FAILURE(status))
        return;

    // Precompute two internal variables which we use to do the actual
    // cutover computations.  These are the normalized cutover, which is the
    // midnight at or before the cutover, and the cutover year.  The
    // normalized cutover is in pure date milliseconds; it contains no time
    // of day or timezone component, and it used to compare against other
    // pure date values.
    double cutoverDay = ClockMath::floorDivide(date, (double)kOneDay);

    // Handle the rare case of numeric overflow where the user specifies a time
    // outside of INT32_MIN .. INT32_MAX number of days.

    if (cutoverDay <= INT32_MIN) {
        cutoverDay = INT32_MIN;
        fGregorianCutover = fNormalizedGregorianCutover = cutoverDay * kOneDay;
    } else if (cutoverDay >= INT32_MAX) {
        cutoverDay = INT32_MAX;
        fGregorianCutover = fNormalizedGregorianCutover = cutoverDay * kOneDay;
    } else {
        fNormalizedGregorianCutover = cutoverDay * kOneDay;
        fGregorianCutover = date;
    }

    // Normalize the year so BC values are represented as 0 and negative
    // values.
    GregorianCalendar *cal = new GregorianCalendar(getTimeZone(), status);
    /* test for NULL */
    if (cal == 0) {
        status = U_MEMORY_ALLOCATION_ERROR;
        return;
    }
    if(U_FAILURE(status))
        return;
    cal->setTime(date, status);
    fGregorianCutoverYear = cal->get(UCAL_YEAR, status);
    if (cal->get(UCAL_ERA, status) == BC)
        fGregorianCutoverYear = 1 - fGregorianCutoverYear;
    fCutoverJulianDay = (int32_t)cutoverDay;
    delete cal;
}

void GregorianCalendar::handleComputeFields(int32_t julianDay, UErrorCode& status) {
    int32_t eyear, month, dayOfMonth, dayOfYear, unusedRemainder;

    if(U_FAILURE(status)) {
        return;
    }

#if defined (U_DEBUG_CAL)
    fprintf(stderr, "%s:%d: jd%d- (greg's %d)- [cut=%d]\n",
        __FILE__, __LINE__, julianDay, getGregorianDayOfYear(), fCutoverJulianDay);
#endif

    if (julianDay >= fCutoverJulianDay) {
        month = getGregorianMonth();
        dayOfMonth = getGregorianDayOfMonth();
        dayOfYear = getGregorianDayOfYear();
        eyear = getGregorianYear();
    } else {
        // The Julian epoch day (not the same as Julian Day)
        // is zero on Saturday December 30, 0 (Gregorian).
        int32_t julianEpochDay = julianDay - (kJan1_1JulianDay - 2);
		eyear = (int32_t) ClockMath::floorDivide((4.0*julianEpochDay) + 1464.0, (int32_t) 1461, unusedRemainder);

        // Compute the Julian calendar day number for January 1, eyear
        int32_t january1 = 365*(eyear-1) + ClockMath::floorDivide(eyear-1, (int32_t)4);
        dayOfYear = (julianEpochDay - january1); // 0-based

        // Julian leap years occurred historically every 4 years starting
        // with 8 AD.  Before 8 AD the spacing is irregular; every 3 years
        // from 45 BC to 9 BC, and then none until 8 AD.  However, we don't
        // implement this historical detail; instead, we implement the
        // computatinally cleaner proleptic calendar, which assumes
        // consistent 4-year cycles throughout time.
        UBool isLeap = ((eyear&0x3) == 0); // equiv. to (eyear%4 == 0)

        // Common Julian/Gregorian calculation
        int32_t correction = 0;
        int32_t march1 = isLeap ? 60 : 59; // zero-based DOY for March 1
        if (dayOfYear >= march1) {
            correction = isLeap ? 1 : 2;
        }
        month = (12 * (dayOfYear + correction) + 6) / 367; // zero-based month
        dayOfMonth = dayOfYear - (isLeap?kLeapNumDays[month]:kNumDays[month]) + 1; // one-based DOM
        ++dayOfYear;
#if defined (U_DEBUG_CAL)
        //     fprintf(stderr, "%d - %d[%d] + 1\n", dayOfYear, isLeap?kLeapNumDays[month]:kNumDays[month], month );
        //           fprintf(stderr, "%s:%d:  greg's HCF %d -> %d/%d/%d not %d/%d/%d\n",
        //                   __FILE__, __LINE__,julianDay,
        //          eyear,month,dayOfMonth,
        //          getGregorianYear(), getGregorianMonth(), getGregorianDayOfMonth()  );
        fprintf(stderr, "%s:%d: doy %d (greg's %d)- [cut=%d]\n",
            __FILE__, __LINE__, dayOfYear, getGregorianDayOfYear(), fCutoverJulianDay);
#endif

    }

    // [j81] if we are after the cutover in its year, shift the day of the year
    if((eyear == fGregorianCutoverYear) && (julianDay >= fCutoverJulianDay)) {
        //from handleComputeMonthStart
        int32_t gregShift = Grego::gregorianShift(eyear);
#if defined (U_DEBUG_CAL)
        fprintf(stderr, "%s:%d:  gregorian shift %d :::  doy%d => %d [cut=%d]\n",
            __FILE__, __LINE__,gregShift, dayOfYear, dayOfYear+gregShift, fCutoverJulianDay);
#endif
        dayOfYear += gregShift;
    }

    internalSet(UCAL_MONTH, month);
    internalSet(UCAL_DAY_OF_MONTH, dayOfMonth);
    internalSet(UCAL_DAY_OF_YEAR, dayOfYear);
    internalSet(UCAL_EXTENDED_YEAR, eyear);
    int32_t era = AD;
    if (eyear < 1) {
        era = BC;
        eyear = 1 - eyear;
    }
    internalSet(UCAL_ERA, era);
    internalSet(UCAL_YEAR, eyear);
}

// -------------------------------------

UDate
GregorianCalendar::getGregorianChange() const
{
    return fGregorianCutover;
}

// -------------------------------------

UBool
GregorianCalendar::isLeapYear(int32_t year) const
{
    // MSVC complains bitterly if we try to use Grego::isLeapYear here
    // NOTE: year&0x3 == year%4
    return (year >= fGregorianCutoverYear ?
        (((year&0x3) == 0) && ((year%100 != 0) || (year%400 == 0))) : // Gregorian
    ((year&0x3) == 0)); // Julian
}

// -------------------------------------

int32_t GregorianCalendar::handleComputeJulianDay(UCalendarDateFields bestField)
{
    fInvertGregorian = FALSE;

    int32_t jd = Calendar::handleComputeJulianDay(bestField);

    if((bestField == UCAL_WEEK_OF_YEAR) &&  // if we are doing WOY calculations, we are counting relative to Jan 1 *julian*
        (internalGet(UCAL_EXTENDED_YEAR)==fGregorianCutoverYear) &&
        jd >= fCutoverJulianDay) {
            fInvertGregorian = TRUE;  // So that the Julian Jan 1 will be used in handleComputeMonthStart
            return Calendar::handleComputeJulianDay(bestField);
        }

        // The following check handles portions of the cutover year BEFORE the
        // cutover itself happens.
        //if ((fIsGregorian==TRUE) != (jd >= fCutoverJulianDay)) {  /*  cutoverJulianDay)) { */
        if ((fIsGregorian==TRUE) != (jd >= fCutoverJulianDay)) {  /*  cutoverJulianDay)) { */
#if defined (U_DEBUG_CAL)
            fprintf(stderr, "%s:%d: jd [invert] %d\n",
                __FILE__, __LINE__, jd);
#endif
            fInvertGregorian = TRUE;
            jd = Calendar::handleComputeJulianDay(bestField);
#if defined (U_DEBUG_CAL)
            fprintf(stderr, "%s:%d:  fIsGregorian %s, fInvertGregorian %s - ",
                __FILE__, __LINE__,fIsGregorian?"T":"F", fInvertGregorian?"T":"F");
            fprintf(stderr, " jd NOW %d\n",
                jd);
#endif
        } else {
#if defined (U_DEBUG_CAL)
            fprintf(stderr, "%s:%d: jd [==] %d - %sfIsGregorian %sfInvertGregorian, %d\n",
                __FILE__, __LINE__, jd, fIsGregorian?"T":"F", fInvertGregorian?"T":"F", bestField);
#endif
        }

        if(fIsGregorian && (internalGet(UCAL_EXTENDED_YEAR) == fGregorianCutoverYear)) {
            int32_t gregShift = Grego::gregorianShift(internalGet(UCAL_EXTENDED_YEAR));
            if (bestField == UCAL_DAY_OF_YEAR) {
#if defined (U_DEBUG_CAL)
                fprintf(stderr, "%s:%d: [DOY%d] gregorian shift of JD %d += %d\n",
                    __FILE__, __LINE__, fFields[bestField],jd, gregShift);
#endif
                jd -= gregShift;
            } else if ( bestField == UCAL_WEEK_OF_MONTH ) {
                int32_t weekShift = 14;
#if defined (U_DEBUG_CAL)
                fprintf(stderr, "%s:%d: [WOY/WOM] gregorian week shift of %d += %d\n",
                    __FILE__, __LINE__, jd, weekShift);
#endif
                jd += weekShift; // shift by weeks for week based fields.
            }
        }

        return jd;
}

int32_t GregorianCalendar::handleComputeMonthStart(int32_t eyear, int32_t month,

                                                   UBool /* useMonth */) const
{
    GregorianCalendar *nonConstThis = (GregorianCalendar*)this; // cast away const

    // If the month is out of range, adjust it into range, and
    // modify the extended year value accordingly.
    if (month < 0 || month > 11) {
        eyear += ClockMath::floorDivide(month, 12, month);
    }

    UBool isLeap = eyear%4 == 0;
    int64_t y = (int64_t)eyear-1;
    int64_t julianDay = 365*y + ClockMath::floorDivide(y, (int64_t)4) + (kJan1_1JulianDay - 3);

    nonConstThis->fIsGregorian = (eyear >= fGregorianCutoverYear);
#if defined (U_DEBUG_CAL)
    fprintf(stderr, "%s:%d: (hcms%d/%d) fIsGregorian %s, fInvertGregorian %s\n",
        __FILE__, __LINE__, eyear,month, fIsGregorian?"T":"F", fInvertGregorian?"T":"F");
#endif
    if (fInvertGregorian) {
        nonConstThis->fIsGregorian = !fIsGregorian;
    }
    if (fIsGregorian) {
        isLeap = isLeap && ((eyear%100 != 0) || (eyear%400 == 0));
        // Add 2 because Gregorian calendar starts 2 days after
        // Julian calendar
        int32_t gregShift = Grego::gregorianShift(eyear);
#if defined (U_DEBUG_CAL)
        fprintf(stderr, "%s:%d: (hcms%d/%d) gregorian shift of %d += %d\n",
            __FILE__, __LINE__, eyear, month, julianDay, gregShift);
#endif
        julianDay += gregShift;
    }

    // At this point julianDay indicates the day BEFORE the first
    // day of January 1, <eyear> of either the Julian or Gregorian
    // calendar.

    if (month != 0) {
        julianDay += isLeap?kLeapNumDays[month]:kNumDays[month];
    }

    return static_cast<int32_t>(julianDay);
}

int32_t GregorianCalendar::handleGetMonthLength(int32_t extendedYear, int32_t month)  const
{
    // If the month is out of range, adjust it into range, and
    // modify the extended year value accordingly.
    if (month < 0 || month > 11) {
        extendedYear += ClockMath::floorDivide(month, 12, month);
    }

    return isLeapYear(extendedYear) ? kLeapMonthLength[month] : kMonthLength[month];
}

int32_t GregorianCalendar::handleGetYearLength(int32_t eyear) const {
    return isLeapYear(eyear) ? 366 : 365;
}

int32_t
GregorianCalendar::monthLength(int32_t month) const
{
    int32_t year = internalGet(UCAL_EXTENDED_YEAR);
    return handleGetMonthLength(year, month);
}

// -------------------------------------

int32_t
GregorianCalendar::monthLength(int32_t month, int32_t year) const
{
    return isLeapYear(year) ? kLeapMonthLength[month] : kMonthLength[month];
}

// -------------------------------------

int32_t
GregorianCalendar::yearLength(int32_t year) const
{
    return isLeapYear(year) ? 366 : 365;
}

// -------------------------------------

int32_t
GregorianCalendar::yearLength() const
{
    return isLeapYear(internalGet(UCAL_YEAR)) ? 366 : 365;
}

// -------------------------------------

/**
* After adjustments such as add(MONTH), add(YEAR), we don't want the
* month to jump around.  E.g., we don't want Jan 31 + 1 month to go to Mar
* 3, we want it to go to Feb 28.  Adjustments which might run into this
* problem call this method to retain the proper month.
*/
void
GregorianCalendar::pinDayOfMonth()
{
    int32_t monthLen = monthLength(internalGet(UCAL_MONTH));
    int32_t dom = internalGet(UCAL_DATE);
    if(dom > monthLen)
        set(UCAL_DATE, monthLen);
}

// -------------------------------------

UBool
GregorianCalendar::validateFields() const
{
    for (int32_t field = 0; field < UCAL_FIELD_COUNT; field++) {
        // Ignore DATE and DAY_OF_YEAR which are handled below
        if (field != UCAL_DATE &&
            field != UCAL_DAY_OF_YEAR &&
            isSet((UCalendarDateFields)field) &&
            ! boundsCheck(internalGet((UCalendarDateFields)field), (UCalendarDateFields)field))
            return FALSE;
    }

    // Values differ in Least-Maximum and Maximum should be handled
    // specially.
    if (isSet(UCAL_DATE)) {
        int32_t date = internalGet(UCAL_DATE);
        if (date < getMinimum(UCAL_DATE) ||
            date > monthLength(internalGet(UCAL_MONTH))) {
                return FALSE;
            }
    }

    if (isSet(UCAL_DAY_OF_YEAR)) {
        int32_t days = internalGet(UCAL_DAY_OF_YEAR);
        if (days < 1 || days > yearLength()) {
            return FALSE;
        }
    }

    // Handle DAY_OF_WEEK_IN_MONTH, which must not have the value zero.
    // We've checked against minimum and maximum above already.
    if (isSet(UCAL_DAY_OF_WEEK_IN_MONTH) &&
        0 == internalGet(UCAL_DAY_OF_WEEK_IN_MONTH)) {
            return FALSE;
        }

        return TRUE;
}

// -------------------------------------

UBool
GregorianCalendar::boundsCheck(int32_t value, UCalendarDateFields field) const
{
    return value >= getMinimum(field) && value <= getMaximum(field);
}

// -------------------------------------

UDate
GregorianCalendar::getEpochDay(UErrorCode& status)
{
    complete(status);
    // Divide by 1000 (convert to seconds) in order to prevent overflow when
    // dealing with UDate(Long.MIN_VALUE) and UDate(Long.MAX_VALUE).
    double wallSec = internalGetTime()/1000 + (internalGet(UCAL_ZONE_OFFSET) + internalGet(UCAL_DST_OFFSET))/1000;

    return ClockMath::floorDivide(wallSec, kOneDay/1000.0);
}

// -------------------------------------

// -------------------------------------

/**
* Compute the julian day number of the day BEFORE the first day of
* January 1, year 1 of the given calendar.  If julianDay == 0, it
* specifies (Jan. 1, 1) - 1, in whatever calendar we are using (Julian
* or Gregorian).
*/
double GregorianCalendar::computeJulianDayOfYear(UBool isGregorian,
                                                 int32_t year, UBool& isLeap)
{
    isLeap = year%4 == 0;
    int32_t y = year - 1;
    double julianDay = 365.0*y + ClockMath::floorDivide(y, 4) + (kJan1_1JulianDay - 3);

    if (isGregorian) {
        isLeap = isLeap && ((year%100 != 0) || (year%400 == 0));
        // Add 2 because Gregorian calendar starts 2 days after Julian calendar
        julianDay += Grego::gregorianShift(year);
    }

    return julianDay;
}

// /**
//  * Compute the day of week, relative to the first day of week, from
//  * 0..6, of the current DOW_LOCAL or DAY_OF_WEEK fields.  This is
//  * equivalent to get(DOW_LOCAL) - 1.
//  */
// int32_t GregorianCalendar::computeRelativeDOW() const {
//     int32_t relDow = 0;
//     if (fStamp[UCAL_DOW_LOCAL] > fStamp[UCAL_DAY_OF_WEEK]) {
//         relDow = internalGet(UCAL_DOW_LOCAL) - 1; // 1-based
//     } else if (fStamp[UCAL_DAY_OF_WEEK] != kUnset) {
//         relDow = internalGet(UCAL_DAY_OF_WEEK) - getFirstDayOfWeek();
//         if (relDow < 0) relDow += 7;
//     }
//     return relDow;
// }

// /**
//  * Compute the day of week, relative to the first day of week,
//  * from 0..6 of the given julian day.
//  */
// int32_t GregorianCalendar::computeRelativeDOW(double julianDay) const {
//   int32_t relDow = julianDayToDayOfWeek(julianDay) - getFirstDayOfWeek();
//     if (relDow < 0) {
//         relDow += 7;
//     }
//     return relDow;
// }

// /**
//  * Compute the DOY using the WEEK_OF_YEAR field and the julian day
//  * of the day BEFORE January 1 of a year (a return value from
//  * computeJulianDayOfYear).
//  */
// int32_t GregorianCalendar::computeDOYfromWOY(double julianDayOfYear) const {
//     // Compute DOY from day of week plus week of year

//     // Find the day of the week for the first of this year.  This
//     // is zero-based, with 0 being the locale-specific first day of
//     // the week.  Add 1 to get first day of year.
//     int32_t fdy = computeRelativeDOW(julianDayOfYear + 1);

//     return
//         // Compute doy of first (relative) DOW of WOY 1
//         (((7 - fdy) < getMinimalDaysInFirstWeek())
//          ? (8 - fdy) : (1 - fdy))

//         // Adjust for the week number.
//         + (7 * (internalGet(UCAL_WEEK_OF_YEAR) - 1))

//         // Adjust for the DOW
//         + computeRelativeDOW();
// }

// -------------------------------------

double
GregorianCalendar::millisToJulianDay(UDate millis)
{
    return (double)kEpochStartAsJulianDay + ClockMath::floorDivide(millis, (double)kOneDay);
}

// -------------------------------------

UDate
GregorianCalendar::julianDayToMillis(double julian)
{
    return (UDate) ((julian - kEpochStartAsJulianDay) * (double) kOneDay);
}

// -------------------------------------

int32_t
GregorianCalendar::aggregateStamp(int32_t stamp_a, int32_t stamp_b)
{
    return (((stamp_a != kUnset && stamp_b != kUnset)
        ? uprv_max(stamp_a, stamp_b)
        : (int32_t)kUnset));
}

// -------------------------------------

/**
* Roll a field by a signed amount.
* Note: This will be made public later. [LIU]
*/

void
GregorianCalendar::roll(EDateFields field, int32_t amount, UErrorCode& status) {
    roll((UCalendarDateFields) field, amount, status);
}

void
GregorianCalendar::roll(UCalendarDateFields field, int32_t amount, UErrorCode& status)
{
    if((amount == 0) || U_FAILURE(status)) {
        return;
    }

    // J81 processing. (gregorian cutover)
    UBool inCutoverMonth = FALSE;
    int32_t cMonthLen=0; // 'c' for cutover; in days
    int32_t cDayOfMonth=0; // no discontinuity: [0, cMonthLen)
    double cMonthStart=0.0; // in ms

    // Common code - see if we're in the cutover month of the cutover year
    if(get(UCAL_EXTENDED_YEAR, status) == fGregorianCutoverYear) {
        switch (field) {
        case UCAL_DAY_OF_MONTH:
        case UCAL_WEEK_OF_MONTH:
            {
                int32_t max = monthLength(internalGet(UCAL_MONTH));
                UDate t = internalGetTime();
                // We subtract 1 from the DAY_OF_MONTH to make it zero-based, and an
                // additional 10 if we are after the cutover. Thus the monthStart
                // value will be correct iff we actually are in the cutover month.
                cDayOfMonth = internalGet(UCAL_DAY_OF_MONTH) - ((t >= fGregorianCutover) ? 10 : 0);
                cMonthStart = t - ((cDayOfMonth - 1) * kOneDay);
                // A month containing the cutover is 10 days shorter.
                if ((cMonthStart < fGregorianCutover) &&
                    (cMonthStart + (cMonthLen=(max-10))*kOneDay >= fGregorianCutover)) {
                        inCutoverMonth = TRUE;
                    }
            }
            break;
        default:
            ;
        }
    }

    switch (field) {
    case UCAL_WEEK_OF_YEAR: {
        // Unlike WEEK_OF_MONTH, WEEK_OF_YEAR never shifts the day of the
        // week.  Also, rolling the week of the year can have seemingly
        // strange effects simply because the year of the week of year
        // may be different from the calendar year.  For example, the
        // date Dec 28, 1997 is the first day of week 1 of 1998 (if
        // weeks start on Sunday and the minimal days in first week is
        // <= 3).
        int32_t woy = get(UCAL_WEEK_OF_YEAR, status);
        // Get the ISO year, which matches the week of year.  This
        // may be one year before or after the calendar year.
        int32_t isoYear = get(UCAL_YEAR_WOY, status);
        int32_t isoDoy = internalGet(UCAL_DAY_OF_YEAR);
        if (internalGet(UCAL_MONTH) == UCAL_JANUARY) {
            if (woy >= 52) {
                isoDoy += handleGetYearLength(isoYear);
            }
        } else {
            if (woy == 1) {
                isoDoy -= handleGetYearLength(isoYear - 1);
            }
        }
        woy += amount;
        // Do fast checks to avoid unnecessary computation:
        if (woy < 1 || woy > 52) {
            // Determine the last week of the ISO year.
            // We do this using the standard formula we use
            // everywhere in this file.  If we can see that the
            // days at the end of the year are going to fall into
            // week 1 of the next year, we drop the last week by
            // subtracting 7 from the last day of the year.
            int32_t lastDoy = handleGetYearLength(isoYear);
            int32_t lastRelDow = (lastDoy - isoDoy + internalGet(UCAL_DAY_OF_WEEK) -
                getFirstDayOfWeek()) % 7;
            if (lastRelDow < 0) lastRelDow += 7;
            if ((6 - lastRelDow) >= getMinimalDaysInFirstWeek()) lastDoy -= 7;
            int32_t lastWoy = weekNumber(lastDoy, lastRelDow + 1);
            woy = ((woy + lastWoy - 1) % lastWoy) + 1;
        }
        set(UCAL_WEEK_OF_YEAR, woy);
        set(UCAL_YEAR_WOY,isoYear);
        return;
                            }

    case UCAL_DAY_OF_MONTH:
        if( !inCutoverMonth ) {
            Calendar::roll(field, amount, status);
            return;
        } else {
            // [j81] 1582 special case for DOM
            // The default computation works except when the current month
            // contains the Gregorian cutover.  We handle this special case
            // here.  [j81 - aliu]
            double monthLen = cMonthLen * kOneDay;
            double msIntoMonth = uprv_fmod(internalGetTime() - cMonthStart +
                amount * kOneDay, monthLen);
            if (msIntoMonth < 0) {
                msIntoMonth += monthLen;
            }
#if defined (U_DEBUG_CAL)
            fprintf(stderr, "%s:%d: roll DOM %d  -> %.0lf ms  \n",
                __FILE__, __LINE__,amount, cMonthLen, cMonthStart+msIntoMonth);
#endif
            setTimeInMillis(cMonthStart + msIntoMonth, status);
            return;
        }

    case UCAL_WEEK_OF_MONTH:
        if( !inCutoverMonth ) {
            Calendar::roll(field, amount, status);
            return;
        } else {
#if defined (U_DEBUG_CAL)
            fprintf(stderr, "%s:%d: roll WOM %d ??????????????????? \n",
                __FILE__, __LINE__,amount);
#endif
            // NOTE: following copied from  the old
            //     GregorianCalendar::roll( WEEK_OF_MONTH )  code

            // This is tricky, because during the roll we may have to shift
            // to a different day of the week.  For example:

            //    s  m  t  w  r  f  s
            //          1  2  3  4  5
            //    6  7  8  9 10 11 12

            // When rolling from the 6th or 7th back one week, we go to the
            // 1st (assuming that the first partial week counts).  The same
            // thing happens at the end of the month.

            // The other tricky thing is that we have to figure out whether
            // the first partial week actually counts or not, based on the
            // minimal first days in the week.  And we have to use the
            // correct first day of the week to delineate the week
            // boundaries.

            // Here's our algorithm.  First, we find the real boundaries of
            // the month.  Then we discard the first partial week if it
            // doesn't count in this locale.  Then we fill in the ends with
            // phantom days, so that the first partial week and the last
            // partial week are full weeks.  We then have a nice square
            // block of weeks.  We do the usual rolling within this block,
            // as is done elsewhere in this method.  If we wind up on one of
            // the phantom days that we added, we recognize this and pin to
            // the first or the last day of the month.  Easy, eh?

            // Another wrinkle: To fix jitterbug 81, we have to make all this
            // work in the oddball month containing the Gregorian cutover.
            // This month is 10 days shorter than usual, and also contains
            // a discontinuity in the days; e.g., the default cutover month
            // is Oct 1582, and goes from day of month 4 to day of month 15.

            // Normalize the DAY_OF_WEEK so that 0 is the first day of the week
            // in this locale.  We have dow in 0..6.
            int32_t dow = internalGet(UCAL_DAY_OF_WEEK) - getFirstDayOfWeek();
            if (dow < 0)
                dow += 7;

            // Find the day of month, compensating for cutover discontinuity.
            int32_t dom = cDayOfMonth;

            // Find the day of the week (normalized for locale) for the first
            // of the month.
            int32_t fdm = (dow - dom + 1) % 7;
            if (fdm < 0)
                fdm += 7;

            // Get the first day of the first full week of the month,
            // including phantom days, if any.  Figure out if the first week
            // counts or not; if it counts, then fill in phantom days.  If
            // not, advance to the first real full week (skip the partial week).
            int32_t start;
            if ((7 - fdm) < getMinimalDaysInFirstWeek())
                start = 8 - fdm; // Skip the first partial week
            else
                start = 1 - fdm; // This may be zero or negative

            // Get the day of the week (normalized for locale) for the last
            // day of the month.
            int32_t monthLen = cMonthLen;
            int32_t ldm = (monthLen - dom + dow) % 7;
            // We know monthLen >= DAY_OF_MONTH so we skip the += 7 step here.

            // Get the limit day for the blocked-off rectangular month; that
            // is, the day which is one past the last day of the month,
            // after the month has already been filled in with phantom days
            // to fill out the last week.  This day has a normalized DOW of 0.
            int32_t limit = monthLen + 7 - ldm;

            // Now roll between start and (limit - 1).
            int32_t gap = limit - start;
            int32_t newDom = (dom + amount*7 - start) % gap;
            if (newDom < 0)
                newDom += gap;
            newDom += start;

            // Finally, pin to the real start and end of the month.
            if (newDom < 1)
                newDom = 1;
            if (newDom > monthLen)
                newDom = monthLen;

            // Set the DAY_OF_MONTH.  We rely on the fact that this field
            // takes precedence over everything else (since all other fields
            // are also set at this point).  If this fact changes (if the
            // disambiguation algorithm changes) then we will have to unset
            // the appropriate fields here so that DAY_OF_MONTH is attended
            // to.

            // If we are in the cutover month, manipulate ms directly.  Don't do
            // this in general because it doesn't work across DST boundaries
            // (details, details).  This takes care of the discontinuity.
            setTimeInMillis(cMonthStart + (newDom-1)*kOneDay, status);
            return;
        }

    default:
        Calendar::roll(field, amount, status);
        return;
    }
}

// -------------------------------------

/**
* Return the minimum value that this field could have, given the current date.
* For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum().
* @param field    the time field.
* @return         the minimum value that this field could have, given the current date.
* @deprecated ICU 2.6. Use getActualMinimum(UCalendarDateFields field) instead.
*/
int32_t GregorianCalendar::getActualMinimum(EDateFields field) const
{
    return getMinimum((UCalendarDateFields)field);
}

int32_t GregorianCalendar::getActualMinimum(EDateFields field, UErrorCode& /* status */) const
{
    return getMinimum((UCalendarDateFields)field);
}

/**
* Return the minimum value that this field could have, given the current date.
* For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum().
* @param field    the time field.
* @return         the minimum value that this field could have, given the current date.
* @draft ICU 2.6.
*/
int32_t GregorianCalendar::getActualMinimum(UCalendarDateFields field, UErrorCode& /* status */) const
{
    return getMinimum(field);
}

// ------------------------------------

/**
* Old year limits were least max 292269054, max 292278994.
*/

/**
* @stable ICU 2.0
*/
int32_t GregorianCalendar::handleGetLimit(UCalendarDateFields field, ELimitType limitType) const {
    return kGregorianCalendarLimits[field][limitType];
}

/**
* Return the maximum value that this field could have, given the current date.
* For example, with the date "Feb 3, 1997" and the DAY_OF_MONTH field, the actual
* maximum would be 28; for "Feb 3, 1996" it s 29.  Similarly for a Hebrew calendar,
* for some years the actual maximum for MONTH is 12, and for others 13.
* @stable ICU 2.0
*/
int32_t GregorianCalendar::getActualMaximum(UCalendarDateFields field, UErrorCode& status) const
{
    /* It is a known limitation that the code here (and in getActualMinimum)
    * won't behave properly at the extreme limits of GregorianCalendar's
    * representable range (except for the code that handles the YEAR
    * field).  That's because the ends of the representable range are at
    * odd spots in the year.  For calendars with the default Gregorian
    * cutover, these limits are Sun Dec 02 16:47:04 GMT 292269055 BC to Sun
    * Aug 17 07:12:55 GMT 292278994 AD, somewhat different for non-GMT
    * zones.  As a result, if the calendar is set to Aug 1 292278994 AD,
    * the actual maximum of DAY_OF_MONTH is 17, not 30.  If the date is Mar
    * 31 in that year, the actual maximum month might be Jul, whereas is
    * the date is Mar 15, the actual maximum might be Aug -- depending on
    * the precise semantics that are desired.  Similar considerations
    * affect all fields.  Nonetheless, this effect is sufficiently arcane
    * that we permit it, rather than complicating the code to handle such
    * intricacies. - liu 8/20/98

    * UPDATE: No longer true, since we have pulled in the limit values on
    * the year. - Liu 11/6/00 */

    switch (field) {

    case UCAL_YEAR:
        /* The year computation is no different, in principle, from the
        * others, however, the range of possible maxima is large.  In
        * addition, the way we know we've exceeded the range is different.
        * For these reasons, we use the special case code below to handle
        * this field.
        *
        * The actual maxima for YEAR depend on the type of calendar:
        *
        *     Gregorian = May 17, 292275056 BC - Aug 17, 292278994 AD
        *     Julian    = Dec  2, 292269055 BC - Jan  3, 292272993 AD
        *     Hybrid    = Dec  2, 292269055 BC - Aug 17, 292278994 AD
        *
        * We know we've exceeded the maximum when either the month, date,
        * time, or era changes in response to setting the year.  We don't
        * check for month, date, and time here because the year and era are
        * sufficient to detect an invalid year setting.  NOTE: If code is
        * added to check the month and date in the future for some reason,
        * Feb 29 must be allowed to shift to Mar 1 when setting the year.
        */
        {
            if(U_FAILURE(status)) return 0;
            Calendar *cal = clone();
            if(!cal) {
                status = U_MEMORY_ALLOCATION_ERROR;
                return 0;
            }

            cal->setLenient(TRUE);

            int32_t era = cal->get(UCAL_ERA, status);
            UDate d = cal->getTime(status);

            /* Perform a binary search, with the invariant that lowGood is a
            * valid year, and highBad is an out of range year.
            */
            int32_t lowGood = kGregorianCalendarLimits[UCAL_YEAR][1];
            int32_t highBad = kGregorianCalendarLimits[UCAL_YEAR][2]+1;
            while ((lowGood + 1) < highBad) {
                int32_t y = (lowGood + highBad) / 2;
                cal->set(UCAL_YEAR, y);
                if (cal->get(UCAL_YEAR, status) == y && cal->get(UCAL_ERA, status) == era) {
                    lowGood = y;
                } else {
                    highBad = y;
                    cal->setTime(d, status); // Restore original fields
                }
            }

            delete cal;
            return lowGood;
        }

    default:
        return Calendar::getActualMaximum(field,status);
    }
}

int32_t GregorianCalendar::handleGetExtendedYear() {
    // the year to return
    int32_t year = kEpochYear;

    // year field to use
    int32_t yearField = UCAL_EXTENDED_YEAR;

    // There are three separate fields which could be used to
    // derive the proper year.  Use the one most recently set.
    if (fStamp[yearField] < fStamp[UCAL_YEAR])
        yearField = UCAL_YEAR;
    if (fStamp[yearField] < fStamp[UCAL_YEAR_WOY])
        yearField = UCAL_YEAR_WOY;

    // based on the "best" year field, get the year
    switch(yearField) {
    case UCAL_EXTENDED_YEAR:
        year = internalGet(UCAL_EXTENDED_YEAR, kEpochYear);
        break;

    case UCAL_YEAR:
        {
            // The year defaults to the epoch start, the era to AD
            int32_t era = internalGet(UCAL_ERA, AD);
            if (era == BC) {
                year = 1 - internalGet(UCAL_YEAR, 1); // Convert to extended year
            } else {
                year = internalGet(UCAL_YEAR, kEpochYear);
            }
        }
        break;

    case UCAL_YEAR_WOY:
        year = handleGetExtendedYearFromWeekFields(internalGet(UCAL_YEAR_WOY), internalGet(UCAL_WEEK_OF_YEAR));
#if defined (U_DEBUG_CAL)
        //    if(internalGet(UCAL_YEAR_WOY) != year) {
        fprintf(stderr, "%s:%d: hGEYFWF[%d,%d] ->  %d\n",
            __FILE__, __LINE__,internalGet(UCAL_YEAR_WOY),internalGet(UCAL_WEEK_OF_YEAR),year);
        //}
#endif
        break;

    default:
        year = kEpochYear;
    }
    return year;
}

int32_t GregorianCalendar::handleGetExtendedYearFromWeekFields(int32_t yearWoy, int32_t woy)
{
    // convert year to extended form
    int32_t era = internalGet(UCAL_ERA, AD);
    if(era == BC) {
        yearWoy = 1 - yearWoy;
    }
    return Calendar::handleGetExtendedYearFromWeekFields(yearWoy, woy);
}

// -------------------------------------

UBool
GregorianCalendar::inDaylightTime(UErrorCode& status) const
{
    if (U_FAILURE(status) || !getTimeZone().useDaylightTime())
        return FALSE;

    // Force an update of the state of the Calendar.
    ((GregorianCalendar*)this)->complete(status); // cast away const

    return (UBool)(U_SUCCESS(status) ? (internalGet(UCAL_DST_OFFSET) != 0) : FALSE);
}

// -------------------------------------

/**
* Return the ERA.  We need a special method for this because the
* default ERA is AD, but a zero (unset) ERA is BC.
*/
int32_t
GregorianCalendar::internalGetEra() const {
    return isSet(UCAL_ERA) ? internalGet(UCAL_ERA) : (int32_t)AD;
}

const char *
GregorianCalendar::getType() const {
    //static const char kGregorianType = "gregorian";

    return "gregorian";
}

/**
 * The system maintains a static default century start date and Year.  They are
 * initialized the first time they are used.  Once the system default century date
 * and year are set, they do not change.
 */
static UDate           gSystemDefaultCenturyStart       = DBL_MIN;
static int32_t         gSystemDefaultCenturyStartYear   = -1;
static icu::UInitOnce  gSystemDefaultCenturyInit        = U_INITONCE_INITIALIZER;

UBool GregorianCalendar::haveDefaultCentury() const
{
    return TRUE;
}

static void U_CALLCONV
initializeSystemDefaultCentury()
{
    // initialize systemDefaultCentury and systemDefaultCenturyYear based
    // on the current time.  They'll be set to 80 years before
    // the current time.
    UErrorCode status = U_ZERO_ERROR;
    GregorianCalendar calendar(status);
    if (U_SUCCESS(status)) {
        calendar.setTime(Calendar::getNow(), status);
        calendar.add(UCAL_YEAR, -80, status);

        gSystemDefaultCenturyStart = calendar.getTime(status);
        gSystemDefaultCenturyStartYear = calendar.get(UCAL_YEAR, status);
    }
    // We have no recourse upon failure unless we want to propagate the failure
    // out.
}

UDate GregorianCalendar::defaultCenturyStart() const {
    // lazy-evaluate systemDefaultCenturyStart
    umtx_initOnce(gSystemDefaultCenturyInit, &initializeSystemDefaultCentury);
    return gSystemDefaultCenturyStart;
}

int32_t GregorianCalendar::defaultCenturyStartYear() const {
    // lazy-evaluate systemDefaultCenturyStartYear
    umtx_initOnce(gSystemDefaultCenturyInit, &initializeSystemDefaultCentury);
    return gSystemDefaultCenturyStartYear;
}

U_NAMESPACE_END

#endif /* #if !UCONFIG_NO_FORMATTING */

//eof


package smo;

/**
 * @author kilian mock
 * @version 08,11.15
 * stellt controler dh.action listener für das lotto programm dar
 */
import java.awt.event.*;

import javax.swing.JToggleButton;
import javax.swing.plaf.basic.BasicBorders.ToggleButtonBorder;
public class Controller implements ActionListener {
	 // Attribute: Model und View
	 private Model m;
	 private View v;

	 /**
	  * Kontruktor: erzeugt Model und View
	  */
	 public Controller() {
		 this.m = new Model();
		 this.v = new View(this.m, this);
	 }

	 /**
	  * @param e der event der den aufruf bewirkt hat
	  *
	  * überprüft von was er aufgerufen wurde und ruft demensprechend die richtigen methoden auf
	  */
	 public void actionPerformed(ActionEvent e) {
		 if (e.getActionCommand() == "neue ziehung")
		 {
			 m.ziehen();
			 v.auswertung();
			 System.out.println("los");
			 return;
		 }
		 if (e.getActionCommand() == "auswerten")
		 {
			 v.auswertung();
			 return;
		 }
		 JToggleButton a = (JToggleButton) e.getSource();
		 v.addToTip(Integer.parseInt(a.getText()));
	 }
	}


<?php

namespace {

from('Hoa')

/**
 * \Hoa\Console\Cursor
 */
-> import('Console.Cursor')

/**
 * \Hoa\Console\Window
 */
-> import('Console.Window');

}

namespace Hoa\Console\Chrome {

/**
 * Class \Hoa\Console\Chrome\Text.
 *
 * This class builts the text layout.
 *
 * @author     Ivan Enderlin <ivan.enderlin@hoa-project.net>
 * @copyright  Copyright © 2007-2014 Ivan Enderlin.
 * @license    New BSD License
 */

class Text {

    /**
     * Align the text to left.
     *
     * @const int
     */
    const ALIGN_LEFT   = 0;

    /**
     * Align the text to right.
     *
     * @const int
     */
    const ALIGN_RIGHT  = 1;

    /**
     * Align the text to center.
     *
     * @const int
     */
    const ALIGN_CENTER = 2;

    /**
     * Colorize a portion of a text.
     * It is kind of a shortcut of \Hoa\Console\Color.
     *
     * @access  public
     * @param   string  $text                Text.
     * @param   string  $attributesBefore    Style to apply.
     * @param   string  $attributesAfter     Reset style.
     * @return  string
     */
    public static function colorize ( $text, $attributesBefore,
                                      $attributesAfter = 'normal' ) {

        ob_start();
        \Hoa\Console\Cursor::colorize($attributesBefore);
        echo $text;
        \Hoa\Console\Cursor::colorize($attributesAfter);
        $out = ob_get_contents();
        ob_end_clean();

        return $out;
    }

    /**
     * Built column from an array.
     * The array has this structure :
     *   array(
     *       array('Firstname', 'Lastname',   'Love', 'Made'   ),
     *       array('Ivan',      'Enderlin',   'Hoa'            ),
     *       array('Rasmus',    'Lerdorf'                      ),
     *       array(null,        'Berners-Lee', null,  'The Web')
     *   )
     * The cell can have a new-line character (\n).
     * The column can have a global alignement, a horizontal and a vertical
     * padding (this horizontal padding is actually the right padding), and a
     * separator.
     * Separator has this form : 'first-column|second-column|third-column|…'.
     * For example : '|: ', will set a ': ' between the first and second column,
     * and nothing for the other.
     *
     * @access  public
     * @param   Array   $line                 The table represented by an array
     *                                        (see the documentation).
     * @param   int     $alignement           The global alignement of the text
     *                                        in cell.
     * @param   int     $horizontalPadding    The horizontal padding (right
     *                                        padding).
     * @param   int     $verticalPadding      The vertical padding.
     * @param   string  $separator            String where each character is a
     *                                        column separator.
     * @return  string
     */
    public static function columnize ( Array $line,
                                       $alignement         = self::ALIGN_LEFT,
                                       $horizontalPadding  = 2,
                                       $verticalPadding    = 0,
                                       $separator          = null ) {

        if(empty($line))
            return '';

        $separator = explode('|', $separator);
        $nbColumn  = 0;
        $nbLine    = count($line);
        $xtraWidth = 2 * ($verticalPadding + 2); // + separator

        // Get the number of column.
        foreach($line as $key => &$column) {

            if(!is_array($column))
                $column = array(0 => $column);

            $handle = count($column);
            $handle > $nbColumn and $nbColumn = $handle;
        }

        $xtraWidth  += $horizontalPadding * $nbColumn;

        // Get the column width.
        $columnWidth = array_fill(0, $nbColumn, 0);

        for($e = 0; $e < $nbColumn; $e++) {

            for($i = 0; $i < $nbLine; $i++) {

                if(!isset($line[$i][$e]))
                    continue;

                $handle = self::getMaxLineWidth($line[$i][$e]);
                $handle > $columnWidth[$e] and $columnWidth[$e] = $handle;
            }
        }

        // If the sum of each column is greater than the window width, we reduce
        // all greaters columns.
        $window    = \Hoa\Console\Window::getSize();
        $envWindow = $window['x'];

        while($envWindow <= ($cWidthSum = $xtraWidth + array_sum($columnWidth))) {

            $diff            = $cWidthSum - $envWindow;
            $max             = max($columnWidth) - $xtraWidth;
            $newWidth        = $max - $diff;
            $i               = array_search(max($columnWidth), $columnWidth);
            $columnWidth[$i] = $newWidth;

            foreach($line as $key => &$c)
                if(isset($c[$i]))
                    $c[$i] = self::wordwrap($c[$i], $newWidth);
        }

        // Manage the horizontal right padding.
        $columnWidth     = array_map(
                               function ( $x ) use ( $horizontalPadding ) {

                                   return $x + 2 * $horizontalPadding;
                               },
                               $columnWidth
                           );

        // Prepare the new table, i.e. a new line (\n) must be a new line in the
        // array (structurally meaning).
        $newLine = array();
        foreach($line as $key => $plpl) {

            $i = self::getMaxLineNumber($plpl);
            while($i-- >= 0)
                $newLine[] = array_fill(0, $nbColumn, null);
        }

        $yek = 0;
        foreach($line as $key => $col) {

            foreach($col as $kkey => $value) {

                if(false === strpos($value, "\n")) {

                    $newLine[$yek][$kkey] = $value;
                    continue;
                }

                foreach(explode("\n", $value) as $foo => $oof)
                    $newLine[$yek + $foo][$kkey] = $oof;
            }

            $i = self::getMaxLineNumber($col);
            $i > 0 and $yek += $i;
            $yek++;
        }

        // Place the column separator.
        foreach($newLine as $key => $col)
            foreach($col as $kkey => $value)
                if(isset($separator[$kkey]))
                    $newLine[$key][$kkey] = $separator[$kkey] .
                                            str_replace(
                                                "\n",
                                                "\n" . $separator[$kkey],
                                                $value
                                            );

        $line   = $newLine;
        unset($newLine);
        $nbLine = count($line);

        // Complete the table with empty cells.
        foreach($line as $key => &$column) {

            $handle = count($column);

            if($nbColumn - $handle > 0)
                $column += array_fill($handle, $nbColumn - $handle, null);
        }

        // Built !
        $out  = null;
        $dash = $alignement === self::ALIGN_LEFT ? '-' : '';
        foreach($line as $key => $handle) {

            $format = null;

            foreach($handle as $i => $hand)
                if(preg_match_all('#(\\e\[[0-9]+m)#', $hand, $match)) {

                    $a = $columnWidth[$i];

                    foreach($match as $m)
                        $a += strlen($m[1]);

                    $format .= '%' . $dash . ($a + floor(count($match) / 2)) . 's';
                }
                else
                    $format .= '%' . $dash . $columnWidth[$i] . 's';

            $format .= str_repeat("\n", $verticalPadding + 1);

            array_unshift($handle, $format);
            $out .= call_user_func_array('sprintf', $handle);
        }

        return $out;
    }

    /**
     * Align a text according a “layer”. The layer width is given in arguments.
     *
     * @access  public
     * @param   string  $text          The text.
     * @param   string  $alignement    The text alignement.
     * @param   int     $width         The layer width.
     * @return  string
     */
    public static function align ( $text,
                                   $alignement = self::ALIGN_LEFT,
                                   $width      = null ) {

        if(null === $width) {

            $window = \Hoa\Console\Window::getSize();
            $width  = $window['x'];
        }

        $out = null;

        switch($alignement) {

            case self::ALIGN_LEFT:
                $out .= sprintf('%-' . $width . 's', self::wordwrap($text, $width));
              break;

            case self::ALIGN_CENTER:
                foreach(explode("\n", self::wordwrap($text, $width)) as $key => $value)
                    $out .= str_repeat(' ', ceil(($width - strlen($value)) / 2)) .
                            $value .  "\n";
              break;

            case self::ALIGN_RIGHT:
            default:
                foreach(explode("\n", self::wordwrap($text, $width)) as $key => $value)
                    $out .= sprintf('%' . $width . 's' . "\n", $value);
              break;
        }

        return $out;
    }

    /**
     * Get the maximum line width.
     *
     * @access  protected
     * @param   mixed      $lines    The line (or group of lines).
     * @return  int
     */
    protected static function getMaxLineWidth ( $lines ) {

        if(!is_array($lines))
            $lines = array(0 => $lines);

        $width = 0;

        foreach($lines as $foo => $line)
            foreach(explode("\n", $line) as $fooo => $lin) {

                $lin = preg_replace('#\\e\[[0-9]+m#', '', $lin);
                strlen($lin) > $width and $width = strlen($lin);
            }

        return $width;
    }

    /**
     * Get the maximum line number (count the new-line character).
     *
     * @access  protected
     * @param   mixed      $lines    The line (or group of lines).
     * @return  int
     */
    protected static function getMaxLineNumber ( $lines ) {

        if(!is_array($lines))
            $lines = array(0 => $lines);

        $number = 0;

        foreach($lines as $foo => $line)
            substr_count($line, "\n") > $number and
                $number = substr_count($line, "\n");

        return $number;
    }

    /**
     * My own wordwrap (just force the wordwrap() $cut parameter)..
     *
     * @access  public
     * @param   string  $text     Text to wrap.
     * @param   int     $width    Line width.
     * @param   string  $break    String to make the break.
     * @return  string
     */
    public static function wordwrap ( $text, $width = null, $break = "\n" ) {

        if(null === $width) {

            $window = \Hoa\Console\Window::getSize();
            $width  = $window['x'];
        }

        return wordwrap($text, $width, $break, true);
    }

    /**
     * Underline with a special string.
     *
     * @access  public
     * @param   string  $text       The text to underline.
     * @param   string  $pattern    The string used to underline.
     * @return  string
     */
    public static function underline ( $text, $pattern = '*' ) {

        $text = explode("\n", $text);
        $card = strlen($pattern);

        foreach($text as $key => &$value) {

            $i   = -1;
            $max = strlen($value);
            while($value{++$i} == ' ' && $i < $max);

            $underline = str_repeat(' ', $i) .
                         str_repeat($pattern, strlen(trim($value)) / $card) .
                         str_repeat(' ', strlen($value) - $i - strlen(trim($value)));

            $value .= "\n" . $underline;
        }

        return implode("\n", $text);
    }
}

}


SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
null

### Remarks
null

life/Plantae/Magnoliophyta/Liliopsida/Poales/Bromeliaceae/Pitcairnia/Pitcairnia integrifolia/ Syn. Pitcairnia anthericoides/README.md


/* ==========================================================================
* ALGO STREAK DETECTION
* ========================================================================== */

/* ==========================================================================
* MODULE FILE NAME: function.cpp
*      MODULE TYPE:
*
*         FUNCTION: Function for image elaboration.
*          PURPOSE:
*    CREATION DATE: 20160727
*          AUTHORS: Francesco Diprima
*     DESIGN ISSUE: None
*       INTERFACES: None
*     SUBORDINATES: None.
*
*          HISTORY: See table below.
*
* 27-Jul-2016 | Francesco Diprima | 0.0 |
* Initial creation of this file.
*
* ========================================================================== */

/* ==========================================================================
* INCLUDES
* ========================================================================== */
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv/highgui.h>
#include "opencv2/gpu/gpu.hpp"
#include "externalClass.cu" // important to include .cu file, not header file

#include "function_GPU.h"
#include "macros.h"

/* ==========================================================================
* MODULE PRIVATE MACROS
* ========================================================================== */

/* ==========================================================================
* MODULE PRIVATE TYPE DECLARATIONS
* ========================================================================== */

/* ==========================================================================
* STATIC VARIABLES FOR MODULE
* ========================================================================== */

/* ==========================================================================
* STATIC MEMBERS
* ========================================================================== */

/* ==========================================================================
* NAME SPACE
* ========================================================================== */

/* ==========================================================================
*        FUNCTION NAME: backgroundEstimation
* FUNCTION DESCRIPTION: Background Estimation
*        CREATION DATE: 20160727
*              AUTHORS: Francesco Diprima
*           INTERFACES: None
*         SUBORDINATES: None
* ========================================================================== */
cv::gpu::GpuMat backgroundEstimation(const cv::gpu::GpuMat& imgInOr, const cv::Point backCnt, cv::Mat& meanBg, cv::Mat& stdBg)
{
  cv::gpu::GpuMat imgIn = imgInOr.clone();
  size_t backSzR = static_cast<size_t>(::round(imgIn.rows / backCnt.y));
  size_t backSzC = static_cast<size_t>(::round(imgIn.cols / backCnt.x));

  std::vector<int> vBackSrow;
  std::vector<int> vBackScol;

  for (size_t o = 0; o < backCnt.y; ++o)
  {
    vBackSrow.push_back(backSzR*o);
  }
  vBackSrow.push_back(imgIn.rows);

  for (size_t o = 0; o < backCnt.x; ++o)
  {
    vBackScol.push_back(backSzC*o);
  }
  vBackScol.push_back(imgIn.cols);

  cv::gpu::GpuMat outImg = cv::gpu::createContinuous(imgIn.rows, imgIn.cols, imgIn.type());
  //in cpu braso a zero

  for (size_t i = 0; i < backCnt.y; ++i)
  {
    for (size_t j = 0; j < backCnt.x; ++j)
    {
      const cv::Point ptTL = {vBackScol.at(j), vBackSrow.at(i)};
      const cv::Point ptBR = {vBackScol.at(j+1), vBackSrow.at(i+1)};

      cv::Rect region_of_interest = cv::Rect(ptTL, ptBR);
      cv::gpu::GpuMat imgPart = imgIn(region_of_interest);
      cv::gpu::GpuMat imgPartTh = cv::gpu::createContinuous(imgPart.rows, imgPart.cols, imgPart.type());
      //in cpu braso a zero
      cv::gpu::GpuMat imgPart2 = cv::gpu::createContinuous(imgPart.rows, imgPart.cols, imgPart.type());

      float oldStd=0;
      float diffPercStd = 1;

      cv::Scalar bg_mean = 0;
      cv::Scalar bg_std = 0;
      cv::gpu::meanStdDev(imgPart, bg_mean, bg_std);

      meanBg.at<double>(i, j) = bg_mean.val[0];
      //meanBg.at<double>(i,j) = *(cv::mean(imgPart, cv::noArray()).val); Not exist mean for gpu

      while (diffPercStd>0.2f)
      {
        cv::Scalar meanBGmod = 0;
        cv::Scalar stdBGs = 0;
        cv::gpu::meanStdDev(imgPart, meanBGmod, stdBGs);

        stdBg.at<double>(i,j) = stdBGs.val[0];//*(stdBGs.val);

        double threshH = meanBg.at<double>(i,j)+2.5*stdBg.at<double>(i,j);//3

        double maxval = 1.0;
        double asdf = cv::gpu::threshold(imgPart, imgPartTh, threshH, maxval, cv::THRESH_BINARY_INV);

        cv::gpu::multiply(imgPart, imgPartTh, imgPart2, cv::gpu::Stream::Null());

        diffPercStd = ::abs((stdBg.at<double>(i,j)-oldStd)/stdBg.at<double>(i,j));
        oldStd=stdBg.at<double>(i,j);
      }

      /*cv::gpu::GpuMat img_RoI = outImg(region_of_interest);
      imgPart2.copyTo(img_RoI);
      //imgPart2.copyTo(outImg(region_of_interest).ptr());*/

      /*externalClass kernelCUDA;
      kernelCUDA.fillImgCUDAKernel(imgPart2, outImg, ptTL.x, ptTL.y, ptBR.x, ptBR.y);*/

    }
  }

#if SPD_FIGURE_1
  cv::Mat result_host;
  outImg.download(result_host);
  // Create a window for display.
  namedWindow("Background estimation", cv::WINDOW_NORMAL);
  imshow("Background estimation", result_host);
  cv::waitKey(0);
#endif

  return outImg;
}

/* ==========================================================================
*        FUNCTION NAME: gaussianFilter
* FUNCTION DESCRIPTION: Gaussian lowpass filter
*        CREATION DATE: 20160727
*              AUTHORS: Francesco Diprima
*           INTERFACES: None
*         SUBORDINATES: None
* ========================================================================== */
cv::gpu::GpuMat gaussianFilter(const cv::gpu::GpuMat& imgIn, int hsize[2], double sigma)
{
  //cv::gpu::GpuMat imgOut;
  cv::gpu::GpuMat imgOut =
    cv::gpu::createContinuous(imgIn.rows, imgIn.cols, imgIn.type());

  cv::Size h = { hsize[0], hsize[1] };

  int columnBorderType=-1;
  cv::gpu::GaussianBlur(imgIn, imgOut, h, sigma, sigma, cv::BORDER_DEFAULT, columnBorderType);

#if SPD_FIGURE_1
  cv::Mat result_host;
  imgOut.download(result_host);
  // Create a window for display.
  namedWindow("Gaussain filter GPU", cv::WINDOW_NORMAL);
  imshow("Gaussain filter GPU", result_host);
  cv::waitKey(0);
#endif

  return imgOut;
}

/* ==========================================================================
*        FUNCTION NAME: subtractImage
* FUNCTION DESCRIPTION: Subtraction of images, matrix-matrix difference.
*        CREATION DATE: 20160727
*              AUTHORS: Francesco Diprima
*           INTERFACES: None
*         SUBORDINATES: None
* ========================================================================== */
cv::gpu::GpuMat subtractImage(const cv::gpu::GpuMat& imgA, const cv::gpu::GpuMat& imgB)
{
  cv::gpu::GpuMat imgOut =
    cv::gpu::createContinuous(imgA.rows, imgA.cols, imgA.type());

  cv::gpu::subtract(imgA, imgB, imgOut);

#if SPD_FIGURE_1
  cv::Mat result_host;
  imgOut.download(result_host);
  // Create a window for display.
  namedWindow("Subtracted image GPU", cv::WINDOW_NORMAL);
  imshow("Subtracted image GPU", result_host);
  cv::waitKey(0);
#endif

  return imgOut;
}

/* ==========================================================================
*        FUNCTION NAME: addiction
* FUNCTION DESCRIPTION: Addiction of images, matrix-matrix addiction.
*        CREATION DATE: 20160727
*              AUTHORS: Francesco Diprima
*           INTERFACES: None
*         SUBORDINATES: None
* ========================================================================== */
cv::gpu::GpuMat addiction(const cv::gpu::GpuMat& imgA, const cv::gpu::GpuMat& imgB)
{
  cv::gpu::GpuMat imgOut =
    cv::gpu::createContinuous(imgA.rows, imgA.cols, imgA.type());

  cv::gpu::add(imgA, imgB, imgOut);

#if SPD_FIGURE_1
  cv::Mat result_host;
  imgOut.download(result_host);
  // Create a window for display.
  namedWindow("Subtracted image GPU", cv::WINDOW_NORMAL);
  imshow("Subtracted image GPU", result_host);
  cv::waitKey(0);
#endif

  return imgOut;
}

/* ==========================================================================
*        FUNCTION NAME: morphologyOpen
* FUNCTION DESCRIPTION: Morphology opening
*        CREATION DATE: 20160727
*              AUTHORS: Francesco Diprima
*           INTERFACES: None
*         SUBORDINATES: None
* ========================================================================== */
cv::gpu::GpuMat morphologyOpen(const cv::gpu::GpuMat& imgIn, int dimLine, double teta_streak)
{
  //cv::gpu::GpuMat imgOut;
  cv::gpu::GpuMat imgOut =
    cv::gpu::createContinuous(imgIn.rows, imgIn.cols, imgIn.type());

  int iter = 1;
  cv::Point anchor = cv::Point(-1, -1);

  //InputArray kernel;
  cv::Mat horizontalStructure = getStructuringElement(cv::MORPH_RECT, cv::Size(dimLine, 1));

  cv::gpu::morphologyEx(imgIn, imgOut, cv::MORPH_OPEN, horizontalStructure, anchor, iter);

#if SPD_FIGURE_1
  cv::Mat result_host;
  imgOut.download(result_host);
  // Create a window for display.
  namedWindow("Morphology opening with rectangular kernel GPU", cv::WINDOW_NORMAL);
  imshow("Morphology opening with rectangular kernel GPU", result_host);
  cv::waitKey(0);
#endif

  return imgOut;
}

/* ==========================================================================
*        FUNCTION NAME: morphologyOpen
* FUNCTION DESCRIPTION: Morphology opening with circular structuring element
*        CREATION DATE: 20160727
*              AUTHORS: Francesco Diprima
*           INTERFACES: None
*         SUBORDINATES: None
* ========================================================================== */
cv::gpu::GpuMat morphologyOpen(const cv::gpu::GpuMat& imgIn, int rad)
{
  cv::gpu::GpuMat imgOut =
    cv::gpu::createContinuous(imgIn.rows, imgIn.cols, imgIn.type());

  int iter = 1;
  cv::Point anchor = cv::Point(-1, -1);
  cv::Size size = cv::Size(rad, rad);

  //InputArray kernel;
  cv::Mat horizontalStructure = getStructuringElement(cv::MORPH_ELLIPSE, size, anchor);

  cv::gpu::morphologyEx(imgIn, imgOut, cv::MORPH_OPEN, horizontalStructure, anchor, iter);

#if SPD_FIGURE_1
  cv::Mat result_host;
  imgOut.download(result_host);
  // Create a window for display.
  namedWindow("Morphology opening with circular kernel", cv::WINDOW_NORMAL);
  imshow("Morphology opening with circular kernel", result_host);
  cv::waitKey(0);
#endif

  return imgOut;
}

/* ==========================================================================
*        FUNCTION NAME: binarization
* FUNCTION DESCRIPTION: Image binarization
*        CREATION DATE: 20160727
*              AUTHORS: Francesco Diprima
*           INTERFACES: None
*         SUBORDINATES: None
* ========================================================================== */
cv::gpu::GpuMat binarization(const cv::gpu::GpuMat& imgIn)
{
  //cv::gpu::GpuMat imgOut, binImg;

  cv::gpu::GpuMat imgOut =
    cv::gpu::createContinuous(imgIn.rows, imgIn.cols, imgIn.type());

  cv::gpu::GpuMat binImg =
    cv::gpu::createContinuous(imgIn.rows, imgIn.cols, imgIn.type());

  double maxval = 255.0;
  double level = 0.0;

  level = cv::gpu::threshold(imgIn, binImg, cv::THRESH_OTSU, maxval, cv::THRESH_BINARY);

  level = level * 2.5;//1.5

  cv::gpu::threshold(imgIn, imgOut, level, maxval, cv::THRESH_BINARY);

#if SPD_FIGURE_1
  /* Create a window for display.
  namedWindow("Binary image", WINDOW_NORMAL);
  imshow("Binary image", binImg);*/

  cv::Mat result_host;
  imgOut.download(result_host);
  // Create a window for display.
  namedWindow("Binary image Otsu threshold GPU", cv::WINDOW_NORMAL);
  imshow("Binary image Otsu threshold GPU", result_host);
  cv::waitKey(0);
#endif

  return imgOut;
}

/* ==========================================================================
*        FUNCTION NAME: binarizationZone
* FUNCTION DESCRIPTION: Image binarization using user threshold
*        CREATION DATE: 20160727
*              AUTHORS: Francesco Diprima
*           INTERFACES: None
*         SUBORDINATES: None
* ========================================================================== */
cv::gpu::GpuMat binarizationZone(const cv::gpu::GpuMat& imgIn, const cv::Point zoneCnt, const cv::Mat& level)
{
  size_t zoneSzR = static_cast<size_t>(::round(imgIn.rows / zoneCnt.y));
  size_t zoneSzC = static_cast<size_t>(::round(imgIn.cols / zoneCnt.x));

  std::vector<int> vBackSrow;
  std::vector<int> vBackScol;

  for (size_t o = 0; o < zoneCnt.y; ++o)
  {
    vBackSrow.push_back(zoneSzR*o);
  }
  vBackSrow.push_back(imgIn.rows);

  for (size_t o = 0; o < zoneCnt.x; ++o)
  {
    vBackScol.push_back(zoneSzC*o);
  }
  vBackScol.push_back(imgIn.cols);

  cv::gpu::GpuMat outImg = cv::gpu::createContinuous(imgIn.rows, imgIn.cols, imgIn.type());

  for (size_t i = 0; i < zoneCnt.y; ++i)
  {
    for (size_t j = 0; j < zoneCnt.x; ++j)
    {
      const cv::Point ptTL = { vBackScol.at(j), vBackSrow.at(i) };
      const cv::Point ptBR = { vBackScol.at(j + 1), vBackSrow.at(i + 1) };

      cv::Rect region_of_interest = cv::Rect(ptTL, ptBR);
      cv::gpu::GpuMat imgPart = imgIn(region_of_interest);
      cv::gpu::GpuMat imgPartTh = cv::gpu::createContinuous(imgPart.rows, imgPart.cols, imgPart.type());

      double maxval = 255.0;
      double asdf = cv::gpu::threshold(imgPart, imgPartTh, level.at<double>(i,j), maxval, cv::THRESH_BINARY);

      cv::gpu::GpuMat img_RoI = outImg(region_of_interest);
      imgPart.copyTo(img_RoI);
    }
  }

#if SPD_FIGURE_1
  cv::Mat result_host;
  outImg.download(result_host);
  namedWindow("Binary image user thresholdZones", cv::WINDOW_NORMAL);
  imshow("Binary image user thresholdZones", result_host);
  cv::waitKey(0);
#endif

  return outImg;
}

#if 0
/* ==========================================================================
*        FUNCTION NAME: binarizationDiffTh
* FUNCTION DESCRIPTION: Image binarization
*        CREATION DATE: 20160727
*              AUTHORS: Francesco Diprima
*           INTERFACES: None
*         SUBORDINATES: None
* ========================================================================== */
cv::gpu::GpuMat binarizationDiffTh(cv::gpu::GpuMat& imgIn, int flag)
{
  cv::gpu::GpuMat imgOut, binImg;
  cv::gpu::GpuMat subBImgTL, subBImgTR, subBImgBL, subBImgBR;

  cv::Point imgSz = { imgIn.rows, imgIn.cols };

  /*int dims[] = { 5, 1 };
  cv::Mat level(2, dims, CV_64F);*/

  cv::gpu::GpuMat subImageTL(imgIn, cv::Rect(0, 0, imgIn.cols/2, imgIn.rows/2));
  cv::gpu::GpuMat subImageTR(imgIn, cv::Rect(0, imgIn.rows/2, imgIn.cols/2, imgIn.rows/2));
  cv::gpu::GpuMat subImageBL(imgIn, cv::Rect(0, imgIn.rows/2, imgIn.cols/2, imgIn.rows/2));
  cv::gpu::GpuMat subImageBR(imgIn, cv::Rect(imgIn.cols/2, imgIn.rows/2, imgIn.cols/2, imgIn.rows/2));

  double maxval = 1.0;
  double level1 = 0.0;
  double level2 = 0.0;
  double level3 = 0.0;
  double level4 = 0.0;
  double level5 = 0.0;

  level1 = cv::gpu::threshold(subImageTL, subBImgTL, cv::THRESH_OTSU, maxval, cv::THRESH_BINARY);
  level2 = cv::gpu::threshold(subImageTR, subBImgTR, cv::THRESH_OTSU, maxval, cv::THRESH_BINARY);
  level3 = cv::gpu::threshold(subImageBL, subBImgBL, cv::THRESH_OTSU, maxval, cv::THRESH_BINARY);
  level4 = cv::gpu::threshold(subImageBR, subBImgBR, cv::THRESH_OTSU, maxval, cv::THRESH_BINARY);
  level5 = cv::gpu::threshold(binImg    ,    imgOut, cv::THRESH_OTSU, maxval, cv::THRESH_BINARY);

  level1 = level1 *1.5;
  level2 = level2 *1.5;
  level3 = level3 *1.5;
  level4 = level4 *1.5;
  level5 = level5 *1.5;

  /*media mediana ordinamento */

  /*da completare*/

  if (SPD_FIGURE_1)
  {
    // Create a window for display.
    namedWindow("Binary image", cv::WINDOW_NORMAL);
    imshow("Binary image", imgOut);
  }

  return imgOut;
}
#endif

/* ==========================================================================
*        FUNCTION NAME: hough
* FUNCTION DESCRIPTION: Hough transform
*        CREATION DATE: 20160911
*              AUTHORS: Francesco Diprima
*           INTERFACES: None
*         SUBORDINATES: None
* ========================================================================== */
std::vector<std::pair<float, int>> hough(const cv::gpu::GpuMat& imgIn)
{
  double rho = 1; //0.5;
  double theta = 2*CV_PI / 180; //CV_PI / (2*180); r:pi=g:180
  int threshold = 60;

  //std::vector<cv::Vec2f> houghVal;
  cv::gpu::GpuMat houghVal;
  bool doSort = true;
  int maxLines = 5;

  cv::gpu::HoughLines(imgIn, houghVal, rho, theta, threshold, doSort, maxLines);

#if 0
  // Select the inclination angles
  std::vector<float> angle;
  for (size_t i = 0; i < houghVal.size(); ++i)
  {
    angle.push_back(houghVal.at(i)[1]);
  }
  angle.push_back(CV_PI / 2); //Force research at 0\B0

  int count = 0;
  std::vector<std::pair<float, int>> countAngle;
  for (size_t i = 0; i < houghVal.size(); ++i)
  {
    int a = std::count(angle.begin(), angle.end(), angle.at(i));
    countAngle.push_back(std::make_pair(angle.at(i), a));
    count = count + a;
    if (houghVal.size() == count) break;
  }
#else
  std::vector<std::pair<float, int>> countAngle;
#endif

#if SPD_FIGURE_1
    cv::Mat color_dst;
    cvtColor( imgIn, color_dst, CV_GRAY2BGR );
    double minLineLength = 20;
    double maxLineGap = 1;
    std::vector<cv::Vec4i> lines;
    HoughLinesP(imgIn, lines, rho, theta, threshold, minLineLength, maxLineGap);

    for (size_t i = 0; i < lines.size(); i++) {
      line(color_dst, cv::Point(lines[i][0], lines[i][1]),
        cv::Point(lines[i][2], lines[i][3]), cv::Scalar(0, 0, 255), 3, 8);
    }

    // Create a window for display.
    namedWindow("Hough transform", cv::WINDOW_NORMAL);
    imshow("Hough transform", color_dst);
    cv::waitKey(0);
#endif

  return countAngle;
}

/* ==========================================================================
*        FUNCTION NAME: convolution
* FUNCTION DESCRIPTION: Image convolution
*        CREATION DATE: 20160727
*              AUTHORS: Francesco Diprima
*           INTERFACES: None
*         SUBORDINATES: None
* ========================================================================== */
cv::gpu::GpuMat convolution(const cv::gpu::GpuMat& imgIn, const cv::Mat& kernel, double thresh)
{
  //cv::gpu::GpuMat imgOut, convImg;
  cv::gpu::GpuMat imgOut =
    cv::gpu::createContinuous(imgIn.rows, imgIn.cols, imgIn.type());

  /*cv::gpu::GpuMat convImg =
    cv::gpu::createContinuous(imgIn.rows, imgIn.cols, imgIn.type());*/
  cv::gpu::GpuMat convImg;

  /*kernel_size = 3 + 2 * (ind % 5);
  kernel = Mat::ones(kernel_size, kernel_size, CV_32F) / (float)(kernel_size*kernel_size);*/

  int ddepth = -1;
  cv::Point anchor = cv::Point(-1, -1);
  cv::gpu::Stream stream;
  stream.Null();

  std::cout << "prima di filter2d " << std::endl;
  cv::gpu::filter2D(imgIn, convImg, ddepth, kernel, anchor, cv::BORDER_DEFAULT);
  std::cout << "dopo di filter2d " << std::endl;
/*thresh=1;
  cv::gpu::boxFilter(const_cast<const cv::gpu::GpuMat&>(imgIn), convImg, ddepth, kernel, anchor, stream);
*/

/*cv::Size ksize(3, 3);
  cv::gpu::blur(const_cast<const cv::gpu::GpuMat&>(imgIn), convImg, ksize, anchor, stream);
*/

  double maxval = 255.0;

  cv::gpu::threshold(convImg, imgOut, thresh, maxval, cv::THRESH_BINARY);
//cv::gpu::threshold(imgIn, imgOut, thresh, maxval, cv::THRESH_BINARY);

#if SPD_FIGURE_1
    cv::Mat result_host;
    imgOut.download(result_host);
    // Create a window for display.
    namedWindow("Convolution image GPU", cv::WINDOW_NORMAL);
    imshow("Convolution image GPU", result_host);
#endif

  return imgOut;
}

/* ==========================================================================
*        FUNCTION NAME: iDivUp
* FUNCTION DESCRIPTION: Rounded division
*        CREATION DATE: 20160727
*              AUTHORS: Francesco Diprima
*           INTERFACES: None
*         SUBORDINATES: None
* ========================================================================== */
int iDivUp(int a, int b)
{
  return ((a % b) != 0) ? (a / b + 1) : (a / b);
}

/* ==========================================================================
*        FUNCTION NAME: gpuErrchk
* FUNCTION DESCRIPTION: CUDA error check
*        CREATION DATE: 20160727
*              AUTHORS: Francesco Diprima
*           INTERFACES: None
*         SUBORDINATES: None
* ========================================================================== */
#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, char *file, int line, bool abort=true)
{
    if (code != cudaSuccess)
    {
        fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
        if (abort) exit(code);
    }
}


<?php
/**
 * PopStop is a PHP script that let's you stream your
 * movie collection to your browser.
 *
 * This software is distributed under the MIT License
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Visit http://www.popstop.io for more information
 *
 * @author Sebastian de Kok
 */
class MovieController extends BaseController {

    /**
     * Get a movie from the database by ID
     *
     * @param array $params
     * @return array
     */
    public function getMovieById($params) {
        $this->db->bind(["id" => $params['id']]);
        $movie =  $this->db->fetch("SELECT * FROM movies WHERE movie_id = :id", true);

        return $movie;
    }

    /**
     * Get a random featured movie from the database
     *
     * @return array|string
     */
    public function getFeaturedMovie() {
        $featured = $this->db->fetch('SELECT * FROM movies ORDER BY RANDOM()', true);

        if (!$featured) {
            return 'The database is empty, delete the database to start the installation process.';
        }

        return $featured;
    }

    /**
     * Get all the movies and order them correctly
     *
     * @param array $params
     * @return array
     */
    public function getMovies($params) {

        /** @var int $batch */
        $batch = $this->getSettings()['batch'];

        switch($params['type']) {
            case "date":
                $query = "ORDER BY created_at desc";
                break;
            case "rating":
                $query = "ORDER BY vote_average desc";
                break;
            case "popular":
                $query = "ORDER BY popularity desc";
                break;
        }

        //get current starting point of records
        $position = ($params['is_loaded']);
        $genre = (!empty($params['genre'])) ? $params['genre'] : '';
        $cast = (!empty($params['cast'])) ? $params['cast'] : '';
        $this->db->bind([
            "position" => $position,
            "batch" => $batch,
            "genre" => "%$genre%",
            "cast" => "%$cast%"
        ]);

        $movies =  $this->db->fetch("SELECT * FROM movies INNER JOIN files ON movies.movie_id = files.movie_id
                                     WHERE (',' || genres || ',') LIKE :genre
                                     AND (',' || casts || ',') LIKE :cast
                                     $query LIMIT :position, :batch");

        return ['movies' => $movies, 'batch' => $batch];
    }

    /**
     * Get the movie file location to play in the browser
     *
     * @param array $params
     * @return array
     */
    public function playMovie($params) {
        $this->db->bind(["id" => $params['id']]);
        $result =  $this->db->fetch("SELECT * FROM movies INNER JOIN files
                                     ON movies.movie_id = files.movie_id
                                     WHERE movies.movie_id = :id", true);

        return $result;
    }

    /**
     * Search the database for the movie
     *
     * @param array $params
     * @return array
     */
    public function searchMovies($params) {
        $query = $params['query'];
        $this->db->bind(["query" => "$query*"]);
        $result = $this->db->fetch("SELECT * FROM movies WHERE movies MATCH :query");

        return $result;
    }

    /**
     * Get all the movie genres in the database
     *
     * @return array
     */
    public function getMovieGenres() {
        $genres = $this->db->fetch('SELECT genres FROM movies');

        foreach($genres as $genre) {
            $genres_explode = explode(',', $genre['genres']);
            foreach($genres_explode as $genre) {
                $array[] = $genre;
            }
        }
        /**
         * Sort the genres on alphabetical order
         */
        function sortAlphabetically($a, $b) {
            return strcmp($a, $b);
        }
        usort($array, "sortAlphabetically");

        return array_count_values($array);
    }

    /**
     * Get the movie cast by ID
     *
     * @param array $params
     * @return array
     */
    public function getMovieCastById($params) {
        $this->db->bind(["id" => $params['id']]);
        $movie =  $this->db->fetch("SELECT casts FROM movies WHERE movie_id = :id", true);

        $movieCast = explode(',', $movie['casts']);
        $casts = [];
        foreach($movieCast as $castId)
        {
            $this->db->bind(["cast_id" => $castId]);
            $casts[] = $this->db->fetch("SELECT * FROM casts WHERE cast_id = :cast_id", true);
        }

        return ['casts' => $casts];
    }

    /**
     * Get the movie file location to play in the browser
     *
     * @param array $params
     * @return array
     */
    public function getMovieSubtitles($params) {

        $this->db->bind(["id" => $params['id']]);
        $result =  $this->db->fetch("SELECT * FROM files WHERE movie_id = :id", true);

        return $this->scan->getSubtitles($result['path'], $result['alias']);
    }

    /**
     * Save the current time of the movie
     *
     * @param array $params
     * @return array
     */
    public function saveCurrentTime($params) {
        $this->db->bind([
            "current_at" => $params['current_time'],
            "movie_id" => $params['movie_id']
        ]);

        $this->db->update("UPDATE movies SET resume_at = :current_at WHERE movie_id = :movie_id");

        return ['saved' => true];
    }

    /**
     * Clean the database with the files that don't exist
     *
     * @return array
     */
    public function cleanDatabase() {
        $files =  $this->db->fetch("SELECT docid, movies.movie_id, target FROM movies LEFT JOIN files
                                    ON movies.movie_id = files.movie_id");

        $i = 0;
        foreach($files as $file) {
           $doc_id = $file['docid'];
           $movie_id = $file['movie_id'];

            if(!file_exists($file['target'])) {
                $this->db->query("DELETE FROM movies WHERE docid = $doc_id; DELETE FROM files WHERE movie_id = $movie_id");
                $i++;
            }
        }

        return ['cleaned' => $i];
    }
}