/* $Id: fors_point.c,v 1.3 2010-09-14 07:49:30 cizzo Exp $
 *
 * This file is part of the FORS library
 * Copyright (C) 2002-2010 European Southern Observatory
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 */

/*
 * $Author: cizzo $
 * $Date: 2010-09-14 07:49:30 $
 * $Revision: 1.3 $
 * $Name: not supported by cvs2svn $
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <fors_point.h>

#include <fors_utils.h>

/**
 * @defgroup fors_point   2d point
 */

/**@{*/

#define LIST_DEFINE
#undef LIST_ELEM
#define LIST_ELEM fors_point
#include <list.h>

/**
 * @brief  Constructor
 * @param  x          1st coordinate
 * @param  y          2nd coordinate
 * @return  newly allocated point
 */
fors_point *fors_point_new(double x, double y)
{
    fors_point *p = cpl_malloc(sizeof(*p));

    p->x = x;
    p->y = y;

    return p;    
}

#undef cleanup
#define cleanup
/**
 * @brief  Copy constructor
 * @param  p       to duplicate
 * @return  newly allocated point
 */
fors_point *fors_point_duplicate(const fors_point *p)
{
    fors_point *p2 = NULL;
    
    assure( p != NULL, return p2, NULL );

    p2 = cpl_malloc(sizeof(*p2));
    p2->x = p->x;
    p2->y = p->y;

    return p2;
}

/**
 * @brief  Destructor
 * @param  p       to delete
 */
void fors_point_delete(fors_point **p)
{
    if (p && *p) {
        cpl_free(*p); *p = NULL;
    }
    return;
}

#undef cleanup
#define cleanup
/**
 * @brief  Metric
 * @param  p     1st point
 * @param  q     2nd point
 * @return squared distance
 */
double fors_point_distsq(const fors_point *p,
			 const fors_point *q)
{
    assure( p != NULL, return -1, NULL );
    assure( q != NULL, return -1, NULL );

    return (
        (p->x - q->x)*(p->x - q->x) +
        (p->y - q->y)*(p->y - q->y));
}

/**
 * @brief  Equality
 * @param  p     1st point
 * @param  q     2nd point
 * @return true iff points are equal
 */
bool fors_point_equal(const fors_point *p,
		      const fors_point *q)
{
    return fors_point_distsq(p, q) <= DBL_EPSILON;
}


/**@}*/
