//
// -=randSat=-
//  main.cpp
//
#include <stdlib.h>
#include <time.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

//
// vrati nahodne cele cislo v intervalu 0 .. max-1
//
int randomInt(int max)
{
  return (int)(max*rand()/RAND_MAX);
}

//
// prevod retezce na integer
//
int parseInt(char* in)
{
    int val = 0;

    if (*in < '0' || *in > '9') fprintf(stderr, "PARSE ERROR! Unexpected char: %c\n", *in), exit(1);
    while (*in >= '0' && *in <= '9')
        val = val*10 + (*in - '0'),
        in++;
    return val;
}

//
// hlavni vypocetni procedura
//
int main(int argc, char *argv[])
{
  srand((unsigned int)time(0));

//argv[1]="aa";
//argv[2]="12";
//argv[3]="100";

  if (argc!=4)
  {
    std::cout << "Bad number of parameters!" << std::endl;
    std::cout << "Use following parameters:" << std::endl;
    std::cout << "randSat [nameOfOutputFile] [numberOfVariables] [numberOfClauses]" << std::endl;
    return 1;
  }

  const char *file=argv[1];

  std::ofstream out (file, std::ios::out);

  if (out.fail())
  {
    out.close();
    return -1;
  }

  std::stringstream ss;

  int vars=parseInt(argv[2]);
  int clas=parseInt(argv[3]);

  if (vars<1 || clas<1)
  {
    std::cout << "Bad number of clauses or variables!" << std::endl;
  }

  ss << "c\nc This file was generated by -=randSat=- cnf formula generator \nc \np cnf " << vars << " " << clas << std::endl;

  int *rndv=new int[3];
  for (int ii=0; ii <clas; ii++)
  {
    do{
      rndv[0]=1+randomInt(vars);
      rndv[1]=1+randomInt(vars);
      rndv[2]=1+randomInt(vars);
    }while(rndv[0]==rndv[1] || rndv[0]==rndv[2] || rndv[2]==rndv[1]);

    for(int jj=0; jj<3; jj++)
    {
      if (randomInt(2)==1){ss << "-";}
      ss << (rndv[jj]) << " ";
    }
    ss << "0" << std::endl;
  }

  out << ss.str();
  out.close();
  return 0;
}
