#include <stdio.h>
#include "exec/types.h"
#include "proto/exec.h"
#include "libraries/controlpad.h"

struct Library *ControlPadBase;

void main(int ac, char **av) {
   UBYTE port;
   CPHANDLE cph;
   UWORD cp0, cp1;

   if (ac > 1) {
      switch(av[1][0]) {
         case '?':
            printf("USAGE:  cp_example [port]\n");
            printf("  where [port] is:  1  for mouseport\n");
            printf("                    2  for joyport\n");
            printf("                    3  for both ports (default)\n");
            return;
         case '1':
            port = CPU_MOUSEPORT;
            break;
         case '2':
            port = CPU_JOYPORT;
            break;
         default:
            port = CPU_BOTHPORTS;
      }
   } else
      port = CPU_BOTHPORTS;



   if (ControlPadBase = OpenLibrary(ControlPadName, 0)) {
      cpShowLogo(120);
      if (cph = cpAlloc(port)) {

         printf("U = up, D = down, L = left, R = right\n");
         printf("A,B,C and S indicate buttons pressed\n");
         printf("3 = 3-button controlpad, I = port is allocated\n");
         printf("E = error.\n\n");

         printf("To Quit: Press B button on a controller that is 'in use' (I)...\n\n");

         printf("CPU_MOUSEPORT:              CPU_JOYPORT:\n");
         printf("U D L R  A B C S  3 I E     U D L R  A B C S  3 I E\n\n");

         do {
            cp0 = cpGet(cph, CPU_MOUSEPORT);
            cp1 = cpGet(cph, CPU_JOYPORT);
            printf("\x1b[A%d %d %d %d  %d %d %d %d  %d %d  %d     ",
               ((cp0 & CPF_UP) != 0),   ((cp0 & CPF_DOWN) != 0),
               ((cp0 & CPF_LEFT) != 0), ((cp0 & CPF_RIGHT) != 0),
               ((cp0 & CPF_A) != 0),    ((cp0 & CPF_B) != 0),
               ((cp0 & CPF_C) != 0),    ((cp0 & CPF_START) != 0),
               ((cp0 & CPF_3BUTTON) != 0), ((cp0 & CPF_INUSE) != 0),
               ((cp0 & CPF_ERROR) != 0));
            printf("%d %d %d %d  %d %d %d %d  %d %d  %d\n",
               ((cp1 & CPF_UP) != 0),   ((cp1 & CPF_DOWN) != 0),
               ((cp1 & CPF_LEFT) != 0), ((cp1 & CPF_RIGHT) != 0),
               ((cp1 & CPF_A) != 0),    ((cp1 & CPF_B) != 0),
               ((cp1 & CPF_C) != 0),    ((cp1 & CPF_START) != 0),
               ((cp1 & CPF_3BUTTON) != 0), ((cp1 & CPF_INUSE) != 0),
               ((cp1 & CPF_ERROR) != 0));
         } while (!( (cp0 & CPF_B) || (cp1 & CPF_B) ));
               // loop until either B button is pressed.

         cpFree(cph);
      }
      CloseLibrary(ControlPadBase);
   }
}
