#include "ad_types.h"
#include <stdio.h>
#include <stdlib.h>

void ADIC_GetSeedMatrixFromFile(const char *filename, double ***seedmatrix, int *row_count,  int *column_count)
{
  int i, j;
  FILE *inputfile = fopen(filename,"r");
  fscanf(inputfile, "%d", row_count);
  fscanf(inputfile, "%d", column_count);
  *seedmatrix = (double **) malloc(*row_count * sizeof(double*));
  for(i=0; i< *row_count;i++){
     (*seedmatrix)[i] = (double *) malloc(*column_count * sizeof(double));
     for(j=0; j< *column_count;j++){
       fscanf(inputfile, "%lf", &((*seedmatrix)[i][j])) ;
     } 
  }
  fclose(inputfile);
}

void ADIC_SetIndepArrayFromSeed(DERIV_TYPE *ad_x, double **seedmatrix, int row_count,  int column_count)
{
  int i, j;
  for(i=0; i< row_count;i++){
     for(j=0; j< column_count;j++){
       DERIV_grad(ad_x[i])[j] = seedmatrix[i][j]*1.0;
     } 
     for(j=column_count; j< ADIC_GRADVEC_LENGTH;j++){
       DERIV_grad(ad_x[i])[j] = 0.0;
     }
  }
}

void ADIC_ReadPatternFromFile(const char * filename, int ***lsi_SparsityPattern)
{
  int i, j, column_count, row_count;
  FILE *inputfile = fopen(filename,"r");
  fscanf(inputfile, "%d", &row_count) ; 
  (*lsi_SparsityPattern) = (int **) malloc(row_count * sizeof(int*));
  for(i=0; i< row_count;i++){
     fscanf(inputfile, "%d", &column_count) ; 
     (*lsi_SparsityPattern)[i] = (int *) malloc((column_count+1)*sizeof(int));
     (*lsi_SparsityPattern)[i][0] = column_count;
     for(j=1; j< column_count+1;j++){
        fscanf(inputfile, "%d", &((*lsi_SparsityPattern)[i][j])) ;
     } 
  }
  fclose(inputfile);
}


void ADIC_ReadVertexColorsFromFile(const char *filename, int **vi_RightVertexColors)
{
  int i, count;
  FILE *inputfile = fopen(filename,"r");
  fscanf(inputfile, "%d", &count);
  (*vi_RightVertexColors) = (int *) malloc(count * sizeof(int));
  for(i=0; i< count;i++){
    fscanf(inputfile, "%d", &((*vi_RightVertexColors)[i]));
  }
  fclose(inputfile);
}

void ADIC_RecoverFullJacobian(DERIV_TYPE* ad_x, double** dp2_fullMatrix, int **lsi_SparsityPattern, int lsi_SparsityPattern_row_count, int *vi_RightVertexColors) 
{
  int i, j;  
  for(i=0; i<lsi_SparsityPattern_row_count; i++) {
    for(j=1; j < lsi_SparsityPattern[i][0]+1; j++) {
      dp2_fullMatrix[i][lsi_SparsityPattern[i][j]] = (DERIV_grad(ad_x[i]))[vi_RightVertexColors[lsi_SparsityPattern[i][j]]];
    }
  }
}

