/* ======================================================================== *\
!
! *
! * This file is part of MARS, the MAGIC Analysis and Reconstruction
! * Software. It is distributed to you in the hope that it can be a useful
! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
! * It is distributed WITHOUT ANY WARRANTY.
! *
! * Permission to use, copy, modify and distribute this software and its
! * documentation for any purpose is hereby granted without fee,
! * provided that the above copyright notice appear in all copies and
! * that both that copyright notice and this permission notice appear
! * in supporting documentation. It is provided "as is" without express
! * or implied warranty.
! *
!
!
!   Author(s): Daniela Dorner, 01/2005 <mailto:dorner@astro.uni-wuerzburg.de>
!
!   Copyright: MAGIC Software Development, 2000-2005
!
!
\* ======================================================================== */

/////////////////////////////////////////////////////////////////////////////
//
// FindCaCoFiles.C
// ===============
//
/////////////////////////////////////////////////////////////////////////////

#include <iostream>
#include <iomanip>
#include <fstream>

#include <TEnv.h>
#include <TSystem.h>

#include <MSQLServer.h>
#include <TSQLRow.h>
#include <TSQLResult.h>

using namespace std;


int findcacofiles(TString date, TString logpath)
{
    TEnv env("sql.rc");

    MSQLServer serv(env);
    if (!serv.IsConnected())
    {
        cout << "ERROR - Connection to database failed." << endl;
        return 0;
    }
    cout << "findcacofiles" << endl;
    cout << "-------------" << endl;
    cout << endl;
    cout << "Connected to " << serv.GetName() << endl;
    cout << endl;

    TString query="SELECT RunProcessStatus.fRunNumber FROM RunProcessStatus ";
    query+=" LEFT JOIN RunData on RunData.fRunNumber=RunProcessStatus.fRunNumber ";
    query+=" WHERE IsNull(fCaCoFileFound) and fExcludedFDAKEY=1 ";
    query+=" and RunProcessStatus.fRunNumber > 10000 and not IsNull(fCCFileAvail)";

    TSQLResult *res = serv.Query(query);
    if (!res)
    {
        cout << "Error." << endl;
        return 0;
    }

    TString filename(Form("%s/findcacofiles-%s.txt", logpath.Data(), date.Data()));
    ofstream fout(filename, ios::app);
    if (!fout)
    {
        cout << "ERROR - Cannot open file " << filename << endl;
        return 0;
    }

    TSQLRow *row=0;
    while ((row = res->Next()))
        fout << (*row)[0] << endl;

    delete res;
    return 1;
}


