#include <stdio.h>
#include "types.h"

interp(in,out,attr)

FileValueList *in,*out;
InterpolationAttributes *attr;

{
 double t0,t1,time,coeff[5];
 FileValueList *infile,*outfile;
 ValueList *in_value_ptr[5],*out_value_ptr;
 int total,num;

 num = attr->num;  /* Number of values in each input file */

  switch(attr->type) {

     case LINEAR:

       /* Move along output file list */

       outfile = out;
       while(outfile != NULL) {

          /* Find output times */

          time = outfile->time;

          /* Find location in input list */

          infile = in;

          if(time < infile->time) {
             fprintf(stderr,
                "Out time not supported- before first in time.\n");
             break;
            }

          while(infile->next != NULL && time > infile->next->time) {
             infile = infile->next; 
            }

          if(infile->next == NULL && infile->time < time) {
             fprintf(stderr,
                  "Out time not supported- after last in time.\n");
             break;
            }

          if(infile->time == time) {  /* Right on interp time */
             out_value_ptr = outfile->value.next;
             in_value_ptr[0] = infile->value.next;
             total = 0;

             while(total < num) {
               out_value_ptr->value = in_value_ptr[0]->value;

               total++;
               out_value_ptr = out_value_ptr->next;
               in_value_ptr[0] = in_value_ptr[0]->next;
              }
            }

          else {  /* Do interpolation */

             t1 = infile->next->time;
             t0 = infile->time;
             coeff[0] = (t1 - time)/(t1 - t0);
             coeff[1] = 1.0 - coeff[0];
 
             total = 0;
             out_value_ptr = outfile->value.next;
             in_value_ptr[0] = infile->value.next;
             in_value_ptr[1] = infile->next->value.next;

             while(total < num) {
               out_value_ptr->value = coeff[0]*in_value_ptr[0]->value
                                + coeff[1]*in_value_ptr[1]->value;

               total ++;
               out_value_ptr = out_value_ptr->next;
               in_value_ptr[0] = in_value_ptr[0]->next;
               in_value_ptr[1] = in_value_ptr[1]->next;
              }
            }

          outfile = outfile->next;
         }

       break;

     case CARDINAL:
       spline_interp(in,out,attr);
       break;

     default:
       fprintf(stderr,"Unknown type of interpolation.\n");
       break;

    }
}

