#include <stdio.h>
#include <math.h>
#include <stdlib.h>


#define Sign(A) ((A>0)?1:(A<0)?(-1):0)

typedef struct axis_s    { long start; long current; long target; char * ID;} axis_t;
typedef struct axies_s   { long axisCount; axis_t * axii; } axies_t;



void axisInit(axies_t * this) {
 this->axii = NULL;
 this->axisCount = 0;
}

void axisAdd(axies_t * this, int start, int end) {
  this->axisCount++;
  this->axii = realloc(this->axii, sizeof(axis_t) * this->axisCount);
  this->axii[(this->axisCount)-1].start  = start;
  this->axii[(this->axisCount)-1].current  = start;
  this->axii[(this->axisCount)-1].target = end;
}

void dumpaxies(axies_t * this ) {
  long i;
  
  for (i = 0; i < this->axisCount; i++) {
    printf( "%d: %d  %d  %d\n", i, this->axii[i].start, this->axii[i].current, this->axii[i].target);
  }
  printf("\n");
}


void SimotaniouslyLinearlyInterpolateMultiAxis(axies_t * this) {
  int longest;
  int i, j, k;
    
  // set it all up, work out how big our master index is  
  longest = 0;
  for (i = 0; i < this->axisCount; i++) {
    this->axii[i].current = this->axii[i].start;
    if (abs(this->axii[i].target - this->axii[i].start) > abs(longest))   longest = abs(this->axii[i].target - this->axii[i].start);
  }     
   
  for ( i = 0; i <= longest; i++) {
    for (j = 0; j < this->axisCount; j++) {   
    // y2 = y1 + (x2 - x1) * ((y3-y1) / (x3-x1))  ; where X is master, 1 is initial, 2 is current, and 3 is target
      this->axii[j].current = this->axii[j].start + (i * (this->axii[j].target - this->axii[j].start)) / longest;      
        
      printf("%d  ", this->axii[j].current);
    }
    printf("\n");
  }
 
}





int main(void) {

  axies_t axies;

  axisInit( &axies );
  axisAdd(&axies,  2,  27);
  axisAdd(&axies, -4, -18);
  axisAdd(&axies,  9, -10);
  axisAdd(&axies,  -10, 40);
  dumpaxies( &axies );
  SimotaniouslyLinearlyInterpolateMultiAxis( &axies );
  
 
  return 0;

}
