\lstset{frame=single, backgroundcolor=\color{pyellow}, basicstyle=\small, columns=flexible, numbers=left, stepnumber=5}

\chapter{\label{example}Examples}

This appendix contains complete examples to write, read
and copy a dataset with the {\CDI} library.


\section{\label{example_write}Write a dataset}

Here is an example using {\CDI} to write a NetCDF dataset with 
2 variables on 3 time steps. The first variable is a 2D field
on surface level and the second variable is a 3D field on 5 pressure
levels. Both variables are on the same lon/lat grid. 

\lstinputlisting[language=Fortran]
{../../examples/cdi_write_f.f}


\subsection{Result}

This is the {\tt ncdump -h} output of the resulting NetCDF file {\tt example.nc}.

\begin{lstlisting}[]
netcdf example {
dimensions:
        lon = 12 ;
        lat = 6 ;
        lev = 5 ;
        time = UNLIMITED ; // (3 currently)
variables:
        double lon(lon) ;
                lon:long_name = "longitude" ;
                lon:units = "degrees_east" ;
                lon:standard_name = "longitude" ;
        double lat(lat) ;
                lat:long_name = "latitude" ;
                lat:units = "degrees_north" ;
                lat:standard_name = "latitude" ;
        double lev(lev) ;
                lev:long_name = "pressure" ;
                lev:units = "Pa" ;
        double time(time) ;
                time:units = "day as %Y%m%d.%f" ;
        float varname1(time, lat, lon) ;
        float varname2(time, lev, lat, lon) ;
data:

 lon = 0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330 ;

 lat = -75, -45, -15, 15, 45, 75 ;

 lev = 101300, 92500, 85000, 50000, 20000 ;

 time = 19850101.5, 19850102.5, 19850103.5 ;
}
\end{lstlisting}


\section{\label{example_read}Read a dataset}

This example reads the NetCDF file {\tt example.nc} from \htmlref{Appendix \ref{example_write}}{example_write}.

\lstinputlisting[language=Fortran]
{../../examples/cdi_read_f.f}


\section{Copy a dataset}

This example reads the NetCDF file {\tt example.nc} from \htmlref{Appendix B.1}{example_write}
and writes the result to a GRIB dataset by simple setting the output file type
to {\tt FILETYPE\_GRB}.

\lstinputlisting[language=Fortran]
{../../examples/cdi_copy_f.f}

\section{\label{examples_f2003}Fortran 2003: mo\_cdi and iso\_c\_binding}

This is the Fortran 2003 version of the reading and writing examples above.
The main differenc to {\tt cfortran.h} is the
character handling. Here {\tt CHARACTER(type=c\_char)} is used instead of
{\tt CHARACTER}. Additionally plain fortran charcters and character variables
have to be convertet to C charcters by
\begin{itemize}
\item appending {\tt '\textbackslash 0'} with {\tt //C\_NULL\_CHAR} 
\item prepending {\tt C\_CHAR\_} to plain charcters
\item take {\tt ctrim} from {\tt mo\_cdi} for {\tt CHARACTER(type=c\_char)} variables
\end{itemize}

\lstinputlisting[language=Fortran]
{../../examples/cdi_read_f2003.f90}

\lstinputlisting[language=Fortran]
{../../examples/cdi_write_f2003.f90}
