/*------------------------------pdb2abc.c------------------------
  This program converts molecular coordinate files from .pdb
  format to .abc format. This software was written by Stephen
  Jordan.
  ---------------------------------------------------------------*/

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

//changes the extension of a filename
void ext_change(char *name, char *ext) {
  int i, max;
  char *out_ext;
  char msg[256];
  out_ext = strrchr(name, '.');
  if(out_ext == NULL) {
    printf("Error, filename with no extension: %s\n", name);
    return;
  } //otherwise:
  i = 0;
  max = strlen(ext);
  for(i = 0; i < max; i++) out_ext[i+1] = ext[i];
  out_ext[i+1] = '\0';
}

int main(int argc, char *argv[]) {
  FILE *infile;
  FILE *outfile;
  char filename[256];
  char inpline[1024];
  char outline[1024];
  char linetype[256];
  int num;
  char type[3];
  double x, y, z;
  char *returnptr;
  int i;
  int a[7];
  if(argc != 2) {
    printf("Usage: pdb2abc filename.pdb\n");
    return EXIT_FAILURE;
  }
  infile = fopen(argv[1], "r");
  if(infile == NULL) {
    printf("Unable to open %s\n", argv[1]);
    return EXIT_FAILURE;
  }
  strcpy(filename, argv[1]);
  ext_change(filename, "abc");
  outfile = fopen(filename, "w");
  if(outfile == NULL) {
    printf("Unable to create %s\n", filename);
    return EXIT_FAILURE;
  }
  returnptr = fgets(inpline, sizeof(inpline), infile);
  while(returnptr != NULL) {
    sscanf(inpline, "%s", linetype);
    if(!strcmp(linetype, "REMARK")) {
      strcpy(outline, "COMM");
      strcat(outline, inpline + 6);
      fprintf(outfile, outline);
    }
    if(!strcmp(linetype, "ATOM")) {
      sscanf(inpline, "%*s %i %s %*s %*s %*i %lf %lf %lf", &num, type, &x, &y, &z);  
      fprintf(outfile, "ATOM\t%i\t%s\t%6f\t%6f\t%6f\n", num-1, type, x, y ,z);
    }
    if(!strcmp(linetype, "CONECT")) {
      a[6] = sscanf(inpline, "%*s %i %i %i %i %i %i",
                    &a[0], &a[1],& a[2], &a[3], &a[4], &a[5]);
      for(i = 0; i < a[6]; i++)
        if(a[i] > a[0]) fprintf(outfile, "BOND\t%i\t%i\n", a[0]-1, a[i]-1);
    }
    returnptr = fgets(inpline, sizeof(inpline), infile);
  }
  fclose(infile);
  fclose(outfile);
  return EXIT_SUCCESS;
}
