/* ======================================================================== *\
!
! *
! * 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)
{
    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 fRunNumber FROM RunProcessStatus WHERE IsNull(fCaCoFileFound) ";
    query+=" and fRunNumber > 10000 and not IsNull(fCCFileAvail)";

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

    Int_t idx = date.First('-');
    TString year = date(0, idx);
    cout << "year: " << year << endl;

    ofstream fout("/magic/datacenter/autologs/filesondisk/"+year+"/findcacofiles-"+date+".txt");
    if (!fout)
    {
        cout << "ERROR - Cannot open file." << endl;
        return kFALSE;
    }
    TString runnumber=0;
    TSQLRow *row=0;
    while ((row = res->Next()))
        fout << (*row)[0] << endl;

    delete res;
    return 1;
}


