#include <conio.h>
#include <stdio.h>
#include <io.h>


#define ANCHO   80
#define ALTOini  5
#define ALTO    20
#define ARRIBA  72
#define ABAJO   80




void MuestraLinea( char Como, char Donde, char *Quien )
{
   if ( Como )
   {
    textattr( 1 );
   } else {
    textattr( 5 );
   }

   // Borramos la linearrr

   gotoxy( 2, Donde+ALTOini );
   cprintf( "%s", Quien );
};

void ObtenLinea( FILE *PT, int LINEA, char *Buffer )
{
   fseek( PT, sizeof(char)*ANCHO*LINEA, SEEK_SET );
   fread( &Buffer, ANCHO*sizeof(char), 1, PT );
};

void PonLinea( FILE *PT, int LINEA, char *Buffer )
{
   fseek( PT, sizeof(char)*ANCHO*LINEA, SEEK_SET );
   fwrite( &Buffer, ANCHO*sizeof(char), 1, PT );
};


void RefreshTexto( FILE *PT, int NLinicio )
{
  char Buffer[ANCHO+1];
  int i;

  i = 0;
  while ( !feof( PT ) && i < 22 )
  {
   ObtenLinea( PT, (i+NLinicio), Buffer );
   MuestraLinea( 0, i, Buffer );
   i++;
  }
};


void PTextos( char *file )
{
  FILE *PTxt;
  int Lvisual, Lrestante;
  char ok = 0;
  char Buffer[ANCHO+1];

  clrscr();

  if ( ( PTxt = fopen( file, "w+b" ) ) == NULL )
  {
   //--ERROR
   return;
  } else {
    Lvisual   = 0;
    Lrestante = 0;
    RefreshTexto( PTxt, Lvisual+Lrestante );
    ObtenLinea( PTxt, Lvisual + Lrestante, Buffer );

    ok = 0;
    do {

      MuestraLinea( 1, Lvisual, Buffer );
      while( !kbhit() );
      MuestraLinea( 0, Lvisual, Buffer );

      switch ( getch() )
      {
       case 27:
         ok = 1;
         break;
       case  0:
         switch ( getch() )
         {
          case ARRIBA:
            Lvisual --;
            if ( Lvisual < 0 )
            {
             Lvisual = 0;
             Lrestante --;
             if ( Lrestante < 0 )
               Lrestante = 0;
            }

            RefreshTexto( PTxt, Lvisual + Lrestante );
            ObtenLinea( PTxt, Lvisual + Lrestante, Buffer );
            break;
          case ABAJO:
            Lvisual ++;
            if ( Lvisual > ALTO )
            {
             Lvisual = ALTO;
             Lrestante ++;
             // Deberias controlar las lineas intermedias, para ponerlas a cero
            }

            RefreshTexto( PTxt, Lvisual + Lrestante );
            ObtenLinea( PTxt, Lvisual + Lrestante, Buffer );
            break;
         }
       default:
         // Editamos la linearrr
//********************************************************************************
//         EditaLinea( 2, Lvisual, Buffer );
//********************************************************************************
         sprintf( Buffer, "Linea %d", Lvisual + Lrestante );
         PonLinea( PTxt, Lvisual + Lrestante, Buffer );
         break;

      }
    } while ( !ok );

   fclose( PTxt );
  }

};


void main( void )
{
 PTextos( "Prueba.txt" );
}
