/* convertgeno1.c - Takes output files from filtshortvcf2 and combines them
into a list of SNPs with positions, genotypes and gq scores.
*/

#include <stdio.h>
#include <stdlib.h>
#define SMAX 700000

int main (int argc, char *argv[])
{
  int a, b, nsamp, *chr, **pos, **geno1, **geno2, narg, *S, *Stemp;
  int nextpos, nextsnp();
  double **gq;
  FILE *fileptr;

  if (argc == 1) {
    printf("Usage: convertgeno1 nsamp file[1] ... file[nsamp]\n");
    exit(0);
  }
  narg = 0;
  nsamp = atoi (argv[++narg]);

  pos = (int **) malloc (nsamp * sizeof (int *));
  for (a=0; a<nsamp; ++a)
    pos[a] = (int *) malloc (SMAX * sizeof (int));
  gq = (double **) malloc (nsamp * sizeof (double *));
  for (a=0; a<nsamp; ++a)
    gq[a] = (double *) malloc (SMAX * sizeof (double));
  geno1 = (int **) malloc (nsamp * sizeof (int *));
  for (a=0; a<nsamp; ++a)
    geno1[a] = (int *) malloc (SMAX * sizeof (int));
  geno2 = (int **) malloc (nsamp * sizeof (int *));
  for (a=0; a<nsamp; ++a)
    geno2[a] = (int *) malloc (SMAX * sizeof (int));
  chr = (int *) malloc (nsamp * sizeof (int));
  S = (int *) malloc (nsamp * sizeof (int));
  Stemp = (int *) malloc (nsamp * sizeof (int));
  for (a=0; a<nsamp; ++a)
    Stemp[a] = 0;

  for (a=0; a<nsamp; ++a) {
    fileptr = fopen (argv[++narg], "r");
    b = 0;
    while (fscanf (fileptr, "%d %d %d %d %lf\n", &chr[a], &pos[a][b], 
		   &geno1[a][b], &geno2[a][b], &gq[a][b]) != EOF)
      ++b;
    S[a] = b;
    fclose (fileptr);
  }

  for (a=1; a<nsamp; ++a)
    if (chr[a] != chr[0]) {
      printf("Error: chromosome numbers are not the same.\n");
      exit(0);
    }
  
  nextpos = nextsnp (Stemp, S, pos, nsamp);
  while (nextpos > 0) {
    printf("%d %d ", chr[0], nextpos);
    for (a=0; a<nsamp; ++a) {
      if (Stemp[a] < (S[a]-1) && pos[a][Stemp[a]] == nextpos)
	printf("%d %d ", geno1[a][Stemp[a]], geno2[a][Stemp[a]]);
      else
	printf("0 0 ");
    }
    for (a=0; a<nsamp; ++a) {
      if (Stemp[a] < (S[a]-1) && pos[a][Stemp[a]] == nextpos) {
	printf("%lf ", gq[a][Stemp[a]]);
	++Stemp[a];
      }
      else 
	printf("-1. ");
    }
    printf("\n");
    nextpos = nextsnp (Stemp, S, pos, nsamp);
  }
}

int nextsnp (int *Stemp, int *S, int **pos, int nsamp)
{
  int nextpos = -1, a, flag;

  for (a=0, flag=0; a<nsamp; ++a)
    if (Stemp[a] < (S[a]-1)) {
      if (flag==0) {
	nextpos = pos[a][Stemp[a]];
	flag=1;
      }
      else
	nextpos = (pos[a][Stemp[a]] < nextpos) ? pos[a][Stemp[a]] : nextpos;
    }
  return (nextpos);
}
