#include <iomanip>
#include <fstream>

#include <MBending.h>

using namespace std;

/* ---------------------------------------------------------------------- */

int main(int argc, char **argv)
{
    cout << "-" << endl;
    cout << "Trying to open prepos.txt.." << endl;
    ifstream fin("prepos.txt");
    if (!fin)
    {
        cout << "ERROR: Predifined posiion in 'prepos.txt' not found." << endl;
        return 1;
    }

    cout << "-" << endl;
    cout << "Initializing bending correction from bending.txt.." << endl;
    cout << "-" << endl;
    MBending bend("bending.txt");
    cout << "-" << endl;
    cout << "Calculate system coordinates for predefined positions..." << endl;
    cout << "-" << endl;

    ofstream fout("prepos_system.txt");
    if (!fout)
    {
        cout << "ERROR: Cannot open prepos_system.txt for writing." << endl;
        return 1;
    }

    fout << setprecision(12);

    while (1)
    {
        TString str;
        Double_t zd, az;
        fin >> str >> zd >> az;
        if (!fin)
            break;

        cout << setprecision(7);
        cout << " -- " << str << " --" << endl;

        ZdAz za(zd, az);

        ZdAz orig = za;

        cout << "Pointing: \t" << za.Zd() << "\t" << za.Az() << endl;

        za = bend(za*kDeg2Rad)*kRad2Deg;

        cout << "Bended:   \t" << za.Zd() << "\t" << za.Az() << endl;
        fout << str << " " << za.Zd() << " " << za.Az() << endl;

        za = bend.CorrectBack(za*kDeg2Rad)*kRad2Deg;
        cout << "Rebended: \t" << za.Zd() << "\t" << za.Az() << endl;

        za -= orig;

        if (za.Zd()*3600<.5)
            za.Zd(0);
        if (za.Az()*3600<.5)
            za.Az(0);

        cout << setprecision(3);
        cout << "Diff:     \t" << za.Zd()*3600 << "\"\t" << za.Az()*3600 << "\"" << endl;

    }
    cout << "-" << endl;


    Double_t min=360;
    Double_t mini=0;
    Double_t minj=0;
    for (int i=-120; i<=120; i++)
        for (int j=-120; j<=120; j++)
        {
            ZdAz za(i/3600., j/3600.);
            ZdAz orig = za;
            za = bend(za*kDeg2Rad)*kRad2Deg;
            za = bend.CorrectBack(za*kDeg2Rad)*kRad2Deg;
            za -= orig;
            if (fabs(za.Zd())<min)
            {
                min = fabs(za.Zd());
                mini = i;
                minj = j;
            }
        }
    cout << "Minimum Distance to Zenith: " << min*3600 << "\"";
    cout << " @ " << mini << "\" " << minj << "\"" << endl;
    cout << "-" << endl;

    return 0;
}
