/*
 *              Copyright (C) 2021 by Robert E. Cousins
 *
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions a
 * are met: 
 * 
 * 1. Redistributions of source code must retain the above copyright 
 * notice, this list of conditions and the following disclaimer.
 * 
 * 2. 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.
 * 
 * 3. Neither the name of the copyright holder nor the names of its 
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * 
 * 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 
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
 * 
 *	$Id: sls.c,v 1.3 2021/08/15 16:01:40 rec Exp $
 */

#include <stdio.h>
#include <math.h>
#include "sls.h"

static void 
sls_solve(SLS *p)
{
  double n_real = p->n;         /* make it real for later */

  double num = n_real * p->sum_xy - p->sum_x * p->sum_y;
  double den = n_real * p->sum_xx - p->sum_x * p->sum_x;
  p->b1 = num / den;

  p->b0 = (p->sum_y - p->b1 * p->sum_x)/n_real;

  num = (n_real * p->sum_xy - p->sum_x * p->sum_y);
  num *= (n_real * p->sum_xy - p->sum_y * p->sum_x);
  den = (n_real * p->sum_xx - p->sum_x * p->sum_x);
  den *= (n_real * p->sum_yy - p->sum_y * p->sum_y);
  p->r2 = num/den;
}

void 
sls_model(SLS *p, 		/* our object (private state) */
	  double *b0, 		/* slope */
	  double *b1, 		/* intercept */
	  double *r2)		/* R^2 quality of fit */
{
  if (p->n >= 2)		/* don't compute if not valid */
    sls_solve(p);
  /*
   * Optionally return values
   *
   * Note: if sls_solve() wasn't called, these will be NaNs.
   */
  if (b0 != NULL)
    *b0 = p->b0;		/* slope */
  if (b1 != NULL)
    *b1 = p->b1;		/* intercept */
  if (r2 != NULL)
  *r2 = p->r2;
}

