
#include "bits/zorder.h"

#include <cmath>  // sqrt()

#include "fxtiomanip.h"

#include "demo/nextarg.h"
#include "fxttypes.h"  // ulong

//% TeX picture of the Z-order curve.


double chop0(double x)  { if ( fabs(x)<0.001 )  x=0.0;  return x; }

void line(double x0, double y0, double x1, double y1)
// For \line(dx,dy){length} and \vector(dx,dy}{length}
// NOTE: The argument 'length' is the VERTICAL coordinate for
// vertical line segments, else the HORIZONTAL coordinate.
{
    double dx = x1 - x0,  dy = y1 - y0;

    // length:
    double len = sqrt( dx*dx + dy*dy );

//    jjassert( len > 0.0001 );

    // slopes:
    long sx = (long)round( 99.0 * dx/len );
    long sy = (long)round( 99.0 * dy/len );
    // simplify for purely horiz/vert case:
//    if ( sx==0 )  sy = 1;
//    if ( sy==0 )  sx = 1;

    // "length" to be used with \vector or \line:
    double vlen = fabs( dx );
    if ( fabs(vlen)<1e-4 )  vlen = 1;

    x0 = chop0(x0);  y0 = chop0(y0);

    cout << "\\put(" << x0 << "," << y0 << ")"
         << "{\\vector(" << sx <<","<< sy << ")"
         << "{" << vlen << "}}"
         << endl;
}
// -------------------------


int
main(int argc, char **argv)
{
    ulong ldn = 6;
    NXARG(ldn,"number of moves == 2**ldn (fxtbook uses 8)");
    ulong n = 1UL<<ldn;

    ulong tx, ty;
    ulong x = 0, y = 0;
    cout << "\\put(" << x << "," << y << ")" << "{\\circle{0.5}}" << endl;
    cout << "\\put(" << x << "," << y << ")" << "{\\circle{0.25}}" << endl;
    ulong ax=0, ay=0;  //  max  x/y
    for (ulong t=1; t<n; ++t)
    {
        tx = x;
        ty = y;
        lin2zorder(t, x, y);

//        cout << "\\curve(" << tx << "," << ty << ", " << x <<","<< y << ")" << endl;

        line(tx, ty, x, y);

        // update max:
        if ( x>ax )  ax = x;
        if ( y>ay )  ay = y;
    }

    double wd = ax+1.0, hg = ay+1.0;
    cout << "%% Put next line (un-commented) on top of pic:" << endl;
    cout << "%\\begin{picture}("
         << wd+1 <<"," << hg+1 << ")"
         <<"("<< -0.5 <<"," << -0.5 << ")" << endl;

    return 0;
}
// -------------------------

/*
Embedding LaTeX code is:

%%\usepackage{curves}% <--=  before \begin{document}

\begin{figure}%[hbt]
\begin{center}
\setlength{\unitlength}{6.0mm}
\begin{picture}(17,17)(-0.5,-0.5)
  \thicklines
 [OUTPUT of the program HERE] <--= there!
\end{picture}
\end{center}
\caption{\jjlabel{fig:zorder2d}
The Z-order curve.}
\end{figure}

*/


/// Emacs:
/// Local Variables:
/// MyRelDir: "demo/bits"
/// makefile-dir: "../../"
/// make-target: "1demo DSRC=demo/bits/zorder-texpic-demo.cc"
/// make-target2: "1demo DSRC=demo/bits/zorder-texpic-demo.cc DEMOFLAGS=-DTIMING"
/// End:

