% \iffalse
% --------------------------------------------------------------------
%<*hex>
% \fi
% 
% \subsubsection{Board splitting}
% \label{sec:impl:hex:split}
%
% \begin{Macro}{\splitboard}
% 
%   Calculates how to split a board into sheets of paper. 
%   
%   \begin{Syntax}
%     \cs{splitboard}\oarg{options}
%   \end{Syntax}
%
%  where options are
%
%  \begin{itemize}
%  \item \spec{paper}=\meta{format}: Specifies the paper format.  One
%    of \spec{a4}, \spec{a3}, \spec{letter}, \spec{tabloid}. Default
%    is \spec{a4}.
%  \item \spec{landscape}: Sets the paper format to be in landscape
%    mode (default is portrait).
%  \item \spec{margin}=\meta{size in centimetres}: Size of margins on
%    each sheet in centimetres \emph{without} unit.  That is put
%    \spec{0.6} for 6mm, \emph{not} \spec{6mm}. Default is \spec{0.6}.
%    This should be \emph{slightly} larger (by roughly 5\%) than the
%    \emph{least} margin required by the printer used. \emph{Must} be
%    given \emph{before} \spec{paper} to have any effect.
%  \item \spec{ncol}=\meta{number of columns}: Sets the number of
%    columns of sheets.  
%  \item \spec{nrow}=\meta{number of rows}: Set the number of rows of
%    sheets.
%  \item \spec{overlap}=\meta{size in centimetres}: Sets the size of
%    the overlap between sheets in centimetres \emph{without} unit.
%    That is put \spec{2} for 2cm, \emph{not} \spec{2cm}. Default is
%    \spec{2}. 
%  \item \spec{image}=\meta{file name}: File name of the board image
%    (a PDF). Default is \spec{board}
%  \item \spec{output}=\meta{file name}: File name (without
%    \spec{.tex} ending) to write calculated split to.
%  \item \spec{standalone}: Boolean flag.  If true, then output file
%    will be a standalone document (i.e., has a \cs{documentclass}).
%  \item \spec{scale}=\meta{scale}: Set scale of board. 
%  \end{itemize}
%
% The macro will produce a file named \cs{jobname}\spec{\_out.tex}
% which can be included in another document to generate the split
% board PDF.
%
% To use, make, for example, the file \spec{calcsplit.tex} with the
% content
%
% \begin{verbatim}
%   \documentclass[11pt]{standalone}
%   \usepackage{wargame}
%   \usepackage{mystyle}
%   \begin{document}
%   \splitboard{paper=letter,margin=.7,ncol=2,nrow=2,overlap=1}
%   \end{document}
% \end{verbatim}
%
% to calculate the split of \spec{board.pdf} over $2\times2$ letter
% paper sheets, with a non-printable margin of 7mm, and an overlap
% between the segments of 1cm.
%
% The final split document can then be
%
% \begin{verbatim}
%   \documentclass[11pt]{article}
%   \usepackage[letterpaper,margin=7mm]{geometry}
%   \begin{document}
%   \input{calcsplit_out}
%   \end{document}
% \end{verbatim}
%
%
% If you need to scale down the board, define the style \spec{board
% scale}.  E.g.,
%
% \begin{verbatim}
%   \tikzset{board scale/.style={scale=.9}}
% \end{verbatim}
% 
% \end{Macro}
%
%
% Styles used for drawing things.
% 
%    \begin{macrocode}
\tikzset{%
  % Margin must be <1cm
  split/paper outline/.style={
    shape=rectangle,
    draw=red!50!black,
    line width=.5mm},
  split/effective outline/.style={
    shape=rectangle,
    draw=green!50!black,
    dashed,
    line width=.5mm},
  split/board outline/.style={%
    draw=magenta,
    line width=.5mm,
    dotted},
}     
%    \end{macrocode}
%
% A scratch dimension used
% 
%    \begin{macrocode}
\newdimen\split@tmp   
%    \end{macrocode}
%
% Get upper right and lower left corners of node. Argument is node name.
% 
%    \begin{macrocode}
\def\split@getem#1{%
  \draw (#1.north east);%  
  \pgfgetlastxy{\split@ulx}{\split@uly}%
  \xdef\split@ulx{\split@ulx}%
  \xdef\split@ulx{\split@ulx}%
  \draw (#1.south west);%  
  \pgfgetlastxy{\split@lrx}{\split@lry}%
  \xdef\split@lrx{\split@lrx}%
  \xdef\split@lry{\split@lry}%
}   
%    \end{macrocode}
%
% Get board dimensions. Argument is node name. 
% 
%    \begin{macrocode}
\def\split@getboard#1{%
  \split@getem{#1}%
  \xdef\split@bulx{\split@ulx}%
  \xdef\split@buly{\split@uly}%
  \xdef\split@blrx{\split@lrx}%
  \xdef\split@blry{\split@lry}%
  \split@w{\@percentchar\space Board:
    (\split@bulx,\split@buly)(\split@blrx,\split@blry)}}   
%    \end{macrocode}
%
% Adjust placement of markers and cut lines.
% \begin{enumerate}
% \item Dimension to adjust
% \item Overlap dimension (with units)
% \end{enumerate}
% 
%    \begin{macrocode}
\def\split@adj#1#2{%
  \split@tmp=#2%
  \divide\split@tmp by 2%
  \advance\split@tmp by #1%
  \edef\t{\the\split@tmp}}   
%    \end{macrocode}
%
% Get initial offset in a direction.
%
% \begin{enumerate}
% \item Number of segments in direction
% \item Overlap in centimetres (without unit)
% \item Effective size, in centimetres (without unit), of sheets in
%   direction
% \item Full size, in centimetres (without unit), of board in
%   direction. 
% \end{enumerate}
% 
%    \begin{macrocode}
\def\split@get@init#1#2#3#4{%
  \pgfmathparse{((#1 * #3 - (#1 - 1) * #2) - #4)/2}%
  \xdef\split@off{\pgfmathresult}%
  \hex@dbg{2}{((#1 * #3 - (#1 - 1) * #2) - #4)/2 -> `\split@off'}}   
%    \end{macrocode}
%
% Get initial offset of first segment.
%
% \begin{enumerate}
% \item Number of rows 
% \item Number of columns
% \item Overlap in centimetres (without unit)
% \item Effective height, in centimetres (without unit), of sheets
% \item Effective width, in centimetres (without unit), of sheets
% \item Full height, in centimetres (without unit), of board
% \item Full width, in centimetres (without unit), of board
% \end{enumerate}
% 
%    \begin{macrocode}
\def\split@getinit#1#2#3#4#5#6#7{%
  \split@get@init{#1}{#3}{#4}{#6}\xdef\dy{\split@off cm}
  \split@get@init{#2}{#3}{#5}{#7}\xdef\dx{\split@off cm}}   
%    \end{macrocode}
%
% Get coordinates of a segment
%
% \begin{enumerate}
% \item Column number
% \item Row number
% \item Overlap, in centimetres (without unit)
% \end{enumerate}
% 
%    \begin{macrocode}
\def\split@getcoords#1#2#3{%
  \hex@dbg{2}{Getting coords `c#1r#2'}%
  \split@getem{c#1r#2}%
  \edef\sulx{\split@ulx}%
  \edef\suly{\split@uly}%
  \edef\slrx{\split@lrx}%
  \edef\slry{\split@lry}%
  \edef\mlx{\split@blrx}%
  \edef\mrx{\split@bulx}%
  \edef\mty{\split@buly}%
  \edef\mby{\split@blry}%
  \pgfmathparse{int(#1-1)}\edef\pc{\pgfmathresult}%
  \pgfmathparse{int(#2-1)}\edef\pr{\pgfmathresult}%
  \pgfmathparse{int(#1+1)}\edef\nc{\pgfmathresult}%
  \pgfmathparse{int(#2+1)}\edef\nr{\pgfmathresult}%
  \pgfutil@ifundefined{pgf@sh@ns@c\pc r#2}{}{% Left
    \hex@dbg{3}{\space Getting left `c\pc r#2'}%
    \split@getem{c\pc r#2}\split@adj{\split@ulx}{-#3}\edef\mlx{\t}}%
  \pgfutil@ifundefined{pgf@sh@ns@c\nc r#2}{}{% Right
    \hex@dbg{3}{\space Getting right `c\nc r#2'}%
    \split@getem{c\nc r#2}\split@adj{\split@lrx}{#3}\edef\mrx{\t}}%
  \pgfutil@ifundefined{pgf@sh@ns@c#1r\pr}{}{% Above
    \hex@dbg{3}{\space Getting above `c#1 r\pr'}%
    \split@getem{c#1r\pr}\split@adj{\split@lry}{#3} \edef\mty{\t}}%
  \pgfutil@ifundefined{pgf@sh@ns@c#1r\nr}{}{% Below
    \hex@dbg{3}{\space Getting below `c#1 r\nr'}%
    \split@getem{c#1r\nr}\split@adj{\split@uly}{-#3}\edef\mby{\t}}%
  \draw[fill=red]  (\mlx,\mty) circle(.2);%
  \draw[fill=green](\mrx,\mty) circle(.4);%
  \draw[fill=blue] (\mlx,\mby) circle(.6);%
  \draw[fill=cyan] (\mrx,\mby) circle(.8);%
  \split@w{%
    \@percentchar^^J%
    \string\segment(\sulx,\suly)(\slrx,\slry){\mlx}{\mrx}{\mby}{\mty}
    \@percentchar\space c#1r#2}
}   
%    \end{macrocode}
%
% Stream to write to
% 
%    \begin{macrocode}
\newwrite\split@calcout   
%    \end{macrocode}
%
% Short-hand for write outs.
% 
%    \begin{macrocode}
\def\split@w{\immediate\write\split@calcout}   
%    \end{macrocode}
%
% Open stream and set-up
% 
%    \begin{macrocode}
\def\split@header#1{%
  \immediate\openout\split@calcout=#1.tex
  \ifsplit@standalone
  \pgfmathparse{\split@margin*.95}\edef\tmp{\pgfmathresult}
  \split@w{\@percentchar\@percentchar\space These are made with
    `calcsplit' with `-jobname \jobname'}
  \split@w{
    ^^J\string\documentclass[twoside]{article}
    ^^J\string\usepackage{geometry}
    ^^J\string\geometry{papersize={\the\paperwidth,\the\paperheight},margin=\tmp cm}
    ^^J\string\usepackage{wargame}
    ^^J\string\setlength{\string\parindent}{0pt}
    ^^J\string\setlength{\string\parskip}{0pt}
    ^^J\string\begin{document}
    ^^J\string\ignorespaces\@percentchar}
  \fi
  \split@w{\string\def\string\boardfile{\split@img}\@percentchar}
  \split@w{\string\def\string\boardscale{\split@scale}\@percentchar}
}   
%    \end{macrocode}
%
% Write final stuff and close stream
% 
%    \begin{macrocode}
\def\split@footer{%
  \ifsplit@standalone
  \split@w{^^J\string\end{document}}
  \fi
  \split@w{^^J\@percentchar\@percentchar End of `\jobname'^^J}
  \immediate\closeout\split@calcout
}   
%    \end{macrocode}
%
% Initial calculations.  This draws the board and then extracts the
% dimensions of the board.  It also defines some styles for drawing
% the board segments. 
% 
%    \begin{macrocode}
\def\split@init#1{%
  \node[scale=\split@scale,
  inner sep=0pt,
  outer sep=0pt,
  anchor=north west,
  transform shape](b){\includegraphics{#1}};
  \split@getboard{b}
  %x
  \split@tmp=\split@blrx cm\advance\split@tmp by -\split@bulx%
  \wg@pt@to@cm{\split@tmp}\edef\split@bw{\pgfmathresult}%
  \pgfmathparse{abs(\split@bw)}\edef\split@bw{\pgfmathresult}%
  %
  \split@tmp=\split@buly cm\advance\split@tmp by -\split@blry%
  \wg@pt@to@cm{\split@tmp}\edef\split@bh{\pgfmathresult}%
  \pgfmathparse{abs(\split@bh)}\edef\split@bh{\pgfmathresult}%
  %
  \wg@pt@to@cm{\paperwidth}\edef\split@pw{\pgfmathresult}%
  \wg@pt@to@cm{\paperheight}\edef\split@ph{\pgfmathresult}%
  %
  \wg@pt@to@cm{\textwidth}\edef\split@ew{\pgfmathresult}%
  \wg@pt@to@cm{\textheight}\edef\split@eh{\pgfmathresult}%
  %
  \hex@dbg{1}{Board:
    (\split@bulx,\split@buly)(\split@blrx,\split@blry) \split@bw x\split@bh
    ^^JPaper: \split@pw x\split@ph
    ^^JEffective: \split@ew x\split@eh
  }
  \tikzset{
    split/paper size/.style={
      shape=rectangle,
      minimum width=\paperwidth,
      minimum height=\paperheight,
      split/paper outline,
    },
    split/effective size/.style={
      shape=rectangle,
      minimum width=\textwidth,
      minimum height=\textheight,
      split/effective outline},
    split/board size/.style={
      shape=rectangle,
      minimum width=\split@bw cm,
      minimum height=\split@bh cm,
      split/board outline}}
  \node[board/.try,split/board size,anchor=north west] {};
}   
%    \end{macrocode}
%
% Calculate effective sheet sizes from sheet dimensions and the
% defined margin.
% 
%    \begin{macrocode}
\def\split@text@dim#1{%
  \textwidth=\paperwidth%
  \textheight=\paperheight%
  \advance\textwidth by -#1cm%
  \advance\textwidth by -#1cm%
  \advance\textheight by -#1cm%
  \advance\textheight by -#1cm%
  \global\textwidth=\textwidth%
  \global\textheight=\textheight%
}   
%    \end{macrocode}
%
% Options for the \cs{splitboard} macro.
% 
%    \begin{macrocode}
\newif\ifsplit@standalone\split@standalonetrue
\tikzset{%
  split/.search also={/tikz},%
  split/.cd,%
  margin/.store in=\split@margin,
  paper/.is choice,%
  paper/a4/.code={%
    \hex@dbg{3}{A4 paper for split}%
    \global\paperwidth=21cm%
    \global\paperheight=29.7cm%
    \split@text@dim{\split@margin}},
  paper/a3/.code={%
    \hex@dbg{3}{A3 paper for split}%
    \global\paperheight=42cm%
    \global\paperwidth=29.7cm%
    \split@text@dim{\split@margin}},
  paper/letter/.code={%
    \hex@dbg{3}{Letter paper for split}
    \paperheight=27.9cm,%
    \paperwidth=21.6cm,%
    \split@text@dim{\split@margin}},%
  paper/tabloid/.code={%
    \hex@dbg{3}{Tabloid paper for split}%
    \paperheight=43.2cm,%
    \paperwidth=27.9cm,%
    \split@text@dim{\split@margin}},
  landscape/.code={%
    \hex@dbg{3}{Landscape option for split}
    \split@tmp=\paperheight
    \global\paperheight=\paperwidth
    \global\paperwidth=\split@tmp
    \split@tmp=\textheight
    \global\textheight=\textwidth
    \global\textwidth=\split@tmp},
  standalone/.is if=split@standalone,
  scale/.store in=\split@scale,
  output/.store in=\split@out,
  ncol/.store in=\split@ncol,
  nrow/.store in=\split@nrow,
  overlap/.store in=\split@ov, % Centimeter, no unit 
  image/.store in=\split@img,
  paper/.default=a4,  paper/.initial=a4,
  margin/.default=.6, margin/.initial=.6,
  ncol/.default=0,    ncol/.initial=0,
  nrow/.default=0,    nrow/.initial=0,
  overlap/.default=2, overlap/.initial=2,
  image/.default=board, image/.initial=board,
  output/.default=\jobname_out,
  standalone/.default=true,
  scale/.default=1,
}   
%    \end{macrocode}
%
% The actual macro. The argument is key-value pairs of options. 
% 
%    \begin{macrocode}
\def\splitboard#1{%
  \pgfkeys{/tikz/split/.cd,%
    standalone,%
    output,%
    margin,%
    paper,%
    image,%
    overlap,%
    scale,%
    ncol,%
    nrow,%
    #1}
  \hex@dbg{1}{%
       Paper:     `\the\paperwidth'x`\the\paperheight'
    ^^JEffective: `\the\textwidth'x`\the\textheight'
    ^^JNcols:     `\split@ncol'
    ^^JNrows:     `\split@nrow'
    ^^JOverlap:   `\split@ov' cm}
  \split@header{\split@out}
  \begin{tikzpicture}
    \split@init{\split@img}
    \split@getinit{%
      \split@nrow}{%
      \split@ncol}{%
      \split@ov}{\split@eh}{\split@ew}{\split@bh}{\split@bw}
    \node[split/effective size,
    above left=\dy and \dx of b.north west,
    anchor=north west] (c1r1) {};
    \node[split/paper size] at (c1r1) {};
    % 
    \foreach \r [remember=\r as \pr (initially 0)] in {1,...,\split@nrow}{%
      \ifnum\r>1
        \hex@dbg{3}{Placing first column of row `\r'}
        \node[split/effective size,
        below=-\split@ov cm of c1r\pr.south west,anchor=north west] (c1r\r){};
        \node[split/paper size] at (c1r\r) {};
      \fi
      \foreach \c [remember=\c as \pc (initially 1)] in {2,...,\split@ncol}{%
        \ifnum\c>\split@ncol\else%
          \ifnum\c>\pc
          \hex@dbg{3}{Placing column `\c' (`\pc') of row `\r'}
            \node[split/effective size,
            right=-\split@ov cm of c\pc r\r.north east,anchor=north west]
            (c\c r\r) {};
            \node[split/paper size] at (c\c r\r) {};
          \fi
        \fi
      }
    }
    \foreach \r [remember=\r as \pr (initially 0)] in {1,...,\split@nrow}{%
      \foreach \c [remember=\c as \pc (initially 0)] in {1,...,\split@ncol}{%
        \split@getcoords{\c}{\r}{\split@ov cm}}}
  \end{tikzpicture}
  \split@footer
}   
%    \end{macrocode}
%
% Macro used by the written file.
%
%
% \begin{enumerate}
% \item first coordinate (e.g., \spec{(hex ak:c=C,r=17)})
% \item second coordinate (e.g., \spec{(hex ak:c=M,r=33)})
% \item Crop mark left
% \item Crop mark right
% \item Crop mark bottom
% \item Crop mark top
% \end{enumerate}
% 
%    \begin{macrocode}
\def\segment(#1)(#2)#3#4#5#6{%
  \begin{tikzpicture}%
    \begin{scope}
      \clip (#1) rectangle (#2);
      \node[scale=\boardscale,
      inner sep=0pt,
      outer sep=0pt,
      anchor=north west,
      transform shape]{\includegraphics{\boardfile}};
    \end{scope}
    \pgfinterruptboundingbox
    \draw(#3,#6)--++( 0.0, 0.3);
    \draw(#3,#6)--++(-0.3, 0.0);
    \draw(#3,#5)--++( 0.0,-0.3);
    \draw(#3,#5)--++(-0.3, 0.0);
    \draw(#4,#6)--++( 0.0, 0.3);
    \draw(#4,#6)--++( 0.3, 0.0);
    \draw(#4,#5)--++( 0.0,-0.3);
    \draw(#4,#5)--++( 0.3, 0.0);
    \endpgfinterruptboundingbox
  \end{tikzpicture}%
  \cleardoublepage}%   
%    \end{macrocode}
%
% 
%
% 
% \iffalse
%</hex>
% --------------------------------------------------------------------
% \fi