#include <iostream>
#include <fstream>

using namespace std;

/*
 * fibonacciFromFile.cpp created 16:14 on 26th August 2005 author Sara Collins
 * 
 * Program to calculate the fibonacci sequence for a specified number
 * to a specified order and output to a file. The inputs are also
 * read in from a file.
 */

int main(int argc, char *argv[]){

  //check the correct number of arguments have been passed.
  if(argc != 3 || strcmp(argv[1],"--help") == 0){
    cerr << "Usage : " << argv[0] << " <input file> <output file>" 
	 <<endl;
    return -1;
  }

  const char *infile = argv[1];

  //open file for reading
  ifstream inputfile(infile);

  //check the file is open
  if(!inputfile.is_open()){
    cerr << "Error opening file " << infile << endl;
    return -1;
  }
  
  string num_str;
  string order_str;

  //read in the number and the order as strings
  inputfile >> num_str;
  inputfile >> order_str;
  
  cout << "Read in "<<num_str<< " " <<order_str<<endl;

  //close the input file
  inputfile.close();

  //convert number string to double
  double number = atof(num_str.c_str());
  //convert order string to integer
  int order = atoi(order_str.c_str());


  const char *outfile = argv[2];

  //open file for writing
  ofstream file(outfile);

  //check the file is open
  if(!file.is_open()){
    cerr << "Error opening file " << outfile << endl;
    return -1;
  }

  //output initial values of the sequence
  file << 1 << endl;
  if(order > 1)  file << number << endl;

  double fib = number;
  double fib_prev = 1;

  //calculate the next values and output
  for(unsigned int i = 3; i <= order; i++){
    double fib_next = fib*number + fib_prev;
    file << fib_next << endl;
    fib_prev = fib;
    fib = fib_next;
  }

  //close the file
  file.close();

  return 0;
}
