#include <stdio.h>
#include <math.h>
#define LPT1 0x378

/* Endereco 0x378 (LPT1): 

Obs: veremos porta paralela na proxima aula!

  7   6   5   4   3   2   1   0     ÍNDICE (ou BIT)
 -------------------------------
| 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 |   PINOS
 -------------------------------
  8   7   6   5   4   3   2   1     LEDS

A definição dos LEDS leva em consideração ao índice que ele está
Ex: #define LD1 0

*/

#define LD1 0
#define LD2 1
#define LD3 2
#define LD4 3
#define LD5 4
#define LD6 5
#define LD7 6
#define LD8 7


#define DEVCpp

#ifdef DEVCpp
		 #include <windows.h>
#endif
#ifdef TURBOCpp
		 #include <dos.h>
#endif

void espera(long tempo){
    #ifdef DEVCpp
    	  Sleep(tempo);
    #endif
    #ifdef TURBOCpp
    	  delay(tempo);
    #endif
}


/* criação de um tipo, que é um ponteiro para função */

     typedef short _stdcall (*inpfuncPtr)(short portaddr);
     typedef void _stdcall (*oupfuncPtr)(short portaddr, short datum);

/* ponteiros para funções, mas que podem ser interpretadas como:
   (a) short inp32(short porta);
   (b) void oup32(short porta, short dado);
*/
     HINSTANCE hLib;
     inpfuncPtr inp32;
     oupfuncPtr oup32;


int main(void)
{
     int entrada;
     if (iniciaBiblioteca()==-1) return -1; // inicia e testa se falhou

     // imprimindo na tela o valor atual da LPT1
     entrada = inp32(LPT1);
     printf("O valor atual da LPT1 vale %d",entrada);

     espera(2000);

     // colocando o valor 4 em LPT1, ou seja, ligando o LED3 (ou BIT2)
     oup32(LPT1,4);   

     espera(2000);
     
     FreeLibrary(hLib);
     return 0;
}


int iniciaBiblioteca(){
     /* Load the library */
     hLib = LoadLibrary("inpout32.dll");

     if (hLib == NULL) {
          printf("A biblioteca inpout32.dll nao foi encontrada\n\n");
          return -1;
     }else {
           printf("Biblioteca inpout32.dll aberta com sucesso...\n\n");
           getch();
           }
     

     /* get the address of the function */

     inp32 = (inpfuncPtr) GetProcAddress(hLib, "Inp32");

     if (inp32 == NULL) {
          printf("GetProcAddress for Inp32 Failed.\n");
          return -1;
     }


     oup32 = (oupfuncPtr) GetProcAddress(hLib, "Out32");

     if (oup32 == NULL) {
          printf("GetProcAddress for Oup32 Failed.\n");
          return -1;
     }  
     
     return 0;   
     
}     
