#include <malloc.h>
#include <stdarg.h>
#include "Main.h"
#include "Util.h"


/* **********************************************************************
 * void *Malloc(int size)
 *   allocate the storage with error checking
 * **********************************************************************/
void *Malloc(int size) {
  void *space;

  if (!(space = malloc(size))) {
    Error("not enough memory");
  }
  return space;
}


/* **********************************************************************
 * void Error(char *fmt, ...)
 *   print an error message and return
 * **********************************************************************/
void Error(char *fmt, ...) {
  va_list args;

  va_start(args, fmt);
  vfprintf(stdout, fmt, args);
  fprintf(stdout, "\n");
  va_end(args);

  exit(1);
}


/* **********************************************************************
 * void Warn(char *fmt, ...)
 *   print a warning message 
 * **********************************************************************/
void Warn(char *fmt, ...) {
  va_list args;

  va_start(args, fmt);
  vfprintf(stdout, fmt, args);
  fprintf(stdout, "\n");
  va_end(args);
}


/* **********************************************************************
 * float RandFrac
 *   emulates drand48
 * **********************************************************************/
float RandFrac() {
  return (float) (lrand48() % 50893) / 50892;
}


/* **********************************************************************
 * float ComputeDist
 *   computes the distance between p1 and p2
 * **********************************************************************/
float ComputeDist(Vector *p1, Vector *p2) {
  float xDiff = p1->x - p2->x;
  float yDiff = p1->y - p2->y;

  return sqrt(xDiff*xDiff + yDiff*yDiff);
}


/* **********************************************************************
 * void ComputeGAcc
 *   computes the gravitational acceleration
 * **********************************************************************/
void ComputeGAcc(Vector *p1, Vector *p2, Vector *acc, float mass, float r) {
  acc->x += (cG*mass*(p1->x - p2->x))/(r*r*r);
  acc->y += (cG*mass*(p1->y - p2->y))/(r*r*r);
}

