/*.........................................................................*/
/* Brandenburg University of Technology at Cottbus                      FM */
/* EuroAquae                                                               */
/*                                                             V 0.1 05.13 */
/*.........................................................................*/
import java.io.*;
import java.text.*;

/*#########################################################################*/
/*  RheinToMike11Application                                              */
/*#########################################################################*/
/**
 * class with main method for RheinToMike11Application
 * converter of Rhein crossection point data to Mike11 import format
 * <HR>
 * @author <A HREF="mailto:frank.molkenthin@tu-cottbus.de">Frank Molkenthin</A>
 * @version 0.2 - 24.10.16
 * stoarge_frequency allows to reduce number of cross sections for Mike11
 */
public class RheinToMike11Application
{
/*#########################################################################*/
/* main function for application                                           */
/*#########################################################################*/

public static void main(String argv[])
{
 System.out.println("*** Start of RheinToMike11Application - quick and dirty");
 System.out.println("    1st argument: source file");
 System.out.println("    2nd argument: target file");
 System.out.println("    storage_frequency set in the source code");

/* system parameter                                                        */

 String sourcefile;        // sourcefile to read rhein crossection data
 String targetfile;        // targetfile to write crosssection data in Kie11 import format
 FileReader reader=null;   // access to input file
 BufferedReader bufferedreader=null;
 FileWriter writer=null;   // access to output file
 BufferedWriter bufferedwriter=null;

 if(argv==null||argv.length==0)
  {
   System.out.println("### Error: no input parameter defined!");
   System.exit(-1);
  }
 else if(argv.length==1)
  {
   System.out.println("### Error: only one input parameter defined!");
   System.exit(-1);
  }
 else if(argv.length>2)
  {
   System.out.println("### Error: more than two parameter defined!");
   System.exit(-1);
  }
 else if(!checkFile(argv[0]))
  {
   System.out.println("### Error: File "+argv[0]+" did not exist!");
   System.exit(-1);
  }
 else if(checkFile(argv[1]))
  {
   System.out.println("--- Warning: File "+argv[1]+" will be overriden!");
  }
 sourcefile =  argv[0];
 targetfile =  argv[1];

/* converter variables                                                     */

 String            line;                           // line string
 double            chainage;                       // actual chainage
 double            x;                              // actual x coodinate
 double            y;                              // actual y coodinate
 double            z;                              // actual z coodinate
 double            x_0=0.;                         // x coodinate begin of cross section
 double            y_0=0.;                         // y coodinate begin of cross section
 double            chainage_old=9999.;             // chainage before
 double            chainage_tolerance = 0.001;     // chainage tolerance
 double            distance;                       // actual node distance
 double            distance_old= -0.001;           // old    node distance
 int               storage_frequency=1;            // how many crossection 2 -> every 2nd
 int               actual_storage=1;               // actual crossection
 boolean           write_data=true;

/* start converter                                                         */

 System.out.println("... Start Converter "+sourcefile+" to "+targetfile+" by every "+storage_frequency+" cross section");

/* open files to read and write                                            */

 try { reader = new FileReader(sourcefile);
       bufferedreader = new BufferedReader(reader);
  }
 catch ( Exception e ) { System.out.println( "### Error: open input file "+sourcefile); }

 try { writer = new FileWriter(targetfile);
       bufferedwriter = new BufferedWriter(writer);
  }
 catch ( IOException e ) { System.out.println("### Error: open ouput file "+targetfile); }

/* loop on lines                                                           */

 try {
   while(true)
    {

/* read line -> stop reading if no line available                          */

     line = bufferedreader.readLine();
     if(line==null)break;
      //System.out.println("Line: "+line);
     if(line.indexOf('R')!=-1) continue; // header line==null)

/* analyze line                                                            */
/* convert to double values                                                */

     int index = line.indexOf(',');
     chainage = Double.parseDouble(line.substring(0,index).trim());
     line = line.substring(index+1).trim();
     index = line.indexOf(',');
     x = Double.parseDouble(line.substring(0,index));
     line = line.substring(index+1).trim();
     index = line.indexOf(',');
     y = Double.parseDouble(line.substring(0,index));
     line = line.substring(index+1).trim();
     z = Double.parseDouble(line);
     // System.out.println("values: "+chainage+"##"+x+"##"+y+"##"+z);

/* check change of chainage (chainage is descending!)                       */

     if((chainage_old-chainage)>chainage_tolerance)
      {
//       System.out.println("new chainage: "+chainage);
       if(chainage_old<9998.&&write_data)bufferedwriter.write("******************************\n");
       chainage_old = chainage;
       x_0 = x;
       y_0 = y;
       distance_old=-0.001;
       if(actual_storage == storage_frequency)
        {
         actual_storage = 1;
         write_data = true;
        }
       else
        {
         actual_storage++;
         write_data = false;
        }
/* last crossection 760.00 */
       if(chainage <780.01)
         write_data = true;


/* write begin of cross section data                                       */

       if(write_data)
        {
         bufferedwriter.write("topo_1\n");
         bufferedwriter.write("Rhein\n");
         bufferedwriter.write("\t"+chainage*1000+"\n"); // converter to m 1000
         bufferedwriter.write("COORDINATES\n");
         bufferedwriter.write("\t0\n");
         bufferedwriter.write("FLOW DIRECTION\n");
         bufferedwriter.write("\t0\n");
         bufferedwriter.write("DATUM\n");
         bufferedwriter.write("\t0.00\n");
         bufferedwriter.write("RADIUS TYPE\n");
         bufferedwriter.write("\t0\n");
         bufferedwriter.write("ANGLE\n");
         bufferedwriter.write("\t0\n");
         bufferedwriter.write("PROFILE\n");
        }
      }
     if(write_data)
      {
       distance = Math.sqrt((x-x_0)*(x-x_0)+(y-y_0)*(y-y_0));
       if(distance>=distance_old)
        {
         bufferedwriter.write("\t"+distance+" "+z+"\n");
         distance_old = distance;
        }
       else System.out.println("Warning distance in crossection"+chainage+" negative: "+distance+" "+distance_old);
      }

/* end of loop                                                             */
    }

/* end of last crossection                                                 */
   bufferedwriter.write("******************************\n");


/* exception handling reading                                              */
  }
 catch ( Exception e ) { System.out.println( "### Error: reading file " +sourcefile); }

/* close file reader                                                       */

 try { bufferedreader.close();
       reader.close();
  }
 catch ( IOException e ) { System.out.println( "### Error: closing file " +sourcefile); }

/* close file writer                                                       */

 try {   bufferedwriter.close();
         writer.close();
  }
 catch ( IOException e ) { System.out.println( "### Error: closing file " +targetfile); }

 System.out.println("... End   Converter "+sourcefile+" to "+targetfile);

/* end of system                                                           */

 System.out.println("*** End   of RheinToMike11Application");
}

/*-------------------------------------------------------------------------*/
/* check file                                                              */
/*-------------------------------------------------------------------------*/
public static boolean checkFile(String source)
{
 try { FileReader reader = new FileReader(source);
     } catch (IOException e) {return(false);}
 return(true);
}
/*#########################################################################*/
/* end of class                                                            */
/*#########################################################################*/
}


