-- Author      : Manuel De Girardi
-- Date        : 2010/12/9
-- Version     : 0.0.0pre-alpha_010
-- Description : artificial neural network generator for MidiSurf
-------------------------------------------------------------------------------

with Ada.Text_Io;
use Ada.Text_Io;
with Ada.Strings, Ada.Strings.Fixed;
use Ada.Strings, Ada.Strings.Fixed;
package body Libsens.Neural_Chord.Io is
      
   procedure Read_From_File(Filename : in String;  Target : in string) is
   begin      
      begin
	 Open(Data_File, In_File, Filename);
	 Register_Io.create(Reg_File, Register_Io.Out_File, Target & ".bin");
	 Buffer_Length := 0;
	 The_Index := 0;
	 Position := 1;
	 while not End_Of_File(Data_File) loop
	    Get_line(Data_File, The_Line, last);
	 end loop;

	 loop
	    The_Index := Index(The_Line(1..Last), ",", position, Forward);
	    exit when The_Index = 0;
	    Buffer(Buffer_Length+1) :=
	      Integer'Value(The_Line(Position..The_Index-1));
	    Position := The_Index+1;
	    Buffer_Length := Buffer_Length + 1;
	 end loop;
	 for I in 0..Buffer_Length-1 loop
	    The_Bbyte := (others => False);
	    The_Bbyte := To_bbyte(Buffer(I+1));
	    for J in 1..7 loop
	       if The_Bbyte(J) then
		  Register(7*I+J) := 1.0;
	       end if;
	    end loop;
	 end loop;
	 Register_Io.Write
	   (Reg_File, Register, Register_io."+"(Register_Io.Size(Reg_File),1));
	 First := Register;
	 Reset(Data_File);
	 loop
	    Buffer_Length := 0;
	    The_Index := 0;
	    Position := 1;
	    Get_line(Data_File, The_Line, last);

	    loop
	       The_Index := Index(The_Line(1..Last), ",", position, Forward);
	       exit when The_Index = 0;
	       Buffer(Buffer_Length+1) :=
		 Integer'Value(The_Line(Position..The_Index-1));
	       Position := The_Index+1;
	       Buffer_Length := Buffer_Length + 1;
	       Put(Integer'Image(Buffer(Buffer_Length)) & ", ");
	    end loop;
	    New_Line;
	    for I in 0..Buffer_Length-1 loop
	       The_Bbyte := (others => False);
	       The_Bbyte := To_bbyte(Buffer(I+1));
	       for J in 1..7 loop
		  if The_Bbyte(J) then
		     Register(7*I+J) := 1.0;
		  end if;
	       end loop;
	    end loop;

	    Register_Io.Write
	      (Reg_File, Register, Register_io."+"(Register_Io.Size(Reg_File),1));
	    exit when End_Of_File(Data_File);
	    Register_Io.Write
	      (Reg_File, Register, Register_io."+"(Register_Io.Size(Reg_File),1));

	    Data_Length := Data_Length + 1;
	    Register := (others => 0.0);

	 end loop;

	 Register_Io.Write
	   (Reg_File, first, Register_io."+"(Register_Io.Size(Reg_File),1));
	 Data_Length := Data_Length + 1;
	 Close(Data_File);
	 Register_Io.Close(Reg_File);


      exception
	 
	 when Name_Error =>
	    raise Arg_Error;
      end;      
   end Read_From_File;
end Libsens.Neural_Chord.Io;