/*-----------------------------relax.c---------------------------------
  This program relaxes carbon structures to their equilibrium positions
  using the Tersoff-Brenner potential.  The forces are evaluated in
  potential.c and the energy minimization (using the conjugate gradient
  method) is performed in calculate.c.  This software was written by
  Stephen Jordan.
  ---------------------------------------------------------------------*/

#include "abcio.h"               //for loadabc and saveabc
#include "cell.h"                //for the cell structure
#include "defs.h"                //for the defs structure
#include "diags.h"               //for the diags structure
#include "calculate.h"           //for calculate
#include "tbinit.h"              //for tbinit
#include "potential.h"           //for energy
#include "handy.h"               //for strip_path
#include <stdio.h>               //for sprintf, fopen, FILE
#include <stdlib.h>              //for EXIT_SUCCESS and EXIT_FAILURE
#include <string.h>              //for strchr and strcpy


int main(int argc, char *argv[]) {
  FILE *infile;
  FILE *outfile;
  char filename[256];
  char header[65536];
  int automatic = 1;
  int digits = 6;
  int i, dash;
  double tb_energy;
  cell C;
  defs d;
  diags dia;
  if(argc < 2) {
    printf("Usage: relax [-m -u] filename.abc\n");
    return EXIT_FAILURE;
  }
  for(i = 1; i < argc; i++) {
    dash = 0;
    if(strcmp(argv[i], "-m") == 0) {
      automatic = 0;
      dash = 1;
    }
    if(strcmp(argv[i], "-u") == 0) {
      digits = 3;
      dash = 1;
    }
    if(dash == 0) { //the argument is a filename
      infile = fopen(argv[i], "r");
      if(infile == NULL) {
        printf("Unable to open %s\n", argv[i]);
        return EXIT_FAILURE;
      }
      strip_path(argv[i]);
      sprintf(filename, "R_%s", argv[i]);
      outfile = fopen(filename, "w");
      if(outfile == NULL) {
        printf("Unable to create %s\n", filename);
        return EXIT_FAILURE;
      }
      printf("creating %s\n", filename);
      loadabc(infile, &C, automatic);
      tbinit(&C, automatic);  
      printf("atoms = %i\tbonds = %i\n", C.atoms, C.bonds);
      d.start  = 0;
      d.stop   = 0;
      d.offset = 0; 
      strcpy(d.infile, argv[i]);
      strcpy(d.outfile, filename);
      strcpy(d.datafile, "none");
      strcpy(d.logfile, "none");
      d.verbose = 0;
      d.digits = digits;
      d.automatic = automatic;
      d.threshold = 1e-9;
      d.f_num = 0;
      d.tip = 0;
      d.randomization = 0;
      calculate(&C, &d, &dia, 0);
      tb_energy = energy(C.bond_array, C.bonds);
      printf("iterations = %i\tenergy = %f\n", dia.iter, tb_energy);
      if(automatic == 1) find_neighb_i(&C); //keep bonds upto date
      makeheader(header, &d, &dia, 0);
      saveabc(outfile, &C, header, digits, 0);
      fclose(infile);
      fclose(outfile);
      destroy_cell(&C);
    }
  }
  printf("Done.\n");
}






