 /**
 * @author        Wolfram Ruehaak
 * @version       1.0
 * @Copyright:    GPL Copyright (c) 2003
 * @e-mail:       w.ruehaak@online.de,
 * @homepage:     http://www.geomath.onlinehome.de
 * @date:			    15. December 2003
 *
 * bln2grd: A program for conversion of a blank file into a regular 
 *          grid file.
 *          The program reads a file with a format like:
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *         Nr of data-points, 0
 *         First Datapoint x-coordinate, y-coordinate
 *         Second Datapoint x-coordinate, y-coordinate 
 *          (...),(...)
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *    Or in Numbers:
 *    4,0
 *    12,10
 *    14,18
 *    17,20
 *    17,17
 *    3,0
 *    5,4
 *    3,4
 *    3,3
 *    ... and so on ...
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *
 *    These datapoints can be polylines or polygons (then the last 
 *    point is the same as the first one).
 *
 *   These scattered datapoints are formed into a regular grid,
 *   where every cell containing a datapoint or the linking line 
 *   between two datapoints gets the value '-1', every other gets 
 *   the value '0'.
 * 
 *   If you want to transform a shape file you will need to convert it 
 *   first into a blankfile wich is easly possible for example with 
 *   program Surfer (tm) bei Golden Software.
 * 
 *  For more hints if you run into any trouble please send me an 
 * e-mail: w.ruehaak@online.de
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *    This program is free software; you can redistribute it and/or 
 *    modify it under the terms of the GNU General Public License 
 *    as published by the Free Software Foundation; either version 2 
 *    of the License, or (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, 
 *    Boston, MA  02111-1307  USA
 ***********************************************************************
*/

import java.io.*;
import java.util.*;
import java.text.*;

public class Bln2Grd {
    int i, j, k;
    int ni, nj;
    private int x, y, z;    
    static final boolean debug = false;
    private double[][] tv;
    private static long begin, end;
// variables of opendata
    private int number_of_rows;
    private int number_of_columns;
    private double[][] dAllValues;
    private static String blndatafile, grddatafile;
    private static String Directory;
    private static String Filename;         /** File to read */
    private static int nx, ny;
    public static double xmax, xmin, ymax, ymin, fstepx, fstepy;
    int    a, na, count;
    public int    fco[][];
    int    nri[];
    double xa[][],ya[][];
    double posx,posy,dx,dy,M;
    double minax,maxax,minay,maxay,deltax,deltay,xs,ys,xs2,ys2; 
    double deltx2,delty2;
    int nx0,ny0;
    static final double ERR = 1.E-12;

    public Bln2Grd(String blndatafile,String grddatafile) {
    System.out.println("bln2raster working");
    Directory = "";
    Open(Directory,blndatafile);
    fco = new int[nx+1][ny+1];
    double nria;    
    int maxa = 0;
    i = 0;
    while(i <= ni){
    nria = dAllValues[i][0];
    i++;
    for (int p=0; p<=nria-1; p++) {
    i++;
    }
    a++;
    maxa = Math.max(maxa,a);
    }
    if(debug) System.out.println("maxa = " + maxa);
    xa  = new double[ni+1][maxa+1];
    ya  = new double[ni+1][maxa+1];
    nri = new int[maxa+1];
    
    i = 0;
    a = 0;
    
    double minxa = +1.E+64;
    double minya = +1.E+64;
    double maxxa = -1.E+64;
    double maxya = -1.E+64;
    
    while(i <= ni){
    nria = dAllValues[i][0];
    i++;
    for (int p=0; p<=nria-1; p++) {
    xa[p][a] = dAllValues[i][0];
    ya[p][a] = dAllValues[i][1];
    minxa = Math.min(minxa,xa[p][a]);
    minya = Math.min(minya,ya[p][a]);
    maxxa = Math.max(maxxa,xa[p][a]);
    maxya = Math.max(maxya,ya[p][a]);    
    nri[a] = p;
    i++;
    }
    a++;
    if(debug) System.out.println("a = " + a);
    }
    na = a-1;
    System.out.println( "min x = " + minxa + 
                       " max x = " + maxxa + 
                       " min y = " + minya +                        
                       " max y = " + maxya);
    
    
// --------------------------------------------------------------------
    count = 0;
// --------------------------------------------------------------------
    if(debug){
    for( a = 0; a <= na; a++){
    for( i = 0; i <= nri[a]; i++){
    System.out.println(
    "i "+i+" a "+a+" xa "+xa[i][a]+" ya "+ya[i][a]); 
    }}}
// --------------------------------------------------------------------
    posx = xmin;
    for( x = 0; x<nx; x++){
    posy = ymin;
    for( y = 0; y<ny; y++){
            finish:
            for( a = 0; a <= na; a++){
            for( i = 0; i < nri[a]; i++){
// there are 4 co-ordinates for the rectangle: 
//      posx, posx+fstepx, posy, posy+fstepy
// we have to solve a straight line equation for this polygon 
//     (xa[i][a],ya[i][a])-(xa[i+1][a],ya[i+1][a])
             minax = Math.min(xa[i][a],xa[i+1][a]);
             maxax = Math.max(xa[i][a],xa[i+1][a]);
             minay = Math.min(ya[i][a],ya[i+1][a]);
             maxay = Math.max(ya[i][a],ya[i+1][a]);
             dx = (xa[i][a] - xa[i+1][a]);
             dy = (ya[i][a] - ya[i+1][a]);
             if(Math.abs(dx)<=ERR){ M = 0.E0; }
             else if(Math.abs(dy)<=ERR){ M = 0.E0; }
             else if(Math.abs(dy)>ERR && Math.abs(dx)>ERR){ M = dy/dx;}
//     Point of intersection is in this cell when: 
//                 posx <= (xa[i][a] + (dx * M)) <= posx+fstepx
//                 posy <= (ya[i][a] + (dy / M)) <= posy+fstepy
             if(M != 0.E0){
//    add-on criteria: restriction of the area to the by  _UV_ 
//    created rectangle: 
//    _UV_ = _(xa[i][a],ya[i][a]),(xa[i+1][a],ya[i+1][a])_
               if(posx+fstepx>=minax&&posx-fstepx<=maxax&&
                  posy+fstepy>=minay&&posy-fstepy<=maxay){
               deltax = posx - minax;
               deltay = posy - minay;
               deltx2 = posx - maxax;
               delty2 = posy - maxay;
                if(posx        >=(minax + (deltax * M))&&
                  (posx+fstepx)<=(maxax + (deltax * M))||
                   posy        >=(minay + (deltax * M))&&
                  (posy+fstepy)<=(maxay + (deltax * M))||
                   posy        >=(minay + (deltay / M))&&
                  (posy+fstepy)<=(maxay + (deltay / M))||
                   posx        >=(minax + (deltay / M))&&
                  (posx+fstepx)<=(maxax + (deltay / M))){
//       calculate point of intersection
                  xs2 = deltax+(.5E0*fstepx);
                  ys2 = deltay+(.5E0*fstepy);
                  ys = (xs2 * M);
                  xs = (ys2 / M);
                  if(ys>=deltay&&ys<=deltay+fstepy||
                     xs>=deltax&&xs<=deltax+fstepx){
                  fco[x][y] = -1;
                  break finish;
                  }
                  else if(M < 0.E0) {
                  if(ys>=delty2&&ys<=delty2+fstepy||
                     xs>=deltx2&&xs<=deltx2+fstepx){
                     fco[x][y] = -1;
                  break finish;
                  }}
                  else {
                  fco[x][y] =  0;
                  }}
                  else {
                  if(Math.abs(dy)<=ERR){ //      HORIZONTAL LINE
                  if(minax<=posx&&maxax>=posx+fstepx&&
                     minay>=posy&&maxay<=posy+fstepy){
                  fco[x][y] = -1;
                  break finish;
                  }}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                  if(Math.abs(dx)<=ERR){ //     VERTICAL LINE 
                  if(minay<=posy&&maxay>=posy+fstepy&&
                     minax>=posx&&maxax<=posx+fstepx){
                  fco[x][y] = -1;
                  break finish;//                  goto 100;
                  }}
//      special case xa[i][a], ya[i][a] are inside a cell
                  if(xa[i][a]>=posx&&xa[i][a]<=posx+fstepx&&
                     ya[i][a]>=posy&&ya[i][a]<=posy+fstepy){
                  fco[x][y] = -1;
                  }
                  else {
                  fco[x][y] = 0;
                  }}}}
            } // end of I Loop
        } // end of A Loop
        if(fco[x][y]<0) {
        count++;
        }
      posy = posy + fstepy;
      }  // end of the Y loop    
    posx = posx + fstepx;
    } // end of the X loop
  if(debug) System.out.println("count = " +  count);
  Save(Directory,grddatafile); // save the data
  }
  
  public static void main(String[] args) {
  begin = System.currentTimeMillis();
  if(debug) System.out.println(args.length);
         if(args.length == 8) {
         blndatafile = args[0];
         grddatafile = args[1];
         nx = Integer.valueOf(args[2]).intValue();
         ny = Integer.valueOf(args[3]).intValue();
         xmin        = Double.valueOf(args[4]).doubleValue();
         xmax        = Double.valueOf(args[5]).doubleValue();
         ymin        = Double.valueOf(args[6]).doubleValue();
         ymax        = Double.valueOf(args[7]).doubleValue();       
         }
         else {
         System.out.println(
         "Please use a syntax like: \n$java -Xmx64M Bln2Grd " +
         "#blank-datafilename# #grid-datafilename# " +
         "#number of datapoints in x-direction# " +
         "#number of datapoints in y-direction# " +
         "#minimum coordinate in x-direction# " +
         "#maximum coordinate in x-direction# " + 
         "#minimum coordinate in y-direction# " +
         "#maximum coordinate in y-direction#");
         System.exit(10);
         }
    fstepx = (xmax - xmin)/nx;
    fstepy = (ymax - ymin)/ny;
    Bln2Grd b2g = new Bln2Grd(blndatafile,grddatafile);
  }
/**
 * the main method for reading the data file (has to be in ASCII column format)
 * uses vector and sets the size of the data arrays
 */
 public void Open(String Directory, String Filename) {
/** AFAIK Vector doubles its size if it becomes to small, so it might be better
to define the increasing size, which is the second value:
Vector v = new Vector(Size,IncreasingsSize);
*/
    Vector v2 = new Vector();
    try {
    File f = new File(Directory+Filename);
         if(f.length()==0) {
         System.out.println("Sorry the file you selected has zero length!");
         }
    } catch (NullPointerException exc) {System.out.println(exc);return;}
    try {
     FileInputStream fis = new FileInputStream(Directory+Filename);
     BufferedReader  r   = new BufferedReader(new InputStreamReader(fis));
     StreamTokenizer st  = new StreamTokenizer(r);
     String s2[] = new String [2];
     int nria = 0;
     int ii = 0;
     int q = 0;
     a = 0;
     st.resetSyntax();
     st.whitespaceChars(' ', ' ');
     st.whitespaceChars('\n', '\n');
     st.whitespaceChars('\t', '\t');
     st.whitespaceChars(',', ',');
     st.whitespaceChars(';', ';');
     st.wordChars('0','9');
     st.wordChars('e','e');
     st.wordChars('E','E');
     st.wordChars('.','.');
     st.wordChars('+','+');
     st.wordChars('-','-');
     st.eolIsSignificant(true);
      while(st.nextToken() != st.TT_EOF) {
      if(i!=st.lineno()) count = 0;
      String s1 = st.sval;
        if(s1!=null){
      if(count == 0 || count == 1){
        v2.addElement(s1);
        }
      count++;
        i=st.lineno();
        }
        }
     } catch (IOException ioe) {}
     ni = i - 1; nj = 1;
     if(debug)System.out.println("v2.size() = "         + v2.size()+
                                 " number_of_rows = "   + (ni+1)+
                                 " number_of_columns = "+ (nj+1));
     dAllValues = new double [ni+1][nj+1];
     int k=0;
       for(i=0;i<=ni;i++) {
         for(j=0;j<=nj;j++) {
        Object f = v2.elementAt(k);
        String s = f.toString();
        if(debug) System.out.println("s: " + s);
        dAllValues[i][j] = Double.valueOf(s).doubleValue();
        k++;
        }
      }
    if(debug) System.out.println("finished reading" + " " + ni + " " + nj );
    }

    public void Save(String Directory, String SaveFilename) {
    int count = 0;
    int mint = +100000000, maxt=-1*mint;
    try {
    FileOutputStream      out = new FileOutputStream(grddatafile);
    BufferedOutputStream bout = new BufferedOutputStream(out);
    PrintStream          pout1 = new PrintStream(bout);

    if(debug) System.out.println(
    "fstepx = " + fstepx + "  fstepy = " + fstepy);
    count++;
    for (x= 0; x < nx; x++) {
      for (y= 0; y < ny; y++) {
      mint = Math.min(mint,fco[x][y]);
      maxt = Math.max(maxt,fco[x][y]);
      } // y
    } // x
// write Surfer(TM) grd file
    pout1.println("DSAA");
    pout1.println(nx + " " + ny);
    pout1.println(xmin + " " + xmax);
    pout1.println(ymin + " " + ymax);
    pout1.println(mint + " " + maxt);
    for(y=0;y<ny;y++) {
      for(x=0;x<nx;x++) {
      pout1.print(fco[x][y]+" ");
      }
    pout1.println("");
    pout1.println("");
    }
    pout1.close();
    bout.close();
    out.close();
    if(debug) System.out.println("Finished: write grid file");
    } catch(IOException ioe) 
    {System.out.println("Save Error" + ioe.toString());}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    long end = System.currentTimeMillis();
    System.out.println("Time (sec): " +  ((end-begin)/1000));
    System.exit(0);
    }
}
